How should I approach 'Blues in all keys' by Jamey Aebersold on the piano?

Question: I am a piano player, new to the world of jazz/blues and have just bought myself a copy of Jamey Aebersold's Blues in all keys and wanted some advice on how to practice using it, starting from simple tasks and progressing in the 'right' way. The following is the plan I have developed so far for each of the 12 tracks:

Transcribe (in my head) or invent a walking bassline with LH
Play the chord (once per chord change) in the RH
Add more of a rhythm to the RH chords when I feel comfortable
Sing some licks and add them into the RH when I feel it
Play along to the track once in its written key and transponse the exact same thing to all other keys

Are there any other important things I should be thinking/doing when working from this book/CD?
EDIT: I mainly want to improve my solo piano improvisational skills
Comment: It's good advice and I have been using it, but I feel I need something else to take it further
Comment: You have a plan, try it.  It seems like you are asking for more than just getting better at soloing.  That process takes time so just get into the exercises and it will follow.  Soloing is really composition on the fly.  Learn the classic approach to composition, arranging, harmony theory etc.  Beyond that the 2 basic changes are 12 bar blues (which you have) and Rhythm changes.  Get these memorized to free your mind from overthinking.
Comment: The best way to practice will depend partly on whether you'll be playing primarily solo piano or in a group. For example, walking bass lines isn't something you'll really ever do if you play in a quartet with a bass and drums, but it would be useful if you plan to do a fair amount of solo piano. Which is more relevant to you?
Comment: Good point - solo piano for the time being, I have a couple of background piano gigs coming up
Comment: What's wrong with Jamey's advice? On page 7, he walks you through a way to imprint the form and harmony in your muscle memory, by playing along with the First (1/2/3/5) notes of each scale, using chord tones, etc. Beyond that, I would sing a few solos and then try to play what you sang.
Answer: Overview
If your focus is improvisation, then I recommend you start by practicing:

a simple chord voicing in the left hand, and
a simple improv technique in the right hand.

It's fine if you can't initially play both hands together (most people can't). Start with your left-hand voicings first, and practice these alone until they become automatic.
Voicing in the left hand
For your left-hand voicings, start with Bud Powell/shell voicings, and then move to rootless A and B voicings. Shell voicings contain only two notes: the root + either the 3rd/10th or the 7th of the chord. In a ii-V-I, you switch between the 1-3 voicing and the 1-7 voicing. Practice both voicings for each chord. This might require playing through the recording twice, switching every chorus, etc.
Improvisation technique in your right hand
For #2 (improvisation techniques), try these:

playing a single chord tone (e.g., the 3rd, then the 5th, then the 7th, etc.)
approach a single chord tone (same exercise as above, but approach the tone from a half step below, a scale step above, or some combination of both)
playing chord arpeggios followed by scale runs
playing scale patterns
finding lick you likes from a recording, transcribing them, and practicing them over the blues in all 12 keys

Improvising solo piano in a jazz context is ultimately a mix of many different skills. The left hand alone has many different techniques you'll ultimately want to master and have at your disposal while improvising with your right hand. My recommendation is to start with a smaller group of skills (like the list above) and making progress on those before moving on. In solo jazz piano, it's easy to overwhelm oneself with trying to learn too much at once. Walking a bass line is something I'd recommend doing later. It tends to be less used in an improvising/soloing context, and it's much more difficult to achieve independence between your two hands.


Não parar setTimeOut quando alterar abas do navegador

Question: Estou construindo um contador com vueJS e notei que a contagem para quando troco o foco da aba; a principio estou utilizando a função setTimeoutdo javscript:
setTimeout(() => {
    this.time++

    this.min  = Math.floor(this.time/100/60)
    this.sec  = Math.floor(this.time/100)
    this.mSec =  this.time % 100

    this.timer() // recursividade

}, 10);

Se eu manter o foco na aba, ou mover a aba para outro monitor o contador funciona perfeitamente, porém se eu trocar de aba o contador é pausado automaticamente, existe uma maneira de não para o setTimeout ao trocar o foco da aba do navegador?
Answer: Os navegadores mais modernos suspendem alguns códigos JavaScript, como o setTimeout, quando a janela não está em foco para economizar recursos de energia e processamento. Imagine se ficasse executando JavaScript quando você minimizasse seu navegador no celular.
Uma solução é criar um listener para alguns hooks. Por exemplo, quando o foco é perdido da aba, você salva o tempo e quando o foco retorna você subtrai e vê quanto tempo passou para ajustar seu timer.
Para verificar esses hooks, pode fazer uso da API de Page Visibility, descrita no MDN.
// Set the name of the hidden property and the change event for visibility
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
  hidden = "hidden";
  visibilityChange = "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
  hidden = "msHidden";
  visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
  hidden = "webkitHidden";
  visibilityChange = "webkitvisibilitychange";
}

var videoElement = document.getElementById("videoElement");

// If the page is hidden, pause the video;
// if the page is shown, play the video
function handleVisibilityChange() {
  if (document[hidden]) {
    videoElement.pause();
  } else {
    videoElement.play();
  }
}

// Warn if the browser doesn't support addEventListener or the Page Visibility API
if (typeof document.addEventListener === "undefined" || typeof document.hidden === "undefined") {
  console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
} else {
  // Handle page visibility change
  document.addEventListener(visibilityChange, handleVisibilityChange, false);

  // When the video pauses, set the title.
  // This shows the paused
  videoElement.addEventListener("pause", function(){
    document.title = 'Paused';
  }, false);

  // When the video plays, set the title.
  videoElement.addEventListener("play", function(){
    document.title = 'Playing';
  }, false);

}

Timeouts in inactive tabs throttled to >=1000ms
To reduce the load (and associated battery usage) from background
  tabs, timeouts are throttled to firing no more often than once per
  second (1000 ms) in inactive tabs.
Firefox implements this behavior since version 5 (see bug 633421, the
  1000ms constant can be tweaked through the
  dom.min_background_timeout_value preference). Chrome implements this
  behavior since version 11 (crbug.com/66078).
Firefox for Android uses a timeout value of 15 minutes for background
  tabs since bug 736602 in Firefox 14, and background tabs can also be
  unloaded entirely.
retirado do Mozilla Developers Network
Comment: meu timer e uma variável simples de incremento como posso "calcular" o tempo que a aba esteve fora de foco se o javascript vai estar "pausado"?


$f_n(x)=\frac{nx}{1+nx}$ in $C[0,1]$ with usual sup-norm metric.

Question: I need to check whether it is Cauchy or not:

$f_n(x)=\frac{nx}{1+nx}$ in $C[0,1]$ with usual sup-norm metric.

As,I know the sequence is Cauchy if for any $\epsilon>0$ there is a no $N$ such that $d(f_m,f_n)<\epsilon$ for all $m,n>N$. So I was calculating $d(f_m,f_n)$ which I got is this:
$$d(f_m,f_n)=(m-n)\sup_{x\in[0,1]}\frac{x}{(mx+1)(nx+1)}$$
Now I am not understanding how to deal with this.
Comment: Yep. The limit of a uniformly convergent sequence of continuous functions is continuous. The pointwise limit of this sequence isn't continuous, hence the sequence doesn't converge uniformly. Hence it's not a Cauchy sequence in $C([0,1])$.
Comment: $d(f_m,f_n)$ is a little inconvenient to deal with. What is the pointwise limit of $(f_n)$?
Comment: Though it's not difficult to see that $f(f_{2n}, f_n) \geqslant \frac{1}{6}$ for $n > 0$.
Comment: No, that's not the pointwise limit.
Comment: Almost. There's one point that begs to differ.
Comment: if $x$ not $0$, then....
Comment: C[0,1] complete. So convergent cauchy is same. Limit function is not continuous.Limit is outside of C[0,1]?....
Comment: Can u link a proof of "limit of a uniformly convergent sequence of continuous functions is continuous"?
Comment: https://en.wikipedia.org/wiki/Uniform_limit_theorem
Answer: Let $m=n^2$, then, as $n$ goes to infinity, we have that
$$d(f_{n^2},f_n)=(n^2-n)\sup_{x\in[0,1]}\frac{x}{(n^2x+1)(nx+1)}\\
\stackrel{x=1/n}{\geq} (n^2-n)\frac{(1/n)}{(n^2(1/n)+1)(n(1/n)+1)}
=\frac{n-1}{2(n+1)}\to \frac{1}{2}\not=0.$$
Hence $(f_n)_{n\geq 1}$ is not a Cauchy sequence (and the sequence is not (uniformly) convergent in $C[0,1]$).
P.S. Note that the pointwise limit is the function which is $1$ in $(0,1]$ and it is 0 at 0. It is not continuous in $[0,1]$.
Comment: @Pedrick Serre Is my answer convincing?
Comment: I dont understand how supremum is greater than the case x=1/n?
Comment: @Pedrick Serre The supremum is taken in $[0,1]$ and $1/n\in[0,1]$.


how to make a recursive racket list that, from the input list, outputs its decreasing to 1 for every element in the list (e.g. ('3 2) outputs ('32121)

Question: ****What I tried****
(define(help num)
        (if(= num 1)
           num
          (cons(num (help( - num 1))))))

;i called this defination in the bottom one
(define (list-expand L)
(cond
  [(empty? L)'()]
  [(=(car L)1)(cons(car L)(list-expand (cdr L)))]
  [(>(car L)1) (cons(help(car L)(list-expand(cdr L))))]))

Answer: In the help procedure, the base case is incorrect - if the output is a list then you must return a list. And in the recursive step, num is not a procedure, so it must not be surrounded by brackets:
(define (help num)
  (if (<= num 0)
      '()
      (cons num (help (- num 1)))))

And in list-expand, both recursive steps are incorrect. You just need to test whether the list is empty or not, calling help with the correct number of parameters; use append to combine the results, because we're concatenating sublists together:
(define (list-expand L)
  (if (empty? L)
      '()
      (append (help (car L)) (list-expand (cdr L)))))

That should work as expected, but please spend some time studying Scheme's syntax, you still have trouble with the basics, for instance, when and where to use brackets...
(list-expand '(3 2))
=> '(3 2 1 2 1)

Answer: Just for fun - a non-recursive solution in Racket:
(append-map (lambda (n) (stream->list (in-range n 0 -1))) '(3 2))

;; or:
(append-map (lambda (n) (for/list ((x (in-range n 0 -1))) x)) '(3 2))

Returning:
'(3 2 1 2 1)


Rails 4 + Rails-API + RSpec + Devise - Trouble testing controllers with custom devise routes

Question: I'm currently building out an API and trying to test my controller. I am getting errors related to Devise that I cannot solve. Here is what I currently have:
# /spec/requests/api/v1/sessions_spec.rb
require 'spec_helper'

describe API::V1::SessionsController do
  describe "POST /sessions" do
    it "on success, returns the user's authentication token" do
      user = FactoryGirl.create(:user)

      user_params = {
        "user" => {
          "email" => user.email,
          "password" => user.password
        }
      }.to_json

      post "/api/v1/sessions", user_params

      expect(response.status).to eq(200)
      json = JSON.parse(response.body)
      expect(json['authentication_token']).to eq(user.authentication_token)
    end
  end
end

# /app/controllers/api/v1/sessions_controller.rb
class API::V1::SessionsController < Devise::SessionsController
  respond_to :json

  def create
  end
end

# routes.rb
MyApplication::Application.routes.draw do
  namespace :api, defaults: { format: :json } do
    namespace :v1 do
      devise_scope :user do
        post 'sessions' => 'sessions#create', :as => 'login'
      end
    end
  end
end

The error am I current getting is:
1) API::V1::SessionsController POST /sessions on success, returns the user's authentication token
 Failure/Error: post "/api/v1/sessions", user_params
 AbstractController::ActionNotFound:
   Could not find devise mapping for path "/api/v1/sessions".
   This may happen for two reasons:

   1) You forgot to wrap your route inside the scope block. For example:

     devise_scope :user do
       get "/some/route" => "some_devise_controller"
     end

   2) You are testing a Devise controller bypassing the router.
      If so, you can explicitly tell Devise which mapping to use:

      @request.env["devise.mapping"] = Devise.mappings[:user]
 # ./spec/requests/api/v1/sessions_spec.rb:21:in `block (3 levels) in <top (required)>'

I have searched around for a solution to this issue, and tried a bunch from different questions. The question's solution here (How to write controller tests when you override devise registration controller?) said to put the below code in a before block in the spec.
before :each do
  request.env['devise.mapping'] = Devise.mappings[:user]
end

But when I add that to my controller, I get another error that says:
1) API::V1::SessionsController POST /sessions on success, returns the user's     authentication token
 Failure/Error: request.env['devise.mapping'] = Devise.mappings[:user]
 NoMethodError:
   undefined method `env' for nil:NilClass
 # ./spec/requests/api/v1/sessions_spec.rb:7:in `block (2 levels) in <top (required)>'

Another question's solution here (undefined method 'env' for nil:NilClass) says to try adding include Devise::TestHelpers to the spec but when I do that, the same error is returned.
The current gems I am using:
rails (4.0.2)
rails-api (0.2.0)
rspec-rails (2.14.1)
devise (3.2.2)
Using these two tutorials as sort of a guide: https://lucatironi.github.io/tutorial/2012/10/15/ruby_rails_android_app_authentication_devise_tutorial_part_one/
http://commandercoriander.net/blog/2014/01/04/test-driving-a-json-api-in-rails/
Any help would be appreciated, thanks!
Answer: I think I may have solved the issue. It seems I had to add in a devise_for outside the api namespace blocks:
MyApplication::Application.routes.draw do

  devise_for :users, skip: [:sessions, :passwords, :registrations]

  namespace :api, defaults: { format: :json } do
    namespace :v1 do
      devise_scope :user do
        post 'sessions' => 'sessions#create', :as => 'login'
      end
    end
  end
end

I will keep the question open for a bit longer in case I run into any other issues when testing.
Answer: Replace
  request.env['devise.mapping'] = Devise.mappings[:user]

With
  @request.env['devise.mapping'] = Devise.mappings[:user]

Notice the error message specifically suggests to use:
 2) You are testing a Devise controller bypassing the router.
      If so, you can explicitly tell Devise which mapping to use:

      @request.env["devise.mapping"] = Devise.mappings[:user]

Comment: Unfortunately, I get the same error with or without the @ in front of request
Comment: Can you share your devise specific routes from `routes.rb` file. Please update in the question.
Comment: It is already in the question, scroll down in the first code box.


Complete tree of height n. A formula in FO.

Question: Let $T$ be a family of finite binary trees under the signature contains two realational symbols:
$$ l(y,x) \iff  \text{ y is left son of x }$$
$$ r(y,x) \iff  \text{ y is right son of x }$$
Prove that for every $n \in \mathbb{N} $ there exists a such FO two-varviables-sentence $\phi_n$ that for every finite tree $t$ it is true:
$$ t \models \phi_n \iff t \text { is complete and its height equals to n}$$.
My solution:
Induction by height of tree:
Let $\phi_1 = \exists x [ (\exists y l(y,x) \wedge (\neg \exists x  l(x,y) \vee r(x,y))) \wedge (\exists y r(y,x) \wedge (\neg \exists x  l(x,y) \vee r(x,y))) ]$. It means that $x$ is a root of complete tree where its height = 1.
Induction step:
Let $\phi_n(x) $ will be a such two-variable-sentence that: $$ t \models \phi_n(x) \iff \text{ t is a complete tree. Its height = n}$$
Now, we define the $$\phi_{n+1}(x) = (\exists y l(y,x) \wedge \phi_n[y/x]) )  \wedge (\exists y r(y,x) \wedge \phi_n[y/x])$$
Now, $phi_{n+1}(x) $ has no free variables.
Now, we can note that if $t \models \phi_{n+1}(x)$ then $t$ is a complete tree, its height = $n+1$. $\phi_{n+1}(x)$ is still 2-variables because the induction step doesnt introduce new variables.
Ok?
Answer: First of all, note that $\varphi_1$ isn't a sentence; it has a free variable $x$. So you need to tweak it.
Even then, you're not quite done: $\varphi_1$ (when fixed) will say that $t$ extends a complete tree of height $1$. How do you know, for instance, that $t$ isn't a complete tree of height $17$? Intuitively, your formulas need to do two things: say that $t$ is at least a complete tree of height $n$, and also say that $t$ isn't more than that. (Your inductive step is fine, after you fix the base case.)
Comment: I edited my post.
Comment: @Logic Still a problem - you've written "Every $y$ is a left successor and right successor of $x$." You were closer before. HINT: do you know how to right "there are exactly three elements" in first-order logic?
Comment: I've edited again. @NoahSchweber, I know but I don't know how to express it having only 2 variables.


Restore Sqlserver Database Using C# Showing Error

Question: I am trying to backup and restore sql server 2008r2 database, and i successfully backup my database , But the problem is when i am trying to restore my DB its showing the following error
 Restore failed for Server 'XXXX-PC\SQLEXPRESS'
And Another important thing is that , When i Close the DB Connection (From server Explorer [right-click->Close Connection]) its working Normally And Correctly
Below is my Backup And Restore Code
Please help me to fix the problem
<code>public static void BackupDatabase(string backUpFile)
{
    ServerConnection con = new ServerConnection(@"XXXX-PC\SQLEXPRESS");
    Server server = new Server(con);
    Backup source = new Backup();
    source.Action = BackupActionType.Database;
    source.Database = "testBD";
    BackupDeviceItem destination = new BackupDeviceItem(backUpFile, DeviceType.File);
    source.Devices.Add(destination);
    //source.Devices.AddDevice(@"G:\MyBackUp.bak", DeviceType.File);
    source.SqlBackup(server);
    con.Disconnect();
}

public static void RestoreDatabase(string backUpFile)
{
    ServerConnection con = new ServerConnection(@"XXXX-PC\SQLEXPRESS");
    Server server = new Server(con);
    Restore destination = new Restore();
    destination.Action = RestoreActionType.Database;
    destination.Database = "testBD";
    BackupDeviceItem source = new BackupDeviceItem(backUpFile, DeviceType.File);

    destination.Devices.Add(source);

    destination.ReplaceDatabase = true;

    con.Disconnect();
    server.ConnectionContext.Disconnect();

    destination.SqlRestore(server);
}
</code>
This is the error :

This is the error message in detail:

Comment: Look at the inner exception. Please post ex.ToString().
Answer: My guess is that your restore process can't get exclusive access to the database. The Server SMO object has a KillAllProcesses method that takes a database as an argument and does what it says on the tin.
Comment: Thanks man.. Its works !!! , i added server.KillAllProcesses("DBName") to my code


WinForm Application -> End Process -> FormClosing() & FormClosed() events Not Fired

Question: I have a started win-form application with some codes in FormClosing() &  FormClosed() events.
With another application i want to forcibly close that first application like this :
<code>    string procId = proc.Id.ToString();

    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.FileName = "taskkill.exe";
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.Arguments = "/f /t /pid " + procId;
    Process.Start(startInfo);
</code>
When i want for forcibly close first application by those codes or using with Task Manager -> End Process , FormClosing() &  FormClosed() events are not fired.
How can i force those events to fire in every situation or what is the solution?
Comment: If your process is being killed, there's nothing you can do. _Why_ do you want that code to run? Can't you do a cleanup of a killed instance upon the next startup?
Comment: check this question :
:http://stackoverflow.com/questions/474679/capture-console-exit-c-sharp
Comment: No man, in startup and close i have different codes for writing some data in a file. i can't change them!
Comment: Generally, either you wait until next startup, or you tell the process you are about to kill it and allow it to perform actions beforehand (assuming both processes are under your control).
Comment: @Ehsan Sajjad that thread simulates Form_Closing() event in a ConsoleApplication and in winforms we have that event. Just need to run it in every termination.
Comment: @CodeCaster thanks for the answer, but didn't help. please forget startup codes and there is no need to clean up codes. my situation is different and in every close i should some values. that's all...
Comment: **You can't**. That's all. If your process is being killed, it is terminated on the spot. There is no code to run anymore. If you don't explain your situation, the answer is "You can't", which I gave.
Comment: but there should be an event during ENDPROCESS!!!!!!!!! Or should a way to capture it. Imagine i want to have a full log file and write it this user forcibly closed app or some thing like that.
Comment: @MoonLight There shouldn't be, and there isn't such event. What are you trying to accomplish?
Answer: See Prevent C# app from process kill.
You cannot prevent your app's process being terminated, and you won't get an event it is being terminated.
So you must cater for the case where a process didn't clean up nicely at shutdown. For that matter, you need to do that anyway, what if the machine BSODs while your app is running? You can never assume the previous instance completed successfully.
It looks like your app closes some data file upon shutdown, so that the next time the program runs it can read the file again. If that is the case, you could write some "dirty flag" in or near the file and clean the file up on startup if it is flagged.
As explained in How does task manager kill my program? and MSDN: Terminating a Process (Windows):

Note that you cannot intercept or react upon TerminateProcess. Your process will die and there is nothing you can do before that happens.
If a process is terminated by TerminateProcess, all threads of the process are terminated immediately with no chance to run additional code. This means that the thread does not execute code in termination handler blocks.


CodePipeline + Beanstalk Connection Refused React + Express Apps

Question: I'll lay this out below in detail:
Goal
A React front-end game that uses socket.io to transfer game state data between players on the Express server.
Setup
After finding that it would be impossible/a real work-around to have both React/Express on an Amplify instance, I decided to move to CodePipeline + CodeDeploy to Beanstalk.
I have the Source coming from GitHub, a CodeBuild step, and then CodeDeploy. The CodeBuild should basically just compile based on my buildspec.yml below:
version: 0.2
  frontend:
    phases:
      preBuild:
        commands:
          - npm ci
      build:
        commands:
          - npm run build
   artifacts:
     baseDirectory: build
     files:
       - '**/*'
   cache:
     paths:

Although this is calling npm run build, which I'm not sure A) The CodeBuild/CodeDeploy will try to do with node start or B) If this will kick off my react-scripts build in package.json:
"scripts": {
    "webpack": "webpack --production",
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

I'm assuming I want it to build the webpack bundle in CodeBuild, then CodeDeploy will call the proper run command, but it seems black boxed? Is there another config file?
Runtime Errors
I get Connection Refused, although my server.js file defaults to localhost and 8080:
var hostname = process.env.IP || 'localhost';
var port = process.env.PORT || 8080;

Web.std.out.log:
Sep 20 18:10:10 ip-172-31-41-5 web: > firstname.lastname@example.com start /var/app/current
Sep 20 18:10:10 ip-172-31-41-5 web: > react-scripts start
Sep 20 18:10:12 ip-172-31-41-5 web: #033[34mℹ#033[39m #033[90m「wds」#033[39m: Project is running at http://172.31.41.5/
Sep 20 18:10:12 ip-172-31-41-5 web: #033[34mℹ#033[39m #033[90m「wds」#033[39m: webpack output is served from
Sep 20 18:10:12 ip-172-31-41-5 web: #033[34mℹ#033[39m #033[90m「wds」#033[39m: Content not from webpack is served from /var/app/current/public
Sep 20 18:10:12 ip-172-31-41-5 web: #033[34mℹ#033[39m #033[90m「wds」#033[39m: 404s will fallback to /
Sep 20 18:10:12 ip-172-31-41-5 web: Starting the development server...

Ngnix error.log: 2020/09/18 03:07:30 [error] 4436#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.40.133, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8080/", host: "172.31.41.5"
Lot of moving parts so I'm sure there are several missteps here, not sure which is which.
Comment: The first step to troubleshoot if to check if you can deploy your app successfully without CodePipeline. Just plain Elastic Beanstalk.
Comment: I am able to run the `npm build` and `serve -s build` locally but Beanstalk fails.
Comment: This might be it, from standalone Beanstalk log: `[ERROR] An error occurred during execution of command [app-deploy] - [check Procfile]. Stop running the command. Error: node.js may have issues starting. Please provide a package.json file or add server.js/app.js file in source bundle`
Comment: EB will look for package.json file. If you want to use other command to start your app, you can provide your own in `Procfile`. I would have to provide an answer to write more details due to limited space in comments.
Answer: Based on the comments.
By default EB will look for package.json to run your application. If it is missing, and will use use script option in your package.json to start your application. For example, if you start sample node.js application that EB provides, the file is:
package.json
{
  "name": "Elastic-Beanstalk-Sample-App",
  "version": "0.0.1",
  "private": true,
  "dependencies": {},
  "scripts": {
    "start": "node app.js"
  }
}

If you don't provide package.json nor Procfile (other option, see below) EB will expect app.js or server.js to be present to start your application.
If you don't want to use package.json, you can also use Procfile to tell EB how to start your application.

When you don't provide a Procfile, Elastic Beanstalk runs npm start if you provide a package.json file. If you don't provide that either, Elastic Beanstalk looks for the file app.js or server.js, in this order, and runs it.

Example in your case could be
web: serve -s build

Comment: I was able to confirm in `eb-engine.log` that the Procfile was being uptaken and the two processes I've specified for the front-end/back-end are ran. The only other error that might be causing it to fail before logs are output is a `The deployment didn't install a specific Node.js version`. Do I need to specify this always in `package.json`? I'm surprised it doesn't automatically install the Node platform version specified when setting up EB.
Comment: Now I'm getting an error on that first process, `See "systemctl status web.service" and "journalctl -xe" for details.`. It might be tough accessing those control commands because I have been having trouble connecting to my EC2 instances. The process command is `web: serve -s build`
Comment: @A13X What's wrong with connecting to the EC2 instance? For the node version, maybe you set somewhere to use non-default version for your environment?
Comment: Locally I've been using 12.16.1, I added it to package.json and that error seems to have cleared up. But now the first process is erroring, maybe because I don't have `serve` installed somehow?
Comment: Can you spinup new EB environment where you can login using ssh. This way would allow you to investigate from the inside what packages are installed, why `systemctl status web.service` fails. Thanks for accepting:-)
Comment: Hmm, I can't seem to get SSH in to even a new EC2 instance, although I'm setting a lot of things to default. I have the private key on my local machine and try to putty/pageant in. I tried installing `serve` in `package.json` but that didn't seem to help. And no problem, at least this got the ball rolling.
Comment: Okay I decided to scrap any fancy commands in Proc and just do `npm start`. That at least got my Deploy green. Still have a 502 Gateway Ngnix error though when navigating to URL. Probably looking for the wrong port/need to forward it? I tried 3000,5000,8000,8080 in my browser.
Comment: In the browser, port is 80. But your app I think should run on port 5000. But can you ssh now to the instance now?. This is bigger issue in my view why you can't access it. You can make new question for it with relevant details.
Comment: Okay now I am getting a `Cannot get /` from the url at least. It looks like it runs commands for both express and React, but I see `Something is already running on port 8080.` from the React/web process. Is it continually calling `npm start`? Still getting `Connection refused` for Ngnix log (also 8080). Maybe they run on same port? But I get the `Cannot get /` from port 80 (regular url).


PHP: Upload de arquivos funciona para imagens mas não funciona para arquivos PDF

Question: Estou com um problema estranho: meu formulário funciona para upload de imagens mas não funciona para o upload de arquivos PDF.
Meu código é o seguinte:
<code>$titulo             = $_POST['txtTitulo'];
$descricao      = $_POST['txtDescricao'];

$extension = pathinfo($_FILES['flFile']['name']);
$extension = ".".$extension['extension'];
$extension != '.';
$file = md5(time().rand()).$extension;
$anexo = 'assets/uploads/'.$file;
move_uploaded_file( $_FILES['flFile']['tmp_name'], $anexo );

$query = "insert into tb_arquivos (id_arquivo, titulo, descricao, anexo)
values (null, '".$titulo."', '".$descricao."', '".$anexo."')";

mysql_query($query) or die (mysql_error());
</code>
Se eu insiro uma imagem, tudo funciona perfeitamente. Mas, se eu insiro um PDF, eu perco todos os valores do formulário (inclusive os da variáveis $titulo e $descricao.
Alguém pode me ajudar?
Muito obrigado!!!
Answer: Descobri que o problema se encontrava no limite para upload de arquivos.
Como as imagens que eu costumo subir para o site são menores que 2MB, o problema nunca ocorria.
Para resolver este problema eu criei um arquivo .htaccess na raiz do projeto com o seguinte conteúdo:
<code>php_value upload_max_filesize 1G
php_value post_max_size 1G
</code>


Redirect angular js page in browser from Java (Spring) Filter

Question: I have created an SQL injection filter in my Spring Boot application that intercepts each request and validates input for a possible SQL injection. If input is invalid, then I want to redirect user back to login page. With my code, I can see internal call being made through DevTools but browser is not redirecting to specified page.
Filter
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

HttpServletRequest req = (HttpServletRequest) request;
String url = req.getRequestURL().toString();

Enumeration<String> enumeration = request.getParameterNames();
while (enumeration.hasMoreElements()) {
    String paramName = enumeration.nextElement();
    String value = request.getParameter(paramName);
    String sqlRegex =
                    "\\b(ALTER\\s+TABLE{0,1}|CREATE\\s+TABLE{0,1}|DELETE\\s+FROM{0,1}|DROP\\s+TABLE{0,1}|EXEC(UTE){0,1}|INSERT\\s+INTO{0,1}|MERGE\\s+INTO{0,1}|SELECT\\s[0-9a-zA-Z_*]*\\s+FROM{0,1}|UPDATE\\s[0-9a-zA-Z_]*\\s+SET{0,1}|UNION\\n+ALL{0,1})\\b";
    int bufferOverflowLength = 4000;
    if (value != null && (Pattern.compile(sqlRegex).matcher(value.toUpperCase()).find()) || value.length() >= bufferOverflowLength) {
        HttpServletResponse resp = (HttpServletResponse) response;
        String redirectUrl = req.getContextPath() + "/logout";
        resp.setStatus(403);
        resp.sendRedirect(redirectUrl);
        return;
    }
}

}
How can I force browser to redirect to logout page?
Update:
As per @buettner123's comment, I have implemented an httpInterceptor in Angular, but that is still unable to intercept my request from Filter.
Angular Interceptor code
$httpProvider.interceptors.push(['$location', '$injector', '$q', function ($location, $injector, $q) {
    return {
        'request': function (config) {
            console.log("Request intercepted");
            return config;
        },
        'responseError': function (rejection) {
            console.log("Response Error Intercepted");
            return $q.reject(rejection);
        },
        'response': function(response) {
            // do something on success
            console.log('I am done');
            var status = response.status;
            console.log(status);
            return response;
          }
    };
}]);

Comment: AngularJs is a single page application. Following your approach with the filter, I would answer the request with a respective http code (e.g. 400) and have an error interceptor on the AngularJs part which does the redirect, using the AngularJs routing
Comment: Please try with `resp.sendError(HttpServletResponse.SC_FORBIDDEN);` instead of `sendRedirect`
Comment: I have added an httpInterceptor in AngularJS which is working fine for other requests but unable to intercept request initiated from my Filter.
Comment: It worked. Thank you so much for your help.
Answer: Posting the solution here in-case someone else might find themselves with the same problem
Filter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;
    String url = req.getRequestURL().toString();
    System.out.println("url : " + url);

    Enumeration<String> enumeration = request.getParameterNames();
    while (enumeration.hasMoreElements()) {

        String paramName = enumeration.nextElement();
        String value = request.getParameter(paramName);
        String sqlRegex =
                        "\\b(ALTER\\s+TABLE{0,1}|CREATE\\s+TABLE{0,1}|DELETE\\s+FROM{0,1}|DROP\\s+TABLE{0,1}|EXEC(UTE){0,1}|INSERT\\s+INTO{0,1}|MERGE\\s+INTO{0,1}|SELECT\\s[0-9a-zA-Z_*]*\\s+FROM{0,1}|UPDATE\\s[0-9a-zA-Z_]*\\s+SET{0,1}|UNION\\n+ALL{0,1})\\b";

        if (value != null && (Pattern.compile(sqlRegex).matcher(value.toUpperCase()).find())) {
            HttpSession session = req.getSession(false);
            if (session != null)
                session.invalidate();
            HttpServletResponse resp = (HttpServletResponse) response;
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "SQL injection detected");
            return;
        }
    }

}
main.js
$httpProvider.interceptors.push(['$location', '$injector', '$q', function ($location, $injector, $q) {
return {
    'request': function (config) {
        return config;
    },
    'responseError': function (rejection) {
        if (rejection.status == 403 && rejection.data.includes("SQL injection")) {
            console.log("Forbidden Resource");
            window.location.href="redirect url";
        }

        return $q.reject(rejection);
    },
    'response': function(response) {
        return response;
      }
};}]);

Make sure js code is under config element


Mock http.Client in Dart gives exception

Question: I have a problem when testing my classes that make http requests.
I want to Mock the client so that every time the client makes a request, I can answer with a Mocked response.
At the moment my code looks like this:
  final fn = MockClientHandler;
  final client = MockClient(fn as Future<Response> Function(Request));

  when(client.get(url)).thenAnswer((realInvocation) async =>
    http.Response('{"userId": 1, "id": 2, "title": "mock"}', 200));

However, when I run the test I get the following exception:
type '_FunctionType' is not a subtype of type '(Request) => Future<Response>' in type cast test/data_retrieval/sources/fitbit_test.dart 26:32  main
According to Flutter/Dart Mockito should be used like this:
 final client = MockClient();

  // Use Mockito to return a successful response when it calls the
  // provided http.Client.
  when(client.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1')))
      .thenAnswer((_) async => http.Response('{"userId": 1, "id": 2, "title":"mock"}', 200));

In the example, the client is mocked without parameters, but I guess this has been changed since the documentation of MockClient now also accepts a parameter.
I have no idea why this exception occurs and nothing can be found on the internet, so I was wondering if someone here knows why this exception is happening.
Comment: Ah, `MockClient` and `MockClientHandler` are provided by `package:http`'s  testing library.  As I suspcted, you need to provide an actual function.
Comment: I suspect that the problem is from `final fn = MockClientHandler;` and later you do `fn as Future Function(Request)`.  What is `MockClientHandler`?  It sounds like it's a `typedef` (which would make it a *type*) and not an instance of a `Function`, which would cause the cast to fail.
Comment: But when I don't add the cast it gives a compilation error: `The argument type 'Type' can't be assigned to the parameter type 'Future Function(Request)'.` Could you help me with how the cast should look like then?
Comment: You missed the point.  `final fn = MockClientHandler;` is what's wrong. (It's ultimately a useless assignment.  There isn't much that you can meaningful do with `fn` afterward.) Once again: what is `MockClientHandler`?  It's unclear what you expect `fn` to be.
Answer: package:http's MockClient is a bit of a misnomer.  It's not really a mock (and it's certainly not related to package:mockito's Mock); it's more like a stub (or arguably a fake): it has an implementation that is meant to simulate a normal http.Client object.
Note that Flutter's Mockito examples create a MockClient object using package:mockito, but this is unrelated to the MockClient class provided by package:http itself.

final fn = MockClientHandler;
final client = MockClient(fn as Future<Response> Function(Request));

package:http's MockClient expects an instance of a MockClientHandler as an argument, but you are attempting to pass the MockClientHandler type itself.  You are expected to provide an actual function (again, because MockClient has an actual implementation).
In other words, if you want to use package:http's MockClient, then you should do:
Future<Response> requestHandler(Request request) async {
   return http.Response('{"userId": 1, "id": 2, "title": "mock"}', 200));
}

final client = MockClient(requestHandler);

Or if you want to use package:mockito, you need to follow https://flutter.dev/docs/cookbook/testing/unit/mocking exactly and generate a Mockito-based MockClient class.
Comment: for mockito: ^5.0.17 , giving this error The function 'MockClient' isn't defined.
Comment: @B.shruti And did you follow the instructions to generate the mock classes?
Comment: Followed each and every step suggested in https://docs.flutter.dev/cookbook/testing/unit/mocking
Answer: This is what the doc's fetch_album_test.dart will look like when they get around to updating it! (tests pass)...
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:mocking/main.dart';
import 'package:mockito/annotations.dart';

// Generate a MockClient using the Mockito package.
// Create new instances of this class in each test.
@GenerateMocks([http.Client])
void main() {
  group('fetchAlbum', () {
    test('returns an Album if the http call completes successfully', () async {
      final client = MockClient((_) async =>
          http.Response('{"userId": 1, "id": 2, "title": "mock"}', 200));

      expect(await fetchAlbum(client), isA<Album>());
    });

    test('throws an exception if the http call completes with an error', () {
      final client = MockClient((_) async => http.Response('Not Found', 404));

      expect(fetchAlbum(client), throwsException);
    });
  });
}


Logical OR does not work properly in the while loop

Question: The problem is that, the first condition in the while loop does not get executed at all even if its true. If i remove the Logical OR from the while loop and just write the first condition (selection.compareToIgnoreCase("O") >0) it works fine. But if there are two conditions with Logical OR, it does not work.
I've tried using equals(), I've also tried to negate the logic using
while(!selection.equals("O") || !selection.equals("E")). The second condition works fine but the first does not work at all.
public class OddsOrEvens {
public  static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
    System.out.println("Let's play a game called \"Odds and Evens\"");
    System.out.println("Whats your name ? ");
    String name = sc.nextLine();
    System.out.println("Hi "+ name +", which do you choose? (O)dds or (E)vens?");
    String selection = sc.nextLine();
    System.out.println("selection: " + selection);

    while (selection.compareToIgnoreCase("O") >0 || selection.compareToIgnoreCase("E") >0){
        System.out.println("Please enter the correct choice. Select 'O' for odds or 'E' for evens");
        selection = sc.next();
    }

    if(selection.equalsIgnoreCase("O")){
        System.out.println(name + " has picked Odds! The computer will be evens.");
    }else if (selection.equalsIgnoreCase("E")){
        System.out.println(name + " has picked Evens! The computer will be Odds.");
    }
}

}
Comment: You should really write out a truth table of your conditions.
Comment: `selection.compareToIgnoreCase("O") >0` is checking if the selection is **greater** than `"O". Try `selection.compareToIgnoreCase("O") == 0`.
Comment: have you tried debugging?
Comment: Yes I have tried debugging, the values in variable(Selection) are always as intended but the loop does not work properly.
Comment: @oldCurmdgeon If i change it to == then it will go in an infinite loop.
Comment: @cargeh Tried using equals() also. But the first condition never works. But the second one does.
Answer: Your string comparison is not correct. Compareto returns -1/0/1 for less/equal/greater.
A clearer way to do this is to use toUppercase().equals(....
    while (!selection.toUpperCase().equals("O") && !selection.toUpperCase().equals("E")){

Answer: That is for not to hold for two cases, one needs !... && ! ... An OR || would have the effect of being always true, as at least one of the cases is false. Alternatively !(... || ...).
while (!selection.equalsIgnoreCase("O") && !selection.equalsIgnoreCase("E")) {

Let's simplify:
!(n == 1) || !(n == 2)       // WRONG
  n != 1  ||   n != 2        // WRONG

will always be true, as either n == 1 is false or n == 2 is false: at most one choice can be true, falsifying the others. So on at least on side is !false, true, so the entire expression is true.
!(n == 1) && !(n == 2)       // GOOD
  n != 1  &&   n != 2        // GOOD

The mental mistake is that the linguistic OR mostly means EXCLUSIVE OR.
Possible would have been the equivalent:
!(n == 1 || n == 2)      <=>      n != 1 && n != 2   [De Morgan's law]

Comment: I understand it much better now. Thank you so much :)


API Manager 2.0 version and Identity server 5.1

Question: We have a stack of WSO2 servers where Identity server 5.1. works with API Manager as key manager. These servers work in a production environment.
Now a new version of API Manager (2.0) have appeard and I found out in documentation that WSO2IS 5.1 isn't compatible to work as key manager with new API manager.
My question is:
It would be better:
To wait for a new IS version (5.2) and then to upgrade together API Manager and IS
or
To upgrade API manager now and to switch  functions of key manager from UIS to new API Manager and later install new IS version.
I think the first way is better because of changes in UM and AM databases for new API Manager. Now AM and UM databases are common for 2 servers.
Am I right?
Answer: I recommending to wait until Identity Server 5.2.0 released, also you can get the latest Identity Server 5.2.0-SNAPSHOT release here. We are hoping to release IS 5.2.0 by mid of September.
Comment: Thank you very much for answer. We are going to implement WSO2 servers (IS, AM and others) as Identity Management Suite in our university. This project have just started and I'll try to use Identity Server 5.2 (snapshot) because mid of September is not so far. Other stack of WSO2 servers works as ESB suite and it will continue to work with IS 5.1 for some time.
Comment: You are welcome, it's glad to hear that you are using WSO2 products in your University. If you want to contribute back to WSO2, you can share your case study with us through email@example.com. We are happy to hear it.


Expected value of $E(X-Y|X+Y)$ if $X \sim Y$

Question: If we have two discret random values with $X \sim Y$, prove that
$$E(X-Y|X+Y)=0$$
My first try was to do this
$$E(X-Y) =E(X)-E(Y)=0$$
In other hand
$$E(X-Y)=\sum_{z} E(X-Y|X+Y=z)P(X+Y=z)$$
I don't know what to do.
Comment: Does "$X \sim Y$" mean $X$ and $Y$ are identically distributed, though not necessarily independent of each other?
Comment: Yes, no necessarily independent just that P(X=x)=P(Y=x)
Comment: When you say $\mathbb{E}[X- Y | X+Y]$ do you want a random variable?
Comment: Inspired by @lonza leggiera's solution, I believe if both X and Y are binary (can take only two values), then the claim is true.
Answer: I don't believe the statement to be necessarily true unless $\ X\ $ and $\ Y\ $ are independent.
Suppose the joint distribution of $\ X\ $ and $\ Y\ $ is given by the following array, the entry in row $\ i\ $ and column $\ j\ $ being $\ P(X=i,Y=j)\ $.
$$
\begin{array}{c|ccc}
&1&2&3\\
\hline
1&\frac{1}{20}&\frac{2}{20}&\frac{3}{20}\\
2&\frac{5}{20}&\frac{2}{20}&\frac{1}{20}\\3&0&\frac{4}{20}&\frac{2}{20}
\end{array}
$$
The distributions of $\ X\ $ and $\ Y\ $ are the same, with probability mass vector $\ \big(\frac{3}{10},\frac{2}{5},\frac{3}{10}\big)\ $. However,
\begin{align}
E(X-Y|X+Y=3)&=\frac{3}{7}\\
E(X-Y|X+Y=4)&={-}\frac{6}{5}\\
E(X-Y|X+Y=5)&=\frac{3}{5}\ .
\end{align}
Answer: Being $X\sim Y$ it is also $X|(X+Y)\sim Y|(X+Y)$
thus
$$\mathbb{E}[X-Y|X+Y]=\mathbb{E}[X|X+Y]-\mathbb{E}[Y|X+Y]=0$$
Comment: I  believe this is not necessarily true unless $\ X\ $ and $\ Y\ $ are independent.


Hosting Drupal and Django together on Production Server

Question: Is it possible to host a Django app side by side with a Drupal project side by side without editing the urls.py?
I have a full fledged website right now made using the Drupal framework,working perfectly.
Now I have implemented some stuff using Django and want to put it on the same server . How easy is this ?
Comment: I think yes. What kind of problem do you foresee? Can you tell us more about these apps?
Answer: It's pretty easy if you just want to host your Django site inside a sub-URL - for example http://mydomain.com/django/. Using mod_wsgi, for example, you'd just set WSGIScriptAlias to the directory name, and everything else will just work (you'll probably need to put that high up in your Apache conf so that it's picked up before the Drupal configuration).


Getting length of words in list in Haskell

Question: I started to write a couple functions where I could count specific words in a sentence and so on, but now I need to count the lengths of the words in a list. So I have a list where each element is a word and want to count the characters of this word.
I couldn't find any solution to do that, since Haskell doesn't use loops. Is there anyway to do this?
Comment: You can made this question better by show code you have already done. Also in haskell question it help to include type signature of your desire output.
Answer: If you think you need a loop when working in Haskell, you're probably looking for recursion. We'll want to recurse through the list of strings, applying the length function to each one. The general pattern of recursion through a list where a function is applied to each value (which you'll become very familiar with as you work through Haskell) looks roughly like this:
func f []     = []
func f (x:xs) = f x : func f xs

So we could solve the problem that way (specializing the function, rather than accepting it as an argument):
wordLengths :: [String] -> [Int]
wordLengths []     = []
wordLengths (x:xs) = length x : wordLengths xs

However, since this behavior is so common, there exists a function map that takes care of all of this for us. Its type signature is (a -> b) -> [a] -> [b], so we know to pass it a function (length) and a list of things (our Strings). If we map the length function to each value in your list of strings, we'll get your desired result:
wordLengths :: [String] -> [Int]
wordLengths = map length

Example usage:
ghci>> wordLengths ["abc","defg"]
[3,4]

Comment: At first, thank you for the very good explanation! But while trying to use it, I get only the error `variable not in scope: wordLengths :: [String] -> [Int]`
Comment: I assume you're trying to enter this directly into `ghci`? The function definition I've included was intended to go in a Haskell source file. You can paste it into some file with the extension `.hs` and then load it via `ghci fileName.hs` in terminal.
Comment: I think that's what I did. I wrote a *.hs-file and added it into this. So I have to "modify" some source file of Haskell itself?
I added my entire HA.hs file.
Comment: Ah, guessed wrong. What you did should be right; it's hard to tell exactly what could be causing the problem. You've taken the second definition (with `map`, right?). If you can paste what you've included verbatim I can be more helpful :)
Comment: Yes I did. I pasted my entire script in the question. You can see it up there.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/129953/discussion-between-mnoronha-and-kendel-ventonda).


Conditions when a non-convex set can be represented as the union of a finite number of convex sets

Question: Are there any theoretical results (including theorems, algorithms, etc) on representing a non-convex set as the union of a finite number of convex sets?
Comment: In what context? How many convex sets? Are you for example asking is there a result on the minimum number of convex sets needed to write every set as a union of at most that many convex sets? Maybe every connected set? I.e. what exactly is your question?
Comment: Think about the integers in $\mathbb{R}$. Or worse, the Cantor set. You can only hope for finiteness if your set is connected. But then think of the circle in $\mathbb{R}^2$. That also can't be the union of a finite number of convex sets.
Comment: I think however, that a smooth concavity in the set will pose problems. E.g. an open annulus.
Comment: Good point. I'm thinking about two steps: (1) is the number of convex sets finite? Can we prove it? (2) If finite, what is the exact number (or a upper bound)?
Comment: Perhaps you want open and connected?
Comment: Take a look at [Mixed-Integer Programming for Control](http://acl.mit.edu/milp/MILP_for_Control.pdf) [PDF].
Answer: I think the general case is hopeless: I don't expect a "typical" set, even an open, connected one, to be representable as the finite union of convex sets.
If you are OK with approximating your set, you can try to compute an approximating triangulation; NB that triangulation in high dimensions is itself a nontrivial problem. Algorithms exists for computing approximate convex decompositions in two and three dimensions, which try to minimize the number of convex pieces. I don't have much hope for a computationally tractable approach in high dimensions as even the 3D case is an active area of research in computational geometry.


WF4: Workflow service stops accepting new requests

Question: I am hosting a small workflow via the WorkflowServiceHost class.
<code>using (WorkflowServiceHost wfHost = new WorkflowServiceHost(new QueueWorkflow(), new Uri("net.pipe://localhost/workflow")))
{
    wfHost.Open();
    Console.ReadLine();
}
</code>
This workflow starts via an incoming WCF call (currently NetPipe binding) using a Receive activity, proceeds into a custom activity does some work and then creates a bookmark and goes idle (does not unload).
All this worked well at the beginning, however when I have my load tester set up to start 1000 workflows, 928 workflow instances start and proceed up to creating their bookmark, the remaining 72 block either in WCF or in the Receive activity.

The test always stops at 928 workflow instances. (A workflow memory restriction maybe?)
Resuming one of the workflows and allowing it to run to completion allows the next workflow in the list of blocked starting requests to begin.

Any ideas greatly appreciated.
Answer: I suspect serviceThrottling is playing a role here. It doesn't just affect WCF but is also used with the WF4 runtime. Try changing the settings to see if it makes a difference.
See here for a blog post I wrote about it.
Comment: That is correct. Adding a ServiceThrottlingBehavior to the service host and increasing the MaxConcurrentInstances property resolved the issue.


PHP Get last n sentences from a string

Question: Let's say I have the string below
$string = 'PHP Coding.
Hello World!
Merry Christmas!
Happy New Year!
Merry Super Early Next Christmas?
I want Pizza, and Cake
Hehehe
Hohohoho';

How do I get the last n sentences from the string, for example, the last 3 sentences, which should give the following output:
I want Pizza, and Cake
Hehehe
Hohohoho

Edit: I'm using data from sql
Comment: split on linebreaks, giving you an array, then pop however many lines you want from the end of the array.
Comment: @MarcB Sure, if there were line breaks to start with. OP's code is set inside a variable producing `PHP Coding. Hello World! Merry Christmas! Happy New Year! Merry Super Early Next Christmas? I want Pizza, and Cake Hehehe Hohohoho`
Comment: @fred: there's line breaks. it's a multi-line string definition, after all.
Comment: then it'd have to be `$foo = "bar\nbaz"`.
Comment: php explode() function should help you split the string. I would suggest reading the PHP string manual though before asking for help.
Comment: Please check this link: http://stackoverflow.com/questions/10494176/explode-a-paragraph-into-sentences-in-php
Comment: @MarcB Multi-line definition, yes I agree. I might have taken your initial comment out of context. However, to me, a line break consists of the ever so famous hidden `\n` which isn't present in OP's long string.
Answer: This should work for you:
<?php

    $string = 'PHP Coding.
            Hello World!
            Merry Christmas!
            Happy New Year!
            Merry Super Early Next Christmas?
            I want Pizza, and Cake
            Hehehe
            Hohohoho';

    list($sentence[], $sentence[], $sentence[]) = array_slice(explode(PHP_EOL, $string), -3, 3);

    print_r($sentence);

?>

Output:
Array ( [2] => Hohohoho [1] => Hehehe [0] => I want Pizza, and Cake )

EDIT :
Here you can define how many sentence you want from the back:
<?php

    $string = 'PHP Coding.
            Hello World!
            Merry Christmas!
            Happy New Year!
            Merry Super Early Next Christmas?
            I want Pizza, and Cake
            Hehehe
            Hohohoho';

    $n = 3;

    $sentence = array_slice(explode(PHP_EOL, $string), -($n), $n);
    $sentence = array_slice(explode(PHP_EOL, nl2br($string)), -($n), $n); // Use this for echoing out in HTML
    print_r($sentence);

?>

Output:
Array ( [0] => I want Pizza, and Cake [1] => Hehehe [2] => Hohohoho )

Comment: @Aesreal What Rizier originally posted as an answer and adding my `foreach` should have worked. You may have to update your question with the SQL you're using in order to achieve your goal. By "not working"; can you define that? Are you getting errors?
Comment: Ahhhh, its working now! had some syntax problems with it. =.= sorry for wasting your time, and thanks for the help!
Comment: are there any ways to do them in a single line?
Comment: *"are there any ways to do them in a single line?"* - Too easy.
Comment: @Aesreal `foreach($sentence as $var){ echo $var . " "; }` producing `I want Pizza, and Cake Hehehe Hohohoho`
Comment: @Aesreal What do you mean with: `a single line`? You can write your entire script on one line!
Comment: *Hm,* I was under the impression OP wanted the output to be on a single line.
Comment: @Rizier123 It's still not working thou, I've tried using nl2br($string) instead. this data is actually obtained from sql, and as such it is as Fred -ii said, PHP_EOL is not working
Comment: @Fred-ii- yup, i wanted them to be in a single line like what you did, but if that is not possible then a function is also fine, just that none of the answers are working right now!
Answer: $string = 'PHP Coding.
Hello World!
Merry Christmas!
Happy New Year!
Merry Super Early Next Christmas?
I want Pizza, and Cake
Hehehe
Hohohoho';

function getLast($string, $n){
    $splits = explode(PHP_EOL, $string);
    return array_slice($splits, -$n, count($splits));
}

$result = getLast($string, 2);
var_dump($result);

Comment: *"Guessing the separator is `\n`"* - There are none, believe me.
Comment: @Fred-ii- you are right, there are no separators, hence the linebreaks the people above suggested are all not going to work as well.

PHP Get last n sentences from a string


Why all differentials are $0$ for Serre Spectral Sequence of trivial fibration?

Question: Consider the fibration $F \hookrightarrow F \times B \to B$.  I understand that if I take kunneth's theorem for granted that the group extensions $F_{n-i,i} \to F_{n-i+1,i-1} \to F_{n-i+1,i-1}/F_{n-i,i}$ associated to the filtration $F_{n,0} \supset ...F_{n-i,i}...$ are all trivial extensions, and that $d_r=0$ for $r>2$.  How can we deduce these two facts without assuming Kunneth's theorem.
For the record, here is the reason why I get these two facts if I assume Kunneth.

The action of the fundamental group of the base on the fiber is nontrivial due to the splitting $H_*(F) \to H_*(B)$.
There is always a map $E^\infty \to H_*(E)$, and by kunneth we have the surjective map
$\text{a subgroup of}(E^2= H_*(B,H_*(F))) \to E^\infty \to H_*(E)=\text{(use kunneth)} H_*(B,H_*(F))$ so that the composition is the identity.  Thus the first subgroup is the whole of $E^2$.  Therefore it is not possible that
either the series $H_n(B \times F) = \text{(by convergence of SSS)} im (H_n(B_n \times F) \mapsto  H_n(B \times F))\supset im (H_n(B_{n-1} \times F) \mapsto  im (H_n(B_{n-2} \times F) \mapsto  H_n(B \times F)) \supset  ... H_n(F)$ of group extensions be nontrivial ,
or $d^r$ be nonzero for $r  \geq 2$.

I would like to know how to deduce two facts without using Kunneth's theorem, and hence deduce Kunneth's theorem from the SSS of this fibration.
I have a hunch that the proof that the differentials are 0 should be something like "Any map from $E^1_{p+q,q}=C_p(B) \otimes H_q(F) \to E^1_{p-2+q+1,q+1}=C_{p-2}(B) \otimes H_{q+1}(F)$ must be zero because either the domain or codomain is 0 and therefore there is no possible way that this map cannot be 0 after restricting and descending to $E^2$, and hence $d_2=0$.
To show that the series $H_n(B \times F) = \text{(by convergence of SSS)} im (H_n(B_n \times F) \mapsto  H_n(B \times F))\supset im (H_n(B_{n-1} \times F) \mapsto  im (H_n(B_{n-2} \times F) \mapsto  H_n(B \times F)) \supset  ... H_n(F)$
is trivial, I need to show that there is a splitting map $im ( H_*(X_{p}) \mapsto H_*(X)) \to im ( H_*(X_{p-1}) \mapsto H_*(X))$.  I also have a hunch that this should have something to do with the topological splitting $B_n \times F \to B_n$.
Can I have some help with turning my gut feeling into a proof?
Comment: Thanks for the suggestion, I am working it out now.  I am using $\mathbb{Z}$ coefficients. I expected the extension problem to be trivial because if one assumes  extension problem is trivial and assumes the differentials are 0, one gets that $H_n(B\times F)=\oplus_{p+q=n} E^2_{p+q,q}=\oplus_{p+q=n} H_p(B,H_q(F))$; this yields the correct answer irrespective of the coefficients used - it takes into account the $Tor$ terms.
Comment: Here is a suggestion: Build an algebraic model of what you would like your spectral sequence to look like and use the comparison theorem to show that its $E_\infty$-term coincides with that of the fibration.
Comment: Actually good point :) I was missing that the Tor terms are already taken into account there.
Answer: The reason all the differentials are 0 is simple.  I'll do it for cohomology because otherwise I need to use the coalgebra structure on homology.
 We know the elements of $E_r^{0,n}$ are permanent cycles for all $r,n$:  there is an edge map $H^n(E)\to E_\infty^{0,n} \subset E_2^{0,n}=H_n(F)$ which has to be surjective because of the obvious splitting.  Thus $E_\infty^{0,n}= E_2^{0,n}$.
The elements of $E_r^{n,0}$ are automatically permanent cycles.  Thus every element $E_r^{n,m}$ that is a product of cycles is a cycle.  This solves the problem for the coefficients in the rationals.
For coefficients in $\mathbb{Z}$, we have an injective map of spectral sequences $E_r \otimes \mathbb{Z}/p \to \epsilon_r$ where $\epsilon$ is the spectral sequence of the fibration with coefficients in $\mathbb{Z}/p$.  Therefore the $d_r$ is 0 modulo p for all $p$ on $E^r$.
This shows that $d_r=0$ for all $r>1$.


How to get the last five messages in Paho?

Question: I use Paho to create Javascript MQTT Web Application.
The client receives just the last message which is sent to it recently, but I need the last five messages everytime I open/refresh the web page.
Is there any solution for this purpose?
Comment: MQTT is not made to send the latest message. The only option is to activate the retained message on your broker. It means that when you connect to it via the client and subscribe to the topic, it will automatically send the retained message. MQTT is not made to send historical data. An option would be to add a script that will subscribe to a topic and save the latest 5 messages. Compact those message in one big message and set it as retained
Answer: MQTT doesn't work this way.
There are a number of factors that need to be covered here.

Retained messages. It sounds like the messages you are receiving have the retained bit in the headers set. This means that the broker will hang on to the last message with that bit set on any topic it is published on, then when a client subscribes to that topic it will always deliver that last message to the client before any new messages arrive. This is just a single message there is no way to have more.
Message queueing. If a client subscribes to a topic at greater than QOS 0 and then disconnects. When it reconnects as long as the clean_session flag is set to false the and the client resubscribes to the same topic then then the broker will deliver any messages that were sent to the topic while the client was offline. Again this will be all missed messages not just the last 5.

As @Weedoze mentioned in their comment, one possible solution is to have another client subscribe to the same topic and every time a message is published use this to update a single message holding the last 5 messages, this would need to then be published to a separate topic with the retained bit set to true. The client could then subscribe to the "history" topic and the "live" topic.


Definition of Overfitting

Question: Consider error of hypothesis h over training data errortrain(h) and error over
entire distribution D of data errorD(h). Hypothesis h in H overfits training data if
there exists an alternative hypothesis h´ in H such that:

errortrain(h) < errortrain(h´)
errorD(h) > errorD(h´)

I am struggling to find literature on that topic.
Is there a more formal (or more detailed) definition of overfitting?
Comment: I know to very good books on the foundations of ML. "Learning from Data" is a little more elementary and " Foundations of Machine Learning" is more encyclopedic.  Search amzn for either term and you will get book authors and you can do a better search than.  In general both books are worth looking at.
Comment: See [this Cross Validated tag information](https://stats.stackexchange.com/tags/overfitting/info).
Comment: Overfitting occurs when a poor model is used because too many parameters are used to fit it. So it will be a poor predictor of future observations.
Answer: I'll partially answer your question, and focus on providing some insight.
Within the scope of this answer, overfitting is caused due to two reasons:
1. bias in training data
2. complexity of model (hypothesis)
There are several cross-validation schemes to help estimate the extent of overfitting in the learnt model. See sklearn cross-validation and analysis of cross-validation on Iris dataset
With the objective of visualization for an intuitive insight, I'll use synthetic data towards regression analysis. The train-test splits of data are in practice done randomly to reduce bias in sample. However, i'm intentionally going to sample training data as contiguous chucks from the entire data in order to artificially emphasize bias while keeping interpretation of results simple.
My data is a polynomial with Gaussian noise. The degree of the polynomial, the mean and standard-deviation of noise are randomly assigned. In the experiment, I consider a hypothesis/model as a polynomial of different degrees. In my training data sampling scheme I progressively split the entire data into smaller equal chunks, wherein 'least bias' samples all the data and 'most bias' samples 1/4 contiguous chunk of data (multiple disjoint subsets).
The code I used to generate the results:
<code>"""
Analysis of over-fitting in regression based on both bias sampling and model complexity
"""

import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
from numpy.polynomial.polynomial import polyval
from sklearn.model_selection import cross_val_predict
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import Pipeline
from sklearn.metrics import mean_squared_error
import itertools
from matplotlib import cm
import matplotlib as mpl

def generate_data(num_data=100, degree=3, mu=0.0, sigma=0.1):
    """
    Generates a set of data points on a polynomial with Gaussian noise
    :param num_data: The number of data points generated
    :param degree: The degree of the polynomial, model complexity
    :param mu: mean of noise
    :param sigma: standard deviation of noise
    :return: array of data points
    """
    degree = np.random.randint(2, 4)
    num_coeff = degree+1
    coeff = list(np.random.rand(num_coeff))
    x_pts = list(np.random.rand(num_data))
    x_pts = [10*(i-0.5) for i in x_pts]
    x_pts = list(np.sort(x_pts))
    mu = 1*np.random.rand()
    sigma = 2*np.random.rand()+1
    noise = np.random.normal(mu, sigma, num_data)
    y_pts = polyval(x_pts, coeff, tensor=False)
    y_pts += noise
    y_pts = list(y_pts)
    data = [x_pts, y_pts]
    return data

def get_fit(input_data):
    reg = linear_model.LinearRegression()
    train_x = [[i, input_data[0][i]] for i in range(len(input_data[0]))]
    train_y = input_data[1]
    reg.fit(train_x, train_y)
    print(reg.coef_)
    x_min = min(input_data[0])
    x_max = max(input_data[0])
    n_pts = len(input_data[0])
    x = [x_min+i*(x_max-x_min)/n_pts for i in range(n_pts)]
    y = polyval(x, reg.coef_, n_pts)
    fig = plt.figure(1)
    plt.plot(input_data[0], input_data[1], 'k.')
    plt.plot(x, y,'r-')
    lr = linear_model.LinearRegression()
    predicted = cross_val_predict(lr, train_x, train_y, cv=10)
    plt.plot(x, predicted, 'gx')
    plt.show()

def polyfit(input_data, ax, input_degree=2, num_split=4):
    data = [[x[0], x[1]] for x in zip(input_data[0], input_data[1])]
    model = Pipeline([('poly', PolynomialFeatures(degree=input_degree)), ('linear', linear_model.LinearRegression(fit_intercept=False))])
    x = input_data[0]
    y = input_data[1]
    xs, ys = zip(*sorted(zip(x, y)))
    xs = np.array(xs)
    ys = np.array(ys)
    handles = []
    h, = ax.plot(xs, ys, 'kx', label='data')
    handles.append(h)
    colors = ['r', 'g', 'b', 'y']
    ns = num_split
    nd = len(x)
    bs = int(np.floor(nd/ns))
    y_max = max(ys)
    y_min = min(ys)
    sum_mse_train = 0.0
    sum_mse_test = 0.0
    for i in range(ns):
        x_train = xs[i*bs:(i+1)*bs]
        y_train = ys[i*bs:(i+1)*bs]
        """ split train and test into disjoint sets"""
        x_test = list(itertools.chain(xs[0:i*bs], xs[(i+1)*bs:-1]))
        y_test = list(itertools.chain(ys[0:i*bs], ys[(i+1)*bs:-1]))
        """ test is the entire available data to avoid discontinuity since training sample isn't random"""
        x_test = xs
        y_test = ys

        model = model.fit(x_train[:, np.newaxis], y_train)
        coeff = model.named_steps['linear'].coef_

        pred_train = polyval(x_train, coeff, len(x_train))
        mse_train = mean_squared_error(y_train, pred_train)
        sum_mse_train += mse_train
        pred_test = polyval(x_test, coeff, len(x_test))
        mse_test = mean_squared_error(y_test, pred_test)
        sum_mse_test += mse_test
        label_str = '#%d, Train:%.2f, Test:%.1E' % (i+1, mse_train, mse_test)
        ax.plot(x_train, pred_train, colors[i]+'.', linewidth=3)
        h, = ax.plot(x_test, pred_test, colors[i], label=label_str, alpha=0.5)
        handles.append(h)
        ax.set_ylim([y_min, y_max])
        ax.legend(handles=handles)
    mean_mse_train = sum_mse_train/ns
    mean_mse_test = sum_mse_test/ns
    return mean_mse_train, mean_mse_test

if __name__ == '__main__':
    data = generate_data(100, 3)
    print(data)
    max_degree = 4
    max_split = 4
    train_err = np.zeros((max_split, max_degree), dtype=np.float32)
    test_err = np.zeros((max_split, max_degree), dtype=np.float32)
    fig, axes = plt.subplots(max_split, max_degree)

    for n_split in range(1, max_split+1):
        for n_degree in range(1, max_degree+1):
            err_train, err_test = polyfit(data, axes[n_split-1, n_degree-1], n_degree, n_split)
            train_err[n_split-1, n_degree-1] = err_train
            test_err[n_split-1, n_degree-1] = err_test

    print(train_err)
    print(test_err)

    fig2 = plt.figure(2, figsize=(16, 8))
    ax1 = fig2.add_subplot(121, projection='3d')
    ax2 = fig2.add_subplot(122, projection='3d')

    # fake data
    _x = np.arange(max_split)
    _y = np.arange(max_degree)
    x, y = np.meshgrid(_x, _y)
    z_train = []
    z_test = []
    for i in x:
        for j in y:
            z_train.append(train_err[i, j])
            z_test.append(np.log(test_err[i, j]))
    print(len(z_train), len(z_test))
    btrain = np.zeros_like(z_train)
    btest = np.zeros_like(z_test)
    width = depth = 1

    nrm = mpl.colors.Normalize(np.min(z_train), np.max(z_train))
    colors = cm.bwr(nrm(np.array(z_train)))
    alpha = np.linspace(0.2, 0.95, len(x), endpoint=True)
    ax1.set_xlabel('level of bias')
    ax1.set_ylabel('model complexity')
    ax1.set_zlabel('mean square error')
    ax1.set_title('Err on Training data')
    for i in range(len(x)):
        ax1.bar3d(x[i], y[i], btrain[i], width, depth, z_train[i], alpha=alpha[i], color=colors[i], linewidth=0)

    ax2.set_xlabel('level of bias')
    ax2.set_ylabel('model complexity')
    ax2.set_zlabel('log(mean square error)')
    ax2.set_title('Err on Test data')
    nrm = mpl.colors.Normalize(np.min(z_test), np.max(z_test))
    colors = cm.RdBu(nrm(np.array(z_test)))
    for i in range(len(x)):
        ax2.bar3d(x[i], y[i], btest[i], width, depth, z_test[i], alpha=alpha[i], color=colors[i], linewidth=0)
    plt.show()
</code>
The regression fits, along with associated train/test error, I get for various degrees of bias introduced by the sampling scheme and the degree of the polynomial (model complexity) is shown below:

The interesting inference from this experiment is that the mean square error of regression fit to the data depends on both training bias and model complexity. So, if you wished to compare between hypotheses for comparative overfitting, you'll have to consider both these factors jointly to derive a meaningful conclusion.
The next figure shows the mean-square-error between the learnt model/hypothesis and the data.

For the training data error analysis. We get a result that corroborates intuition. When the training data is the entire available data (low bias) and the model complexity is low (polynomial of order 1 or straight line) the training error is high. This is natural when fitting a straight line to a quadratic or cubic function with Gaussian noise. As we increase the bias, i.e. only consider a small section of the data, the training error goes down. We'd expect this since a higher-order polynomial can be better approximated by a lower-order polynomial for a small continuous part of x-axis (recall Calculus). Again, when the model complexity goes up, i.e. degree of the hypothesis approaches the degree of the polynomial used to generate the data, the error diminishes.
The important point to note here in the graph is that as the degree of the hypothesis polynomial goes beyond that of the actual data, the training error continues to diminish. This is classical visualization of overfitting!
Now, if you look at the mean square error for test set, we get a different picture. Note that I've shown log of the error since high-order polynomials trained on highly biased training data diverge from the rest of the data dramatically.
In the test data case, the error follows a different profile. I hope you can notice it, but there is a 'sweet spot' when the mean square error is minimum for an optimal value of degree of polynomial of hypothesis and the degree of bias in the data.
If there is no bias in our sampled data (which never happens for real world data), then higher complexity model tend to fit the testing data better. However, when there is even a slight bias in the data, simply increasing model complexity is evidently counter-productive. It's better to have complexity somewhere in the 'middle', i.e. prefer quadratic to both linear and cubic.
I realize this is not the definition of overfitting, nevertheless, I hope the answer helps towards a better intuition of overfitting and the part that both the nature of the data and the hypothesis play.

Definition of Overfitting


Why does my thumb hurt when I play bar chords?

Question: Certain chords cause my thumb to be sore. How can I play in a way to prevent this?
Comment: Which chords ? Where does it hurt ?
Comment: franssu, any bar chord does it. It's the base of my thumb.
Comment: I had the same problem when I started to learn bar chords. It went away after a few weeks of regular practice (without forcing too much when I felt sore).
Answer: Basically, neither fingers nor your wrist should hurt. Tension is your enemy, you have to become aware of tension before it becomes pain. In the words of Joe Satriani : No pain, no pain.
If it's the thumb, chances are you're grabbing the neck as if you were falling and needed to hold onto it, that's not the way it should be : the thumb is an anchor for the rest of the hand.
When you feel tension, stop, relax your fingers, neck and shoulders. Then get back in playing position but do not hold the strings down, use your fretting hand as if it was caressing the strings. Hold onto that feeling, and carry on practicing.
You can also try practicing slower, which anyway always helps focusing on different aspects of your playing.
Comment: For addtional details, I would like to refer you to a previous answer I made to another question
http://music.stackexchange.com/questions/1419/how-can-i-best-learn-to-play-barre-chords/10120#10120
Answer: Your thumb hurts because you are pushing your thumb backwards on itself in order to support your hand position on the neck. The only way forward is to practice bar chords as much as you can, and your thumb and hand will eventually become stronger. Hope this helps.
Comment: I remember when I started playing songs with bar chords. My hand and forearm got quite sore until it strengthened up
Answer: Here's just some additional thoughts:
My hand usually hurts the most when gripping the neck like this:

This is a grip used by classical guitarists, as they rarely do full-on barre chords. Note the thumb resting on the back of the neck: when you grip the neck firmly, as you do for barre chords, you put a lot of pressure on your thumb. It's easy to accidentally choose this grip for barre chords because it initially makes chording faster; however, stay away from this grip for barre chords!

I prefer to grip the neck like this:

Note how the thumb isn't "pressing" on the back of the neck anymore; it's "pinching" or "hugging" it. The force from pressing on the strings affects your thumb-hand joint less. This grip isn't initially as ergonomic as the above grip, but it will help prevent pain, which has been said above is very bad!
Comment: It doesn't look like there's a barre chord being played in either picture.
Comment: Classical grip, if done right, is perfectly suitable for full-on barre chords. In particular, there is almost no pressure on the thumb because the force comes directly from the arm (the biceps) – though that, of course, only works properly when playing seated with a footrest.
Comment: When playing slow arpeggiated barre chords (eg. Radiohead's "Creep"), I like to use the pinch grip method with the thumb wrapped around the top fretting the low E string. Then my index finger (#1) only has to fret the high G, B, and E strings.
Comment: In the second picture, how do you keep your index finger from hitting the high E?
Answer: I've answered a similar question before, so same answer. With barre chords there is a misconception that you need to squeeze hard with your thumb. It is easily possible to play barre chords without the thumb even on the neck.If you pull the guitar body onto your own body, then use the fretting arm to pull the barring finger (usually index) onto the fretboard.I'm not advocating not using your thumb to tension barre chords, but you never need to squeeze as hard as you think.It's a sort of extension to B.B.King's butterfly vibrato - yes, only fretting one string, but pulling that finger onto it with arm, not thumb.
Comment: This is the same technique that I adopted after two decades of playing guitar and it was a revelation. DO THIS!
Answer: I experience this when I haven't played for a while, almost like I strain my thumb. I haven't found another way to circumvent this but to keep playing (after you've rested your thumb of course ;). It's like any physical exercise.
But then I might be wrong, which would be great :)
Answer: Please see my answer to an earlier question here:
https://music.stackexchange.com/a/3694/1044
You may be using much more tension and pressure than is necessary to fret the barre chord in the first place, and this may be what is causing the pain. You can train yourself not to squeeze your hand and fingers too hard.
Answer: http://www.nextlevelguitar.com/aforum/showthread.php?t=12559 discusses a couple of options:

taking a break from barre chords when the pain begins
icing the painful area
painkillers
Comment: This totally neglects the important notion that perhaps the technique is poor and should be addressed so that there is no sore thumb in the first place.


$\{U_{\alpha} \}_{\alpha \in I}$ collection of connected sets , for every $U_{\alpha}$ , $\exists U_{\beta}\ne U_{\alpha}$ not mutually disjoint

Question: A probable further strengthening of $\{U_{\alpha} \}$ is a collection of connected sets in a metric space such that no two connected sets in the collection is disjoint ... If $\{U_{\alpha} \}_{\alpha \in I}$ is a collection of connected sets in a metric space such that for every $U_{\alpha}$ in the collection , there is $U_{\beta}$ in the collection , distinct from $U_{\alpha}$ , such that $U_{\alpha} \cap U_{\beta} \ne \phi$  , then is the union of all the sets in the collection i.e. $\cup_{\alpha \in I}U_{\alpha}$  connected ?
$\Bbb EDIT :$ Does it hold in $\mathbb R^n$ with $n \ge 2$ , with usual Euclidean metric ? Does it hold in real normed linear spaces of dimension more than $1$ ?
Answer: No. Take the intervals $U_1 = (0,1)$, $U_2 = (.5,1.5)$, $U_3 = (2,3)$, $U_4 = (2.5,3.5)$ in $\mathbb{R}$ with the usual topology.
Similar examples exist in any metric space (with at least six points), including $\mathbb{R}^n$ for any $n > 0$.
You need a stronger connectivity condition, that there is a chain of connected elements from any $U_\alpha$ to any other $U_\beta$. In other words, if you make a graph whose vertices are $\{ U_\alpha : \alpha \in I\}$, with an edge from $U_\alpha$ to $U_\beta$ whenever $U_\alpha \cap U_\beta \neq \emptyset$, then the connected components of your graph correspond to subsets of the collection whose union is connected.
The connectivity of these unions was addressed in the question Family of connected sets, proving union is connected.
Comment: Thanks , I have added more to the question , please take a look at it
Comment: Could you please state explicitly and give an exposition of the proof of the stronger connectivity condition ; or should I ask it as a new question ?
Comment: @user123733: That was answered in this question: http://math.stackexchange.com/questions/521867/family-of-connected-sets-proving-union-is-connected


google maps not working

Question: I want to display a map in a fragment, this fragment is made visible if the user select a tab, this tab is contained in another fragment contained in MainActivity. The fragment that shows the map extends from SupportMapFragment.
I followed the instructions provided by android developers and it worked, in the beginning. Due to some changes caused by android versions incompatibility: actionBar, viewPager... I quit the library and relink it ( in two ways: first doing the link from the library project and since it didn't work, deleting the library project and reimported it and add the library to my project. Hope this explanation can be understood and don't mess it up).
First log-cat asked me to change the manifest's metadata to
<meta-data
        android:name="com.google.android.gsm.version"
         android:value="@integer/google_play_services_version" />

I did that and it repeat the error:
12-18 08:36:27.589: E/AndroidRuntime(1613): FATAL EXCEPTION: main
12-18 08:36:27.589: E/AndroidRuntime(1613): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.comercio/com.comercio.activities.MainActivity}: java.lang.IllegalStateException: The meta-data tag in your app's AndroidManifest.xml does not have the right value.  Expected 4030500 but found 0.  You must have the following declaration within the <application> element:     <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
12-18 08:36:27.589: E/AndroidRuntime(1613):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at android.os.Looper.loop(Looper.java:137)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at android.app.ActivityThread.main(ActivityThread.java:5103)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at java.lang.reflect.Method.invokeNative(Native Method)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at java.lang.reflect.Method.invoke(Method.java:525)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at dalvik.system.NativeStart.main(Native Method)
12-18 08:36:27.589: E/AndroidRuntime(1613): Caused by: java.lang.IllegalStateException: The meta-data tag in your app's AndroidManifest.xml does not have the right value.  Expected 4030500 but found 0.  You must have the following declaration within the <application> element:     <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
12-18 08:36:27.589: E/AndroidRuntime(1613):     at com.google.android.gms.common.GooglePlayServicesUtil.n(Unknown Source)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at com.google.android.gms.common.GooglePlayServicesUtil.isGooglePlayServicesAvailable(Unknown Source)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at com.google.android.gms.maps.internal.q.v(Unknown Source)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at com.google.android.gms.maps.internal.q.u(Unknown Source)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at com.google.android.gms.maps.MapsInitializer.initialize(Unknown Source)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at com.google.android.gms.maps.SupportMapFragment$b.cE(Unknown Source)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at com.google.android.gms.maps.SupportMapFragment$b.a(Unknown Source)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at com.google.android.gms.dynamic.a.a(Unknown Source)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at com.google.android.gms.dynamic.a.onCreate(Unknown Source)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at com.google.android.gms.maps.SupportMapFragment.onCreate(Unknown Source)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at android.support.v4.app.Fragment.performCreate(Fragment.java:1477)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:893)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:570)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at android.app.Activity.performStart(Activity.java:5143)
12-18 08:36:27.589: E/AndroidRuntime(1613):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
12-18 08:36:27.589: E/AndroidRuntime(1613):     ... 11 more

Manifest
<meta-data
       android:name="com.google.android.gsm.version"
        android:value="@integer/google_play_services_version" />
<permission
    android:name="com.comercio.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

I've looked for the answer here and everywhere and can't find the fix to this.
Thanks for your help
Comment: the `meta-data` needs to be in your application tag
Comment: it is, i only write the things that i consider relevant.
Answer: You have misspelled gms with gsm. It should be like this:
<meta-data
       android:name="com.google.android.gms.version"
       android:value="@integer/google_play_services_version"     />

google maps not working


Delete ToDo Widgets in Flutter

Question: I want to delete ToDo Widgets in Flutter. I store the Widgets in a list and return that list in the function _getItems().
 List<Widget> _getItems() {

final List<Widget> _todoWidgets = <Widget>[];

for (String title in eintrage) {
  _todoWidgets.add(_buildTodoItem(title));
}

return _todoWidgets;

}
Here is my function to build a ToDO Widget:
Widget _buildTodoItem(String title) {
return ListTile(
    leading: Theme(
      data: ThemeData(unselectedWidgetColor: Colors.white),
      child: Checkbox(
        value: isChecked,
        onChanged: (bool? value) {
          setState(() {
            isChecked = value!;
          });
        },
      ),
    ),
    title: Text(
        title, style: TextStyle(fontSize: 32.0, color: Colors.white)),
    trailing: FlatButton(
      onPressed: () {
        setState(() {

        });
      },
      child: Text(
          'delete', style: TextStyle(fontSize: 20, color: Colors.white)),
    ),
  );

}
In the body I use a ListView that creates all the ToDo Items:
body: ListView(
    children: _getItems(),
  ),

How can I delete one single ToDo Widget when I press the FlatButton with the title "delete"?
Answer: You can do it like this in FlatButton :
onPressed: () {
          setState(() {
            eintrage.remove(title);
          });
        },

Delete ToDo Widgets in Flutter


Carregar JS antes de renderizar a pagina

Question: Boa tarde,
Tenho um codigo de php onde tem uma lista de publicações e ele utiliza o Ajax, mas infelizmente ele está sendo o ultimo a ser baixado pela pagina.
Depois de todos os arquivos que tem dentro do while, e está fazendo com que o Ajax não funcione corretamente..
Dúvida: Existe forma de importar o JS antes de qualquer load?
Tentei pela tag Defer e Async do HTML5 mas não funcionou.
Comment: Coloque seu código HTML e onde está referenciando o código pra gente poder te ajudar
Comment: Se você não quer que a resposta seja assíncrona, por que utilizar AJAX? Por que já não entrega todos os dados na resposta HTTP com o PHP?
Comment: Boa leitura https://css-tricks.com/prefetching-preloading-prebrowsing/ mas procure tb em outras fontes!
Comment: @VictorLaio o código é bem grande para colocar aqui, tentei carregar assincrono, mas nao deu diferença http://prntscr.com/m5g24c
Comment: Sem o código nao tem como te ajudar amigo...
Answer: Olá,
Acredito que uma boa abordagem junto a chamada do javascript logo depois da tag Head é utilizar em seu arquivo JS uma estrutura IIFE (Immediately Invoked Function Expression),
Desta forma você estará auto-executando sua função. Mais informações podem ser vistas aqui: https://developer.mozilla.org/pt-BR/docs/Glossario/IIFE
Answer: Basta você colocar o código Javascript ou o link dele logo depois da tag Head.
A pagina sempre espera que o script seja carregado e verificado antes de continuar a carregar todos os outros elementos abaixo dele.


Ocaml vs Python - Valor de retorno da função

Question: Tenho a seguinte função escrita em ocaml
let rec pow((x:int), (y:int)) : int =
  if y=0 then
    1
  else
    x * pow(x,y-1)
;;
let pr = 13;;
let bs = 31;;
let getvalor num ch1 ch2 tam =
  (num * bs + int_of_char(ch1) - int_of_char(ch2) * (pow(bs, tam) mod pr)) mod pr
;;
print_int (getvalor 1 'A' 'A' 2);;

No print devolve -8 e implementei uma função similar em python e devolveu este valor 5 mas não estou a perceber porque os valores são diferentes nas duas saídas.
Versão em python:
def int_of_char(char):
  return ord(char)
def getvalor(num, ch1, ch2, bs, length, nmb2):
  return (num * bs + int_of_char(ch1) - int_of_char(ch2) * pow(bs, length, nmb2)) % nmb2

print (getvalor (1,'A','A',31,2,13))

Comment: Como você implementou a essa potenciação entre inteiros em OCaml?
Comment: esqueci de colocar. Ja fiz update
Comment: **Obs para quem não conhece a linguagem OCaml**, tente fazer `2 ** 3` e descobrirá que terá que fazer como ele fez ou então, se não me falhe a memória, algo assim `float_of_int 2 ** float_of_int 3|> int_of_float`
Answer: Respondendo sua pergunta "porque os valores são diferentes nas duas saídas?".
Essa função pow() que definiu em OCaml funciona bem com números pequenos:
# pow(2,5) ;;
- : int = 32

Porém na magnitude exigida em seu cálculo bs=31 e tam=412 o resultado ultrapassa algumas vezes o valor de max_int:
# max_int;;
- : int = 4611686018427387903

Estourando o limite numérico e retornando um valor negativo, lembrando potencia positiva de inteiros positivos o resultado é sempre positivo.
# pow(31,412) ;;
- : int = -1355500415

Já em python o builtin pow() irá retornar o valor correto pois em python virtualmente não há limite para inteiros:
>>> print(pow(31,412))
276069138324941945105491334106743548343721891253395677647688980210268338479815494895702857569705905259215554766122880414081265412222862455070422343941123563226292693898588710424868593004715576400093926321790564436401576623753610968630429707481035503096221766405055115180414065291029160680597540318300168902837206474368389783537831824941035360031248630200395997664286279876185196611747109383548663603552453004476274809140462798037718731829815781875721556412228287401860555521034466663555186417962593312862133585901989904028712225121222048901049818453241421257430604049981206904806269761521337270272284591644143301761

Em OCaml ao invés de realizar esses cálculos com o tipo int utilize algum tipo numérico de precisão arbitrária.
Edição:
Como o AP restringiu o domínio da função, apareceu outro problema. Existe uma diferença na maneira que OCaml trata o operador mod e a maneira como Python trata o operador %.
A definição de módulo diz que dados dois números positivos, a e b , um módulo b (abreviado como mod b ) é o restante da divisão euclidiana de a por b:
a = bq + r

Onde:

a é o dividendo.
b é o divisor.
q é o quociente.
r é o resto.

Quando dividendo e divisor são positivos tudo bem, o problema se dá quando um dos operadores é negativo e dois resultados são matematicamente possíveis.
Outro fator que influencia o resultado é pela maneira como as linguagens tratam a divisão inteira:

Em OCaml a divisão inteira é arredondada para 0, o que faz com que o resultado do módulo sempre tenha o mesmo sinal que o dividendo.
Em Python a divisão inteira sempre arredonda para baixo (em direção ao infinito negativo), o que faz com que o resultado do módulo sempre tenha o mesmo sinal que o divisor.

Um exemplo de divergência seria módulo da divisão de -684 por 13:
Em OCaml:
# -684 mod 13 ;;
- : int = -8

Em Python:
>>> -684 % 13
5

Então são duas soluções. Uma solução seria fazer o código OCaml se comportar como o código Python, a outra solução seria fazer o código Python se comportar como o código OCaml.
Primeira Alternativa: Fazer código OCaml se comportar como Python:
Para fazer o operador OCaml mod apresentar o mesmo resultado que em Python é preciso reimplementar o operador:
# let (mod) x y = let res = x mod y in if res < 0 then res + y else res;;

Ou no seu código:
let rec pow((x:int), (y:int)) : int =
  if y=0 then
    1
  else
    x * pow(x,y-1)
;;

let (mod) x y = let res = x mod y in if res < 0 then res + y else res;;

let pr = 13;;
let bs = 31;;
let getvalor num ch1 ch2 tam =
  (num * bs + int_of_char(ch1) - int_of_char(ch2) * (pow(bs, tam) mod pr)) mod pr
;;

Resultando:
# print_int (getvalor 1 'A' 'A' 2);;
5

Segunda Alternativa: Fazer código Python se comportar como OCaml:
Nesse caso basta substituir o operador OCaml mod pelo seu equivalente Python math.fmod()
from math import fmod

def int_of_char(char):
  return ord(char)
def getvalor(num, ch1, ch2, bs, length, nmb2):
  return int(fmod(num * bs + int_of_char(ch1) - int_of_char(ch2) * fmod(pow(bs, length), nmb2), nmb2))

Resultando:
>>>print (getvalor (1,'A','A',31,2,13))
-8

Usar uma ou outra solução depende de sua intenção.
Comment: pow (31,2) acho que é assim
Comment: alterei os valores das variáveis para ser possível representar em ambos programas mas devolve resultados diferentes
Comment: Continua com o mesmo problema `pow(31,13) ;;
- : int = -505558625` veja: https://imgur.com/a/Bu3PhpP
Comment: Decompus a operação em python https://repl.it/repls/DotingDapperEmulation vou fazer o mesmo em OCalm...
Comment: Em OCalm deu `a=96 b=-780 c=-684 d=-8`. Quando faz em python `(...) % nmb2` ele retorna `5` e  em OCalm `(...) mod nmb2` está retornando `-8`
Comment: Se fizer a mesma conta na [calculadora do Google](https://www.google.com/search?sxsrf=ALeKk00Gs1eMxYb3zIPtcXkxafTwnXqfYA:1586982979231&q=-684+%25+13&stick=H4sIAAAAAAAAAOMwf8RowS3w8sc9YSn9SWtOXmPU5OJyTsxJLs1JLMkvEpLm4nKtKChKLS7OzM8T4pXi5uLUNbMwUVBVMDTmWcSK4AAAzPiBYUkAAAA&sa=X&ved=2ahUKEwjS6falpOvoAhWXIbkGHQxiCmkQ6RMwJXoECAwQBA&sxsrf=ALeKk00Gs1eMxYb3zIPtcXkxafTwnXqfYA:1586982979231&biw=1366&bih=695) o resultado vai ser `5` o mesmo resultado que no python
Comment: Porém se você fizer `684 % 13`(Valor positivo) o [resultado é `8`](https://www.google.com/search?sxsrf=ALeKk01O34e_eQtO0IuOi8qJZ2Y-u2pkrQ:1586983085246&q=684+%25+13&stick=H4sIAAAAAAAAAOMwf8Rozi3w8sc9YSm9SWtOXmPU4OJyTsxJLs1JLMkvEpLi4nKtKChKLS7OzM8T4gFyOcwsTBRUFQyNeRaxwtkAMXpHT0cAAAA&sa=X&ved=2ahUKEwiU1b3YpOvoAhXlD7kGHW8NDsUQ6RMwC3oECAsQBA&biw=1366&bih=695)
Comment: Isso significa que em OCaml quando faz `mod` de um negativo o interpretador converte o negativo para positivo e depois calcula o remanescente e depois adiciona o sinal.
Comment: Para devolver o valor 5 em ocaml devo fazer o que?
Comment: @user185544 fiz uma edição na resposta espero que lhe satisfaça.
Comment: Em relação aos números de precisão arbitrária eu não estou a conseguir fazer o carregamento da biblioteca para o programa #load "nums.cma";; devolve erro de sintaxe ao tentar compilar
Comment: Ai eu não posso ajudar pois foge da minha área, já é caso de infraestrutura. É uma questão de colocar os libs no diretório certo e fazer apontamentos do OS.