text:
Q: Ruby add value to json array I have this json code:
{
  "kind": "something",
  "rules": [
    {
      "rule1": [
        "something1",
        "something2",
        "something3"
      ],
      "rule2": "something"
    }
  ]
}

I want to add something4 to rule1. How can I do this in Ruby?
thanks

A: Let json_string be your JSON string
require 'json'

h = JSON.parse(json_string)
h["rules"][0]["rule1"] << "something4"

A: Your Nesting Structure Uses Keys and Indexes
Your problem is that your JSON is really poorly-designed for finding specific keys, because the various rules are actually wrapped inside an array. In your example, you only have one, but if you have more array elements then you've got to find the right array element to modify. It can be done with a lot of work via Enumerable#each_with_index or a related method, but if you are confident of the structure of your JSON you can take a shortcut.
require 'json'

json = <<~'EOF'
  {
    "kind": "something",
    "rules": [
      {
        "rule1": [
          "something1",
          "something2",
          "something3"
        ],
        "rule2": "something"
      }
    ]
  }
EOF

# Get the first array from "rules", and append the string
# to the array inside the hash value referenced by the
# "rule1" key.
hash['rules'].first['rule1'] << 'something4'

puts JSON.pretty_generate(hash)

{
 "kind": "something",
 "rules": [
   {
     "rule1": [
       "something1",
       "something2",
       "something3",
       "something4"
     ],
     "rule2": "something"
   }
 ]
}

In the real world, you'd likely have to iterate over the rules array to find the index of the array element you want to modify. After that, you can find the rule1 key and append the value you want to the value's hash.

A: Saying that you assign that code to a variable
settings = {
  "kind": "something",
  "rules": [
    {
      "rule1": [
        "something1",
        "something2",
        "something3"
      ],
      "rule2": "something"
    }
  ]
}

you can do this:
settings["rules"][0]["rule1"] << "test"


text:
Q: Bitmap size exceed VM budget while using gallery and imageviews I am trying to implement the code written under "Imageswitcher View" on this link
http://mobiforge.com/designing/story/understanding-user-interface-android-part-3-more-views
When I click first Image it enlarges but on clicking the second image the code crashes but if I start from the second image it does not crash .
Logcat says
08-08 22:15:08.655: E/AndroidRuntime(1349): FATAL EXCEPTION: main
08-08 22:15:08.655: E/AndroidRuntime(1349): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.graphics.Bitmap.nativeCreate(Native Method)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.graphics.Bitmap.createBitmap(Bitmap.java:477)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.graphics.Bitmap.createBitmap(Bitmap.java:444)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:349)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.graphics.BitmapFactory.finishDecode(BitmapFactory.java:498)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:473)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:336)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:697)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.content.res.Resources.loadDrawable(Resources.java:1709)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.content.res.Resources.getDrawable(Resources.java:581)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.widget.ImageView.resolveUri(ImageView.java:501)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.widget.ImageView.setImageResource(ImageView.java:280)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at com.k.TestingActivity$1.onItemClick(TestingActivity.java:47)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.widget.AdapterView.performItemClick(AdapterView.java:284)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.widget.Gallery.onSingleTapUp(Gallery.java:867)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.view.GestureDetector.onTouchEvent(GestureDetector.java:557)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.widget.Gallery.onTouchEvent(Gallery.java:842)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.view.View.dispatchTouchEvent(View.java:3885)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:903)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1691)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1125)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.app.Activity.dispatchTouchEvent(Activity.java:2096)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1675)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.view.ViewRoot.deliverPointerEvent(ViewRoot.java:2194)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1878)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.os.Looper.loop(Looper.java:123)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at android.app.ActivityThread.main(ActivityThread.java:3683)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at java.lang.reflect.Method.invokeNative(Native Method)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at java.lang.reflect.Method.invoke(Method.java:507)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-08 22:15:08.655: E/AndroidRuntime(1349):     at dalvik.system.NativeStart.main(Native Method)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Language Server Provider - Get Line Break Type I'm trying to get the line break type (CRLF or LF) of the client document, but can't find any reference to it in the docs. I need something like this in the server.ts file:
function validateTextDocument(textDocument) {
    return __awaiter(this, void 0, void 0, function* () {
        if (textDocument.lineBreak === "\n") {
            // ...
        }
    })
}

This is the last piece of information I need to finish my extension, can you please shed a light on this?
Thank you!

A: I missed the obvious, the solution has nothing to do with LSP, you can find it here: Detecting type of line breaks


text:
Q: Is the process name always the name of the exe? I need to know whether a process is already running but I don't want to hardcode its name. I'd rather derive it from the *.exe so I performed some experiments and created a simple console application where I set the assembly name in project properties to foo and then renamed the foo.exe to bar.exe. I checked the running processes and indeed it was bar that was running.
Is it by design and I can rely on this behavior or can a process have a different name from the exe and does it apply to all kinds of exe files or only to .NET assemblies?

A: You can't change the image name of the process. That is set by Windows and not changeable. It will use the name of the executable to set it, so it is safe to use.
Instead of using the process to get the executable name, you could simply use the assembly name from .NET:
System.AppDomain.CurrentDomain.FriendlyName


text:
Q: Is "agree" an ordinary transitive verb?
We choose evidence that everyone can agree shows him being out of touch with reality.

Is this sentence grammatically correct? To me it only sounds correct when it's modified to

We choose evidence that everyone can agree that it shows him being out of touch with reality.

Is the meaning still same with the bolded words omitted?

A: The different usages of agree are complicated. The Cambridge Dictionary gives four senses/subsenses for the verb, saying that three of them may be either intransitive or transitive. But there is only one transitive example (unless one extends 'transitivity' to include taking a clause as object) provided:

agree verb [ I or T ]
(2) to decide something together:
They agreed not to tell anyone about what had happened.
We couldn't agree on what to buy.
UK We finally agreed a deal.

M-W has 'to settle on by common consent' for this usage. One speaks of 'agreeing terms / a date / a ceasefire / a price ...'.
.....................
However, the sense of 'agree' in the question here is 'give mental assent'.
Breaking the sentence down into simpler ones, in either order we have:

Everyone can agree that the evidence we choose shows him being out of touch
  with reality.
We choose this evidence. [With this purpose.]

Note that the 'that' here is the complementiser, not the relative pronoun appearing in the original sentence (substituting 'which' there would make things clearer).
Combining without making deletions:

We choose evidence which is of such a nature that everyone can agree
  that it shows him being out of touch with reality.

So we retain the 'agree that' colligation. However, deletion reduces in a single step to

We choose evidence which everyone can agree
  shows him being out of touch with reality.

The second variant suggested is ungrammatical.


text:
Q: count of items from another table for each row in table I have a list of user-profiles when I have this query. I want to retrieve nr of followers for each (every) user, but I only get one row result from query (there are a lot of users)
$this->db->select('up.name, up.id, up.image, up.name_id, up.created, COUNT(followers.user_id) as followed_by_count');
$this->db->join('user_profiles up', 'u.id = up.user_id', 'left');
$this->db->join('followers', 'up.user_id = followers.user_id', 'left');

//Something like this? (It doesn't work)
//$this->db->group_by('COUNT(followers.user_id) as followed_by_count');
//When tried this I get:
//"You have an error in your SQL syntax; check the manual that corresponds to your
//MySQL server version for the right syntax to use near 'as followed_by_count"

$this->db->order_by('up.created', 'DESC');

I guess I should use group by in some way? The query works when not using followers-table. It also works when not using group_by but I obviously don't get the count(s) I want then.

A: Change
$this->db->group_by('COUNT(followers.user_id) as followed_by_count');

To
$this->db->group_by('u.id');

Note : This code given as per your given code and assume that your code is syntactically right.


text:
Q: playing with ip route to connect to VPN and lost local internet I'm following this tutorial about openVPN, every goes good until this following step on client (just before autostart section from wiki):
# ip route add VPNSERVER_IP via LOCALGATEWAY_IP dev eth0  proto static
# ip route change default via 10.9.8.5 dev tun0  proto static   //client tun0 10.9.8.5

I'm losing internet after 2nd line.
And I really want to have internet thru VPN server.
those tips can help me:

*

*how to roll back with ip route ?

*how to configure my client with graphical interface (kubuntu) ?

A: how to roll back with ip route ?

In order to show the routing cache, you can use the following command:
ip route show cache

You can clear the cache by issuing the following one:
ip route flush cache

or e.g.
route del -net 10.66.66.66/24

for seperate rules.

As far as OpenVPN is concerned, the only routing setting I had to do was the following one (note: i used iptables to do so):
iptables -t nat -A POSTROUTING -s 10.66.66.0/24 -o eth0 -j SNAT --to xxx.xx.xxx.xxx

Where xxx.xx.xxx.xxx would be the static (public) IP address of your server and 10.66.66.0 would be the virtual network between all VPN connected machines. You should replace these with your own values.

I hope this already helps you in finding a solution. If you've further questions just let me know in a comment.


text:
Q: Custom SQL response (JOIN TABLE) I have two tables, table1 and table2
I want to link the two tables with the id, by grouping the information in one and the same answer.
table1:
╔════╦══════════════╦
║ id ║  product_id  ║
╠════╬══════════════╬
║  1 ║      123     ║
║  2 ║      456     ║
║  3 ║      789     ║
╚════╩══════════════╩

table2:
╔════╦══════════════╦══════════════╦
║ id ║    status    ║     date     ║
╠════╬══════════════╬══════════════╬
║  1 ║   received   ║    02/20     ║
║  1 ║   shipped    ║    03/20     ║
║  2 ║   received   ║    04/20     ║
║  2 ║   shipped    ║    05/20     ║
║  3 ║   received   ║    06/20     ║
║  3 ║   shipped    ║    07/20     ║
╚════╩══════════════╩══════════════╩

I want this output:
╔════╦══════════════╦══════════════╦══════════════╦
║ id ║    r_date    ║   s_date     ║  product_id  ║
╠════╬══════════════╬══════════════╬══════════════╬
║  1 ║     02/20    ║    03/20     ║     123      ║
║  2 ║     04/20    ║    05/20     ║     456      ║
║  3 ║     06/20    ║    07/20     ║     789      ║
╚════╩══════════════╩══════════════╩══════════════╩

How Can i have this result ?

A: You can do conditional aggregation to pivot table2 over table1:
select
    t1.id,
    max(case when t2.status = 'received' then t2.date end) r_date,
    max(case when t2.status = 'shipped' then t2.date end) s_date,
    t1.product_id
from table1 t1
inner join table2 t2 on t.id = t2.id
group by t1.id, t2.product_id
order by t1.id

A: You can use two LEFT JOINs, as in:
select
  a.id,
  r.date as r_date,
  s.date as s_date,
  a.product_id
from table1 a
left join table2 r on r.id = a.id and r.status = 'received'
left join table2 s on s.id = a.id and s.status = 'shipped'


text:
Q: Testing a before filter in rails controller I seem to be stuck. I am trying to shore up some rspec testing and want to make sure the the correct before_filter methods are getting called for controllers. However, I am getting feedback saying the method never gets called.
The error:
Failure/Error: expect(controller).to receive(:authorize)
   (#<UsersController:0x007fca2fd27110>).authorize(*(any args))
       expected: 1 time with any arguments
       received: 0 times with any arguments

The spec:
require "rails_helper"

RSpec.describe UsersController, :type => :controller do
  let(:school){ FactoryGirl.create :school }
  let(:user){ FactoryGirl.create :teacher}
  before(:each){
    allow(controller).to receive(:current_user).and_return(user)
    school.teachers << user
  }

  context "Get #show" do
    before(:each){ get :show, school_id: school.id, id: user.id }
    it "responds successfully with an HTTP 200 status code" do
      expect(controller).to receive(:authorize)
      expect(response).to have_http_status(200)
    end

    it "renders the show template" do
      expect(response).to render_template("show")
    end
  end
end

The controller:
class UsersController < ApplicationController
  before_filter :authorize

  def show
    @user = User.find_by_id params[:id]
    @school = @user.school
    @coordinators = @school.coordinators
    @teachers = @school.teachers
    @speducators = @school.speducators
    @students = @school.students
  end
end

Manual testing shows that before is being called, and when I put a p in the authorize method it is called when I run the test, any thoughts on where the test is going wrong?

A: You must set method expectation before actual call, so your test should look like:
context "Get #show" do
  subject { get :show, school_id: school.id, id: user.id }

  it "calls +authorize+ befor action" do
    expect(controller).to receive(:authorize)
    subject
  end
end

Check the documentation https://github.com/rspec/rspec-mocks#message-expectations


text:
Q: Find the distribution of numbers of arrivals of the Poisson process $N(t)$ in time interval $[t, t+\tau)$, $\tau \sim Exp(a)$. Poisson process has rate $\lambda$ and $\tau \perp \!\!\! \perp  N(t)$.
To find distribution i've started with $P(N(t+\tau)-N(t)=k) = P(N(\tau) = k)$. I know that $N(t) \sim Poiss(\lambda t)$, but i don't know what to do next to find distribution.

A: Hint: use the formula
$$ P(N(\tau) = k) = \int_0^\infty P(N(s)=k|\tau = s) ae^{-as}\, ds.$$


text:
Q: Are rational polynomials a product of linear and quadratic factors? Is this statement true? I'm not quite sure...

In the polynomial ring ℚ[X], every non-constant polynomial can be written as a product of polynomials of degree ≤ 2.

A: Hint Try to write $X^3-2$ as a product of such polynomials.

A: Alternative hint:
Try to write $X^4+1$ as a product of such polynomials.


text:
Q: Get element that doesn't have a specific id - jQuery This is pretty simple ... but I just can't get it to work. This is what I m doing.

Click1

Click2

If I click Click1 pickID will be idOne, but I don't know how to get the idTwo. What s the syntax for getting the id from the element with class myClass that doesn't have the id  pickID ?
$(".myClass").click(function(e) {
    e.preventDefault;

    var pickID = $(this).attr('id');
    var notPickId = $('myClass').attr(not(pickID));// ??? this is probably so wrong ... I didn't even try it

});

A: Try
var notPickId = $('.myClass').not(this).attr('id');

or
var notPickID = $('.myclass').not('#' + pickID).attr('id');

or
var notPickId = $(this).parent().siblings().find('a').attr('id');

this keyword
.not()

A: Try this:
var notPickID = $(".myclass:not(#" + pickID + ")");

A: another way
var pickID = $(this).attr('id');
$(".myClass[id!='" + pickID  + "']").attr("id")


text:
Q: How to just output value in context.write(k,v) In my mapreduce job, I just want to output some lines.
But if I code like this:
    context.write(data, null);
the program will throw java.lang.NullPointerException.
I don't want to code like below:
    context.write(data, new Text(""));
because I have to trim the blank space in every line in the output files.
Is there any good ways to solve it?
Thanks in advance.

Sorry, it's my mistake. I checked the program carefully, found the reason is I set the Reducer as combiner.
If I do not use the combiner, the statement
    context.write(data, null);
in reducer works fine. In the output data file, there is just the data line.

Share the NullWritable explanation from hadoop definitive guide:
NullWritable is a special type of Writable, as it has a zero-length serialization. No bytes
are written to, or read from, the stream. It is used as a placeholder; for example, in
MapReduce, a key or a value can be declared as a NullWritable when you don't need
to use that position—it effectively stores a constant empty value. NullWritable can also
be useful as a key in SequenceFile when you want to store a list of values, as opposed
to key-value pairs. It is an immutable singleton: the instance can be retrieved by calling
NullWritable.get().

A: You should use NullWritable for this purpose.


text:
Q: What's the connection between $\theta$ series and the number of integer solutions on a curve? Proof Verification I just started learning about theta series and am now flexing my muscles. I hope that everything looks good. This is a request for a proof verification. I am asking for what the proper name in the literature would be for $\mu$ defined below.
For a variable $q$ with an absolute value less than 1 we can define the absolutely convergent series.
$$\mu_b(q)=\sum_{k\in\mathbb{Z}}{q^{|k|^b}} $$
This is a generalization of $\theta_3(q)=\mu_2(q)$. This would be equation $(33)$ in the link above. I am not sure what $\mu_b$ is referred to as in the literature. I suspect there is a better expression for this.
Let $\vec{a}, \vec{b}$ be tuples of $m$ positive integers $(a_1,\dots, a_m), (b_1,\dots,b_m)$ respectively. And we let $\phi_{\vec{a}}(n)$ denote the number of integer solutions to $$\sum_{i=1}^m a_i |x_i|^{b_i}=n$$.
Claim
$$\sum_{n=0}^\infty \phi_\vec{a}(n)q^n=\prod_{i=1}^m{\mu_{b_i}(q^{a_i})}$$
Proof
Starting with the RHS we need to expand the product of $m$ different doubly infinite series. We can think of this product as an $m$-dimensional array where we need to sum over $\mathbb{Z^m}$. We arrive at
$$\sum_{\vec{x}\in \mathbb{Z^m}}q^{\sum{a_i|x_i|^{b_i}}}$$
But then we need to traverse this summation somehow. For each $n\in \mathbb{N}$ we will collect the $\phi_\vec{a}(n)$ instances where $\sum_{i=1}^m a_i |x_i|^{b_i}=n$, so we arrive at the LHS.
Honestly, I think that's all that must be said for the proof but I will write it out like this:
$$\prod_{i=1}^m{\mu_{b_i}(q^{a_i})}= \prod_{i=1}^m{\sum_{k\in\mathbb{Z}}{q^{a_i|k|^{b_i}}}} = \sum_{\vec{x}\in \mathbb{Z^m}}q^{\sum{a_i|x_i|^{b_i}}}=\sum_{n=0}^\infty\sum_{\sum{a_i|x_i|^{b_i}}=n}{q^{\sum{a_i|x_i|^{b_i}}}}=\sum_{n=0}^\infty{ \phi_\vec{a}(n)q^{n}}$$
Equality 1) Definition of $\mu_{b}$
Equality 2) Multiplying $m$ doubly infinite series will give us an $m$ dimensional array. Also we use $q^Aq^B=q^{A+B}$
Equality 3) The plan for traversing this infinite sum is to start at the middle of the array and work outward. We need to be confident that we hit every single $\vec{x}\in \mathbb{Z^m}$ but this is really the same as asking if for every $\vec{x} \in \mathbb{Z^m}$ there is some $n\in \mathbb{N}$ such that $\sum_{i=1}^m a_i |x_i|^{b_i}=n$. But this boils down to closure of the natural numbers under $+$ and $\times$.
Equality 4) This is the definition of $\phi_\vec{a}(n)$.
$\square$
Questions.
1) Does everything look ok?
2) Is there a better name for $\mu_b$?
Comments/Consequence of the proof above.
If you ever spent your afternoon pondering why this OEIS sequence is entitled "Coefficients in expansion of $\theta_3(q) \times \theta_3(q^{15})$ in powers of $q$." even though it's much more intuitive to think of it as the number of integer solutions to $x^2+15y^2=n$ then you should know: Those are the same thing.
Motivations
I wrote this first and then realized I could generalize.

A: To address your questions and comments. First, your equating of the sum and product is standard and there are very many examples similar to it. Second, there is no standard name for $\, \mu_b \,$ that I know of. In the case that $\,b\,$ is odd, there is a complication that requires the use of $\, |k|^b \,$ instead of $\, k^b \,$ for convergence reasons.
For example, if $\, b=1 \,$ then $\, \sum_{k\in \mathbb{Z}} q^k \,$ is never convergent.
However, $\, \mu_1(q) = (1+q) / (1-q) \,$ if $\, |q|<1. \,$ It is usually unnatural
 to ask for the number of integer solutions to, for one example,
 $\, |x| + 2|y| + 3|z| = |n| \,$ although this is
 OEIS sequence A053799.
As for the OEIS sequence A260671 which you mentioned, it is
just one of many similar sequences that are the coeffcients of functions expressed in
terms of Elliptic amd related functions. Some of them have negative coefficients and because
of this have no direct interpretation as enumerating solutions of Diophantine equations.
In those cases where the coefficients are non-negative often no such interpretation is known to the author of the sequence, or else they forgot to mention it.
I do agree that if an interpretation of a sequence in terms of solutions to Diophanthine equations is known, then it should be entered in OEIS eventually. Thanks to your question, I have just entered another such interpretation for
OEIS sequence A028625 which is directly related to my A260671.


text:
Q: parse HTML using DOMDocument in PHP I want to use DOMDocument to parse sting came from Rich-Text-Editor, exactly what I need are:
1) Allow only (div, p, span, b, ul, ol, li, blockquotem br) tags, remove others tags with its content
Edit:
I'm using strip_tags() for this
2) allow only these styles:

*

*style="font-weight:bold"

*style="font-style: italic"

*style="text-decoration: underline"

3) remove any attributes in the allowed tags like class, id ...etc except align attribute only
any ideas ?

A: I would recommend against trying to filter HTML input using DOMDocument for security reasons, in particular, due to the risk of cross-site scripting. You can easily take care of your requirements in 1 and 3 with a filter library like HTML Purifier. For the reasons Spudley mentions, number 2 is a little more difficult. I'd start by whitelisting those style attributes in HTML Purifier and then using some logic to scan for them after filtering, adding the appropriate tags inside that element.
Here's an example for using HTML Purifier how you want (taken from basic.php). The only things I've changed are the HTML.AllowedAttributes and HTML.AllowedElements settings.
<?php
// replace this with the path to the HTML Purifier library
require_once 'library/HTMLPurifier.auto.php';

$config = HTMLPurifier_Config::createDefault();

// configuration goes here:
$config->set('Core.Encoding', 'UTF-8'); // replace with your encoding
$config->set('HTML.Doctype', 'XHTML 1.0 Transitional'); // replace with your doctype
$config->set('HTML.AllowedAttributes', '*.style, align');
$config->set('HTML.AllowedElements', 'div, p, span, b, ul, ol, li, blockquote, br');
$config->set('CSS.AllowedProperties', 'font-weight, font-style, text-decoration');

$purifier = new HTMLPurifier($config);

$html = '
Allowed
  ';

$filteredHtml = $purifier->purify($html);
echo '
' . htmlspecialchars($filteredHtml) . '
';

Which outputs:

Allowed
,

A: Since you only want to allow a small number of HTML elements, you could consider cleaning up the HTML code with the PHP strip_tags() function prior to giving it to the DOMDocument classes.
This will certainly be easier than parsing the DOM yourself to find elements than need to be stripped.
That should deal with part 1 of your question.
It won't deal with parts 2 or 3, but it's a good start.

A: I have a code exactly to do this but its rather undocumented and uses some code I do not own but in public domain. Its pretty easy to use and it ensures all tags are closed so they do not affect your code, use fix_html function for that. It can also limit use of tags and attributes strip_tags_attributes for this, also use strip_javascript to remove javascript functionality of any sort. I used this extensively but to be honest I do not know if this one is from production. For your second answer, I guess its best to remove styles all together so they can use  or  as they like. And please dont let anyone to use underline.
function findNodeValue($parent, $node) {
    $nodes=array();
    if(!is_a($parent, "DOMElement")) return NULL;

    foreach($parent->childNodes as $child)
        if($child->nodeName==$node) $nodes[]=$child;

    if(count($nodes)==0) return NULL;
    if(count($nodes)==1) return $nodes[0]->nodeValue;
    else {
        $ret=array();
        foreach($nodes as $node)
            $ret[]=$node->nodeValue;

        return $ret;
    }
}

function strip_javascript($filter){

    // realign javascript href to onclick
    $filter = preg_replace("/href=(['\"]).*?javascript:(.*)?\\1/i", "onclick=' $2 '", $filter);

    //remove javascript from tags
    while( preg_match("/<(.*)?javascript.*?\(.*?((?>[^()]+)|(?R)).*?\)?\)(.*)?>/i", $filter))
        $filter = preg_replace("/<(.*)?javascript.*?\(.*?((?>[^()]+)|(?R)).*?\)?\)(.*)?>/i", "<$1$3$4$5>", $filter);

    // dump expressions from contibuted content
    $filter = preg_replace("/:expression\(.*?((?>[^(.*?)]+)|(?R)).*?\)\)/i", "", $filter);
    $filter = preg_replace("//", "", $filter);
    $filter = preg_replace("/<\/iframe>/", "", $filter);

    while( preg_match("/<(.*)?:expr.*?\(.*?((?>[^()]+)|(?R)).*?\)?\)(.*)?>/i", $filter))
        $filter = preg_replace("/<(.*)?:expr.*?\(.*?((?>[^()]+)|(?R)).*?\)?\)(.*)?>/i", "<$1$3$4$5>", $filter);

    // remove all on* events
    while( preg_match("/<(.*)?\s?on[^>\s]+?=\s?.+?(['\"]).*?\\2\s?(.*)?>/i", $filter, $match) ) {
        $filter = preg_replace("/<(.*)?\s?on[^>\s]+?=\s?.+?(['\"]).*?\\2\s?(.*)?>/i", "<$1$3>", $filter);
    }

    return $filter;
}

function html2a ( $html ) {
  ini_set('pcre.backtrack_limit', 10000);
  ini_set('pcre.recursion_limit', 10000);

  if ( !preg_match_all( '@\<\s*?(\w+)((?:\b(?:\'[^\']*\'|"[^"]*"|[^\>])*)?)\>((?:(?>[^\<]*)|(?R))*)\<\/\s*?\\1(?:\b[^\>]*)?\>|\<\s*(\w+)(\b(?:\'[^\']*\'|"[^"]*"|[^\>])*)?\/?\>@uxis', $html = trim($html), $m, PREG_OFFSET_CAPTURE | PREG_SET_ORDER) )
    return $html;
  $i = 0;
  $ret = array();
  foreach ($m as $set) {
    if ( strlen( $val = trim( substr($html, $i, $set[0][1] - $i) ) ) )
      $ret[] = $val;
    $val = $set[1][1] < 0
      ? array( 'tag' => strtolower($set[4][0]) )
      : array( 'tag' => strtolower($set[1][0]), 'val' => html2a($set[3][0]) );
    if ( preg_match_all( '/(\w+)\s*(?:=\s*(?:"([^"]*)"|\'([^\']*)\'|(\w+)))?/usix', isset($set[5]) && $set[2][1] < 0 ? $set[5][0] : $set[2][0],$attrs, PREG_SET_ORDER ) ) {
      foreach ($attrs as $a) {
        $val['attr'][$a[1]]=$a[count($a)-1];
      }
    }
    $ret[] = $val;
    $i = $set[0][1]+strlen( $set[0][0] );
  }
  $l = strlen($html);
  if ( $i < $l )
    if ( strlen( $val = trim( substr( $html, $i, $l - $i ) ) ) )
      $ret[] = $val;
  return $ret;
}

function a2html ( $a, $in = "" ) {
  if ( is_array($a) ) {
    $s = "";
    foreach ($a as $t)
      if ( is_array($t) ) {
        $attrs="";
        if ( isset($t['attr']) )
          foreach( $t['attr'] as $k => $v )
            $attrs.=" ${k}=".( strpos( $v, '"' )!==false ? "'$v'" : "\"$v\"" );
        $s.= $in."<".$t['tag'].$attrs.( isset( $t['val'] ) ? ">\n".a2html( $t['val'], $in).$in."</".$t['tag'] : "/" ).">";
      } else
        $s.= $in.$t."";
  } else {
    $s = empty($a) ? "" : $in.$a."";
  }
  return $s;
}

function remove_unclosed(&$a, $allowunclosed) {
    if(!is_array($a)) return;

    foreach($a as $k=>$tag) {
        if(is_array($tag)) {
            if(!isset($tag["val"]) && !in_array($tag["tag"],$allowunclosed)) {
                //var_dump($tag["tag"]);
                unset($a[$k]);
            } elseif(is_array(@$tag["val"]))
                remove_unclosed($a[$k]["val"], $allowunclosed);
        }
    }
}

function fix_html($html, $allowunclosed=array("br")) {
    $a = html2a($html);
    remove_unclosed($a, $allowunclosed);
    return a2html($a);
}

function strip_tags_ex($str,$allowtags) {
    $strs=explode('<',$str);
    $res=$strs[0];
    for($i=1;$i<count($strs);$i++)
    {
        if(!strpos($strs[$i],'>'))
            $res = $res.'<'.$strs[$i];
        else
            $res = $res.'<'.$strs[$i];
    }
    return strip_tags($res,$allowtags);
}

function strip_tags_attributes($string,$allowtags=allowedtags,$allowattributes=allowedattributes){
    $string=strip_javascript($string);

    $string = strip_tags_ex($string,$allowtags);

    if (!is_null($allowattributes)) {
        if(!is_array($allowattributes))
            $allowattributes = explode(",",$allowattributes);
        if(is_array($allowattributes))
            $allowattributes = implode(")(?<!",$allowattributes);
        if (strlen($allowattributes) > 0)
            $allowattributes = "(?<!".$allowattributes.")";
        $string = preg_replace_callback("/<[^>]*>/i",create_function(
            '$matches',
            'return preg_replace("/ [^ =]*'.$allowattributes.'=(\"[^\"]*\"|\'[^\']*\')/i", "", $matches[0]);'
        ),$string);
    }
    return $string;
}

I found the source for strip_javascript http://www.php.net/manual/en/function.strip-tags.php#89453 I don't know why its not there in the code already. Probably because no name, no email no identity to refer.

A: $allowedTags = array( 'div' => true, 'p' => true, 'span' => true, 'b' => true,
    'ul' => true, 'ol' => true, 'li' => true, 'blockquot' => true, 'em' => true, 'br' => true );

$allowedStyles = array( 'font-weight: bold' => true, 'font-style: italic' => true, 'text-decoration: underline' => true );

$allowedAttribs = array( 'align' => true );

$doc = new DOMDocument();
$doc->loadXML( '<doc>
test
 asdfasd faksd</doc>' );

sanitizeNodeChildren( $doc->documentElement );

echo htmlentities( $doc->saveXml() );

function sanitizeNodeChildren( $parentNode ) {
    $node = $parentNode->firstChild;
    while( $node ) {
        if( !sanitizeNode( $node ) ) {
            $nodeToDelete = $node;
            $node = $node->nextSibling;
            $parentNode->removeChild( $nodeToDelete );
        } else {
            sanitizeNodeChildren( $node );
            $node = $node->nextSibling;
        }
    }
}

function sanitizeNode( $node ) {
    global $allowedTags, $allowedStyles, $allowedAttribs;
    if( $node->nodeType == XML_ELEMENT_NODE ) {
        if( !isset( $allowedTags[ $node->tagName ] ) ) return false;

        foreach( $node->attributes as $name => $attrNode ) {
            if( $name == 'style' ) {
                if( isset( $allowedStyles[ $attrNode->nodeValue ] ) ) continue;
            }
            if( isset( $allowedAttribs[ $name ] ) ) continue;
            $node->removeAttribute( $name );
        }
    }

    return true;
}


text:
Q: Uncaught (in promise) TypeError: _firebase__WEBPACK_IMPORTED_MODULE_0__.db.firestore is not a function I installed version 9 of FireBase on React 18, I did all the settings correctly, but I do not know why I can not solve the problem no matter what I do, can you help me?
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
    apiKey: x,
    authDomain: x,
    projectId: x,
    storageBucket: x,
    messagingSenderId: x,
    appId: x
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
export { db };


text:
Q: How can I typeset long integral borders? I currently would like to typeset an integral with long integral borders. But either I get too much space after the integral sign and before the function I integrate, or I get a wrong alignment of the border:

How can I typeset long integral borders?
MWE
\documentclass[a5paper]{scrartcl}
\usepackage{amssymb, amsmath} % needed for math
\usepackage[utf8]{inputenc} % this is needed for umlauts
\usepackage[ngerman]{babel} % this is needed for umlauts
\usepackage[T1]{fontenc}    % this is needed for correct output of umlauts in pdf
\usepackage{mathtools}
\begin{document}
\section*{With mathclap}
\begin{align*}
\int_S f \mathrm{d} A &= \sum_{i=1}^n \int_{\mathclap{V_i}} f \mathrm{d} A \\
&- \sum_{i \neq j} \int_{\mathclap{V_i \cap V_j}} f \mathrm{d} A \\
&+ \sum_{i,j,k} \int_{\mathclap{V_i \cap V_j \cap V_k}} f \mathrm{d} A\\
&- \dots
\end{align*}

\section*{Without mathclap}
\begin{align*}
\int_S f \mathrm{d} A &= \sum_{i=1}^n \int_{V_i} f \mathrm{d} A \\
&- \sum_{i \neq j} \int_{V_i \cap V_j} f \mathrm{d} A \\
&+ \sum_{i,j,k} \int_{V_i \cap V_j \cap V_k} f \mathrm{d} A\\
&- \dots
\end{align*}
\end{document}

A: \mathrlap{…} could do the job.
\documentclass[a5paper]{scrartcl}
\usepackage{amssymb, amsmath} % needed for math
\usepackage[utf8]{inputenc} % this is needed for umlauts
\usepackage[ngerman]{babel} % this is needed for umlauts
\usepackage[T1]{fontenc}    % this is needed for correct output of umlauts in pdf
\usepackage{mathtools}
\begin{document}
\section*{With mathrlap}
\begin{align*}
\int_S f \mathrm{d} A &= \sum_{i=1}^n \int_{\mathrlap{V_i}} f \mathrm{d} A \\
&- \sum_{i \neq j} \int_{\mathrlap{V_i \cap V_j}} f \mathrm{d} A \\
&+ \sum_{i,j,k} \int_{\mathrlap{V_i \cap V_j \cap V_k}} f \mathrm{d} A\\
&- \dots
\end{align*}

\section*{Without mathrlap}
\begin{align*}
\int_S f \mathrm{d} A &= \sum_{i=1}^n \int_{V_i} f \mathrm{d} A \\
&- \sum_{i \neq j} \int_{V_i \cap V_j} f \mathrm{d} A \\
&+ \sum_{i,j,k} \int_{V_i \cap V_j \cap V_k} f \mathrm{d} A\\
&- \dots
\end{align*}
\end{document}

A: Some hand tuning is necessary, with formulas like these.
\documentclass[a5paper]{scrartcl}
\usepackage{amsmath} % needed for math

\newcommand{\diff}{\mathop{}\!\mathrm{d}}
\newcommand{\back}[1]{\mspace{-#1mu}}

\begin{document}

\begin{align*}
\int_S f \diff A
&      = \sum_{i=1}^n    \; \int\limits_{V_i} f \diff A \\
&\quad - \sum_{i \neq j} \; \int\limits_{V_i \cap V_j}          \back{6} f \diff A \\
&\quad + \sum_{i,j,k}    \; \int\limits_{V_i \cap V_j \cap V_k} \back{12} f \diff A\\
&\quad - \dotsb
\end{align*}
\end{document}

With \back you get some back spacing. The integration domain should be below the integral sign.
Don't use explicit \mathrm{d} for the differential (and don't use an upright "d", but this is another matter), prefer a high level command. The one I propose automatically takes care of a thin space before the "d".

A: \documentclass[a5paper]{scrartcl}
\usepackage{amssymb, amsmath} % needed for math
\usepackage[utf8]{inputenc} % this is needed for umlauts
\usepackage[ngerman]{babel} % this is needed for umlauts
\usepackage[T1]{fontenc}    % this is needed for correct output of umlauts in pdf
\usepackage{mathtools}
\usepackage{stackengine}
\stackMath
\begin{document}

\section*{With stacks}
\begin{align*}
\int_S f \mathrm{d} A &= \sum_{i=1}^n \stackunder{%
  \displaystyle\int}{\scriptstyle V_i} f \mathrm{d} A \\
&- \sum_{i \neq j} \def\stackalignment{l}\addstackgap{\stackunder{%
  \displaystyle\int}{\rlap{$\scriptstyle V_i \cap V_j$}}} f \mathrm{d} A \\
&- \sum_{i ,j,k} \def\stackalignment{l}\addstackgap{\stackunder{%
  \displaystyle\int}{\rlap{$\scriptstyle V_i \cap V_j\cap V_k$}}} f \mathrm{d} A \\
&- \dots
\end{align*}
\end{document}

EDITED to provide more vertical gap between equations.


text:
Q: VSCode Run Launch configuration via Tasks.json I currently have a tasks.json that runs 3 tasks together, grouped in a panel on folder startup:
tasks.json
{
"version": "2.0.0",
"tasks": [
  {
    "label": "Run dev",
    "type": "shell",
    "command": "npm run dev",
    "presentation": {
      "reveal": "always",
      "panel": "new",
      "group": "develop",
    },
    "runOptions": { "runOn": "folderOpen" }
  },
  {
    "label": "Run css",
    "type": "shell",
    "command": "npm run watch:css",
    "presentation": {
      "reveal": "always",
      "panel": "new",
      "group": "develop",
    },
    "runOptions": { "runOn": "folderOpen" }
  },
  {
    "label": "Run tunnel",
    "type": "shell",
    "command": "npm run tunnel",
    "presentation": {
      "reveal": "always",
      "panel": "new",
      "group": "develop",
    },
    "runOptions": { "runOn": "folderOpen" }
  },
  {
    "label": "Start Dev",
    "dependsOn": [
      "Run dev",
      "Run css",
      "Run tunnel"
    ],
    "problemMatcher": []
  }
]
}

What i'm looking to do is move Run dev to a launch configuration instead so I have debugging enabled by default, and keep the same terminal experience:
launch.json
{
"configurations": [
{
    "name": "Run npm run dev",
    "command": "npm run dev",
    "request": "launch",
    "type": "node-terminal",
    "cwd": "${workspaceFolder}",
    "console": "internalConsole",
    "serverReadyAction": {
        "pattern": "started at http://localhost:([0-9]+)",
        "uriFormat": "http://localhost:%s",
        "action": "openExternally"
    }
}
]
}

So the end result will be the same 3 tasks, but "Run dev" triggers the "Run npm run dev" launch configuration in it's terminal window
The problem is there doesn't seem to be a way to do this?


text:
Q: how to display data in format using javascript extract from mysql? This is what i get to render data in view when I extract from the database as well as when "Exception" comes i want to show in new line.  But I want to display them in proper manner in single sring
The requirements of this chapter apply to the following: (1) New buildings or portions thereof used as health care occupancies (see 1.4.1) (2) Additions made to, or used as, a health care occupancy (see 4.6.6 and 18.1.1.4) Exception: The requirement of 18.1.1.1.1 shall not apply to additions classified as occupancies other than health care that are separated from the health care occupancy in accordance with 18.1.2.1(2) and conform to the requirements for the specific occupancy in accordance with Chapters 12 through 17 and Chapters 20 through 42, as appropriate.(3) Alterations, modernizations, or renovations of existing health care occupancies (see 4.6.7 and 18.1.1.4) (4) Existing buildings or portions thereof upon change of occupancy to a health care occupancy (see 4.6.11) Exception*: Facilities where the authority having jurisdiction has determined equivalent safety has been provided in accordance with Section 1.5.

I want to display this in the following order in dynamically
The requirements of this chapter apply to the following:
(1) New buildings or portions thereof used as health care occupancies (see 1.4.1)

 (2) Additions made to, or used as, a health care occupancy (see 4.6.6 and 18.1.1.4)

Exception: The requirement of 18.1.1.1.1 shall not apply to additions classified as occupancies other than health care that are separated from the health care occupancy in accordance with 18.1.2.1(2) and conform to the requirements for the specific occupancy in accordance with Chapters 12 through 17 and Chapters 20 through 42, as appropriate.

(3) Alterations, modernizations, or renovations of existing health care occupancies (see 4.6.7 and 18.1.1.4)

(4) Existing buildings or portions thereof upon change of occupancy to a health care occupancy (see 4.6.11) Exception*: Facilities where the authority having jurisdiction has determined equivalent safety has been provided in accordance with Section 1.5.

While I am doing this in javascript. Where I get this content in section_data.title. How can I manage to this.

A: I have a feeling that your line breaks aren't in html. Try using str_replace('\n', '<br>', $queryResultString); in your PHP before writing encoding it as JSON (replacing $queryResultString with whatever strings you're sending through JSON).
Let me know if this works, or we can try something else.

A: Use JavaScript method "String[] split(String regex)" to split the string according to regular expression and store in array.Then you can add breakline tags to format it.


text:
Q: plt.yticks not working properly - matplotlib I'm working on a project in unity and from a C# script I'm calling a Python script to plot some values on a graph using matplotlib, everything works fine except for the yticks on the graph.
The values that are going to be plotted are floats within 0.5 and 5.5 circa, here is the graph for reference:

what I've done to set the yticks is the following:
plt.plot(x,y)
plt.yticks([0, 2, 4, 5])
plt.xlabel("frame")
plt.ylabel("distance")
plt.show()

As you can see instead of having ticks in the specified positions [0, 2, 4, 5] it displays 4 ticks all around 0.5. It looks like no matter what array I pass to yticks(), it only takes the len() of it and puts the exact number of ticks but in the wrong places, i guess the first n-th values of y axis
Python version: 3.8.8, Matplotlib version: 3.4.1
Many thanks to anyone who will help.
EDIT: minimal reproducible example.
The image above is generated using 600 values, in the example below only 50 values are used so the graph is different but the ytick problem remains.
import matplotlib.pyplot as plt

y = ['0.5356', '0.5356', '0.5615', '0.5509', '0.4958', '0.4944', '0.5056', '0.5512', '0.6314',
     '0.7394', '0.8761', '1.0320', '1.2066', '1.3692', '1.5456', '1.7262', '1.9124', '2.0955',
     '2.2262', '2.2424', '2.2363', '2.2285', '2.1811', '2.1159', '2.0400', '1.9590', '1.8685',
     '1.7614', '1.6517', '1.5322', '1.3897', '1.2642', '1.1080', '0.9256', '0.8161', '0.6624',
     '0.5240', '0.3763', '0.2361', '0.1649', '0.2151', '0.3441', '0.5065', '0.6785', '0.8355',
     '1.0118', '1.1708', '1.3253', '1.4888', '1.6247']
x = [i for i in range(1, 51)]

# plotting
plt.plot(x,y)
plt.yticks([0, 2, 4, 5])
plt.xlabel("frame")
plt.ylabel("distance")
plt.show()

graph should be like this:

A: Ok i'm an idiot.
As usual it was the stupidest thing i could have ever done.
values are not floats but strings.

A: You could explicitly set the tick frequency like this :
import matplotlib.pyplot as plt

y = ['0.5356', '0.5356', '0.5615', '0.5509', '0.4958', '0.4944', '0.5056', '0.5512', '0.6314',
     '0.7394', '0.8761', '1.0320', '1.2066', '1.3692', '1.5456', '1.7262', '1.9124', '2.0955',
     '2.2262', '2.2424', '2.2363', '2.2285', '2.1811', '2.1159', '2.0400', '1.9590', '1.8685',
     '1.7614', '1.6517', '1.5322', '1.3897', '1.2642', '1.1080', '0.9256', '0.8161', '0.6624',
     '0.5240', '0.3763', '0.2361', '0.1649', '0.2151', '0.3441', '0.5065', '0.6785', '0.8355',
     '1.0118', '1.1708', '1.3253', '1.4888', '1.6247']
y = [float(i) for i in y]
x = [i for i in range(1, 51)]

# plotting
plt.plot(x,y)
plt.yticks(np.arange(min(y), max(y)+1, 1.0))
plt.xlabel("frame")
plt.ylabel("distance")
plt.show()


text:
Q: Hide/Unhide sheets using username I just want to ask if it's possible to create a VBA that detects the identity of the person opening the workbook using Environ$("username") and using that I can hide some of the worksheet and unhide other worksheet that only that person can see?. Then if another person opens up the same workbook it will then hide/unhide worksheets for that other person.

A: Example of what you want (for educational purposes only):
Private Sub Workbook_Open()

Select Case Environ("username")
    Case "bloggsj"
        Sheets(1).Visible = False
        Sheets(2).Visible = True
    Case "doej", "murphyp", "manm"
        Sheets(2).Visible = True
        Sheets(1).Visible = False
    Case Else
        '// Unknown, close workbook
        ThisWorkbook.Close False
End Select

End Sub

Important: As already mentioned in the comments, this is not a secure way of protecting data, two quick reasons as an example:

*

*The Environment variable "username" can easily be changed which would trick the code into thinking that the person is a different user.

*The Workbook_Open event can be easily bypassed by holding the shift button when opening the file.


text:
Q: How to solve the warning message about "But a callback is not registered (anymore) to process this response" in WSO2 ESB I called HTTP endpoint and get correct response.
But I don't know why the warning message as below in EI log.
How can I do to solve this warning? Thank you.
Synapse received a response for the request with message Id : urn:uuid:f1d3d901-322e-4ac2-ad28-5c4fd3c97aa5 But a callback is not registered (anymore) to process this response

A: I noticed that I was getting these errors on latency between the executing WSO2 EI thread and certain clients (mainly IIS hosted sites)
After approx 120 seconds after receiving the expected response, the client would send a TCP RST, ACT command back to WSO2.  This seems to cause the SynapseCallbackReceiver warning:
[2019-09-12 10:57:20,776] [] DEBUG - SynapseCallbackReceiver Callback added. Total callbacks waiting for : 1
[2019-09-12 10:57:20,925] [] DEBUG - SynapseCallbackReceiver Callback removed for request message id : urn:uuid:f269f019-9c2f-4b7d-81a1-d6e447687c90. Pending callbacks count : 0
........
[2019-09-12 10:59:19,137] []  WARN - SynapseCallbackReceiver Synapse received a response for the request with message Id : urn:uuid:f269f019-9c2f-4b7d-81a1-d6e447687c90 But a callback is not registered (anymore) to process this response
As the WSO2 EI default for KEEP-ALIVE is TRUE, by setting it to FALSE forces the Client to close the session and no further TCP requests are sent.
Disable KEEP-ALIVE using the following:
<property name="NO_KEEPALIVE" value="true" scope="axis2"/>
However, this can increase latency between the WSO2 EI and the client as all requests are handled as separate connections. I am not sure whether the additional latency is less beneficial than the EI handling delayed TCP RST requests.
See WSO2 ESB Keep Alive Property

A: The warning message will be logged from SynapseCallbackReceiver if there is no callback available for the message received.
Probable causes:

*

*This happens when the client has time out before receiving the response.

*Consider using the OUT_ONLY property for messages which are sent / forwarded from EI / ESB.
This will prevent the ESB from registering unnecessary callbacks for response handling and also eventually running out of memory.
Refer the following resource.
https://docs.wso2.com/display/ESB490/Generic+Properties#GenericProperties-OUT_ONLY


text:
Q: Make report customer viewed product follow useragent I'm trying to make a report about customer viewed product follow useragent but still not yet understand the relationship between tables in magento database diagram clearly. You can see my desire bellow(I'm a new member so still not enough point to post screenshoot):
Period          Customername     Productname    Device   Time

Sep 17, 2011    customername1    Iphone4        Wap     Sep 17, 2011 12:17:28 PM
                customername1    Iphone4        Web     Sep 17, 2011 2:03:35 PM

Table "report_event" and related tables are used to get "customer name" and "product name". And now, I want to know each of product view request times from which useragent. I also found the attribute "http_user_agent" in table "log_visitor_info" but don't know whether it's useful
Can I make this report? Please give me your ideas about that

A: yes log_visitor_info table has all the details of visitors, we can track that user by the way.


text:
Q: How to save image url in firebase real-time database? I want to save image url in real-time database but none of the solutions that I tried is solve the problem, the code that I wrote it saving the image in firebase storage but I want to save the image url in real-time database, so can anyone help?
this code just save the image in firebase storage
private Button btn_upload,btn_choose;
private ImageView imageView;
private Uri filepath;
private FirebaseStorage storage;
private StorageReference storageReference;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btn_choose= (Button) findViewById(R.id.btn_choose);
    btn_upload= (Button) findViewById(R.id.btn_upload);
    imageView= (ImageView) findViewById(R.id.myImage);

    storage = FirebaseStorage.getInstance();
    storageReference = storage.getReference();

    btn_upload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            uploadImage();

        }
    });

    btn_choose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            chooseImage();

        }
    });

}

// choose image function code

private void uploadImage() {

    if(filepath!=null)     {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Uploading...");
        progressDialog.show();

        StorageReference reference = storageReference.child("images/" + UUID.randomUUID().toString());

        reference.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                progressDialog.dismiss();

                Toast.makeText(MainActivity.this, "Image uploaded", Toast.LENGTH_SHORT) .show();
            }
        })
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {

                        double progres = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
                        progressDialog.setMessage("Uploaded"+(int)progres+"%");
                    }
                }) ;

    }   }

I want to store image in real-time database

A: You can request download URL for the file after uploading finishes.
Then Add the URL to Real-time Database
  reference.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                progressDialog.dismiss();

                Toast.makeText(MainActivity.this, "Image uploaded", Toast.LENGTH_SHORT) .show();
                reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                      //You will get donwload URL in uri
                      Log.d(TAG, "Download URL = "+ uri.toString());
                      //Adding that URL to Realtime database
                      mDatabase.child("imageUrl").setValue(uri.toString());
                    }
                });
            }
        })

A: @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
            && data != null && data.getData() != null )
    {
        filePath = data.getData();
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            imageView.setImageBitmap(bitmap);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

private void uploadImage() {
        name = txtname.getText().toString();
    if(filePath != null)
    {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Uploading...");
        progressDialog.show();

        StorageReference ref = storageReference.child("images/"+ name);
        ref.putFile(filePath)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        progressDialog.dismiss();
                        Toast.makeText(MainActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        progressDialog.dismiss();
                        Toast.makeText(MainActivity.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
                                .getTotalByteCount());
                        progressDialog.setMessage("Uploaded "+(int)progress+"%");
                    }
                });
    }

            Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}


text:
Q: Dirac Delta Integration by Parts
$$\int_{-\infty}^{\infty}\left(\sin ^{2} x+2 \tan x\right) \delta^{\prime}(x)$$

$1.$ Is this integral missing  a $dx$ at the end?
$2.$ Assuming that it is then performing integration by parts leaves me with $$
\left.\left[(\sin ^{2}(x)+2 \tan (x)\right) \delta(x)\right]_{-\infty}^{\infty}-\int_{-\infty}^{\infty} 2[\cos (x)\sin(x)+\sec^2(x)] \delta(x) d x
$$
But how does one evaluate the left hand side?

A: *

*Technically yes.

*The first term is just zero; in fact this always happens when $f$ is a test function and $d$ is a distribution*, so that distributional integration by parts reads $\int f d' = -\int f' d$ (in shorthand). The second term is just evaluated using the definition of $\delta$.

* Here I mean either "$f$ is compactly supported smooth and $d$ is a distribution" or "$f$ is Schwarz class and $d$ is a tempered distribution".

A: When we define the distributional derivative, the form is like
\begin{align*}
\left<\partial^{\alpha}\varphi,f\right>=(-1)^{|\alpha|}\left<\varphi,\partial^{\alpha}f\right>
\end{align*}
for good functions $f$, we define in this way such that the integration by parts is allowed.


text:
Q: SSRS Expressions For end of week date I need to use an SSRS expression to find two dates -

*

*The date that's the end of this week.

*The dates that's the start of the week, 2 weeks ago.

For example, if today is 27/05/2016

1 = 29/05/2016
2 = 09/05/2016

This needs to be dynamic e.g. getdate()
I'm using these functions to filter a matrix.
Thanks.

A: It may be something like below,
1. The date that's the end of this week.
=DateAdd("d", 7 - DatePart("w", CDate(Today)), CDate(Today).AddDays(1)).ToString("dd/MM/yyyy")

2. The dates that's the start of the week, 2 weeks ago.
=DateAdd("d", 2 - WeekDay(Today), DateAdd("d", -14, Today).ToString("dd/MM/yyyy")

SSRS Expression Cheat Sheet

A: May be something like this,
End of this week
 =DateAdd("d", 8 - Weekday(Today), Today).ToString("dd/MM/yyyy")

Start of the week (2 weeks ago)
 =DateAdd("d", -(Weekday(Today)+12) , Today).ToString("dd/MM/yyyy")


text:
Q: Proof of $A = \{x \mid f(x) \leq g(x)\}$ is closed in X I am facing trouble in the following problems in Munkres:
Let $X$ be a topological space. Let $Y$ be an ordered set with its order topology. let $f, g : X \rightarrow Y$ be continuous. Show that the set $A = \{x \mid f(x) \leq g(x)\}$ is closed in X.
I found a solution which is as follows:
The complement of $A$ in $X$ is
$X − A = \{x \mid g(x) < f(x)\}$. We will show that $X − A$ is open. Suppose that $ X − A$ is non-empty and pick an arbitrary element $x_{0} \in X − A$. Let $a$, $b$ and $c$ be elements in $Y$ such
that $a \leq g(x_0) < b \leq f(x_0) \leq c$. In the order topology, $[a, b)$ and $[b, c]$ are open sets. Because $ f $ and $g$ are continuous, $g^{-1}([a, b))$ and $f^{-1}[b,c)$ are open in $X$. Their intersection is an open neighborhood of $x_0$ which is entirely contained in $ X − A$. Since $x_0 $is an arbitrary element of $X − A$, we conclude that $X − A$ is open.
Link for the solution: http://www.personal.psu.edu/auw4/math429-practice1.pdf
Is this the correct solution?
Because if $b= f(x_0) = c$, then $[b,c] = \{c\}$ is not open in $Y$.
Please advise me.

A: No the solution is not completely correct. You'll have to consider cases.

*

*There is no element of $Y$ between $g(x_0)$ and $f(x_0)$; then $(\gets,g(x_0)]$ and $[f(x_0),\to)$ are disjoint open sets around $g(x_0)$ and $f(x_0)$ respectively and the intersection of their preimages works

*There is a $b$ between $g(x_0)$ and $f(x_0)$; then $(\gets,b)$ and $(b,\to)$ are disjoint open sets around $g(x_0)$ and $f(x_0)$ respectively and the intersection of their preimages works.


text:
Q: What part of memory does a mutex lock? (pthreads) All the documentation I've read on the pthreads mutex states only that a mutex prevents multiple threads from accessing shared memory, but how do you specify in the program what exactly is that? Is it all the global variables in the program, the variables being accessed between the locking and unlocking functions, or... ? Everything I've found on pthreads, including the examples, is irritatingly vague.

A: Strictly speaking, a mutex only locks/unlocks itself. What shared resources it protects depends entirely on how you use it. You use mutexes (or more generally any synchronisation primitives) to establish a protocol for yourself to safely access shared resources such as data.
For example, you have an array double d[10] which is to be access by different threads. To protect this from concurrent modifications, you can create one mutex, let's say mutex_for_d, and program your code so that every time any code accesses d, it will lock mutex_for_d first. That way, access to d is protected by the mutex.
Alternatively, you could decide that each element of the array will be synchronised separately - and have an array of mutexes, always locking the one for the element you access.
This is purely your own protocol and you must make sure you stick to it - if you forget to lock the mutex in one function which modifies d, the program will still run, but can potentially introduce a data race. For this reason, you will normally want to hide shared data behind a class interface which will guarantee correct locking, something like this:
struct SharedArray
{
  double get(size_t idx) const { std::lock_guard<std::mutex> lock(mut); return d[idx]; }
  void set(size_t idx, double v) { std::lock_guard<std::mutex> lock(mut); d[idx] = v; }
private:
  double d[10];
  std::mutex mut;
};

A:
a mutex prevents multiple threads from accessing shared memory

The above is an incorrect statement. By itself, a mutex does not do that. It lets you build code that prevents multiple threads from accessing shared memory or other resources concurrently, but it does not lock anything by itself.
You can build a program that uses a mutex to prevent multiple threads from executing specific pieces of code concurrently. If these pieces of code happen to be accessing a shared memory region, and no other code would try accessing that region concurrently without locking the mutex, then the effect would be that of "locking" that region of memory.

A: A mutex doesn't lock memory, it "locks" a part of the execution
path, and synchronizes memory (but when locking and when
unlocking).  What is guaranteed is that if one thread holds the
mutex, no other threads can acquire it, and any thread
attempting to acquire it will be blocked until it is released.
It is also guaranteed that any memory accesses (read or write)
will be ordered with respect to acquiring or releasing the
mutex; in other words, that any reads made while the mutex is
held will reflect any changes made before the mutex was acquired
(including those made in a different thread), and that any
modifications made while the mutex is held will be potentially
visible to all other threads at the latest when the mutex is
released.  (The other threads will, of course, have to ensure
that their memory reads see up to date values for this to work.)
For more information, you really should read Programming with POSIX Threads,
by David Butenhof.  It's the reference, and explains them in detail.

A: See this code:
bool initialized_array = false;

int some_array[10];

void do_some_initialization() { ... };

int get_array_element(int i)
{
    if (!initialized_array) {
        do_some_initialization();
        initialized_array = true;
    }
    return some_array[i];
}

As you can see, the variables initialized_array and some_array are deeply related, but the relationship exists only in the code that handles them both.
That's how mutexes are associated with shared memory; the association happens because you write code that does so. There is no way to say "this mutex protects that shared object", the programmer has to make sure every time the shared object is accessed by a thread, it also performs the synchronization on the correct mutex.

A: When locked, a mutex prevents any other thread from obtaining a lock on that same mutex. So, if you want some particular data to be thread safe (i.e., a critical section of memory), you should obtain a lock on the mutex before reading from it or writing to it, then release the lock when finished. The mutex itself does not refer to any particular section of memory. It is simply a tool you can use.

A: Mutex locks a piece of code. For example:
mutex.lock();
    //some code here
mutex.unlock();

If one thread enters the code above it locks it, until it is done with it. At the same time no other thread can execute this piece of code.
mutex and threads independence

A: A mutex locks itself and that's all it locks. It does not lock other memory, it does not lock code. You can design your code so that something other than just the mutex is protected but that's down to how you design the code, not a feature of the mutex itself.
You can tell it doesn't lock data memory because you can freely modify the memory when the mutex is locked by someone else just by not using the mutex:
thread1:            thread2:
    lock mtx            set i to 4  // i is not protected here
    set i to 7
    unlock mtx

To say it locks code is also not quite right since you can run all sort of different sections of code under the control of a single mutex.
And, if someone manages to get to the code within a mutex block without first claiming the mutex, it can freely run the code even when someone else has the mutex locked:
threadN:
    if thread_id == 2: goto skip_label1
    lock mtx
  :skip1_label1

    set i to 7              // not as protected as you think

    if thread_id == 2: goto skip_label2
    unlock mtx
  :skip1_label2


text:
Q: System Verilog Associative Array Is it possible to define a associated array of different element types - something like below ?
typedef enum {M1, M2} mod_t;
typedef struct {...} m1_reg_t;
typedef struct {...} m2_reg_t;

array[mod_t] = {
   M1: { string name;
         m1_reg_t cfg
       }
   M2: { string name;
         m2_reg_t cfg;
         int m2_indx;
       }
}

A: No, all arrays must have the same element type.
If you really want an array with just two elements of a different type, use another struct instead of an array.
typedef struct {
         string name;
         m1_reg_t cfg;
       } M1_t;
typedef struct {
         string name;
         m2_reg_t cfg;
         int m2_indx;
       } M2_t;
struct { M1_t M1;
         M2_t M2;
} opcodes;

But if you are looking for an array of many elements where each element might hold a different opcode, consider a dynamic array of tagged unions.
typedef union tagged {
   struct {
             string name;
             m1_reg_t cfg;
           } M1;
   struct {
             string name;
             m2_reg_t cfg;
             int m2_indx;
           } M2;
} opcode_t;

opcode_t opcodes[];

Accessing tagged unions requires pattern matching statements. See section 12.6 in the 1800-2017 LRM.


text:
Q: WCF Service reference not working on other PC I have a Windows Store - Metro app that connects with a Net TCP WCF Service running on same PC (hosted in a console application) but on Desktop mode of Windows 8. I have added a reference of WCF Service inside metro app and everything works fine.
I package my store/metro app and WCF Service and try out on another PC which don't have Visual Studio installed so I don't recompile the code, I just install the metro app package and run the executable of WCF Service. WCF Service starts fine but when I launch my metro app it give me error (see the image below)
It seems that for some reason metro app when installed on other PC is unable to find the service reference. I have tried many things after googling but nothing works. Any ideas/hint/suggestion would be greatly appreciated.

A: Windows Store Apps generally cannot use the loopback address, except for 1) communication within the SAME process, or 2) for development purposes.  From How to enable loopback and troubleshoot network isolation:

Network communications using an IP loopback address cannot be used for interprocess communication (between two different apps) in a Windows Store app since this is restricted by network isolation. Network communication using an IP loopback address is allowed within an app within the same process for communication purposes.
A developer may want to use loopback for testing or debugging purposes, even though that capability will not be available for customers. For example, an app may want to download data from a web service from a Windows Store app. For development purposes, the developer wants to test the app on a single computer that is configured with the web service locally on 127.0.0.1.
Loopback is permitted only for development purposes. Usage by a Windows Store app installed outside of Visual Studio is not permitted.

In a production scenario, you will likely have to install the WCF service on a separate machine. Note that you will have to enable the "private network" capability in your application manifest (on the client app) to enable local network access.


text:
Q: Preserving a hard disk, plugged or unplugged from power? We have a few hard disks we use as data backup. We keep them in a cool store room until they are needed (we manually copy data into them). These data aren't exactly critical, we won't shed a single tear if it were to fail but that's another story.
I've heard from the internet that unused hard disks tend to clog, the oil in their spindle becomes sticky and will eventually stop working.
Would you say it would be better to keep them plugged into a computer even though there is no I/O operation?

A: IMHO, IME, that would be "things from the internet that were true-ish, 20 years ago" but are misleading to perpetuate now.
Unplugged. I have several in a safe-deposit box on a rotating basis.


text:
Q: Explaining the color of objects: classification and molecular perspective Intro
I have been interested in this topic for a while, at the conceptual level.
Normally we group interaction of objects with light as as reflection, transmission and absorption/emission.
I'd like to narrow those down a bit and ask a few questions at the end of the summary.
Besides, it seems that Scattering is diffuse reflection. Which is one of the questions at the bottom.
For both Scattering and Reflection it seems enough to imagine some type of surface and the light as beams of light.
Summary of Ideas

*

*Scattering: This "echoes" the light in different directions with different intensity.
There are at least 2 different types of scattering:

*

*Rayleight (psize << lambda): It is that it scatters more for shorter wavelengths (example blue of sky)

*Mie (psize ~ lambda)

*Reflection

*

*Specular reflection_ Occurs when the material "echoes" the incident light, with same angle (relative to the surface normal line).

*Diffuse reflection seems quite similar to Scattering. Yet the article says:

Few materials do not cause diffuse reflection: among these are metals, which do not allow light to enter; gases, liquids, glass,
The incident light ray is somewhat reflected to every direction (i.e broadcasted), and it is more intense in the direction normal to the surface (Lambert cosine law). It seems that as a difference to Scattering, we only focus on the reflected light.

Diffuse reflection is actually the main reason why we see objects, if there were much specular reflection we would see the reflection and would be a lot more like a mirror. Then, the color itself will depend on absorption.

*Absortion and Emission, in this case it is necessary to talk about the electronic structure. It also includes a huge n
umber of phenomenons. The best simplified description I know of is the Jablonski diagram.

*Transmission: not very relevant either but included for completion (see first paragraphs).

*

*Refraction just included for completeness but this normally isn't responsible for the color of objects.

Question
I thought that would be useful to know which type of explanation I'd expect. And also expose it for corrections and maybe important missing phenomenons.

*

*Is Scattering Lambertian in type? Is it phenomenologically the same than diffuse reflection? If not, why.

*When light is not electronically absorbed by atoms and molecules, but instead it is reflected or scattered, what would be the molecular/atomic phenomenon that explains it (reflection) ?


text:
Q: Why do these two items have the same barcode? I am trying to build an iOS app that involves scanning barcodes and I came across this weird scenario where this api and this api gave me different items for the same UPC-A barcodes.
Is it possible for two item issued in the same country to have the same UPC-A barcode or is this the APIs fault?
Here's the barcode image? It'll be great if someone can give me some general barcode guidelines. It's my first time dealing with barcodes.

A: I don't know anything about API's, but I was a 3rd party seller on Amazon, and it looks like that shower gel was sold on Amazon, and the website http://www.upcitemdb.com that was used to pull those results pulls data from Amazon, somehow. When you enter an item for sale on Amazon, some catergories require you to use a barcode in order to place an item for sale on Amazon. If an item does not have a barcode it is conceivable that the seller invented one simply to get their listing on Amazon. In this case, it looks like they entered the same barcode that RedBull has registered to them.
I also find it fishy that the website http://www.upcitemdb.com not only pulls data from Amazon, but uses Amazon ads, and is likely owned by an Amazon affiliate who has a vested interest in directing traffic to Amazon, not in displaying correct barcode information.


text: Q: how to handle an unexpected popup in calabash-android I am testing an app , which gives popup 1s or two times a day. and my script fails when this popup appears ... how to handle this kind of unexpected popup from the app.


text:
Q: Is every symmetric graph a strongly regular graph? I have a bit of a problem to develop an intuition about symmetric graphs (I only consider in the following connected simple graphs)... For example cycles (but only up to 5 vertices) and complete graphs are symmetric and strongly regular. But is every symmetric graph also strongly regular?
Counter-examples or some intuitive explanation is welcome. Complicated proofs
are maybe beyond what I can understand at the moment. Unfortunarely, also I am not very strong in group theory.
I know that every symmetric graph is regular.
Greets,
Lando

A: Wolfram's article on symmetric graphs shows $4$ connected, symmetric, simple graphs on $6$ vertices; Wolfram's article on strongly regular graphs shows only $3$ connected, strongly regular, simple graphs on $6$ vertices. Thus, there must be a symmetric graph that isn't strongly regular. From the illustrations it appears that $C_6$ and $K_{3,3}$ are symmetric but not strongly regular, and the graph obtained from $C_6$ by adding the $3$ edges between diametrically opposite vertices is strongly regular but not symmetric.


text:
Q: Ajax Not Working If The Handler is Located Outside Plugin Submenu Page Function I am using wordpress ajax to trigger a submission. I located the submission code in the submenu page, because of it is have conflict with the function in plugin main page. The problem here is, I should placed the ajax handler in the submenu page function while it will not triggered if it is placed there.
It always returning 0 if the handler is located in the submenu page function. I had added nopriv in the handler hook and also localize the javascript.
The Ajax example from Wordpress Codex is also not working if I put it inside the submenu page function of my plugin.
My question:

*

*How to make wordpress ajax working while its handler is placed inside submenu page function?

Thanks in advance!


text:
Q: Route model binding not working on Laravel I have been trying to solve this issue since two days but no luck. I do have a update method on my ArticleController that is responsible to update the articles on my database:
public function update(Article $articles,  ArticleRequest $request){

    $article = Article::findOrFail($articles);

    $article->update($request->all());

    return redirect('articles');
    }

Here is my blade file to show those results:
@extends('app')

@section ('content')

Edit:  {{$article->title}}

{!!Form::model($article,['method'=>'PATCH', 'action'=>['ArticleController@update', $article->id] ])!!}
 @include('pages.partials', ['submitButtonText' => 'Edit Article'])

{!!Form::close()!!}
@include('errors.error')

@endsection

I get error Article var doesnt exists.

A: When you set up route-model binding, behind the scenes Laravel retrieves the appropriate model instance for you and passes it into your controller method. In your example, the Article $articles argument represents an instance of the Article model - not just the id. Therefore, the following line is both unnecessary (since you already have the appropriate model instance), and incorrect (since findOrFail expects an integer to be passed to it - not a model instance):
$article = Article::findOrFail($articles);

I would change your controller method to be:
public function update(Article $articles,  ArticleRequest $request)
{
    $articles->update($request->all());

    return redirect('articles');
}

If you still have trouble with that, "die and dump" your $articles variable to ensure you have route-model binding set up correctly.


text:
Q: If $A$ is a symmetric matrix, then $\operatorname{rank}(A) = \operatorname{rank}(A^2)$. True by the spectral theorem? $A$ is a symmetric $m\times m$ matrix. Can I say $\operatorname{rank}(A) = \operatorname{rank}(A^2)$ is true by the spectral theorem?
My reasoning is as follows:

*

*The spectral theorem states that every real, symmetric matrix is
diagonalizable.

*This means $A = P^{−1}DP$, where $D$ is a diagonal matrix and $P$ is some invertible matrix.

*To calculate $A^2$, the diagonal matrix would just be raised to $2$: $A^2 = P^{−1}D^2P$
Intuitively, all that is changing is the diagonal matrix. It makes sense that the rank/nullity would not change, but I'm not exactly clear why.

A: Yes, you can conclude that $\operatorname{rank}(A) = \operatorname{rank}(A^2)$ by the spectral theorem.
Since $A$ is symmetric, it is diagonalizable. Thus, there exists an invertible matrix $P$ and a diagonal matrix $D$ such that $A = P^{-1}DP$. Because $D$ is diagonal, $D^2$ is also diagonal, so
$$A^2 = P^{-1}D^2P = P^{-1} \begin{pmatrix} \lambda_1^2 & & \ & \ddots & \ & & \lambda_m^2 \end{pmatrix} P.$$
Since $P$ is invertible, the rank of $A$ is equal to the rank of $D^2$, which is equal to the rank of $D$, which is equal to the rank of $A^2$. Thus, we have $\operatorname{rank}(A) = \operatorname{rank}(A^2)$.


text:
Q: PHP GET number query Hi to all!
I have a query that gets the name and an id.
The results is like this :
54 - Rian Ree Barrientos
I wanted to get the number 54.
I used echo (int)$_GET['number'];
But the result is "0". How can I get the number?

A: You can't get it that way, you need to make two query string vars for it eg:
<a href="somepage.php?number=54&str=some_string">

Make sure that if you do so, you use the urlencode function.
Now you can use:
echo (int) $_GET['number'];

And:
echo $_GET['str'];

Otherise you can use the explode function to get the two values by specifying the - delimiter.

A: I think you want id from the value you get from the query
I think you want something like following
$strPrice1 = mysql_query("SELECT id, name FROM table_name where id=".$_GET['id'] );
$strPrice = mysql_fetch_array($strPrice1);
echo (int)$_strPrice['id'];

A:
But the result is "0". How can I get the number?

Really?
When I run:
print (int)('54 - Rian Ree Barrientos') . "\n";

I get 54
(php v 5.1.6)
Maybe $_GET['number'] doesn't contain what you think.
C.


text:
Q: Handling HTTP/1.1 Upgrade requests in CherryPy I'm using CherryPy for a web server, but would like it to handle HTTP/1.1 Upgrade requests.  Thus, when a client sends:
OPTIONS * HTTP/1.1
Upgrade: NEW_PROTOCOL/1.0
Connection: Upgrade

I'd like the server to hand the connection off to some NEW_PROTOCOL handler after responding with the necessary HTTP/1.1 101 Switching Protocols..., as specified in RFC 2817.
I'm pretty new to CherryPy, and couldn't find anything in the documentation on how to handle specific client requests such as the above.  If someone could point me to a tutorial or parts of the CherryPy documentation or even a solution, that would be very helpful.

A: This is fairly easy to do in trunk (which will eventually be 3.2 final). I'm sure it's possible in older versions but much more convoluted.
All you need to do is make a new subclass of wsgiserver.Gateway that looks for the headers in question and then either hands off the conn or proceeds to the usual gateway. For example:
class UpgradeGateway(Gateway):
    def respond(self):
        h = self.req.inheaders
        if h.get("Connection", "") == "Upgrade":
            # Turn off auto-output of HTTP response headers
            self.req.sent_headers = True
            # Not sure exactly what you want to pass or how, here's a start...
            return protocols[h['Upgrade']].handle(self.req.rfile, self.req.wfile)
        else:
            return old_gateway(self.req).respond()

old_gateway = cherrypy.server.httpserver.gateway
cherrypy.server.httpserver.gateway = UpgradeGateway

There may be a couple other fine points but that's the general technique.


text:
Q: Como puedo descargar todos los archivos en el arreglo? Tengo el siguiente arreglo:
foreach (string Id in Arguments.SelectedValues)
{
    string temp = @"http://localhost:17277/blob.ashx?Pdf=o|" + Id;
    Result.NavigateUrl = @"http://localhost:17277/blob.ashx?Pdf=o|" + Id;
}

en el cual accedo al BLOB donde se encuentra el archivo y lo descarga.
Cuando lo ejecuto, el arreglo si me trae todos los IDs, pero únicamente me descarga el archivo del último ID en el arreglo.
¿A qué se debe y cómo puedo hacer que descargue todos los seleccionados?

A: Claro esto sucede porque en cada iteracion del for estas pisando el dato previo quedandolo solo el ultimo asignado para navegar
Si en a url puedes definir una lista de Ids entonces deberias unirlos y navegar al final
 string Ids = string.Join("|", Arguments.SelectedValues);

 string temp = @"http://localhost:17277/blob.ashx?Pdf=o|" + Ids;

 Result.NavigateUrl = temp;

si puedes separar cada id con algun caracter como imagino es el | podrias enviar varios ids en la url para que descargue las imagenes,o imagino genere el pdf con las imagenes de esos Ids

A: Para descargar multiples archivos, podrias hacerlo de varias formas, la primera sera modificar el handler para que reciba los ids a descargar genere un zip y lo retorne para descargar, otra es que el action actual retorne un java script que contenga todos los urls a el handler, en tags a con el atributo target="_blank", los cuales por js les simulas el click para que asi se inicie la descarga de archivos.
Ejemplo de js

En el caso del zip existen librerias como DotNetZip que facilitan el trabajo de hacer un zip


text:
Q: Why convert in ImageMagick not working I try to convert pdf file to png image in ImageMagick from windows 10 command line as follows:
convert a.pdf a.png

But I get error: Invalid Parameter - a.png. I'd like to know why. ImageMagick has been installed correctly as magick wizard.jpg win: popup an image.

A: convert might be another command on Windows (see convert issue)
Note also that starting from version 7

The "magick" command is the new primary command of the Shell API,
  replacing the old "convert" command.

(from https://imagemagick.org/script/porting.php)
so you should use:
magick a.pdf a.png

A: To expand on @Ben Harris answer Windows has a convert program that from memory renames files which will be selected by default. If you allowed Imagemagick to add itself to the environmental variables on install it should have worked.
You can either change convert to the path of Imagemagick convert.exe or rename convert.exe to something else (such as IMconvert.exe) to stop the confusion. Then use IMconvert.exe in place of convert.
As @user2314737 says the version 7 of Imagemagick uses magick rather than convert to prevent that problem. (try magick.exe)

A: My guess is that you are calling the wrong convert. Use where to determine which executable that you are actually running.
Additionally, make sure you watch out for some of the strange behaviors of imagemagick on windows.


text:
Q: HttpURLConnection first works but stops without error I build a app that gets it's data from json on a server. On this moment i use the code under this post to connect to the json files. First it works great but after some time it stopt working and i do not see a error in the monitor or on the android screen. I think it is the DataOutputStream, but i can not see what the problem is.
Can someone get it working?
public String makeServiceCall(String reqUrl, Context con) {
    String response = null;
    context = con;
    DB = new DatabaseVerwerker(context); //<-- database verbinden

    try {
        URL url = new URL(reqUrl);
        String[] UrlOnderdeel = reqUrl.split("://");
        if(UrlOnderdeel[0].equals("http")) {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setAllowUserInteraction(false);
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes("key="+DB.GetVar(DB, "authkey", "null"));
            dos.close();
            conn.connect();
            int responseCode = conn.getResponseCode();
            InputStream in = new BufferedInputStream(conn.getInputStream());
            if(responseCode >= 300 && responseCode < 400) {
                response = makeServiceCall(conn.getHeaderField("Location").toString(), context);
            } else {
                response = convertStreamToString(in);
            }
        }
        if(UrlOnderdeel[0].equals("https")) {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[]{new TrustAll()}, null);
            HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setAllowUserInteraction(false);
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes("key="+DB.GetVar(DB, "authkey", "null"));
            dos.close();
            conn.connect();
            int responseCode = conn.getResponseCode();
            if(responseCode >= 300 && responseCode < 400) {
                response = makeServiceCall(conn.getHeaderField("Location").toString(), context);
            } else {
                response = convertStreamToString(conn.getInputStream());
            }
        }
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }

    if(response != null) {
        Log.v("JsonRespons", response.toString());
    }
    return response;
}

A: It doesn't look like you're closing the connection. You'll want to do something like:
HttpUrlConnection conn = null;
InputStream is = null;
try {
    conn =  (HttpURLConnection) url.openConnection();
    // ... connection handling code here ...
    is = conn.getInputStream();
    // ... InputStream consumption here ...
} finally {
    if(conn != null) {
        conn.disconnect();
    }
    if(is != null) {
        is.close();
    }
}

More info about the HttpUrlConnection can be found at the official dev docs explaining how to properly use the HttpUrlConnection.


text:
Q: Android Volley onResponse not getting Called in Certain Activity I am making Volley GET Requests which will work until I get to a specific activity and then it stops calling the onResponse in the Response.Listener. Here is my Volley Request method:
    public static void stringReqGet(String url, final VolleyCallback callback){
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            System.out.println("In VolleyRequest onResponse(): " + response);
            callback.onSuccess(response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("Error" ,error.getMessage());
        }

    });
    System.out.println("Adding request to queue: " + stringRequest.toString());
    Utilities.getInstance().addToRequestQueue(stringRequest);
    }

Here's how I'm making the request in the activity in question:
CourseUtil.loadCourse(courseID, new VolleyCallback() {
        @Override
        public void onSuccess(String response) {
            System.out.println("JSON Success");
            courseJSON = response;
        }
});

and in CourseUtil class:
public static void loadCourse(int courseID, VolleyCallback callback){
    VolleyRequest.stringReqGet(Const.URL_COURSE + courseID,callback);
}

I'm getting no Volley errors just seemingly no response. Here are my (truncated) logs:
I/System.out: Adding request to queue: [ ] http://server/courses/267267267 0xebb503b0 NORMAL null
I/System.out: In VolleyRequest onResponse(): *Correct Response Object*
.
.
.
I/System.out: 267267267  <-- Same course ID used in first request
I/System.out: Adding request to queue: [ ] http://server/courses/267267267 0xebb503b0 NORMAL null
*onResponse never called*

The first time this request is made you can see that the onResponse() method is called and it returns the correct object. The signature of this 'correct' request is the exact same as the one above. The next time that exact request is made the onResponse is never called and I get no error.
I've looked at other posts on here but none of their solutions fixed the problem I am having and no error makes it hard to know what's going on.
Any help would be greatly appreciated.

A: Put:
System.out.println("JSON Success");
courseJSON = response;

into a separate method outside the callback and it works now. Not sure why...


text:
Q: Whether Camel Improves Performance?
*

*I used simple java code to receive messages from ActiveMQ queues. It
takes more than 1 hour to read 1000 messages from a queue.

*But now I used Apache camel for reading messages from ActiveMQ queue.
It even does not take a single minute (52 seconds) to read 1000
messages.

*I tried with the same messages for both programs.

My question is whether Camel improves the performance too?

A: Most likely the performance variance is due to a problem in your Java client code. If you share a link to the source, might be able to identify the issue.


text:
Q: Classifying the solutions of the function $f(x)= \frac{1}{2}f(x-1)+\frac{1}{2}f(x+1)$ I found this question on a GRE practice exam. It is stated as follows.
Let $f$ be a real-valued function defined on the set of integers and satisfying $f(x)= \frac{1}{2}f(x-1)+\frac{1}{2}f(x+1)$. Which of the following must be true?
I. The graph of $f$ is a subset of a line.
II. $f$ is strictly increasing.
III. $f$ is a constant function.
My approach was to plot points on a graph. First I choose 2 arbitrary points for $f(x-1)$ and $f(x+1)$. Then, $f(x)$ is the midpoint between $f(x-1)$ and $f(x+1)$ while $x$ is the midpoint between $x-1$ and $x+1$. These three points lie on a line which led me to believe that I. is true. If I choose $f(x-1)$ to be greater than $f(x+1)$, then the three points will be a subset of a line with negative slope, which would rule out II. and III.. Since what I've done isn't very rigorous, I am wondering if my reasoning is correct or if there is an easier/faster way to look at this problem. Thanks in advance.

A: Here's how I look at it: after some rearrangement you have that
$$f(x+1) - f(x) = f(x) - f(x-1)$$
Or $\Delta {f}_{x+1} = \Delta f_x$ where $\Delta f_i$ is the change in $f$ between $i-1$ and $i$. Since the function is increasing by the same amount every step, it must be a subset of a line.


text:
Q: How to read a text file with a mix of int and strings delimited by space and store each into arrays I have a text file with about 200 item numbers and descriptions, which is formatted like this (without the bullets):

*

*1642 Pure wool t-shirt

*613  Red laced shoes

*3477 Blue hat with feather

*...

I am trying to read and store the items numbers and descriptions into respective arrays, which is delimited by space. My issues are:

*

*I want to ignore the spaces in the description.

*When I sort or delete items, I want to ensure that the description gets deleted as well.

Here's what I have tried so far but getting ArrayIndexOutOfBoundsException error and I am not even sure if it will read the description properly:
private Scanner file;
private int item = 0;
private String desc = "";
private int[] itemArr = new int[200];
private String[] descArr = new String[200];
int n = 0;

public void openFile(){

    try{
        file = new Scanner(new File("inventory.txt"));
    }

    catch(Exception e){
        System.out.println("file not found");
    }

}

public void readFile(){

    while(file.hasNextLine()){
        if (file.hasNextInt()){
            item = file.nextInt();
        }

        while(!file.hasNextInt() && !file.hasNextLine()){
            desc = desc + file.next() + " ";
        }

        itemArr[n] = item;
        descArr[n] = desc;
        n++;
    }

    for (int i = 0; i < n; i++){
        System.out.println(itemArr[i] + " " + descArr[n] + "\n");
    }
    System.out.println("Total Records (n): " + n);

}

Or is there a better way to do this? I've read some post about Patterns and Regex, but not sure how to use that either.
Thank you!

A: I would personally do an IndexOf for the first space, then followed by a substring from 0 to the resulst of the IndexOf and a ParseInt to get the item number.
Then I would do a substring of IndexOf to end of the line, and do a Trim on the result for good measure.
In your example, you also have no protection on your Array, if you have more than 200 lines in your file, you're gonna run out of space on your array. You should use a collection like ArrayList
It would look something like this:
First we change the declaration of your Array for ArrayList
private ArrayList<Integer> itemArr = new ArrayList<Integer>();
private ArrayList<String> descArr = new ArrayList<String>();

Second, we change your algorithm to use SubStrings and IndexOf and use ArrayList
public void readFile(){

while(file.hasNextLine()){

     String line = file.getNextLine();
     int indexOfSpace = line.IndexOf(" ");
     int item = Integer.parseInt(line.substring(0,indexOfSpace));
     String description = line.substring(indexOfSpace).trim();

     itemArr.add(item);
     descArr.add(description);
     }
 }

If you want to go one step further, you could create a Class to represent your items and only have to use one ArrayList instead of 2, but I think I covered your question already!

A: There is no protection on n exceeding 200. If there are more that 200 iterations of the while loop then:
itemArr[n] = item;

will throw an ArrayIndexOutOfBoundsException.
If the int at the beginning of each line is unique you could use a Map<Integer, String> to store the data. This will not place a limit of 200 on the number of items that can be read from the file and if you selected a TreeMap as the implementation it would sort them (you can either accept the natural ordering of Integer or define you own Comparator). As suggested by sethu you could use a BufferedReader to read the file.
For example:
BufferedReader br = new BufferedReader(new FileReader("inventory.txt"));
Map<Integer, String> items = new TreeMap<Integer, String>();

String line;
while (null != (line = br.readLine()))
{
    String[] line_parts = line.split(" ");
    if (line_parts.length > 1)
    {
        StringBuilder desc = new StringBuilder(line_parts[1]);
        for (int i = 2; i < line_parts.length; i++)
        {
            desc.append(line_parts[i]);
        }
        items.put(new Integer(line_parts[0]), desc.toString());
    }
}

for (Integer key: items.keySet())
{
    System.out.println(key + " = " + items.get(key));
}

A: I wont write the code but I'll give you an algorithm:

*

*Use a BufferedReader to read each line of the file.

*Split each line into a String array based on space using String.split(" ")

*Go through each element of the String array and it to a StringBuffer until you reach a String which all numbers. There are many ways of checking if the String is all numbers. Check each character, use a regular expression and match the pattern, use the apache commons StringUtils class.

*If you have reached a number, then you know whatever you collected in the StringBuffer is the description. The ideal data structure to use in this case, is a TreeMap. Add the description as the key and the value as the price. You can sort the map and delete entries as you please.

A: You can use some thing like this which would be much better
Pattern itemPatt = Pattern.compile("([0-9]+)\\s([a-zA-z\\s]*)");

Matcher m = itemPatt.matcher(fileStr);

if (m.matches()) {

  int itemNumber = Integer.parseInt(m.group(1));

  String itemDescription = m.group(2);

}


text:
Q: Service Worker not working when hosted, but works on localhost I'm working on a PWA and I'm facing an issue with the service worker and I can't figure out what's wrong.
So when I run the lighthouse audit on localhost, it passes every criteria except for the HTTPS one. You can view it below;

However, when I publish the code to my github pages, and run the same audit there, the service worker is never activated. It gives me the error. The status becomes 'redundant' when I run the audit online.
Link: https://ibr4h1m.github.io/MAD5/index.html
Below I'll show the code, which is the exact same on the website that I've mentioned above.
main.js:
//Simple ServiceWorker
if('serviceWorker' in navigator) {
  navigator.serviceWorker.register('sw.js');
};

sw.js
const cacheName = 'tourguide-site';
const appShellFiles =  ['index.html',
    'help.html',
    'destinations.html',
    'contact.html',
    'js/main.js',
    'css/style.css',
    'sw.js'
];

self.addEventListener('install', (e) => {
  console.log('[Service Worker] Install');
  e.waitUntil((async () => {
    const cache = await caches.open(cacheName);
    console.log('[Service Worker] Caching all: app shell and content');
    await cache.addAll(appShellFiles);
  })());
});

// Simple Activate since the other one is BS

self.addEventListener('activate', function () {
  console.log('SW Activated');
});

self.addEventListener('fetch', (e) => {
  e.respondWith((async () => {
    const r = await caches.match(e.request);
    console.log(`[Service Worker] Fetching resource: ${e.request.url}`);
    if (r) { return r; }
    const response = await fetch(e.request);
    const cache = await caches.open(cacheName);
    console.log(`[Service Worker] Caching new resource: ${e.request.url}`);
    cache.put(e.request, response.clone());
    return response;
  })());
});

Online audit:

A: const appShellFiles =  ['index.html',
    'help.html',
    'destinations.html',
    'contact.html',
    'js/main.js',
    'css/style.css',
    'sw.js'
];

Remove the sw.js from your appShellFiles