How should I close urllib.urlopen connection in python

Question: I have a python code that reads from a URL.
 def submitTest(self,url):
    response = None
    if url is not None:
        wptUrl = WebPageTestConfigUtils.getConfigValue('runTestURL')+"?f=json&url="+url+"&runs=3&video=1&web10=0&fvonly=1&mv=1&private=1&location=us_east_wptdriver:Chrome.DSL"
        with closing(urllib.urlopen(wptUrl)) as response:
            json.load(response)
            return response["data"]["testId"]

I used the context lib docs https://docs.python.org/2/library/contextlib.html to close the python connection. But then I get the following error on executing.
Traceback (most recent call last):
File "webPageTestUtils.py", line 59, in <module>
main()
File "webPageTestUtils.py", line 56, in main
print webPageTestProcessor.submitTest("www.amazon.com")
File "webPageTestUtils.py", line 27, in submitTest
return response["data"]["testId"]
AttributeError: addinfourl instance has no attribute '__getitem__'

What I am doing wrong here . I need a way to close the connection if something bad happens or if I am done with it.
Comment: possible duplicate of [should I call close() after urllib.urlopen()?](http://stackoverflow.com/questions/1522636/should-i-call-close-after-urllib-urlopen)
Answer: What I am doing wrong here?
An error occurred that was not caught.
The error occured because: quote from @Nonnib:

json.load returns the object you need. You are probably looking for:
  response_dict = json.load(response) and then return
  response_dict["data"]["testId"]

Possible solution:
Catch possible errors and return the appropriate result
def submitTest(self,url):
    response = None
    if url is not None:
        wptUrl = WebPageTestConfigUtils.getConfigValue('runTestURL')+"?f=json&url="+url+"&runs=3&video=1&web10=0&fvonly=1&mv=1&private=1&location=us_east_wptdriver:Chrome.DSL"
        with closing(urllib.urlopen(wptUrl)) as response:
            json.load(response)
            try:
                return response["data"]["testId"]
            except AttributeError:
                return "an AttributeError occured" # or return something else, up to you
            except:
                return "an error occured"

This way the with block will always execute normally and close the connection when it's done
Comment: Because `response` is not a dict
Comment: but the same code works fine if I use json.load(urllib.urlopen(wptUrl))
Comment: json.load returns the object you need. You are probably looking for: response_dict = json.load(response) and then return response_dict["data"]["testId"]
Comment: Yeah what Nonnib said


Questions regarding backward propagation

Question: I am reading article regarding backward propagation https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/ . Lets say if I follow the example in the article but using only 3 nodes, with the 1st node an input, 2nd node the hidden layer and 3rd node the output so at 2nd node, the result is $$n_1=I_1*W_1+B_1$$ which is feed into the logistic function $$O_1=\frac{1}{1+e^{-n_1}}$$ and this outputs($O_1$) is then feed into the last node $$n_2=O_1*W_2+B_2$$ that is finally feed into the logistic function again to get $$O_2=\frac{1}{1+e^{-n_2}}$$ The error with respect to w1 can be written as $$error=\frac{1}{2}(target-O_2)2$$
a)Let's say initially using $w_1=0.4$ and get the result of $E_1$, then using $w_1=0.401$ to get the result of $E_2$ again. Does this represent numerical approximation for $dE/dw$ ?$$\frac{dE}{dw_1}=\frac{E_2-E_1}{0.401-0.400}$$
b)Is this
$$E(w1+h)=E(w1)+h*\frac{dE}{dw1}+\frac{1}{2}h^2\frac{d^2E}{dw1^2}+...?$$
A correct representation of error expanded using Taylor series around w1?
c)Is it possible to use similar Runge-Kutta methods to obtain higher order of the error?
Answer: Yes, difference quotients give approximations to derivatives.
The problem is that you want all the partial derivatives, and the coefficient $W_1$ is usually a matrix. Forward differentiation like with divided differences, complex step or dual numbers only computes one partial derivative at a time, thus backwards differentiation is applied which computes all derivatives in one sweep.
You can still use the difference quotients to do some spot testing of the result of the backpropagation implementation.
There is the use of truncated Taylor series to compute higher order derivatives. One can combine such Taylor series computed at different lines to get to higher order mixed derivatives. The extraction of the derivatives becomes rapidly ill-conditioned as solution of a linear system.


Uso do Display do CSS

Question: Eu reparei que eu ando usando bastante o display:none para retirar blocos de códigos de uma página. Faço isso por instruções de superiores, mas eu sempre acreditei que é uma prática que pode afetar a performance dos sites desenvolvidos.
A pergunta:
O uso excessivo de display:none pode afetar o sistema de alguma forma?
Lembrando que são sites que raramente sofrem de manutenções.
Answer: O display:none em si não afeta o desempenho do site ja que o css é processado pelo cliente e não o servidor, no entanto o conteudo escondido é sim um disperdício de recurso, já que ele será enviado para o usuário independente da sua utilização.
Este overhead pode afetar tanto os custos da empresa como o requisito minimo do cliente. É uma prática comum em CSS e JS fazer uso da versão minima (min), que reduz o tamanho do arquivo facilitando o acesso a ele e diminuindo o consumo de banda.
Para grandes sites com muitos acessos essa redução tem impacto significante, da mesma forma que para clientes que usam smartphones com internet móvel.

Uso do Display do CSS


Flyway migration after jpa tables have been created

Question: I'm using flyway database migration tool with a spring boot jpa project. When I run the server first flyway wants to migrate sqls, but tables have not created yet. In this case flyway returns an error which like
Caused by: org.flywaydb.core.internal.command.DbMigrate$FlywayMigrateSqlException:
Migration V1__countries_and_states.sql failed
SQL State  : 42S02
Error Code : 1146
Message    : Table 'wallet.country' doesn't exist
Location   : db/migration/V1__countries_and_states.sql (/root/IdeaProjects/service/target/classes/db/migration/V1__countries_and_states.sql)
Line       : 1

I configured application.properties file with these options:

spring.flyway.baseline-on-migrate=true
spring.flyway.enabled=true
spring.flyway.clean-on-validation-error=true
spring.flyway.init-on-migrate=true

I want that my migration will have been successfully  done.
Comment: You probably should have the JPA provider output the DDL script(s) to files instead of having it create tables &c. on the fly at runtime. Then you can use those DDL scripts with flyway. It's not a good practice to have a normal application execute DDL anyway.
Answer: Your first migration must create the tables!
Read this tutorial: https://flywaydb.org/getstarted/firststeps/api
Comment: Plus that's not a good idea! The best is to let hibernate create the SQL DDL file and then improve this and use as the first migration.
Comment: Thank you **Simon Martinelli** but I wanted migrate flyway sqls after hibernate autocreate tables. I think it is impossible with flyway
Answer: Can be used configuration properties like: flyway.out-of-order = true. It says flyway works after hibernate/jpa has been created/updated tables.


How to change subdomain in requests test with Rspec (for API testing)

Question: I have a question which is really specific.
I don't want to do a controller test but a requests test. And I don't want to use Capybara because I don't want to test user interaction but only response statuses.
I have the following test under spec/requests/api/garage_spec.rb
require 'spec_helper'

describe "Garages" do

  describe "index" do
    it "should return status 200" do
      get 'http://api.localhost.dev/garages'
      response.status.should be(200)
      response.body.should_not be_empty
    end
  end
end

This works. But as I have to do more tests.. is there any way to avoid to repeat this? http://api.localhost.dev
I tried with setup { host! 'api.localhost.dev' } But it doesn't do anything.
A before(:each) block setting @request.host to something, of course crashes because @request is nil before performing any http request.
The routes are set correctly (and in fact they work) in this way
namespace :api, path: '/', constraints: { subdomain: 'api' } do
  resources :garages, only: :index
end

Answer: You can create a helper method in the spec_helper.rb, something like:
def my_get path, *args
  get "http://api.localhost.dev/#{path}", *args
end

And its usage will be:
require 'spec_helper'

describe "Garages" do

  describe "index" do
    it "should return status 200" do
      my_get 'garages'
      response.status.should be(200)
      response.body.should_not be_empty
    end
  end
end

Comment: Interesting idea. But in this way every action should have its own helper. I could end writing more code than the the one I want to dry!
Answer: Try this:
spec_helper.rb
RSpec.configure do |config|
  config.before(:each, type: :api) do |example|
    host! 'api.example.com'
  end
end

your spec file
require 'spec_helper'

describe "Garages", type: :api do

  describe "index" do
    it "should return status 200" do
      get 'garages'
      response.status.should be(200)
      response.body.should_not be_empty
    end
  end
end


Object this keyword in properties

Question: const canvas = document.getElementById("canvas");
canvas.width = canvas.height = 700;
const h = canvas.height;
const w = canvas.height;
const ctx = canvas.getContext("2d");
const snake = {
  width: w / 12,
  height: h / 12,
  blocks: [[40, 30, this.width, this.height]],
  renderSnake() {
    this.blocks.forEach((b) => {
      ctx.fillStyle = "black";
      ctx.fillRect(...b);
      console.log(this.blocks);
    });
    console.log(this.blocks);
  },
};

In my code the problem is in the blocks property in the snake object. this.width and this.height was undefined and I added some console.log and realised that the this keyword in the blocks array property was pointing to the Window object, how do i make it point at the snake object or make this work without hardcoding the width and height.
Comment: If you want `blocks` to be dynamic it should be a function
Comment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#as_an_object_method
Comment: Does this answer your question? [Self-references in object literals / initializers](https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers)
Answer: You can make blocks a getter.
get blocks(){
    return [[40, 30, this.width, this.height]];
}

Object this keyword in properties


Adding takeUntil stops triggering all the actions rxJS, redux-observable

Question: I'm trying to figure out a way to cancel all the HTTP request once the user logs out.
I've created a generic function that is responsible for creating the ajax request. This is the function
const createRequest = (ajaxParameters) => {
  return ajax(ajaxParameters).pipe(
    takeUntil([ofType("LOGOUT")])
  )
};

and all of my epic functions are importing the above function to make the HTTP request. I'm doing something like this
   const sendRequest = (url) => {
       xhr = createRequest(_.merge({}, requestDefaults, {
             method: "GET",
             url: url
          }, token))
      xhr.pipe(
          map(
             // some code over here and triggering some actions over here
          )
      )
   }

The problem is whenever I add takeUntil like the way I did above it stops triggering all of the epics. Any idea what is it that I'm doing wrong over here?
epic code
const fetchUserData = action$ => action$.pipe(
  ofType(user.FETCH_USER_DATA.PENDING),
  mergeMap(sendRequest(URL_OVER_HERE))
);

Comment: You usually don't need to complete the requests with `takeUntil` because when you logout you should destroy all components and these components should unsubscribe. Can you show one of your epics that don't work any more?
Comment: @martin I've added the epic code
Answer: I don't know what [ofType("LOGOUT")] is doing there, but most-likely, what you want is to pipe off action$:
const createRequest = (ajaxParameters) => {
  return ajax(ajaxParameters).pipe(
    takeUntil(action$.pipe(ofType("LOGOUT")))
  )
};

takeUntil completes your observable if it receives a value. The way you have it, it probably thinks the array is an observable and the value is the operator ofType. So it completes before anything even starts. That's why you have to listen to action$ instead.
As another optimization, you can immediately pipe off the xhr observable:
const sendRequest = (url) => {
  createRequest(_.merge({}, requestDefaults, {
    method: "GET",
    url: url
  }, token))
  .pipe(
    map(
      // some code over here and triggering some actions over here
    )
  )
}

Comment: Sawtaytoes the problem with this solution is  `takeUntil(action$.pipe(ofType("LOGOUT")))` I don't have action$ variable available over here. Due to which I cannot do the way you mentioned.

Secondly, I've created generic get, post etc request. All the epics import request object from one file and then do the work they need to do
Comment: once thing which I can do is this `takeUntil(from(ofType("LOGOUT")))` but this also does not helps
Comment: That won't work either. `ofType` is an operator. You need to pass in `action$`. If you want something truly generic, use an action. `AJAX_GET` and then do your AJAX call in there.
Comment: hey sorry for the late reply, but is it possible for you to give an example


OxyPlot: How to set ticks/decade to 1 on a logarithmic axis

Question: I have a log-log plot with both axes in the range 0.1 to 1000. I want only 1 major tick per decade. So far I have found no way to control the tick spacing, except to set IntervalLength as in this code.
<code>        var logxAxis = new LogarithmicAxis
        {
            Position = AxisPosition.Bottom,
            Title = "Resistivity of Approaching Bed (ohm-m)",
            IntervalLength = 100,
            MajorGridlineStyle = LineStyle.Solid,
            MinorGridlineStyle = LineStyle.None,
            MinorTickSize = 0.0,
            Key = "logx"
        };
</code>
The default IntervalLength is 60, which gave me 2 ticks/decade. Unfortunately, as I increase the window size of my application the number of major ticks increase. So setting IntervalLength is not an ideal solution. I have looked through the OxyPlot source and found nothing. Is there something I am missing, or perhaps I need to derive my own LogarithmicAxis class?
Edit: I decided to derive my own logarithmic axis and replace the function the generated the ticks.
<code>    public override void GetTickValues(out IList<double> majorLabelValues, out IList<double> majorTickValues,
        out IList<double> minorTickValues)
    {
        majorLabelValues = new List<double> { 0.1, 1, 10, 100, 1000 };
        majorTickValues = new List<double> { 0.1, 1, 10, 100, 1000 };
        minorTickValues = new List<double>();
    }
</code>
This at least lets me get my application out the door.
Answer: After some thought, I decided that hard coding the ticks was not the best idea. I decided to create a logarithmic axis where I could lock in the tick placement, but I could also unlock, and let the built in algorithms of OxyPlot work. You will that I reused some OxyPlot methods that are internal, so I just copied the code into my class and made them private. This problem was a lot easier to solve with access to the code. I am stiil open to hearing other solutions.
<code>public class LockableLogarithmicAxis : LogarithmicAxis
{
    #region Properties

    public bool IsLocked { get; set; }
    public double[] MajorTickPositions { get; set; }
    public double[] MinorTickPositions { get; set; }

    #endregion

    #region Constructor

    public LockableLogarithmicAxis()
    {
        IsLocked = true;
    }

    #endregion

    #region Methods

    public override void GetTickValues(out IList<double> majorLabelValues, out IList<double> majorTickValues,
        out IList<double> minorTickValues)
    {
        if (!IsLocked)
        {
            base.GetTickValues(out majorLabelValues, out majorTickValues, out minorTickValues);
            return;
        }

        if (MajorTickPositions != null && MajorTickPositions.Length > 0)
        {
            majorTickValues = MajorTickPositions.ToList();
        }
        else
        {
            majorTickValues = this.DecadeTicks();
        }

        if (MinorTickPositions != null && MinorTickPositions.Length > 0)
        {
            minorTickValues = MinorTickPositions.ToList();
        }
        else
        {
            minorTickValues = this.SubdividedDecadeTicks();
        }

        majorLabelValues = majorTickValues;
    }

    /// <summary>
    /// Calculates ticks of the decades in the axis range with a specified step size.
    /// </summary>
    /// <param name="step">The step size.</param>
    /// <returns>A new IList containing the decade ticks.</returns>
    private IList<double> DecadeTicks(double step = 1)
    {
        return this.PowList(this.LogDecadeTicks(step));
    }

    /// <summary>
    /// Calculates logarithmic ticks of the decades in the axis range with a specified step size.
    /// </summary>
    /// <param name="step">The step size.</param>
    /// <returns>A new IList containing the logarithmic decade ticks.</returns>
    private IList<double> LogDecadeTicks(double step = 1)
    {
        var ret = new List<double>();
        if (step > 0)
        {
            var last = double.NaN;
            for (var exponent = Math.Ceiling(this.LogActualMinimum); exponent <= this.LogActualMaximum; exponent += step)
            {
                if (exponent <= last)
                {
                    break;
                }

                last = exponent;
                if (exponent >= this.LogActualMinimum)
                {
                    ret.Add(exponent);
                }
            }
        }

        return ret;
    }

    /// <summary>
    /// Raises all elements of a List to the power of <c>this.Base</c>.
    /// </summary>
    /// <param name="logInput">The input values.</param>
    /// <param name="clip">If true, discards all values that are not in the axis range.</param>
    /// <returns>A new IList containing the resulting values.</returns>
    private IList<double> PowList(IList<double> logInput, bool clip = false)
    {
        return
            logInput.Where(item => !clip || !(item < this.LogActualMinimum))
                .TakeWhile(item => !clip || !(item > this.LogActualMaximum))
                .Select(item => Math.Pow(this.Base, item))
                .ToList();
    }

    /// <summary>
    /// Calculates ticks of all decades in the axis range and their subdivisions.
    /// </summary>
    /// <param name="clip">If true (default), the lowest and highest decade are clipped to the axis range.</param>
    /// <returns>A new IList containing the decade ticks.</returns>
    private IList<double> SubdividedDecadeTicks(bool clip = true)
    {
        var ret = new List<double>();
        for (var exponent = (int)Math.Floor(this.LogActualMinimum); ; exponent++)
        {
            if (exponent > this.LogActualMaximum)
            {
                break;
            }

            var currentDecade = Math.Pow(this.Base, exponent);
            for (var mantissa = 1; mantissa < this.Base; mantissa++)
            {
                var currentValue = currentDecade * mantissa;
                if (clip && currentValue < this.ActualMinimum)
                {
                    continue;
                }

                if (clip && currentValue > this.ActualMaximum)
                {
                    break;
                }

                ret.Add(currentDecade * mantissa);
            }
        }

        return ret;
    }

    #endregion
}
</code>


Electric guitar buzzing sound electricity

Question: My guitar making buzzing sound. I don't know what is happening. Sometimes it making buzzing sound and then its gone and then it comes again. But when i touch a metal part from the guitar ( near to the guitar plug-in / jack ) sound suddenly gone. I couldn't tell you so much , so i post a video to YOUTUBE so you guys can find out what is happening.
Help me please.
Comment: Have a look at this thread: [pickups-and-selector-switch-stop-buzzing-when-touched](http://music.stackexchange.com/questions/15878/pickups-and-selector-switch-stop-buzzing-when-touched). _Sometimes_ this is caused by your own body picking up noise from nearby computer screens, fluorescent lights etc.
Comment: Either there is earthing issues with your guitar, or with your home. If its something with guitar, Tim's solution will help you out.
Answer: Seems to me that there is an earthing problem with the guitar. All of the metal parts should be electrically joined, often with a braided wire. This puts them all at the same voltage level. Open up the guitar, which on a Strat involves taking strings and scratchplate off, and check that the earth wire joins all of the components. If that sounds scary, you need to find a guitar tech to do the job. Good luck.
Comment: hahah definitely sounds like it. I have so much static in my strat strings that one of the capacitors will occasionally create a popping sound in my signal.


Image Upload into Database

Question: I try to upload two images for each object of a certain type following those instructions: http://archive.railsforum.com/viewtopic.php?id=4642
Thats what my models look like:
Models:
class Mepager < ActiveRecord::Base
    has_many :images
end

class Image < ActiveRecord::Base
    belongs_to :mepager

     def image_file=(input_data)
         self.filename = input_data.original_filename
         self.content_type = input_data.content_type.chomp
         self.binary_data = input_data.read
     end
end

Schema:
create_table "images", force: true do |t|
    t.string   "content_type"
    t.string   "filename"
    t.binary   "binary_data"
    t.string   "connector"
    t.integer  "mepager_id"
    t.datetime "created_at"
    t.datetime "updated_at"
end

Controller
def new
@mepager = @pimp.build_mepager
@pre_image = @mepager.images.build(:connector => "pre")
@post_image = @mepager.images.build(:connector => "post")
end

def mepager_params
  params.require(:mepager).permit(:id,
    :images_attributes => [:id, :content_type, :filename, :binary_data, :mepager_id, :connector])
end

Form:
<%= simple_form_for :mepager, url: mepager_path, html: {multipart: true} do |f| %>

<%= f.simple_fields_for :images, @pre_image do |image| %>
    Pre-Image
        <%= image.input :image_file, :as => :file, label: false, input_html:{:size => 15} %>
        <%= image.input :connector %>
<% end %>

<%= f.simple_fields_for :images, @post_image do |image| %>
    Post-Image
        <%= image.input :image_file, :as => :file, label: false, input_html:{:size => 15} %>
        <%= image.input :connector %>
<% end %>
<% end %>

But if I choose a file in that form and submit it, its not getting saved!
Anyone?
Best regards!
Answer: Why don't you instead just save the image link to the database and then upload the image to a given directory on your server, its much better and secure. And for that to work you have to use paperclip look at this example
Start by adding paperclip gem in the gem file like this
gem "paperclip", "~> 2.3"

After run bundle install in your project directory
Then generate a migration to add the field to your table like this
rails g migration add_attach_paperclip

Then add these columns to your table
class AddattachPaperclip < ActiveRecord::Migration
def self.up
add_column :images, :attach_file_name, :string
add_column :images, :attach_content_type, :string
add_column :images, :attach_file_size, :integer
add_column :images, :attach_updated_at, :datetime
end

def self.down
remove_column :images, :attach_file_name
remove_column :images, :attach_content_type
remove_column :images, :attach_file_size
remove_column :images, :attach_updated_at
end
end

The you go and rake you migration
After you change your model for images by adding this
has_attached_file :pic

After change the name of your file field to pic
That is all you need when you want to display your image you just use
<%= @image.pic.url %>

Comment: But is it possible to attach 2 images to 1 object and map them accordingly? Thats what I meant with the `connector` attribute.
Comment: yes you can what you do just create another migration say add_pic_paperclip then in the model create another validation as attach and then go to your form and add it their as attach
Comment: Sorry, not really getting what you're saying! So you say I have to create a new migration named `add_pic_paperclip`? But what kind of validation do I have to create in my model? And didnt get that with the form either. Could you explain it a little more, that would be awesome.

Image Upload into Database


Como colocar um "mostrar mais" no gridview

Question: Como fazer isso:

Virar isso:

A única coisa que consigo imaginar é colocar uma treeview dentro da gridview, mesmo assim, nem sei se isso é possível.
A dúvida é só sobre a parte funcional mesmo, a parte estética eu vou fazer depois que resolver isso.
Comment: Com o gridview do webforms vai ser punk, já fiz uma vez com ele formatado usando o DataTables.net mas não é mamão com açúcar..RS ou usa o gridview do devexpress apesar de ser pago é bem fácil usar
Comment: Caso alguém precise, fiz do jeito que esse site mostra e deu certo: http://www.codescratcher.com/asp-net/expand-collapse-nested-gridview-asp-net/
Answer: Com o gridview do webforms vai ser punk, já fiz uma vez com ele formatado usando o DataTables.net mas não é tão fácil se tiver q mostrar muitos dados na linha child
 ou usa o gridview do devexpress apesar de ser pago é bem fácil usar.
URL do Datatable.net plugin jquery gratuito que pode ser sua solução.
http://datatables.net/examples/api/row_details.html


How to simplify my bash code?

Question: I've write the following code in bash, this code tends to print a matrix of 200x13 random numbers (we have 200 line printed with 13 numbers per line). I want this code to be more flexible such that one can change size of the matrix printed (number of line and number of number per line) without re-write the code
for (( k = 0; k < 200; k++  ))
do

    echo $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 )) $(( $RANDOM - 16384 ))

done

thanks for any help.
Answer: First, you want to change the printing of the columns to another for-loop:
for (( k = 0; k < 200; k++  ))
do
 for (( j = 0; j < 3; j++))
 do
    echo -n $(( $RANDOM - 16384 ))" "  # print your random number

 done

 echo     # print newline
done

Then, you can parametrize your k max and j max:
rows=200   # set the number of rows
cols=3    # set the number of columns

for (( k = 0; k < $rows; k++  ))
do
   for (( j = 0; j < $cols; j++))
   do
       echo -n $(( $RANDOM - 16384 ))" "

   done

   echo
done

Comment: I think you mean parameterize rows/cols (of course, just semantics, as you're referring to the same thing.)
Answer: To do this simply, just add a nested loop to repeat the columns.
Also in bash you can do a for loop with brace expansion ...
for a in {1..200}
do # Rows...
    for b in {1..13}
    do # Columns...
        echo -n "$(( $RANDOM - 16384 )) "
        # -n suppresses newlines
    done
    echo
    # do newline at the end of the row.
done

If the script was going to become more complicated. I'd suggest abstracting the script into functions.
function printRandomNumber() {
   seed={1:-16384}
   echo -n "$(( $RANDOM - $seed ))"
}

function printRandomMatrix() {
    rows={1:-200} # default 200 if not set.
    cols={2:-13} # default 13 if not set.

    for a in {1..$rows}
    do
        for b in {1..$cols}
        do
            printRandomNumber
        done
        echo
    done
}

Then call it with
printRandomMatrix
# print the default row/column matrix.

printRandomMatrix 10 10
# print a matrix of 10 by 10.

This way you can more easily maintain the script and adapt to changes, e.g. if you needed to format the output using printf as shown in D.Shawley's answer. Of course you may want a variety of possible visual formatting (left/right column alignment etc.) these can be achieved with a variety of tricks... More on shell text formatting
Comment: I suggest we clean up the noise.
Answer: Put it in a shell function and use printf instead of echo.
printMatrix() {
  cols=${1:-13}
  rows=${2:-200}
  for (( i=0; i<$rows; i++ ))
  do
    for (( j=0; j<$cols; j++ ))
      printf "%13d" $(( $RANDOM - 16384))
    done
    echo
  done
}

printMatrix # will print 200x13 matrix
printMatrix 5 10  # with print 10x5 matrix

Since this is in a shell function, you can source the function definition and call it directly from the shell.  If the function is in a file named shfuncs, then you can source it and run it like follows:
bash$ source shfuncs
bash$ printMatrix 3 2
11118        31           -9753
-13700       -12008       -1779
bash$

How to simplify my bash code?


How to set checkbox if validation fails?

Question: I am creating a form which has checkbox, and options for checkbox are coming dynamically. In submit function I am rebuilding form if validation fails. all values are rendering but previously checked checkbox is not checking.
below is the code:
function modulename_form(){
      $header = array();
      $rows = array();
      $conditions = '';
      $orderby = array( 'pass_lname' => 'ASC');
      $unmapped_data = capcup_get_unmapped_passengers_data($conditions , $orderby);

      foreach ($unmapped_data as $key => $value) {
        $user = user_load($value->pass_uid);
        $insertion = !empty($value->pass_insertion)? $value->pass_insertion . ' ': '';
        if (empty($buttons)) {
          $row['name'] = 'mail . '">' . check_plain($value->pass_lname . ' ' . $insertion . $value->pass_fname) . '';
        }
        else {
          $row['name'] = 'passenger_uid . '">' . check_plain($value->passenger_lname . ' ' . $insertion . $value->passenger_fname) . '';
        }
        $row['phone'] = $value->pass_tel;
        $row['practicecode'] = $value->pass_practcode;
          $form['active'] =  array(
          '#type' => 'checkbox',
          '#return_value' => $value->pass_uid,
          '#attributes' => array(
              'name' => array('nodes[' . $value->pass_uid . ']'),
            )
          );
          $row['active'] =  drupal_render($form['active']);
        $rows[$value->pass_uid] = $row;
      }

      $form['nodes'] = array(
        '#theme' => 'table',
        '#header' => $header,
        '#rows' => $rows,
        '#empty' => t('No passenger available.'),
      );
return $form;
}

submit function:
function modulename_submit($form, $form_state) {
  if (in_array('boat', $account->roles)) {
      $form_state['rebuild'] = TRUE;
      form_set_error('boat_user_info][emailaddress', 'Dit e-mailadres is al in gebruik.');
      return FALSE;
    }
}

I am writing form function like above because to get structure like below image:

When form will rebuilt all fields will remembered there previous value but checkbox is not remembered its value. I tried by adding default_value and all but not worked. Please suggest me how can I achieve that.
Comment: Can you show me where and how you add #default_value for this checkbox in the form function?
Answer: All form validations should be done in form validate function and not in submit function. Read this article
Hope it helps. :)


Is there any way to link a field in a Scapy Packet to its portion in the built str?

Question: I'm using Scapy to manipulate CoAP packets. Now I found one thing I want to do which I actually can't figure out how.
I have the following CoAP Packet:
>>> pkt
<CoAP  ver=1L type=CON tkl=8L code=PUT msg_id=<RandShort> token=<RandBin> options=[('If-Match', '\x04\xfc\xbbL'), ('Content-Format', ''), ('Uri-Path', '.well-known'), ('Uri-Path', 'core')] paymark='\xff' |<Raw  load='CC22 at 12:39:31.495' |>>
>>> str(pkt)
'H\x03\xf4\x08\xbdR_\x85\xa3\x04\xe9\xe9\x14\x04\xfc\xbbL\xab.well-known\x04core\x10\xffCC22 at 12:39:31.495'

What I'd like to do now is to replace the whole part (not the Option Value '') representing the option at index 1 ('Content-Format', '') to null (\x00) chars. I know this part is represented by str(pkt)[-22:-21] near the end of the str(pkt), which has value \x10 to represent the Content-Format option with no actual value on it.
So, I wonder: is there a way to obtain \x10 (actually, to obtain the reference str(pkt)[-22:-21]) from the high-level field (pkt.options[1]), so I can replace this part of the string by another value?
Thanks in advance!
Answer: Ok, a few hours on the problem and I came up with a solution which, if I'm correct to assume there's no easy way to do this through Scapy itself (probably due to the way CoAP Options are implemented in the CoAP contrib layer), seems to be a fair enough one.
The following function can be used to "nullify" an entire CoAP Option field:
def coap_option_to_null(pkt, opt_idx):
  ''' Changes the whole CoAP Option field at @opt_idx to null '''
  opt = pkt.options[opt_idx]
  l = pkt.options
  # Sort the list of options by option number
  l.sort( lambda x, y: cmp(coap_options[1][x[0]], coap_options[1][y[0]]) )
  # Replace options for the sorted one and grabs new opt_idx
  pkt.options = l
  opt_idx = pkt.options.index(opt)

  cur_delta = 0
  opt_total_len = []
  for opt in pkt.options:
    if (option_model[opt[0]][0] - cur_delta) < 13:
      delta_extended = 0
    elif (option_model[opt[0]][0] - cur_delta) < 269:
      delta_extended = 1
    else:
      delta_extended = 2
    cur_delta += (option_model[opt[0]][0] - cur_delta)

    if len(opt[1]) < 13:
      len_extended = 0
    elif len(opt[1]) < 269:
      len_extended = 1
    else:
      len_extended = 2

    opt_total_len.append(1+delta_extended+len_extended+len(opt[1]))

  opt_lidx = sum(opt_total_len[:opt_idx])
  opt_hidx = sum(opt_total_len[opt_idx+1:])
  new_pkt = str(pkt)[:4+pkt.tkl+opt_lidx] + '\x00'*opt_total_len[opt_idx] + str(pkt)[-(len(pkt.payload)+1+sum(opt_total_len[opt_idx+1:])):]
      return CoAP(new_pkt)

Below is a demonstration:
>>> pkt
<CoAP  ver=1L type=CON tkl=8L code=PUT msg_id=<RandShort> token=<RandBin> options=[('If-Match', '\x04\xfc\xbbL'), ('Content-Format', ''), ('Uri-Path', 'separate')] paymark='\xff' |<Raw  load='CC22 at 12:39:31.495' |>>
>>> str(pkt)
'H\x03*\x88%T\xbe\xac\xd9\xee\xcd\xbd\x14\x04\xfc\xbbL\xa8separate\x10\xffCC22 at 12:39:31.495'
>>> npkt = coap_option_to_null(pkt, 1)
>>> npkt
<CoAP  ver=1L type=CON tkl=8L code=PUT msg_id=47784 token='\x90L\x0f\xd4u\xbe&\xd7' options=[('If-Match', '\x04\xfc\xbbL'), ('Uri-Path', 'separate'), ('Uri-Path', '')] paymark='\xff' |<Raw  load='CC22 at 12:39:31.495' |>>
>>> str(npkt)
'H\x03\xba\xa8\x90L\x0f\xd4u\xbe&\xd7\x14\x04\xfc\xbbL\xa8separate\x00\xffCC22 at 12:39:31.495'

>>> pkt
<CoAP  ver=1L type=CON tkl=8L code=PUT msg_id=<RandShort> token=<RandBin> options=[('If-Match', '\x04\xfc\xbbL'), ('Content-Format', ''), ('Uri-Path', 'separate')] paymark='\xff' |<Raw  load='CC22 at 12:39:31.495' |>>
>>> npkt = coap_option_to_null(pkt, 0)
>>> npkt
<CoAP  ver=1L type=CON tkl=8L code=PUT msg_id=14606 token='s\xad\xd0\xf5\x05\xac\x87C' options=[(0L, ''), (0L, ''), (0L, ''), (0L, ''), (0L, ''), (10L, 'separate'), ('Uri-Path', '')] paymark='\xff' |<Raw  load='CC22 at 12:39:31.495' |>>
>>> str(npkt)
'H\x039\x0es\xad\xd0\xf5\x05\xac\x87C\x00\x00\x00\x00\x00\xa8separate\x10\xffCC22 at 12:39:31.495'


Sum of squareroots of primes under Galois action

Question: Let $p_1, ..., p_r$ be distinct prime numbers, $L = \mathbb{Q}(\sqrt{p_1}, ..., \sqrt{p_r})$ and $\alpha = \sqrt{p_1} + ... + \sqrt{p_r}$.
Is there any way to proof, that
$$ \{ \sigma(\alpha) \ | \ \sigma \in \text{Gal}(L/\mathbb{Q}) \}$$
is contained in $\mathbb{Q}(\alpha)$ without showing, that $L = \mathbb{Q}(\alpha)$?
Answer: If the set of $\alpha$'s conjugates in $\mathbb{C}$ is $A=\{\alpha_1= \alpha, \alpha_2, \dots, \alpha_n\}$, it suffices to show that $\mathbb{Q}(A) = \mathbb{Q}(\alpha)$. Since the former is a splitting field, it is Galois, with Galois group $G$.
Now note that if all of $G$'s  subgroups are normal, then, in particular, $\mathbb{Q}(\alpha)$ is normal over $\mathbb{Q}$, therefore it contains all of $\alpha$'s conjugates and the result follows.
Since $L/\mathbb{Q}$ is normal $L$ and contains $\mathbb{Q}(A)$, $G$ is a subgroup of $\text{Gal}(L/\mathbb{Q}) \approx \mathbb{Z}_2^r$, and since $\mathbb{Z}_2^r$ is abelian, all of its subgroups are normal, including those of $G$.
In general, this argument works for any $\alpha \in L$, for example $\alpha = \sqrt{p_1}\sqrt{p_3}+\sqrt{p_2}$.
Comment: Yeah thats a nice observation, in an Abelian extension, all elements are normal. One can go a step further in this case an note that $\sqrt{p_1}+\cdots +\sqrt{p_r}$ has $2^r$ conjugates and thus is equal to the whole extension.
Comment: Yes, normally that would be the standard solution, however the OP asked for a solution without showing that $\mathbb{Q}(\alpha)$ is equal to the whole extension. @ReneSchipperus
Comment: Granted. But what is the standard solution ? Is there some other way to see equality of the extensions ?
Comment: Yes. Since $\mathbb{Q}(\sqrt{p_1}, \dots, \sqrt{p_{r-1}})(\sqrt{p_r}):\mathbb{Q}(\sqrt{p_1}, \dots, \sqrt{p_{r-1}})=2$, there is $\sigma$ in Gal$(L/\mathbb{Q})$ such that $\sigma(\sqrt{p_r})=-\sqrt{p_r}$, and $\sigma$ fixes other $p_i$s. Then these $\sigma$s and their compositions, together, make $2^r$ distinct automorphisms. @ReneSchipperus
Comment: Ok, but that is the argument that I gave.
Comment: Then your argument is the standard solution :D.
Also, without using Galois theory, it can be shown by induction that $\sqrt{p_1}+\dots+\sqrt{p_r}$ is a primitive element. @ReneSchipperus
Comment: Do you mean by squaring and doing algebra etc. That gets kind of complicated doesnt it ? In simple cases yeah its ok, but as a general method or is there some clever neat way of doing it ?
Comment: I just looked at your profile you say you are in high school, its amazing that you understand Galois theory so well.
Comment: @ReneSchipperus My brother is studying math in university, and I learn many things from him :D


Gostaria de pegar apenas o horário dessa string usando javascript

Question: Gostaria de pegar apenas o horário dessa string usando javascript
2022-04-29T19:56:36.327Z

Ficaria apenas 19:56
Comment: Veja **slice()** https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/String/slice, **substr()** https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/String/substr e **substring()** https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/String/substring
Comment: Eu converteria para `Date` e pegaria as informações desse objeto
Answer: O seu formato de data (2022-04-29T19:56:36.327Z) é ISO 8601, sendo assim, pode utilizar a API de Date: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Date/parse.

let d = new Date("2022-04-29T19:56:36.327Z")
console.log(d.getUTCHours()+":"+d.getUTCMinutes())

Note que a sua data atual é UTC, por isso usa o getUTC*.


MatLab - como colocar um expoente no xlabel

Question: Boa tarde. Quero colocar no xlabel as unidades de m^(-1).
f=[40.82,52.63,75.80];
inversoL=[1/0.730,1/0.600,1/0.400];
coeficientes=polyfit(inversoL,f,1)
f_est=coeficientes(1).*inversoL+coeficientes(2);
plot(inversoL,f,'kd-');
hold on;
plot(inversoL,f_est, 'ro-');
title('Frequência em função do inverso do comprimento da corda','FontSize', 16);
xlabel('Inverso do comprimento da corda m^(-1)','FontSize', 16,'Color','k');

O problema é que só o parêntesis curvo é que fica em expoente, e eu queria utilizar as unidades do inverso do metro ou m^(-1). Obrigada a quem puder ajudar.
Answer: Já encontrei a solução. Fica o código igual, apenas se altera esta linha:
xlabel('Inverso do comprimento da corda m^{-1}','FontSize', 16,'Color','k');


How to calculate second -order derivative of height function?

Question: I quote a paragraph of "Morse Theory and floer homology"

The critical points of the height function on the sphere are nondegenerate.
  Indeed, in the neighborhood of the point $(0, 0, \varepsilon) \in\Bbb S^2$, we can take $(x, y)$ as
  local coordinates. Then
  $$f(x, y) = z = \varepsilon\sqrt{1 − x^2 − y^2},$$
  is a function whose second-order derivative is the quadratic form
  $$(d^2f)(0,0,\varepsilon)(x, y) = −\varepsilon(x^2 + y^2),$$
  which is indeed nondegenerate.

Question : How to calculate second -order derivative of this height function?
Answer: If $x_0$ is a critical point,  you can compute the Hessian in local coordinates as you would do with a function defined on an open set of $\mathbb{R}^n$ so $Hess (f)_{x_0} = (\frac {\partial f(x_0)}{\partial x_i \partial x_j})_{i,j}$.
In your case since $f$ is represented in local coordinates near the critical point $(0,0,\epsilon)$ as $f(x,y)= \epsilon\sqrt{1-x^2-y^2}$, you simply have to compute the partial derivatives $\frac {\partial{f}(x,y)}{\partial x_i \partial x_j}$ and evaluate them at $(x,y)=(0,0)$. You will get a diagonal matrix $diag(-\epsilon,-\epsilon)$ so the quadratic form associated is $(x,y)\mapsto -\epsilon(x^2+y^2)$.
Comment: Hello, there is something not clear that I can explain further? How can  I improve my answer?


Verify Complex Solutions of Riemann Zeta Function?

Question: I've recently been trying to visualize the Riemann Zeta complex function by graphing it on a 3D plot.
I wrote some code to compute the value of the following integral representation of the Riemann Zeta function, which should be defined in Re(Input) $\neq$ 1:
$$\zeta(s) = \frac{2^{s-1}}{s-1} -2^{s} \int_{0}^{\infty}\frac{\sin(s\arctan(x))}{(1+x^{2})^{\frac{s}{2}}(e^{\pi x}+1)}dx$$
Where s is the complex Input.
Through the use of GNUPlot's code libraries, I graphed the following:

Re(Input) - X-axis
Im(Input) - Y-axis
Re(Output) - Z-axis
Im(Output) - Color

As far as I understand, this is one of the standard ways to visualize & graph complex functions.
With this setup I'm able to generate some plots:

Plots above depicts the function on -5 < Re(Input) < 5 and -5 < Im(Input) < 5. (forgive the messed up colorbar label on the right, it appears that C++'s GNUPlot library is quite old...)

Plots above depicts the function on -30 < Re(Input) < 30 and -30 < Im(Input) < 30.
So far, so good. However, I want to be able to verify whether my code produces the correct answers for this representation of the RZ function.
I'm able to compare some of my answers to some of the known answers out there, such as any answer with Re(Input) > 1, real negative integers and discovered nontrivial zeroes, and those all appear to check out. However, apart from those, I haven't really been able to find a good way of reliably verifying the rest of my answers here. Most popular online function graphing calculators either fail to compute that integral function (such as Desmos), are unable to accept complex inputs (such as GeoGebra), or only have static plots of it (such as Wolfram).
Since I'm not a mathematician, and since I'm not aware of all the possible resources out there or methods for verifying solutions for complex functions, I wanted to ask that here.
What would be some good ways of verifying solutions to complex functions, such as the Riemann Zeta function? Is there a tool that is used when computing complex functions such as these, for verifying solutions?
Thanks for reading my post, any guidance is appreciated.
Comment: +1 (also) to your posting.  Personally, I am not knowledgeable in this area.  However, your posted question is of such high quality organization, presentation, and provided background, relative to most of the questions posted at MathSE, that it is like a breath of fresh air.
Comment: You can use [PARI/GP](http://pari.math.u-bordeaux.fr/download.html) "zeta(s): Riemann zeta function at s with s a complex or a p-adic number."
Answer: You can do it in Wolfram Alpha (or Mathematica if you have access to that). Like this, for example:
Plot3D[Re[Zeta[x+I y]],{x,-5,5},{y,-5,5}]
If you're a Python programmer, you can use the mpmath library to compute the zeta function for complex arguments.
Comment: Wow, I wasn't aware of this page on Wolfram. Guess my original posting was incorrect, you can visualize the RZ function there.

I have a quick question, is it possible to also set a custom limit to the Z-axis on the displayed plots, like you did for the X-axis and Y-axis? I tried adding a `{z,-5,5}` to the argument, but it appears to not have an effect. Is there a way to add it? Also, is there a way to download the data points in some way?
Comment: In Mathematica you can do it with `Plot3D[Re[Zeta[x+I y]],{x,-5,5},{y,-5,5},PlotRange->{-5,5}]` (and there are also lots of other options you can give to customize the plot, plus you can rotate and zoom with the mouse), but that doesn't seem to work in WA. I also doubt that you can download the data points used for making a plot, but you can generate data yourself, for example `Table[N[Re[Zeta[2+I y]]],{y,0,2,0.1}]`.
Answer: In addition to mpmath as suggested above, you should also try out Sage if you plan to do more computational stuff. There is even a online platform for you to try. Here I give a template for a 3d interactive (!) plot for $f(x, y) = |\zeta(x + iy)|$. It looks quite funny:

If you need help with translating math formulas into Python/Sage code many can help here :)
Comment: Thank you for sharing this library, I'll check it out! I tried plotting the function on an `-30,30` interval, and it appears to remain blank... not sure if it's not able to plot that, or whether I'm doing something wrong. I wrote my code in C++, and used the GNUPlot libraries to create the graphs in my posting. I actually tried this originally in Python, however the graphs were so detailed that it took AGES for Matplotlib to plot them. I guess I have to try the stuff you showed here.
Comment: @Runsva I haven't tried it myself but it's probably blank because of singularities and just exponential blow up, since the plot is linear scale by default. You can probably change it, or just throw some logs in yourself. Glad you learned something new :D
Comment: @Runsva: You're just seeing the pole at $z=1$. It will be a lot more interesting if you plot it on a larger domain.


Material UI select multiple component using an object in the value property, adds duplicate entry

Question: I have a multi select that i pass an object into the value property with the structure:

The select component looks like this:
<Select
            multiple
            value={entities}
            onChange={handleChange}
            input={<Input />}
            renderValue={(selected) => (

                {selected.map((value) => (
                  <Chip
                    key={value.entityId}
                    label={value.entityName}
                    className={classes.chip}
                  />
                ))}

            )}
          >
            {props.entityList.map((item, index) => (
              <MenuItem key={item.entityId} value={item}>
                {item.entityName}
              </MenuItem>
            ))}
          </Select>

when the select pops up it shows the entity name correct but does not show it as selected in the dropdown.
If i select this item in the drop down it adds another entry which has the same id and same name rather than removing the item that is already there, this newly added duplicate can be removed and is highlighted when selected so the functionality works somewhat.
I am storing entities in the state like so that comes in from a parent component:

Solution:
I have made sure that the same object is being used across the select, the initial object was not the same as the objects that where being assigned in the on Change function. this fixed my problem.
const [entities, setEntity] = React.useState(
props.entityList.filter((e) =>
  props.assignedEntities.some((ae) => e.entityId === ae.entityId)
)

);
Comment: Without seeing a full reproduction of your problem (particularly how `props.entityList` and `props.assignedEntities` are managed), it is difficult to recommend a solution. My suspicion is that `props.assignedEntities` has separate copies of the objects in `props.entityList` rather than reusing the exact same objects. I would recommend initializing your `entities` state using `props.entityList.filter(...)` where you filter by the assigned entity ids such that `entities` is guaranteed to reuse objects from `props.entityList`.
Comment: When using objects as the values for a `Select`, they will only be considered matching if they are the [exact same object](https://github.com/mui-org/material-ui/blob/v4.10.2/packages/material-ui/src/Select/SelectInput.js#L16). Two different objects that happen to have the same content will not be considered matching.
Comment: @RyanCogswell Awesome i understand this concept now and will defo help me going forward, i have updated my answer to include the fix, Thanks.
Comment: @RyanCogswell This makes sense, so are you saying here my props.assignedEntities is not match even.target.value. Can you recommend a solution.
Answer: I had exact problem and I solved it in the following way.
In my example I'm using role to user assignment:
Here is my role object:
Role
-----
id,
name,
access,
createdUtc

My component receives these props:
allRoles
user // that has user.roles

Here I extract only ids of the roles:
 const [selectedRoleIds, setSelectedRoleIds] = useState([]);

 useEffect(() => {
    if(user) {
      setSelectedRoleIds(user.roles.map(i => i.id));
    }

 }, [user]);

My multi select component:
<Select
    multiple
    value={selectedRoleIds}
    onChange={handleRoleChange}
    input={<OutlinedInput id="select-multiple-chip" label="Chip" />}
    renderValue={(selected) => (
    <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
        {selected.map((roleId) => (
        <Chip key={roleId} label={allRoles?.find(e => e.id === roleId).name} />
        ))}
    </Box>
    )}
    MenuProps={MenuProps}
>
    {roles.map((role) => (
    <MenuItem key={role.id} value={role.id}>
        <Checkbox checked={selectedRoleIds.includes(role.id)} />
        <ListItemText primary={role.name} />
    </MenuItem>
    ))}
</Select>

Handling role change is easy as:
  const handleRoleChange = (event) => {
    const {value} = event.target;
    setSelectedRoleIds(value);

  };

Answer: My version for this:
    import React, { useState } from 'react';
import { Select, MenuItem, InputLabel, FormControl } from '@material-ui/core';

interface Option {
  id: number;
  name: string;
}

const options: Option[] = [
  { id: 1, name: 'Option 1' },
  { id: 2, name: 'Option 2' },
  { id: 3, name: 'Option 3' },
];

const MultipleSelect: React.FC = () => {
  const [selectedOptions, setSelectedOptions] = useState<Option[]>([]);

  const handleChange = (event: React.ChangeEvent<{ value: unknown }>) => {
    const values = event.target.value as number[];
    const selected = values.map(value => options.find(option => option.id === value)!);
    setSelectedOptions(selected);
  };

  return (
    <FormControl fullWidth>
      <InputLabel id="multiple-select-label">Select</InputLabel>
      <Select
        labelId="multiple-select-label"
        id="multiple-select"
        multiple
        value={selectedOptions.map(option => option.id)}
        onChange={handleChange}
        renderValue={(selected) => (
        <Box sx={{ display: "flex", flexWrap: "wrap", gap: 0.5 }}>
          {selected.map((roleId) => (
            <Chip key={roleId} label={options.find((o) => o.id === roleId)!.name} />
          ))}
        </Box>
      )}
      >
        {options.map(option => (
          <MenuItem key={option.id} value={option.id}>
            {option.name}
          </MenuItem>
        ))}
      </Select>
    </FormControl>
  );
};

export default MultipleSelect;


Problemas com socket em C

Question: Tenho 3 functions responsáveis pela criação de um socket, envio de dados e recebimento de dados. A function sock_create cria um novo socket retornando um int desse socket, a function sock_send envia um header para o sockfd(server), e por último a function sock_recv que é responsável pelo rebimento dos dados, tem como argumento o int sockfd(criado pela function sock_create). Aqui segue segue o código e logo abaixo a questão.
<code>#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
//#include <unistd.h>
#include <string.h>

char *DEFAULT_GET = "GET /index.html HTTP/1.1\r\nHost:
www.example.com\r\n\r\n";

void sock_send(int, char *);
char* sock_post(int, char *);
char* sock_recv(int, int);
int sock_create(char*);
char* getline();

int main()
{
    char url[200];
    memset(url, 0, sizeof url);
    printf("Enter URL: \n");
    scanf("%s", url);
    url[strlen(url)] = 0;
    printf("%s\n", url);
    int sockfd = sock_create(url);
    printf("socket created\n");

    while (1)
    {
        printf("send a request: \n");
        char header[200];
        memset(header, 0, 200);
       //scanf("%s", header);
        sock_send(sockfd, DEFAULT_GET);
        char *resp = sock_recv(sockfd, 2048);

        printf("%s\n", resp);
    }

    return 0;
}

void sock_send(int sockfd, char *header)
{
    send(sockfd,header,strlen(header),0);
    printf("sock_send: sockfd[%d], header[]\n", sockfd);
}

char* sock_recv(int sockfd, int buf_bytes)
{
    char buf[buf_bytes];
    int byte_count = recv(sockfd, buf, sizeof(buf) - 1, 0);
    buf[byte_count] = 0;

    printf("sock_recv: count[%d]\n", byte_count);

    return buf;
}

char* sock_post(int sock, char *post_header)
{

}

int sock_create(char *url)
{
    struct addrinfo hints, *res;

    memset(&hints, 0,sizeof hints);

    hints.ai_family=AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    getaddrinfo(url,"80", &hints, &res);
    int sockfd = socket(res->ai_family,res->ai_socktype,res-
  >ai_protocol);

    connect(sockfd,res->ai_addr,res->ai_addrlen);
    printf("sock created\n");

    return sockfd;
}
</code>
Quando executo o código recebo uma mensagem: You have stoped jobs, que acredito que seja o mesmo que segmentation fault. Enfim, não sei por quê desse erro.
Answer: Você deve definir tudo corretamente no prototipo:
<code>void sock_send(int sockfd, char * header);
char* sock_post(int sockfd, char * post_header);
char* sock_recv(int sockfd, int  buf_bytes);
int sock_create(char*);
</code>
Este foi o erro que estava causando problemas! (Testei aqui, compilei e funcionou certinho)
.
Pronto, espero espero ter ajudado!

Problemas com socket em C


Problema com JS/JQuery/JSON/AJAX

Question: Estou com alguns problemas com JSON na minha aplicação e queria ver se vocês podem me ajudar, por favor.
A situação é a seguinte:
Tenho um método no meu controller que busca alguns itens:
@RequestMapping(value = "/buscaTodosCardapios", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public String buscaTodosCardapios(Usuario usuario, Model model){
    JSONObject retorno = new JSONObject();
    try{
        retorno.put("data", cardapioRepository.findBySubmenuIsNull());
    }catch (Exception ex){
        retorno.put("situacao", "ERRO");
        retorno.put("mensagem", "Falha ao iniciar produção!");
    }
    return retorno.toString();
}

Um arquivo JS que pega esses itens:
function buscaTodosCardapios(){
$.ajax({
    url: "buscaTodosCardapios",
    type: 'GET',
    dataType: 'json',
    cache: false,
    success: updateCardapios
});
}

function updateCardapios(data){
    console.log(data);
    console.log(data.cardapioId);
}

Retorna tudo OK:

Só que, como podem ver, o segundo console.log, não retorna nada e eu não consigo fazer ele pegar algum elemento de dentro do data. Alguém pode me ajudar com isso?
-EDIT-
Solução para quem precisar, foi só mudar para:
console.log(data.data[0].cardapioId);

Comment: Marque uma resposta se você encontrou a solução, para mais informações veja [tour]
Answer: você esta retornando um array.
Use Isto
console.log(data.data[0].cardapioId);

Comment: Retorna o seguinte erro: Uncaught TypeError: Cannot read property 'cardapioId' of undefined
Comment: Exato Alterei agora para isto tente assim
Comment: Um pouco antes de abrir aqui, acabei testando desta forma e funcionou, de qualquer forma, muito obrigado!
Comment: Quando uma resposta conter a solução da sua pergunta, aceite ela como resposta não edite sua pergunta para isso
Answer: Como você está trazendo um array de objetos,
para conseguir acesso, terá que ser:
console.log(data.data[0].atributo);

Comment: Já tentei assim e me retorna o seguinte erro: Uncaught TypeError: Cannot read property 'cardapioId' of undefined
Comment: de um console.log(data[0]) e mostre o que aparece.
Comment: Deu tudo certo por aqui, já editei o post. Obrigado por tentar ajudar!
Answer: Olá, quando vc utiliza na anotação @RequestMapping a instrução produces={"application/json"}
você não precisa anotar com @RespondeBody. Você também não precisa que o retorno seja do tipo string, pode retornar diretamente o objeto e o Spring vai transforma-lo no formato json.

Problema com JS/JQuery/JSON/AJAX


p-Value from Z-ratio

Question: I have run an Interrupted Time Series Analysis based upon the below code:
glm(`Subject Total` ~ Quarter + int2 + time_since_intervention2 ,
     df, family = "poisson")

I have used the emmeans package to estimate the pairwise difference between the counterfactual and point estimate and get the below output:
contrast                                                                              estimate    SE  df z.ratio p.value
  Quarter20 int21 time_since_intervention24 - Quarter20 int20 time_since_intervention20   -0.341 0.160 Inf  -2.140  0.1406

The above estimate (0.341) cross-checks against manually derived outcomes. However I had a question about the p-value included within the above output and the manually derived equivalent [undertaken as a means of checking]. The p-value in the above is 0.146 [non-significant]. However, when calculated directly from the z-ratio (2*pnorm(-2.140)) I get a p-value of 0.03. Is the emmeans output correct (am I doing something wrong by assuming pnorm?) or is the manually calculated more likely to be accurate?
UPDATE:
The data frame is as below. Quarters represent time. Subject Total the outcome. Int2 a dummy variable to identify the point of intervention (0 pre/1 post). Time_since_intervention2 another dummy variable 0 prior to intervention 1:8 after.
> df[,c(1,2,9,11)]
   Quarter Subject Total int2 time_since_intervention2
1        1            33    0                        0
2        2            32    0                        0
3        3            35    0                        0
4        4            34    0                        0
5        5            23    0                        0
6        6            34    0                        0
7        7            33    0                        0
8        8            24    0                        0
9        9            31    0                        0
10      10            32    0                        0
11      11            21    0                        0
12      12            26    0                        0
13      13            22    0                        0
14      14            28    0                        0
15      15            27    0                        0
16      16            22    0                        0
17      17            14    1                        1
18      18            16    1                        2
19      19            20    1                        3
20      20            19    1                        4
21      21            13    1                        5
22      22            15    1                        6
23      23            16    1                        7
24      24             8    1                        8

Call:
glm(formula = `Subject Total` ~ Quarter + int2 + time_since_intervention2,
    family = "poisson", data = df)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-1.4769  -0.5111   0.1240   0.6103   0.9128

Coefficients:
                         Estimate Std. Error z value            Pr(>|z|)
(Intercept)               3.54584    0.09396  37.737 <0.0000000000000002 ***
Quarter                  -0.02348    0.01018  -2.306              0.0211 *
int2                     -0.23652    0.21356  -1.108              0.2681
time_since_intervention2 -0.02624    0.04112  -0.638              0.5234
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for poisson family taken to be 1)

    Null deviance: 63.602  on 23  degrees of freedom
Residual deviance: 13.368  on 20  degrees of freedom
AIC: 140.54

Number of Fisher Scoring iterations: 4

The above suggests that the level change at the intervention point was non-significant.
We want to report the difference between the point estimate at Quarter 20 with the corresponding counterfactual (extrapolation of pre-policy trends/patterns) at the same point. At the moment I have done that using emmeans pairwise comparison.
emmeans(
   object = fit1a,
  specs = c("Quarter", "int2", "time_since_intervention2"),
  at = list(
    Quarter = c(20),
    int2 = c(0, 1),
    time_since_intervention2 = c(0,4)
  )
) |>
  contrast(method = "revpairwise")

 contrast(method = "revpairwise")
 contrast                                                                              estimate    SE  df
 Quarter20 int21 time_since_intervention20 - Quarter20 int20 time_since_intervention20   -0.237 0.214 Inf
 Quarter20 int20 time_since_intervention24 - Quarter20 int20 time_since_intervention20   -0.105 0.164 Inf
 Quarter20 int20 time_since_intervention24 - Quarter20 int21 time_since_intervention20    0.132 0.346 Inf
 Quarter20 int21 time_since_intervention24 - Quarter20 int20 time_since_intervention20   -0.341 0.160 Inf
 Quarter20 int21 time_since_intervention24 - Quarter20 int21 time_since_intervention20   -0.105 0.164 Inf
 Quarter20 int21 time_since_intervention24 - Quarter20 int20 time_since_intervention24   -0.237 0.214 Inf
 z.ratio p.value
  -1.108  0.6849
  -0.638  0.9197
   0.380  0.9813
  -2.140  0.1406
  -0.638  0.9197
  -1.108  0.6849

The only outcome that can exist is Quarter20 int21 time_since_intervention24 - Quarter20 int20 time_since_intervention20.
Not sure I'm doing this the right way.
Comment: Can you provide a reproducible example, or show us the output of `summary(coef(model))` and `emmeans(model, ...)`? That would help us understand the problem better ... e.g. can you illustrate with `g1 <- glm(round(mpg) ~ factor(cyl) + vs + am, data = mtcars, family = poisson); library(emmeans); coef(summary(g1)); pairs(emmeans(g1, ~factor(cyl))` ... ?
Comment: @BenBolker I've updated with additional code. Thanks for your help
Answer: In general, since emmeans is a widely used package you should probably assume that whatever computation it's doing is being done correctly: the danger is that it might not be doing what you want, or you might not understand what it's doing (or both). The most obvious thing that occurs to me is that computing pairwise contrasts automatically invokes a multiple-comparisons correction. From the vignette:

In its out-of-the-box configuration, pairs() sets two defaults for summary(): adjust = "tukey" (multiplicity adjustment), and infer = c(FALSE, TRUE) (test statistics, not confidence intervals). You may override these, of course, by calling summary() on the result with different values for these.

So if the contrast you're showing us is one of several pairwise contrasts, the p-value will be larger than that computed from a single Z-statistic (google provides lots of good hits for "tukey pairwise contrasts correction" , I wasn't sure which one to pick).
Comment: Thanks Ben. TBH I'm not sure whether I want to go with the Tuckey adjusted or not. Both Int2 and time_since_intervention2 are dummy variable.

p-Value from Z-ratio


como fazer passagem por valor em JavaScript

Question: Tenho a seguint situação:
let a=[{nome:"oi"},{nome:"xau"}]
let b=Object.assign([], a)

b[0].nome=5

console.log(b) //[{nome:5},{nome:xau}]
console.log(a) //[{nome:5},{nome:xau}]

a pouco tempo atras perguntei aqui como passar valores sem ser por referencia, me falaram para usar o Object.assing, mas ainda assim nao esta dando certo, alguem pode me ajudar como faria para alterar o b[0].nome sem alterar o a?
Comment: Já tentou utilizar a mesma estrutura de `a`, no primeiro parâmetro de ´assign´?
Comment: tipo Object.assign([{}],a)? isso eu ja tentei e nao funcionou
Answer: O método assign faz uma cópia rasa, ou seja, copia os valores de atributos que são do objeto, mas o que for referência ele copia o valor da referência. No seu exemplo a contém duas referências e por isso não está funcionando.
A sugestão que eu achei que poderia ajudar seria usar:
var b = JSON.parse(JSON.stringify(a))

Answer: Uma solução é serializar o objeto e deserializar em um novo usando JSON, assim:
let b=JSON.parse(JSON.stringify(a))

let a=[{nome:"oi"},{nome:"xau"}]
let b=JSON.parse(JSON.stringify(a))

b[0].nome=5

console.log(b[0]) //[{nome:5},{nome:xau}]
console.log(a[0]) //[{nome:5},{nome:xau}]

EDIT: @Everson apontou sobre explicar melhor a razão de serializar/deserializar:
O serializar transforma objeto em stream, no caso uma string JSON, o que irá "quebrar" a referência com o objeto original, e o deserializar transforma novamente em objeto, que a referência, criando um novo objeto
Comment: Coloque na resposta, por gentileza.
Comment: O serializar transforma objeto em stream, no caso uma string `JSON`, o que irá "quebrar" a referência com o objeto original, e o deserializar transforma novamente em objeto, que a referência, criando um novo objeto
Comment: Feito @Everson obrigado
Answer: O que você precisa é fazer uma Deep copy.
Diferente da Shallow copy ou cópia rasa(explicada na resposta do prmottajr), você precisa de uma cópia que seja criada sem qualquer referência aos dados originais, que seja aplicável para os arrays do objeto por exemplo.
Solução criando um método:
(método que criará um novo objeto e copiará as propriedades para esse objeto)

var a=[{nome:"oi"},{nome:"xau"}]
var b = Clonar(a);

b[0].nome=5;

console.log(a, b);

function Clonar(source) {
    if (Object.prototype.toString.call(source) === '[object Array]') {
        var clone = [];
        for (var i=0; i<source.length; i++) {
            clone[i] = Clonar(source[i]);
        }
        return clone;
    } else if (typeof(source)=="object") {
        var clone = {};
        for (var prop in source) {
            if (source.hasOwnProperty(prop)) {
                clone[prop] = Clonar(source[prop]);
            }
        }
        return clone;
    } else {
        return source;
    }
}

Solução com Jquery:

var a=[{nome:"oi"},{nome:"xau"}]
var b = jQuery.extend(true, {}, a);

b[0].nome=5;
console.log(a, b);

Assim como já foi citado em outras respostas.
Solução serializando e deserializando:

let a=[{nome:"oi"},{nome:"xau"}]
let b=JSON.parse(JSON.stringify(a))

b[0].nome=5

console.log(a,b)

Fontes:

What is the most efficient way to deep clone an object in
JavaScript?
JavaScript: How to pass object by value?


jKit paginate automating the page change

Question: I have this example: http://jsfiddle.net/bwk43/4/
I have been looking for a while for a method of turning a table into a pages like so but I am still struggling to find something that can automate the page change every 10 minutes or so.
I am using this in a TV display for some information from a database and it needs to change automatically as the display its on is somewhat like a board for flight times in a airport so no keyboard and mouse will be attached.
The only events I can see for this plugin are triggered when pages load so not sure how to tie these in with the initial load.
Any help would be appreciated.
<code>Plugin Source:
http://jquery-jkit.com/commands/paginate.html
</code>
Answer: Well it adds an li list at the bottom so you can just call click on them
<code>(function(){
    var waitTime = 1000*60*10;
    function showPage() {
        var lis = $(".jkit-pagination").find("li");  //get the lis
        var next = lis.filter(".active").next();     //find the next li after the active one
        if (!next.length) next = lis.eq(0);          //if it is the last li, switch to first
        next.click();                                //click it
        window.setTimeout(showPage,waitTime);      //set timer to do it all over again
    }
    window.setTimeout(showPage,waitTime);          //wait for initial page to have its time
})();
</code>
Comment: Many many thanks for that speedy response I was thinking along those lines but I need to work on my skills with JS/Jquery :(
Comment: Quite funny I removed this code from my app around a year ago and only just realized it was missing and had to re-add it and tried to up vote this answer without realizing this was my own question.


What's in a name: bias (intercept)

Question: In linear regression,  $y = w_0 + w_1x_1 + w_2x_2 + \cdots$. The intercept term is called 'bias'. Why is it called bias? And how is this different from the 'bias-variance' trade-off?
Comment: It's not called that, you may be thinking of neural networks where they use "bias" and "weights". In linear regression it's called intercept or constant. Bias-variance trade-off is a property of the model as a whole with all of it's components, how good the model is at generalization, while the intercept is just one component of the model (unless your linear model has only the intercept term in which case it is the whole model) and may have only a small effect on the model as a whole.
Comment: I think Murphey's is a fairly rare and odd use of "bias". You should not take this as a general terminology.
Comment: It is. Check 'Machine Learning: A Probabilistic Perspective" by Murphey. page 20.
Comment: One (of many) issues with machine learning is the habit of using existing statistical words to mean something else.  If you follow through the book, you will find *bias* first used in terms of unbalanced coins, and then in the "expected error of estimator" sense for  example in (6.33) - this is where bias-variance trade off comes in - and only in the sense you quote in the later half of the book  for the constant or intercept term.
Comment: @RichardHardy That's been pretty much standard use of "bias" in the Machine Learning community. See e.g. Bishop, p. 138, or "Notation" in Cristianini and Shawe-Taylor. It developed historically; see my answer here: https://stats.stackexchange.com/a/511862/169343
Comment: @Henry One (of many) issues with humans is their habit of believing that the way they do it is the right way, and every other way wrong. Bloody, "holy" wars have been fought for that reason. The word *bias* was not invented by statisticians and is several centuries older. Statisticians have no copyright on it. Its usage in Machine Learning developed independently from statistics and derives its meaning from electronics. After all, Machine Learning is about *machines*.
Comment: @IgorF., that is a cool piece of history!
Answer: Bias is a general term and can have different meanings.

In statistics the term is used to describe a systematic error in an estimation method. It relates to splitting up error in accuracy and precision, and bias is the lack of precision.

Bias is also used in relation to activation functions in neural networks. In that case it is the intercept as in your question. It is a term that changes how easily a particular node will 'activate' in response to the input values.

Why is it called bias?

You could say that the intercept is a term that makes the node biased to give a low/high value as response to certain input.

And how is this different from the 'bias-variance' trade-off?

Bias is a word used in different places.
In the list of uses of 'bias' above, the second use of bias has nothing to do with the bias in the bias-variance tradeoff which relates to the first use of bias.
Comment: And, as a further application of the second meaning, *bias* is also used in Support Vector Machines, with the same purpose.

What's in a name: bias (intercept)


Cauchy-Schwarz Inequality

Question: I have to show the following is equivalent to the Cauchy-Schwarz Inequality:
$$\left( \sum (r_i +s_i )^2 \right)^{\frac {1}{2}} \leq \left( \sum r_i ^2 \right)^{\frac {1}{2}}  + \left( \sum s_i ^2 \right)^{\frac {1}{2}}$$
The Cauchy-Schwarz Inequality is defined as :
$$ \left( \sum {(r_i s_i)} \right)^2 \leq  \left( \sum{r_i}^2 \right)\left( \sum{s_i}^2 \right) $$
My Attempt:
Since both sides are non-negative we can square both sides.
$$ \sum (r_i +s_i )^2 \leq \sum {r_i ^2}  +2 \left( \sum r_i ^2 \right)^{\frac {1}{2}}\left( \sum s_i ^2 \right)^{\frac {1}{2}} +  \sum s_i ^2  $$
Expanding the left-hand side.
$$ \sum (r_i^2 + 2r_is_i + s_i^2 )\leq \sum {r_i ^2}  +2 \left( \sum r_i ^2 \right)^{\frac {1}{2}}\left( \sum s_i ^2 \right)^{\frac {1}{2}} +  \sum s_i ^2  $$
Using identities of Summation.
$$ \sum r_i^2 + 2\sum {(r_i s_i)} + \sum s_i^2 \leq \sum {r_i ^2}  +2 \left( \sum r_i ^2 \right)^{\frac {1}{2}}\left( \sum s_i ^2 \right)^{\frac {1}{2}} +  \sum s_i ^2  $$
Cancelling like terms
$$
 \require{cancel}
\cancel  {\sum r_i^2} + 2\sum {(r_i s_i)} + \cancel{\sum s_i^2} \leq \cancel{\sum {r_i ^2}}  +2 \left( \sum r_i ^2 \right)^{\frac {1}{2}}\left( \sum s_i ^2 \right)^{\frac {1}{2}} +  \cancel{\sum s_i ^2}
$$
We obtain the following:
$$ 2\sum {(r_i s_i)}  \leq  2 \left( \sum r_i ^2 \right)^{\frac {1}{2}}\left( \sum s_i ^2 \right)^{\frac {1}{2}}
$$
Dividing by 2:
$$ \sum {(r_i s_i)}  \leq   \left( \sum r_i ^2 \right)^{\frac {1}{2}}\left( \sum s_i ^2 \right)^{\frac {1}{2}}
$$
It is at this point that I am stuck. Does squaring both sides preserve the inequality at this point?
Thanks in advance.
Comment: But then you already have it! Just square both sides in your last line and it is exactly what you cal CS inequality. And yes: squaring preseves the inequality. The other way around can be false, though.
Comment: If that is negative then the inequality is trivially true, and otherwise you can square. The other way around is not generally true, as  $\;a^2=b^2\implies a=\pm b\;$ , so equality or inequality cannot be assured.
Comment: Just check it: $\;2^2=4=(-2)^2\;$ , yet $\;2\neq-2\;$, or $\;(-3)^2>2^2\;$ , but $\;(-3)\rlap{\;\,/}>2\;$
Comment: Perhaps you should write what you call Cauchy Schwarz inequality to.
Comment: The Cauchy-Schwarz Inequality is $\left(  \sum (r_i s_i) \right)^2  \leq \left( \sum r_i^2 \right) \left( \sum s_i^2 \right)$
Comment: @Joanpemo Fixed
Comment: @Joanpemo I think you misunderstood.  I was referring  to "If that is negative then the inequality is trivially true" . If $\sum{r_i s_i}$ <0 then how is $ \left(  \sum (r_i s_i) \right)^2  \leq \left( \sum r_i^2 \right) \left( \sum s_i^2 \right)$?
Answer:
Does squaring both sides preserve the inequality at this point?

In a word, "yes":
$$
\sum(r_{i} s_{i})
  \leq \left|\sum(r_{i} s_{i})\right|
  \leq \left(\sum r_{i}^{2}\right)^{1/2} \left(\sum s_{i}^{2}\right)^{1/2},
$$
with the second inequality being the square root of "your" Cauchy-Schwarz inequality.

As a stylistic point, two-column proofs are a (less-than-optimal) habit from school courses that should generally be outgrown if you aspire to be a mathematician. In published work, mathematicians instead build chains of equalities and inequalities. Here, for example, you might argue that "your" C-S inequality implies the "new" one like this:
\begin{align*}
\sum (r_{i} + s_{i})^{2}
  &= \sum r_{i}^{2} + 2 \sum (r_{i}s_{i}) + \sum s_{i}^{2} \\
  &\leq \sum r_{i}^{2} + 2 \left|\sum (r_{i}s_{i})\right| + \sum s_{i}^{2} \\
  &\leq \sum r_{i}^{2} + 2 \left(\sum r_{i}^{2}\right)^{1/2} \left(\sum s_{i}^{2}\right)^{1/2} + \sum s_{i}^{2} \\
  &= \left[\left(\sum r_{i}^{2}\right)^{1/2} + \left(\sum s_{i}^{2}\right)^{1/2}\right]^{2}.
\end{align*}
Comment: The four-step inequality in my answer is (omitting square roots) a proof of one direction. :)
Comment: By "two-column proof" I mean an argument that starts from one (in)equality and proceeds (as in your question) by performing operations to both sides, arriving at a conclusion. (Or worse, that starts with the desired conclusion and arrives at a tautology. Many "proofs" that $0 = 1$ have this form.) In published papers and most textbooks, you'll find (in)equalities are proven by starting on one side and building a succession of equalities (or "$\leq$"s) leading to the other side. [...]
Comment: I didn't mean to criticize your existing argument, incidentally, but _am_ pointing out that (i) chains of (in)equalities are generally preferable, and (ii) in this case can be made fairly short (e.g., four steps). :)
Comment: I don't mind criticism. I would love to "hear" how one prove that two inequality without the use of the "two-column proof". Would it be simply dealing with the LHS and RHS one at a time?

Cauchy-Schwarz Inequality


mysql SQL statement doesn't work C#

Question: I have been trying to make this code block work, but I can't seem to find the error in it. It doesn't return the value that I am looking for. I would try to run the SQL statement in workbench and it returns my desired number of rows(which is 3).
        try
        {
            using (MySqlConnection con = new MySqlConnection(GlobalValues.ConnectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand())
                {
                    cmd.CommandText =
                        @"
                            SELECT strDetPremID, strPremiseName
                                    FROM tbldetailprem
                                    INNER JOIN tblpremise ON strDetPremID = strPremiseID
                                    WHERE strDetPremContID = @id;
                            ;
                            "
                        ;

                    cmd.Parameters.AddWithValue("@id", id);
                    cmd.Connection = con;
                    using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
                    {
                        con.Open();
                        cmd.ExecuteNonQuery();
                        this.Clear();
                        da.Fill(this);
                        con.Close();
                    }
                }
            }
        }
        catch (MySqlException ex)
        {
            MessageBox.Show(ex.ToString() + " - " + ex.Number);
        }

Can you please tell me what's wrong with this code
Comment: Your running a select statement, and calling for 2 values (strDetPremID and strPremiseName) and you're expecting a int back? How is that statement only returning `3`? You're also not affecting any rows by selecting.
Comment: A select statement is a query, but you use `ExecuteNonQuery`.  Also it's not clear what part of that query should give you a result of only 3.
Comment: What kind of application is this?  Typically what I do is execute a datareader, then assign the variable based on the datareader's property.  Your SQL is a `SELECT` statement, so why are you doing `ExecuteNonQuery`?
Comment: @kalamazoowho - It appears to be an instance of `MySqlDataAdapter`.
Answer: When you want to count the number of rows, use the following query:
SELECT COUNT(*) FROM tbldetailprem
INNER JOIN tblpremise ON strDetPremID = strPremiseID
WHERE strDetPremContID = @id;

Then use the ExecuteScalar() method on the command object to get the value of COUNT(*).
The ExecuteNonQuery() is used for adding, updating and deleting records, not for selecting them.
More information can be found here:
https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-sql-command.html
Answer: This may serve more as a comment but I lack the rep to comment.
It's not exactly clear, to me, in the code where the issue may be coming from so my assumption is that there's a bug that's not being caught as a MySQLException.
Have you tried removing the try/catch statement in order to catch any bugs that would prevent affectedRows being updated?
Also, I'm not sure if it's causing a SyntaxError or not but it seems you have an extra semicolon in cmd.CommandText... I think.

mysql SQL statement doesn't work C#


Interrupted time series analysis of data with deterministic trend and seasonality

Question: I am trying to evaluate the impact of an intervention on a selected outcome variable using interrupted time series data. I have aggregated a five-year data into monthly values to create a data-set 0f 60 time periods.
I have checked for serial correlation, normality, trend, and seasonality using Durbin-Watson test, Augmented Dickey-Fuller test, acf and pacf plots of the preliminary OLS model, ad.test, MannKendall test, kpps test, seasdum tests, etc and found the data to be non-serially correlated and normally distributed.
However, since there are deterministic trend and seasonality, as confirmed by MnnKendall and seasdum tests, I cannot consider it to be stationary. The auto.arima function in R also suggests to take ARIMA(0,1,1) model with first order differencing.
 I do not want to make predictions using ARIMA models. I want to fit appropraite regression model to determine the impact of the intervention on the selected outcome. A linear regression model is not appropriate for non-stationary data and corCLASSES of the generalized least square function of R does not include ARIMA models; it includes only corARMA (p,q).
How can I examine the effect of the intervention?
I have setup the data for interrupted time series analysis as follows:

outcome variable- is continuous that is to be evaluated for change in level and trend following the intervention

Trend is set up to estimate the change in  trend following the intervention
Time- Time (in months) (1-24- pre-intervention, 25-60- post-intervention)
Intervention- dichotomous variable to estimate the change in level on the outcome variable following the intervention (0- pre-intervention; 1- post-intervention)
nur- continuous, independent variable that we thought might contribute to the changes in the outcome variable

Here is the data:
outcome:
22.07110439
18.90095847
18.91359773
19.20793651
20.88607595
18.20779221
19.15797788
21.25701625
20.88034188
21.86503067
24.01552795
19.9045045
18.5278174
18.46753247
20.83765348
17.94267516
18.60979463
19.90101892
16.67349927
17.83104396
18.35260116
17.97080292
17.26436782
18.6896
21.21225071
19.06471495
17.41436464
16.96333333
16.82025678
18.2585034
19.05191257
15.92080537
17.07025411
16.67902996
17.398017
17.45731707
17.47838617
17.12740741
15.23802612
16.64904552
16.50793651
20.46721311
15.08291457
17.80658436
14.71666667
16.48233861
15.48533724
13.4244898
16.81895504
14.59757739
13.5566879
14.08549223
13.14965035
13.53341289
15.83421751
13.20208605
16.10674157
16.70136986
14.79861111
14.95229983
Trend:-
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

Intervention:
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1

Time:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

Nur:
0.571666667
0.57
0.571666667
0.586666667
0.591666667
0.591666667
0.565
0.568333333
0.566666667
0.58
0.571666667
0.57
0.563333333
0.561666667
0.561666667
0.613333333
0.615
0.623333333
0.606666667
0.613333333
0.611666667
0.611666667
0.615
0.611666667
0.625
0.611666667
0.623333333
0.706666667
0.72
0.73
0.716666667
0.715
0.72
0.715
0.71
0.703333333
0.703333333
0.701666667
0.693333333
0.781666667
0.79
0.781666667
0.788333333
0.778333333
0.775
0.775
0.776666667
0.781666667
0.781666667
0.773333333
0.781666667
0.851666667
0.846666667
0.853333333
0.838333333
0.84
0.826666667
0.825
0.825
0.815

Answer: My answer to you is in two parts. In the first part I set up AUTOBOX to estimate the model that you have pre=specified.  The 60x4 DATA MATRIX is partially shown here
My approach is to simply estimate your model and report the results. You are assuming two intervention variables , one a step and the other a deterministic time trend. The problem with this is that your are not forming the intervention variables analytically ... apparently to eye-balled the original plot of the outcome series and divined the two deterministic predictors . Here is the plot of the Y series called "LIKKA-outcome"
I estimated your model and did not perform any tests of significance for stepping down NOR did I examine the residuals for purposes of model augmentation. Although you stated that you were not interested in forecasting , the pattern of the forecasts speaks volumes about the model and it's adequacy. In addition the residual plot tells a lot about the sufficiency of the assumed model.
Here is the Actual/Fit and Forecast for the model you specified.

The plot of the residuals (clearly non-random )
The acf of the residuals showing no evidence of structure ( due to the untreated anomalies ! )

The model ( presented twice )
  and
The user-specified two intervention.deterministic  series are not-significant while the NUR SERIES ) the user-suggested stochastic series is significant. In summary your two guesses at the form of the latent deterministic structure are of no value.
SECOND ANALYSIS (using AUTOBOX's expert system):
Now I took your data set using the LIKKA-Outcome (Y) series and the user-suggested stochastic input series (MUR) . . I employed the standard paradigm  http://www.autobox.com/pdfs/A.pdf to identify/form/revise a Transfer Function Model and obtained the following model
 and here   with acf here
Note that a seasonal ar(12) was found along with a sophisticated memory model for the MUR series along with 2 downwards level shifts and a seasonal pulse at period 25 and 4 one-time anomalies. Following is the Actual and CLeansed graph
The Actual/Fit and Forecast plot is here  . The plot of the residuals is here
The available r stuff doesn't meet your needs BUT there is an R VERSION of the software that I used (AUTOBOX) which does.
Comment: Thank you for your clear and detailed explanation and analysis.