text:
Q: Ubuntu 13.10 and Raedon HD 7700, which drivers? Should I use the FGLRX or the open source drivers for this card, to get the best use out of it? Ie, gaming and good visual effects in Gnome 3.

A: Look no further than this, I've had excellent results for the first time with RadeonSI in gaming:
cd /tmp; wget http://kernel.ubuntu.com/~kernel-ppa/mainline/v3.12-rc6-saucy/linux-headers-3.12.0-031200rc6-generic_3.12.0-031200rc6.201310191635_amd64.deb
wget http://kernel.ubuntu.com/~kernel-ppa/mainline/v3.12-rc6-saucy/linux-headers-3.12.0-031200rc6_3.12.0-031200rc6.201310191635_all.deb
wget http://kernel.ubuntu.com/~kernel-ppa/mainline/v3.12-rc6-saucy/linux-image-3.12.0-031200rc6-generic_3.12.0-031200rc6.201310191635_amd64.deb
sudo dpkg -i linux*.deb

Then download fglrx debs from here: https://copy.com/DctT73MTnQM2 and install them with cd ~/Downloads; sudo dpkg -i fglrx*.deb then reboot
You'll be up and running Linux kernel 3.12-rc6 which has a massive improvement with the CPU governors which was discovered to drastically improve GPU performance, along with Catalyst 13.11 which has given Radeon HD 7000+ cards some amazing performance while fixing a lot of bug issues.


text:
Q: If $a,b,c\in(0;+\infty)$, prove that $\frac{a^2+b^2+c^2}{ab+bc+ca}+a+b+c+2\ge2(\sqrt{ab}+\sqrt{bc}+\sqrt{ca})$. If $a,b,c\in(0;+\infty)$ and $$\frac{c}{1+a+b}+\frac{a}{1+b+c}+\frac{b}{1+c+a}\ge\frac{ab}{1+a+b}+\frac{bc}{1+b+c}+\frac{ca}{1+c+a}$$Prove that $$\frac{a^2+b^2+c^2}{ab+bc+ca}+a+b+c+2\ge2(\sqrt{ab}+\sqrt{bc}+\sqrt{ca})$$
I know that $$a^2+b^2+c^2\ge\frac{(a+b+c)^2}{3}\ge ab+bc+ac$$
So we could prove that $$a+b+c+3\ge2(\sqrt{ab}+\sqrt{bc}+\sqrt{ca})$$
I.e. $$2(\sqrt{ab}+\sqrt{bc}+\sqrt{ca})\le a+b+c+3$$
By using AM-GM we see that we could prove that: $$2(a+b+c)\le a+b+c+3\Rightarrow a+b+c\le3$$
So this didn't work.

A: The given condition is equivalent to:
$$\sum_{cyc}\frac{c-ab}{1+a+b} \ge 0$$
$$\implies \sum_{cyc}\frac{c(1+a+b)-ab}{1+a+b} \ge  \sum_{cyc}\frac{c(a+b)}{1+a+b} \qquad \text{adding to both sides}$$
$$\implies \sum_{cyc}c \ge  \sum_{cyc}\frac{c(a+b)+ab}{1+a+b} = (ab+bc+ca)\sum_{cyc}\frac{1}{1+a+b} \tag{1}$$
By Cauchy-Schwarz, we also have
$$\left(\sum_{cyc}\frac{1}{1+a+b}\right)\left(\sum_{cyc}(c+ca+bc)\right)\ge \left(\sum_{cyc} \sqrt{c} \right)^2 \tag{2} $$
Using this in $(1)$, we have:
$$a+b+c \ge (ab+bc+ca)\frac{(\sqrt{a}+\sqrt{b}+\sqrt{c})^2}{a+b+c+2(ab+bc+ca)}$$
Cross multiplying and expanding we get,
$$(a+b+c)^2 + 2(ab+bc+ca)(a+b+c)\ge (ab+bc+ca)(a+b+c+2\sqrt{ab}+2\sqrt{bc}+2\sqrt{ca})$$
Expanding the first term, cancelling part of the second term with RHS and dividing throughout by $ab+bc+ca$, we get the result.

A: Here are some thought I have, but no proof (yet):
Both the condition and the inequality to be proven have equality when $(a,b,c)=(x,x,x)$ and when $(a,b,c)=(1,1,4)$ (or permutations). We know that the inequalities of means only have equality when the term we apply them to are equal. Thus, we can never use AM-GM on $a$, $b$ and $c$, because $(1,1,4)$ wouldn't give equality and thus the inequality is to lossy.
If we apply AM-GM on $f(a,b,c)$, $g(a,b,c)$ and $h(a,b,c)$, we want $f(1,1,4)=g(1,1,4)=h(1,1,4)$, $f(1,4,1)=g(1,4,1)=h(1,4,1)$ and the same for $(1,1,4)$. I think it is not easy to find functions that satisfy this (apart from $f=g=h$, but then, you won't get any information from the inequality).
We can thus only use the given inequality and use rewriting of terms. Maybe we can also use Cauchy-Schwarz, because it has not-so-trivial cases for equality.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fetching UUID with NamedNativeQuery: [B cannot be cast to java.util.UUID I have a special Hibernate query which I had to write as NamedNativeQuery. This looks like this:
@Entity
@Table(name = "XYZ")
@NoArgsConstructor
@AllArgsConstructor
@NamedNativeQueries({
    @NamedNativeQuery(
        name = [...],
        query = " SELECT DISTINCT uuid [...]"
    )
})
public class XyzEntity implements Serializable {

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    @Type(type = "uuid-binary")
    @Column(name = "uuid", columnDefinition = "RAW(32)", nullable = false)
    private UUID uuid;
}

The query itself works. The result set is accessed in this way:
public List<UUID> getXyz() {
    final Query query = getEntityManager().createNamedQuery([...]);
    final List<UUID> resultList = query.getResultList();
    return resultList;
}

But now, if I try to iterate over this result list, I get Caused by: java.lang.ClassCastException: [B cannot be cast to java.util.UUID
The invocation looks like this:
public void abc() {
    final List<UUID> uuids = service.getXyz();

    //the start of the loop causes java.lang.ClassCastException: [B cannot be cast to java.util.UUID
    for (UUID uuid : uuids) {
        //do something
    }
}

Obviously Hibernate cannot map the NamedNativeQuery result to a Java UUID properly because the content seems to be just binary. What's the proper way to handle this?


text:
Q: Why are people from Sunderland called "mackems"? In the north-east of England, if nowhere else, people from Sunderland are called "mackems". Does anyone know why this should be? Wikipedia suggests a number of possibilities. Are any of these correct?

A: As Sunderland was once known for shipbuilding there was only 2 main forms of employment...shipbuilding by day and stealing from the ships they'd helped build by night. Apparently there was a saying "they mak'em then tak'em" meaning they build (the ships) then steal from them. The mak'em bit stuck and so we are now known as 'makems' or so they say!!?

A: The Wikipedia entry has sourced its answer from the Oxford English Dictionary entry for 'mackem'. As far as word origins are considered, probably as authentic as it gets.
EDIT: As it seems that everyone cannot access the OED link, here's an excerpt. There are two possible origins attributed:

Probably with allusion to the phrase
  mack 'em and tack 'em
  and variations thereof, freq. said
  to refer to the shipbuilding industry
  of the region

or..

Perhaps partly also with allusion to
  the pronunciation of make typical of
  Wearside, as contrasted with that of
  Tyneside.

A: My uncle was from Sunderland and was clear that it was a reference to the difference in accent which differentiated a Tynesider from a Wearsider.  Geordies would say "maek" and "taek", Wearsiders "mak" and "tak".  Nothing to do with shipbuilding.  There was probably more shipbuilding on the Tyne than the Wear.
I should add that my uncle and my parents were born in the 1920s and knew this usage from childhood.  It's not a recent coinage.

A: It may have been a derogatory term at first. As the people of Sunderland Mak or made the ships but all the money stayed in Newcastle!
As a mackem of today and a proud inhabitant of Sunderland it is a local term we love as it defines us as separate from the people of Newcastle.
The most insulting term you can call anyone from Sunderland is a geordie.

A: I'm a born and bred Sunderland lad and a proud Mackem.
I can confirm the term comes from the ship-building history as we used to "Mak" the ships, or make the ships.

A: It comes from when miners, Geordies (Newcastle) called Sunderland makems. It's also to do with football and the rivalry, but the name "Mackem" came from the mining days and is an insulting word towards people of Sunderland.

A: To just add to the comment about "Mackem" also being related to football, the word effectively seems to have two meanings now: someone who's from Sunderland, and someone who supports Sunderland AFC.  Clearly, many or most Sunderland fans will be from the city anyway, so there's no distinction for those people.  But, someone from outside Sunderland, and who therefore isn't a Mackem in the "traditional" sense of the word, will be referred to as a Mackem if they support that team.

A: As a child in Newcastle, it was explained to me that the Wearside (Sunderland) ship-builders would vigorously underquote those on Tyneside (Newcastle).  They would make the ships, but run out of resources, and hence the more reputable shipbuilders on Tyneside would take the partially finished ships and complete the work.  Hence "They mack'em and we tack'em".  This is translated as one of the following:

*

*They make them and we take them

*They make them and we tack them, i.e. fix them up.

As you might guess, this explanation was given to me by a loyal and wildly biased Geordie, who would never have a good word to say about "the great unwashed" from local rivals Sunderland, so is added more as an aside, rather than genuine etymology.


text:
Q: Changing specific row in listview cause another row to mirror the change Hey guys I am new to android and trying to wrap my head around this bug I have. So I have a basic listview with 2 buttons, one to increment and another to decrement a textview in that row. When I click either button, the desired textview (row 0) changes but so does another row which is not even onscreen (row 5).
public class ItemAdapter extends ArrayAdapter<Item> {
public ItemAdapter(Context context, ArrayList<Item> items) {
    super(context, 0, items);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // Get the data item for this position
    Item item = getItem(position);
    // Check if an existing view is being reused, otherwise inflate the view
    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_list_view, parent, false);
    }
    // Lookup view for data population
    TextView tvItem = (TextView) convertView.findViewById(R.id.item_lv_name);
    ImageView ivItemPicture = (ImageView) convertView.findViewById(R.id.item_lv_item_pic);
    final TextView tvAmount = (TextView)convertView.findViewById(R.id.item_lv_amount);
    // Populate the data into the template view using the data object
    tvItem.setText(item.getName());
    ivItemPicture.setImageResource(item.getImageResId());

    //incremt textview
    ImageButton ibtnPlus = (ImageButton)convertView.findViewById(R.id.item_lv_plus);
    ibtnPlus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int value = Integer.parseInt(tvAmount.getText().toString());
            if(value >= 0){
                value = value + 1;
                tvAmount.setText(Integer.toString(value));

            }
        }
    });
    //decrement textview
    ImageButton ibtnMinus = (ImageButton)convertView.findViewById(R.id.item_lv_btn_minus);
    ibtnMinus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int value = Integer.parseInt((tvAmount.getText().toString()));

            if (value > 0){
                value = value - 1;
                tvAmount.setText(Integer.toString(value));
            }
        }
    });

    // Return the completed view to render on screen
    return convertView;
}

}

A: The way you are implementing your adapter is wrong. Your code is calling findViewById() for each item you are scrolling of ListView, which is slowing down performance. Beside that to hold the components view we usually use the view holder design pattern.
In your Adapter class make a ViewHolder class according to your specific requirements:
static class ViewHolder {
  TextView tvItem;
  TextView tvAmount;
  ImageView ivItemPicture;
}

Then populate the ViewHolder and save it inside the layout:
ViewHolder holder = new ViewHolder();
holder. ivItemPicture = (ImageView) convertView.findViewById(R.id.item_lv_item_pic);
holder. tvAmount = (TextView) convertView.findViewById(R.id.item_lv_amount);
holder. tvItem = (TextView) convertView.findViewById(R.id.item_lv_name);
convertView.setTag(holder);

Search view holder for more information and this should solve your problem.


text:
Q: Open stack Octavia quota exceeded for resources and failed I using open stack Victoria on Ubuntu and i want to use from Octavia.
but when i create a load balancer, it failed and in Octavia worker logs show this:
ERROR oslo_messaging.rpc.server neutronclient.common.exceptions.OverQuotaClient: Quota exceeded for resources: ['security_group'].
what happened?

A: Just in plain text meaning by 'Quota exceeded for resources: ['security_group'] tips, the number of your security groups equal or bigger than the value of openstack quota show -c secgroups -f value your_project_name.
Maybe the main point is create a load balancer, and spend the resource, check from this: "The global amount of Octavia loadbalancers is constrained by the service project quotas".
Quote the problem and resolve:
Description of problem:
LB creation creates neutron ports, security groups and instances(cores, RAM, keypairs, etc).

Those objects, when created with LB create command execution are needed not to be omitted while planning the cloud with Octavia.

Possible solutions 1 of 3 :
a- Agreed quota numbers
b- Unlimited quota numbers
c- Documentation of the effect of LB creation on the resources in neutron and nova so the operator could include that in the cloud planning and services quotas configuration.


text:
Q: Android Calling API using Remote Server IP Address - Connection Refused Due to some other issues at the moment I'm having to use my remote API server IP address instead of our domain.
I have a console application that uses the exact API client code from the Xamarin Forms application. I can run this console test harness and call the API without any issues.
But when I run the same API client code on an Android device or the Google emulator the connection is refused.
Not sure what to try to get it working.  Is this an Android policy of not allowing IP address hosts?
How could I whitelist our IP address if this is the case?
Any advice would be great.
UPDATE
I just added a controller to the API that returns "hello".  I redeployed the service and I can browse to this endpoint using the browser on the device and the emulator.

A: I had a similar problem a while back. An app was running for over a year and suddenly it stopped working after updating the server. The fix for me was setting the HttpClient implementation to 'Android'. The default configuration couldn't set up a safe connection.
Projectname.Android
-> Properties
-> Android Options
-> Advanced
-> HttpClient implementation - Android


text:
Q: How to implement This MP problem in ECLIPSE CLP or Prolog? I want to implement this Summations as Objective and Constraints(1-6)
Could anyone help me that how I can Implement them?
OBJ: Min ∑(i=1..N)∑(j=1..N) Cij * ∑(k=1..K)Xijk
constraint :
              ∑(k=1..K) Yik=1 (for all i in N)

A: The following answer is specific to ECLiPSe (it uses loops, array and array slice notation, which are not part of standard Prolog).
I assume that N and K (and presumably C) are given, and your matrices are declared as
dim(C, [N,N]),
dim(X, [N,N,K]),
dim(Y, [N,K]),

You can then set up the constraints in a loop:

constraint : ∑(k=1..K) Yik=1 (for all i in N)

( for(I,1,N), param(Y) do
    sum(Y[I,*]) $= 1
),

Note that the notation sum(Y[I,*]) here is a shorthand for sum([Y[I,1],Y[I,2],...,Y[I,K]]) when K is the size of this array dimension.
For your objective, because of the nested sum, an auxiliary loop/list is still necessary:

OBJ: Min ∑(i=1..N)∑(j=1..N) Cij * ∑(k=1..K)Xijk

( multifor([I,J],1,N), foreach(Term,Terms), param(C,X) do
    Term = (C[I,J] * sum(X[I,J,*]))
),
Objective = sum(Terms),
...

You then have to pass this objective expression to the solver -- the details depend on which solver you use (e.g. eplex, ic).


text:
Q: How are chainlink requests processed when forking mainnet in Brownie? From the brownie chainlink-mix, why does the PriceFeed works fine on mainnet-fork while the ApiConsumer does not fulfill the request on the same network?
Are prices cached on the Aggregator?

A: When you fork the mainnet, it literally forks the blockchchain state at that point in time. So when you query the Price Feed Aggregator contract, you get the price at the time of forking.
However because there are no Chainlink oracles connected to your forked chain, there's no way to do a real API or VRF request...and the latest price data in Price Feed contracts won't update either.
Check out the tests to see how mocks are used for local environments where there is no connectivity to Chainlink nodes


text:
Q: Is there a way to enumerate the open windows on Mac and X11? Basically, I am looking for something like Win32's EnumChildWindows on Mac and X11, which takes a handle to a window and returns a list of its child windows.

A: For X11, look at the xwininfo source to see how xwininfo -children works.


text:
Q: We would like to register a user if space is available or put on waiting list if space is full. Any ideas how to approach this? I am trying to create a waiting list.
The idea behind this waiting list is that we have a training problem that requires users to sign up for a seat in the class.
There is a maximum capacity seating of 45 people.
If all 45 seats have been occupied, then available_seating which starts at 45 and decreases per course registration, will be 0.
If available_seating is 0, that means that the class is full and no seatings are available.
When a user attempts to sign up for a class where available_seating = 0, we would want to let the user know that this class is full and
 s/he will be put on waiting list.
I think I know how to solve this problem.
When available_seating > 0 insert the user into tblTrainings table.
However, if available_seating = 0 then insert user into a table called waitingList.
My problem is how to blend that conditional statement with the counter below.
Below, the SELECT Count(*) query checks to see if user has already registered for a particular class.
If no, register the user for the class. If yes, alert the user that s/he has already registered for the class.
How do I integrate the two in such that we first check to see if the user has already registered for the class.
If no, then we check whether the class is not full yet. If full, insert user into waitingList. If not full, insert user into tblTrainings.
See current code and thanks a lot in advance.
    'If user already registered for a class, alert user
    s = "SELECT Count(*) FROM tblTrainings WHERE Username = '" & username & "' AND CourseID = " & Request.QueryString("cosId") & "  AND LocationID = " & Request.QueryString("locid") & " AND dateId = " & Request.QueryString("iddate") & ""
    Dim connSt As String = ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString
    Dim connc As New SqlConnection(connSt)
    Dim cmdc As New SqlCommand(s, connc)
    connc.Open()
    cmdc.ExecuteNonQuery()
    counter = cmdc.ExecuteScalar()

    '   Now let's see if we found existing record
    If counter = 0 Then
        'User hasn't signed up for this class yet

        s = "INSERT INTO tblTrainings (CourseId, tblLocations.LocationId, dateId,AvailableSeats,username) VALUES (@CosID, @LocID, @dat, @Available_Seating, @Username)"
        Dim cmd = New SqlCommand(s, conn)
        cmd.Parameters.AddWithValue("@cosID", Request.QueryString("cosId"))
        cmd.Parameters.AddWithValue("@locID", Request.QueryString("locid"))
        cmd.Parameters.AddWithValue("@dat", Request.QueryString("iddate"))
        cmd.Parameters.AddWithValue("@Available_Seating", 45 - 1)
        cmd.Parameters.AddWithValue("@UserName", username)
        conn.Open()

A: Maybe I'm missing something, but it doesn't seem that complicated to me.
This answer only uses the SQL pieces that matter to preserve legibility, since I'm mainly referring to queries and not the VB.
First, you do what you were already doing--check to see if they're already signed up/on the waiting list.
SELECT Count(*) FROM (
   SELECT * FROM tblTrainings UNION SELECT * FROM waitingList
) AS t
WHERE Username = XXX AND CourseID = XXX AND LocationID = XXX AND dateID = XXX
/* Tells you whether the person is signed up already, whether for the course itself
or the waiting list. */

SELECT Count(*) FROM tblTrainings
WHERE CourseID = XXX AND LocationID = XXX AND dateID = XXX
-- This will give you the number of people in the course.

Then, once you have that, you can decide whether to add them to that table or add them to waiting list.
Update
Maybe this will help.
'Here build your querystring s from the SQL query above, filling in whatever values your need.
s = "SELECT Count(*) FROM (" & _
    "SELECT * FROM tblTrainings UNION SELECT * FROM waitingList" & _
    ") AS t" & _
    "WHERE Username = XXX AND CourseID = XXX AND LocationID = XXX AND dateID = XXX"

Dim connSt As String = ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString
Dim connc As New SqlConnection(connSt)
Dim cmdc As New SqlCommand(s, connc)
connc.Open()
cmdc.ExecuteNonQuery()
counter = cmdc.ExecuteScalar()

If counter = 0 Then 'this means that the person is in neither the waitlist nor courselist

    'Fill in the XXX as necessary
    qs = "SELECT Count(*) FROM tblTrainings WHERE CourseID = XXX AND LocationID = XXX AND dateID = XXX"
    Set cmdc = New SqlCommand(s, connc)
    cmdc.ExecuteNonQuery()
    courseSize = cmdc.ExecuteScalar()

    If courseSize <= 45 Then
          'Insert the guy into the course
    Else
          'Insert the guy into waitList
    End If
End If

A: Let's say you have a TableA and you want to insert a record only when TableB count is zero. Then you could write this:
insert into TableA (ColA, ColB)
select 'a', 'b' from TableB
 where 0 = (select count(*)
              from TableB
             where ColC = 'c')

It should be easy to fit the above statement to your scenario.


text:
Q: How do a make a API request in Swift like the working Python request I'm currently using? I'm looking to convert this Python request to a Swift script.
Here is my working python script that returns the accessToken!
#!/usr/bin/python

import requests
import json

#MAKE THE REQUEST
URL = "http://this/is/the/url"
headers = {
'Accept': "application/json",
"Accept-Language": "en_US"
}
data = {
    "grant_type": "password",
    "username" : "GROUP\SITE\USERNAME",
    "password" : "somepassword"
}
r = requests.get(url = URL, params = headers, data = data)
data = r.json()

accessToken = data['access_token']
print(accessToken)

When I run the Swift Playground for the code below nothing is returned!
It seems the script exits at  guard let data = data else { return }
How could I get the same results as the Python Script above.
I've tried implementing URLComponents using this tutorial...
import UIKit

var url = "http://just/the/url"
extension Dictionary {
    func percentEncoded() -> Data? {
        return map { key, value in
            let escapedKey = "\(key)"
            let escapedValue = "\(value)"
            print(escapedKey + "=" + escapedValue)
            return escapedKey + "=" + escapedValue
        }
        .joined(separator: "&")
        .data(using: .utf8)

    }
}

extension CharacterSet {
    static let urlQueryValueAllowed: CharacterSet = {
        let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
        let subDelimitersToEncode = "$&'()*+,;="

        var allowed = CharacterSet.urlQueryAllowed
        allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
        return allowed
    }()
}

var request = URLRequest(url: URL(string:url)!)
   request.httpMethod = "GET"
let parameters: [String: String] = [
    "grant_type":"password",
    "username":"GROUP\\SITE\\USER",
    "password":"somePassword"
]
   request.httpBody = parameters.percentEncoded()
   request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
   request.setValue("application/XML", forHTTPHeaderField: "Accept")

let config = URLSessionConfiguration.default
    URLSession(configuration: config).dataTask(with: request) { (data, response, err) in

       guard let data = data else { return }
        print(data)
       guard let dataAsString = String(data: data, encoding: .utf8)else {return}
     print(dataAsString)

       guard let httpResponse = response as? HTTPURLResponse,
             (200...299).contains(httpResponse.statusCode) else {
           print("Bad Credentials")
           return
       }

       //HTTP Status Code!
        print("HTTP RESPONSE:"+"\(httpResponse.statusCode)")
//
           }.resume()

A: If I remember correctly, starting in iOS 13, you cant have httpBody for a GET call, so you'll either need to switch to a POST/PUT or add the params into the url string (See below)
You also had different Accept headers in your python vs. swift.  One was xml the other was json.
var urlComponents = URLComponents(string: "http://this/is/the/url")
urlComponents?.queryItems = [
    URLQueryItem(name: "grant_type", value: "password"),
    URLQueryItem(name: "username", value: "username"),
    URLQueryItem(name: "password", value: "somepassword")
]

guard let url = urlComponents?.url else { return } // You can print url here to see how it looks
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("en_US", forHTTPHeaderField: "Accept-Language")

let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data,
            let response = response as? HTTPURLResponse,
            error == nil else {
            print("error", error ?? "Unknown error")
            return
        }
        print(response)
        guard (200 ... 299) ~= response.statusCode else {
            print("response = \(response)")
            return
        }

        let responseString = String(data: data, encoding: .utf8)
        print(responseString)
    }
    task.resume()

A: The problem was the following...
 request.httpMethod = "GET"

I had to change the get to "POST" and now I have the token!!!!
I was confused because the python script used GET.  I had a bash script that that used curl to get the token displayed the logged post.
In short my above Swift Playground now works by changing the request.httpMethod to "POST". THANKS FOR ALL THE HELP


text:
Q: Kotlin sealed class and type inference im using a sealed class to report back success or error to client code:
sealed class Result<out T : Any> {
    data class Success<out T : Any>(val data: T) : Result<T>()
    data class Error(val exception: Exception) : Result<Nothing>()
}

But im stuck getting even the simplest unit test to compile using it:
    val error = Result.Error(IOException("message"))
    assertThat(error, instanceOf(Result.Error::class.java))

I get the message : Type Inference failed. Not enough information to infer parameter T in fun  instanceOf(type : Class<*>) : Matcher!
Looks like im missing something important in Kotlin.
Thanks for helping me out!

A: there is no problem with your code for me.
import org.hamcrest.CoreMatchers.instanceOf
import org.junit.Test

import org.junit.Assert.*
import java.io.IOException

class ExampleUnitTest {
    @Test
    fun test1() {
        val error = Result.Error(IOException("message"))
        assertTrue(error is Result.Error)
    }

    @Test
    fun test2() {
        val error = Result.Error(IOException("message"))
        assertThat(error , instanceOf(Result.Error::class.java))
    }

    sealed class Result<out T : Any> {
        data class Success<out T : Any>(val data: T) : Result<T>()
        data class Error(val exception: Exception) : Result<Nothing>()
    }
}

Also, I'll suggest you to use the keyword is to check if your class is an instance of something in kotlin (like in test1)

A: Looks like i was looking in the false API. As im mostly using assertj.
Below code is clean and fluent to read
assertThat(result).isInstanceOf(Result.Error::class.java)

A: To avoid ::class I prefer this.
assertThat(result is Result.Error).isTrue()


text:
Q: Как перезапустить mongoDB в случае перезагрузки сервера? При перезагрузке ubuntu 18.4 нужно вручную перезапускать mongoDB. Как можно автоматизировать данный процесс?

A: Для автоматического запуска после запуска системы:
sudo systemctl enable mongodb


text:
Q: Solution of integral equation If $x$ is a real-valued, differentiable function of $t$, what is, and how do I find the solution of
$$\int_a^b x(t) \frac{dx(t)}{dt} dt$$

A: Fundamental theorem of calculus:
$${1\over 2}x(t)^2\bigg|_a^b={1\over 2}\left(x(b)^2-x(a)^2\right).$$
It comes from the fact that
$$dx={dx\over dt}\,dt={dx(t)\over dt}\,dt$$


text:
Q: Check if file exists before showing image? I need to make an image gallery with a variable number of images. I'm making a loop that checks for a lot of image names, like image1, image2, image3 and so on.
I need to make a condition so that it doesn't show a missing file icon if an image doesn't exists. How can I check if the file exists and if true show it?
Thanks.

A: I think there are several PHP functions that will let you check for the existence of a file.  One of them is file_exists:
bool file_exists ( string $filename )

Another function that you can use is is_file.  According to the documentation:

Returns TRUE if the filename exists
  and is a regular file, FALSE
  otherwise.

So in your code you can do something like:
if (file_exists($fileName)) {
    // do stuff with file
}

// OR

if (is_file($fileName)) {
    // do stuff with file
}

A: file_exists is your friend.


text:
Q: Bean to PreparedStatement I am wondering if there is an opposite tool like bean-loader ( http://code.google.com/p/bean-loader/ ). I just want to genereate a prepared statement out of a bean. Because I do not need a fully blown ORM framework but want to save the time for coding all the different jdbc prepared statement setters for all the different data types.

A: You might have a look at POJava Persistence.  You can find some example code here to see if it matches your needs.  Full disclosure... I wrote the thing, but I still think it's a good fit for what you're asking.


text:
Q: What is the purpose of willSet and didSet in Swift? Swift has a property declaration syntax very similar to C#'s:
var foo: Int {
    get { return getFoo() }
    set { setFoo(newValue) }
}

However, it also has willSet and didSet actions. These are called before and after the setter is called, respectively. What is their purpose, considering that you could just have the same code inside the setter?

A:
The willSet and didSet observers for the properties whenever the property is assigned a new value. This is true even if the new value is the same as the current value.

And note that willSet needs a parameter name to work around, on the other hand, didSet does not.

The didSet observer is called after the value of property is updated. It compares against the old value. If the total number of steps has increased, a message is printed to indicate how many new steps have been taken. The didSet observer does not provide a custom parameter name for the old value, and the default name of oldValue is used instead.

A: The point seems to be that sometimes, you need a property that has automatic storage and some behavior, for instance to notify other objects that the property just changed. When all you have is get/set, you need another field to hold the value. With willSet and didSet, you can take action when the value is modified without needing another field. For instance, in that example:
class Foo {
    var myProperty: Int = 0 {
        didSet {
            print("The value of myProperty changed from \(oldValue) to \(myProperty)")
        }
    }
}

myProperty prints its old and new value every time it is modified. With just getters and setters, I would need this instead:
class Foo {
    var myPropertyValue: Int = 0
    var myProperty: Int {
        get { return myPropertyValue }
        set {
            print("The value of myProperty changed from \(myPropertyValue) to \(newValue)")
            myPropertyValue = newValue
        }
    }
}

So willSet and didSet represent an economy of a couple of lines, and less noise in the field list.

A: You can also use the didSet to set the variable to a different value. This does not cause the observer to be called again as stated in Properties guide. For example, it is useful when you want to limit the value as below:
let minValue = 1

var value = 1 {
    didSet {
        if value < minValue {
            value = minValue
        }
    }
}

value = -10 // value is minValue now.

A: These are called Property Observers:

Property observers observe and respond to changes in a property's
  value. Property observers are called every time a property's value is
  set, even if the new value is the same as the property's current
  value.

Excerpt From: Apple Inc. "The Swift Programming Language." iBooks. https://itun.es/ca/jEUH0.l
I suspect it's to allow for things we would traditionally do with KVO such as data binding with UI elements, or triggering side effects of changing a property, triggering a sync process, background processing, etc, etc.

A:
NOTE
willSet and didSet observers are not called when a property is set in an initializer before delegation takes place

A: Getter and setter are sometimes too heavy to implement just to observe proper value changes. Usually this needs extra temporary variable handling and extra checks, and you will want to avoid even those tiny labour  if you write hundreds of getters and setters. These stuffs are for the situation.

A: In your own (base) class, willSet and didSet are quite reduntant , as you could instead define a calculated property (i.e get- and set- methods) that access a _propertyVariable and does the desired pre- and post- prosessing.
If, however,  you override a class where the property is already defined, then the willSet and didSet are useful and not redundant!

A: My understanding is that set and get are for computed properties (no backing from stored properties)
if you are coming from an Objective-C bare in mind that the naming conventions have changed. In Swift an iVar or instance variable is named stored property
Example 1 (read only property) - with warning:
var test : Int {
    get {
        return test
    }
}

This will result in a warning because this results in a recursive function call (the getter calls itself).The warning in this case is "Attempting to modify 'test' within its own getter".
Example 2. Conditional read/write - with warning
var test : Int {
    get {
        return test
    }
    set (aNewValue) {
        //I've contrived some condition on which this property can be set
        //(prevents same value being set)
        if (aNewValue != test) {
            test = aNewValue
        }
    }
}

Similar problem - you cannot do this as it's recursively calling the setter.
Also, note this code will not complain about no initialisers as there is no stored property to initialise.
Example 3. read/write computed property - with backing store
Here is a pattern that allows conditional setting of an actual stored property
//True model data
var _test : Int = 0

var test : Int {
    get {
        return _test
    }
    set (aNewValue) {
        //I've contrived some condition on which this property can be set
        if (aNewValue != test) {
            _test = aNewValue
        }
    }
}

Note The actual data is called _test (although it could be any data or combination of data)
Note also the need to provide an initial value (alternatively you need to use an init method) because _test is actually an instance variable
Example 4. Using will and did set
//True model data
var _test : Int = 0 {

    //First this
    willSet {
        println("Old value is \(_test), new value is \(newValue)")
    }

    //value is set

    //Finaly this
    didSet {
        println("Old value is \(oldValue), new value is \(_test)")
    }
}

var test : Int {
    get {
        return _test
    }
    set (aNewValue) {
        //I've contrived some condition on which this property can be set
        if (aNewValue != test) {
            _test = aNewValue
        }
    }
}

Here we see willSet and didSet intercepting a change in an actual stored property.
This is useful for sending notifications, synchronisation etc... (see example below)
Example 5. Concrete Example - ViewController Container
//Underlying instance variable (would ideally be private)
var _childVC : UIViewController? {
    willSet {
        //REMOVE OLD VC
        println("Property will set")
        if (_childVC != nil) {
            _childVC!.willMoveToParentViewController(nil)
            self.setOverrideTraitCollection(nil, forChildViewController: _childVC)
            _childVC!.view.removeFromSuperview()
            _childVC!.removeFromParentViewController()
        }
        if (newValue) {
            self.addChildViewController(newValue)
        }

    }

    //I can't see a way to 'stop' the value being set to the same controller - hence the computed property

    didSet {
        //ADD NEW VC
        println("Property did set")
        if (_childVC) {
//                var views  = NSDictionaryOfVariableBindings(self.view)    .. NOT YET SUPPORTED (NSDictionary bridging not yet available)

            //Add subviews + constraints
            _childVC!.view.setTranslatesAutoresizingMaskIntoConstraints(false)       //For now - until I add my own constraints
            self.view.addSubview(_childVC!.view)
            let views = ["view" : _childVC!.view] as NSMutableDictionary
            let layoutOpts = NSLayoutFormatOptions(0)
            let lc1 : AnyObject[] = NSLayoutConstraint.constraintsWithVisualFormat("|[view]|",  options: layoutOpts, metrics: NSDictionary(), views: views)
            let lc2 : AnyObject[] = NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: layoutOpts, metrics: NSDictionary(), views: views)
            self.view.addConstraints(lc1)
            self.view.addConstraints(lc2)

            //Forward messages to child
            _childVC!.didMoveToParentViewController(self)
        }
    }
}

//Computed property - this is the property that must be used to prevent setting the same value twice
//unless there is another way of doing this?
var childVC : UIViewController? {
    get {
        return _childVC
    }
    set(suggestedVC) {
        if (suggestedVC != _childVC) {
            _childVC = suggestedVC
        }
    }
}

Note the use of BOTH computed and stored properties. I've used a computed property to prevent setting the same value twice (to avoid bad things happening!); I've used willSet and didSet to forward notifications to viewControllers (see UIViewController documentation and info on viewController containers)
If I've made a mistake anywhere, please edit to fix it!

A: The many well-written existing answers cover the question well, but I'll mention, in some detail, an addition that I believe is worth covering.

The willSet and didSet property observers can be used to call delegates, e.g., for class properties that are only ever updated by user interaction, but where you want to avoid calling the delegate at object initialization.
I'll cite Klaas up-voted comment to the accepted answer:

willSet and didSet observers are not called when a property is first
  initialized. They are only called when the property's value is set
  outside of an initialization context.

This is a quite neat as it means e.g. the didSet property is a good choice of launch point for delegate callbacks & functions, for your own custom classes.
As an example, consider some custom user control object, with some key property value (e.g. position in rating control), implemented as a subclass of UIView:
// CustomUserControl.swift
protocol CustomUserControlDelegate {
    func didChangeValue(value: Int)
    // func didChangeValue(newValue: Int, oldValue: Int)
    // func didChangeValue(customUserControl: CustomUserControl)
    // ... other more sophisticated delegate functions
}

class CustomUserControl: UIView {

    // Properties
    // ...
    private var value = 0 {
        didSet {
            // Possibly do something ...

            // Call delegate.
            delegate?.didChangeValue(value)
            // delegate?.didChangeValue(value, oldValue: oldValue)
            // delegate?.didChangeValue(self)
        }
    }

    var delegate: CustomUserControlDelegate?

    // Initialization
    required init?(...) {
        // Initialise something ...

        // E.g. 'value = 1' would not call didSet at this point
    }

    // ... some methods/actions associated with your user control.
}

After which your delegate functions can be used in, say, some view controller to observe key changes in the model for CustomViewController, much like you'd use the inherent delegate functions of the UITextFieldDelegate for UITextField objects (e.g. textFieldDidEndEditing(...)).
For this simple example, use a delegate callback from the didSet of the class property value to tell a view controller that one of it's outlets have had associated model update:
// ViewController.swift
Import UIKit
// ...

class ViewController: UIViewController, CustomUserControlDelegate {

    // Properties
    // ...
    @IBOutlet weak var customUserControl: CustomUserControl!

    override func viewDidLoad() {
        super.viewDidLoad()
        // ...

        // Custom user control, handle through delegate callbacks.
        customUserControl = self
    }

    // ...

    // CustomUserControlDelegate
    func didChangeValue(value: Int) {
        // do some stuff with 'value' ...
    }

    // func didChangeValue(newValue: Int, oldValue: Int) {
        // do some stuff with new as well as old 'value' ...
        // custom transitions? :)
    //}

    //func didChangeValue(customUserControl: CustomUserControl) {
    //    // Do more advanced stuff ...
    //}
}

Here, the value property has been encapsulated, but generally: in situations like these, be careful not to update the value property of the customUserControl object in the scope of the associated delegate function (here: didChangeValue()) in the view controller, or you'll end up with infinite recursion.

A: One thing where didSet is really handy is when you use outlets to add additional configuration.
@IBOutlet weak var loginOrSignupButton: UIButton! {
  didSet {
        let title = NSLocalizedString("signup_required_button")
        loginOrSignupButton.setTitle(title, for: .normal)
        loginOrSignupButton.setTitle(title, for: .highlighted)
  }

A: I do not know C#, but with a little guesswork I think I understand what
foo : int {
    get { return getFoo(); }
    set { setFoo(newValue); }
}

does. It looks very similar to what you have in Swift, but it's not the same: in Swift you do not have the getFoo and setFoo. That is not a little difference: it means you do not have any underlying storage for your value.
Swift has stored and computed properties.
A computed property has get and may have set (if it's writable). But the code in the getter and setter, if they need to actually store some data, must do it in other properties. There is no backing storage.
A stored property, on the other hand, does have backing storage. But it does not have get and set. Instead it has willSet and didSet which you can use to observe variable changes and, eventually, trigger side effects and/or modify the stored value. You do not have willSet and didSet for computed properties, and you do not need them because for computed properties you can use the code in set to control changes.


text:
Q: Can't access value in my data store using reducer I'm dispatching an action after I query my db for an array of data:
dispatch({
                type: "SET_EDIT_PRODUCTS",
                item: [
                  {
                    name: productData.name,
                    price: productData.price,
                    description: productData.description,
                    quantity: productData.description,
                  },
                ],
              });

Here is how the data is stored in my reducer:
export const initialState = {
  editProductBasket: [],

};

Here is how my case is structured:
case "SET_EDIT_PRODUCT":
      return {
        ...state,
        editProductBasket: [...state.editProductBasket, action.item],
      };

Now, when I try to access the name property in my editProductBasket, I get the following error:
TypeError: Cannot read property 'name' of undefined
I think I may be incorrectly destructuring the array when I try to access the property:
const [
    {
      editProductBasket: [{ name }],
    },
    dispatch,
  ] = useStateValue();

return (
    <div className="phone__mockup">
     {name}
    </div>
  );

A: You're getting undefined because there's a mistake in the way you're destructuring the action.item and setting it in the reducer.
Instead of doing editProductBasket: [...state.editProductBasket, action.item],,
try this :
editProductBasket: [...state.editProductBasket, ...action.item],.
You're not destructuring the array coming from action.item. Due to this an array is created inside the editProductBasket array instead of creating a new object of product details.


text:
Q: How to stop scrolling in ListView? I want the listview not to be scrolled and the items to be displayed in it normally; then I can manage the scrolling with ScrollView.
look the codes:
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/submit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/submit"
                android:textColor="@color/white"
                android:textSize="20dp"
                android:padding="12dp"
                android:background="@drawable/button_success"
                android:gravity="center"

                android:layout_marginTop="12dp"
                android:layout_marginRight="12dp"
                android:layout_marginLeft="12dp"/>
            <ListView
                android:id="@+id/listview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:divider="@color/Color_Red"
                android:padding="12dp"
                android:layout_marginTop="16dp"/>

        </LinearLayout>
    </ScrollView>

A: use this method to your view, it will stop scrolling,
listView.smoothScrollBy(0, 0);


text:
Q: ASP.NET MVC Config Question What exactly is this line in the config doing when it is using IIS7 Integrated mode?
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*"
     path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web,
         Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

Without this I get an error saying it cannot find the .axd when trying to run my site but with it my site works, what does it do?
Thanks

A: That is necessary to work around an obscure issue when using IIS7 in integrated mode and extensionless URLs. It enables extensionless URLs to work. This issue will be fixed in the future and we'll be able to remove that line. For now, just ignore it and don't remove it. :)


text:
Q: Why aren't there well-hinted Type1 Computer Modern fonts supporting the T1 encoding yet? Given the popularity of PDF, the pain that is OT1, and the bad on-screen rendering of bitmapped fonts in Adobe's software, I would have expected that someone would have undertaken conversion/extension of the BlueSky fonts to the T1 encoding while maintaining the quality of the hints ... but I've seen nothing about such a project anywhere.
Why is that? (Or am I wrong? I would love to be wrong!)
Edit:
Now I've seen that someone is selling European Computer Modern fonts in Type1(?), and evidently they use T1 -- but why are they not free yet?

A: read the web page of the font project "The Latin Modern (LM) Family of Fonts" and the demo page


text:
Q: Too many positional arugments using constructor My First Post - Please Help me to Solve my Issue
Guys This is My Code of Cart Screen I Have to Call My Main Screen With Selected Index = 2 from Cart Screen
but I am Having Issues with this.
Can Somebody Help me to Solve My Issue
My Main Screen Code is here -
const MainScreen(selectedMainIndex == 2);

class MainScreen extends StatefulWidget {
final int? id;
const MainScreen({Key? key, this.id}) : super(key: key);

I Have to Call
MainScreen With selectedMainIndex = 2
from Another Screen
I Have Imported Main Screen But I Cant Find Where is My Mistake??
Using Flutter 3.3

A: To pass value on a named constructor,
final int? id;
const MainScreen({Key? key, this.id}) : super(key: key);

you need to do
MainScreen(selectedMainIndex: 2)

Instead of ==, it will be :.
Find more about #using-constructors


text:
Q: Can I install Google Chrome without typing lines of text? I am a complete dork when it comes to computers so maybe I should forget Linux altogether! I want to install Chrome, it has all my bookmarks etc. Is there an easy way without writing lines of code in places I cannot find?

A: You can google for Chrome, go to Google official web site, download the appropriate .deb (probably 32bits), double click it and follow the instructions.
EDIT: Here is the download link: https://www.google.com/chrome?brand=CHMO#eula. Choose .deb for 32bits (or 64bits if you installed Ubuntu x64).

A: Use your current browser to download Chrome from the Google Chrome website. It should download a .deb file. The default download location for most downloads is the Downloads folder for your user account unless you changed it in your browser settings. Open a Terminal session with Control-Alt-T. Navigate to your Downloads folder with
cd ~/Downloads ;ls -l

which will also show the contents of the Downloads folder. You should see a file named something like google-chrome-stable_current_i386.deb Get dpkg to handle the install by issuing
sudo dpkg -i google-chrome-stable_current_i386.deb

Enter your user password when asked. dpkg will handle the install and place a launcher for Chrome in your Dash.


text:
Q: Stop video at specific position using windows media player SDK Is there a way to stop a video at a particular position using Windows Media Player SDK? I am using C# for embedding the player and trying to see if the IWMPControls3 Interface has any stopping capability at a particular point in terms of position or time. If it can be done, then how to do it?

A: It certainly can be done, though I no longer remember the techniques.  There are ways that you can access the data in the stream well enough to reconstruct the audio and individual frames of video.  People have written systems where the user can type a precise time and frame number and the video player jumps to that spot.
Since your question was "is there a way", the answer is "Yes".  However, I can't remember enough of the specifics to tell you how to do it.

A: Like I explained in the same question here, you can use a timer to control the CurrentPosition:
private Timer tmrWmpPlayerPosition;
private TimeSpan StopPosition;

private void btn_Click(object sender, EventArgs e)
{
    wmpPlayer.Ctlcontrols.currentPosition = 4;
    StopPosition=TimeSpan.Parse("00:20:20");
    StopWmpPlayerTimer();
    StartWmpPlayerTimer();
}

private void tmrWmpPlayerPosition_Tick(object sender, EventArgs e)
{
    if ((Convert.ToInt32(StopPosition.TotalSeconds) != Convert.ToInt32(wmpPlayer.Ctlcontrols.currentPosition))) return;
    wmpPlayer.Ctlcontrols.pause();
    StopWmpPlayerTimer();
}

private void StartWmpPlayerTimer()
{
    tmrWmpPlayerPosition = new Timer();
    tmrWmpPlayerPosition.Tick += new EventHandler(tmrWmpPlayerPosition_Tick);
    tmrWmpPlayerPosition.Enabled = true;
    tmrWmpPlayerPosition.Interval = 1000;
    tmrWmpPlayerPosition.Start();
}

private void StopWmpPlayerTimer()
{
    if (tmrWmpPlayerPosition != null)
        tmrWmpPlayerPosition.Dispose();
    tmrWmpPlayerPosition = null;
}


text:
Q: Xamarin function error I got this error when I start the emulator:

An unhandled exception occured

I have tried to call the function ciao in every way, using delegate. Can someone explain why this is wrong?
using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace Prova
{

    [Activity(Label = "Prova", MainLauncher = true, Icon = "@drawable/icon")]

    public class MainActivity : Activity
    {

        Button saved;
        protected override void OnCreate(Bundle bundle)
        {
            saved = FindViewById<Button>(Resource.Id.Saved);
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);
            saved.Click += (object sender, EventArgs e) => {
                ciao(sender, e);
            };
        }

        private void ciao (object sender, EventArgs e)
        {

        }
    }
}

A: It's hard to say for sure what the issue is since you didn't include the full exception and stacktrace, but one thing I can see here that would cause the code to fail is that you're trying to pull the button out of the UI before you actually set the view. FindViewById() returns null if the view can't be found, so you're likely hitting a NullReferenceException when trying to attach the click handler.
You should update your OnCreate method to look something like this:
protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    SetContentView(Resource.Layout.Main);

    saved = FindViewById<Button>(Resource.Id.Saved);
    saved.Click += ciao;
}


text:
Q: Set selected option JQuery I am using jquery-1.12.3.min.js and dynamically get options for select
function loadCompanies() {
if ($("#isSubsidiaryCompany").is(":checked")) {
    $.ajax({
        type : "GET",
        url : "get_companies",
        success : function(data) {
            $.each(data, function(i, data) {
                $('#companiesList').append($('<option>', {
                    value : data.id,
                    text : data.name
                }));
            });
        }

    })
    $("#companiesSelect").show();
    $('#companiesList').val(data.id);
} else {
    $("#companiesSelect").hide();
}

I want to set option selected but $('#companiesList').val(data.id) doesn`t work, could you suggest me the right way do achieve this, thanks in advance

A: You are setting the value outside of the AJAX callback function. Which means that those options are not guaranteed that they will be there. Put your code into the success callback:
if ($("#isSubsidiaryCompany").is(":checked")) {
    $.ajax({
        type : "GET",
        url : "get_companies",
        success : function(data) {
            $.each(data, function(i, data) {
                $('#companiesList').append($('<option>', {
                    value : data.id,
                    text : data.name
                }));
            });
            $("#companiesSelect").show();               // < === HERE ===
            $('#companiesList').val(data.id);
        }

    })
// ...

Also, to which data are you referring to in your .val(data.id)?

A: $('#companiesList').val(data.id)
I think there is problem with your data object. please make sure that data.id shoudl contain something.


text:
Q: Working with a css3 key frame slide effect but cant figure out how to configure correctly.. Fiddle included The idea is to have a responsive version of this fiddle(see below) that is 100% wide and has a height of 500px... If I adjust the width of this to 100% it messes up along the end of the animation.. How should I go about making a simple animation like this that will work cross browser, have a width of 100%, be displayed seamlessly, and a switchable height via media queries(I can do the queries part)..
my code: http://jsfiddle.net/hkJsm/
html

css
@-webkit-keyframes slide {
from{
    background-position:575px;
}
to{
    background-position:1725px;
}
}

#logo{
text-align:center;
width:575px;
height:200px;
background:url(http://f.cl.ly/items/0g3q1A203t2A2m182i1k/newbg.png);
-webkit-animation: slide 10s linear infinite;
 }

Thanks for all the help

A: Your problem is interesting, so I realized the image had to be cropped because in CSS3 you can't manually flip images, so I've edited it.  It is working in this fiddle, and was fixed by editing this image to this, and changing the background-position property a bit on to in the animation:
background-position:1725px;
to
background-position:1645px;
The image conversions are shown below.
This image
To this

A: Here's what you can do:
Fiddle: http://jsfiddle.net/hkJsm/1/
CSS
 .outer{
     background:url(http://f.cl.ly/items/0g3q1A203t2A2m182i1k/newbg.png);
     -webkit-animation: slide 10s linear infinite;

 }
 #logo{
     min-height: 80px;
 }

HTML


text:
Q: Finding Intersection points using array, linspace and IF I am plotting two equations against each other, I did this by creating a 2x100 array and a linspace. I have successfully plotted the curves, but I don't know how to find the values (of u and c) that they intersect at?
I have tried intersect(,), find(==), but they doesn't work with my problem, I think because it uses an if loop.
Here is my code:
clear all
A = 3;
B = 1.8;
d = 1;
c2 = 1;
c1 = 0.7;
s = 0.1;

c = linspace(0,1.5);
u = zeros(2,numel(c));

for i = 1:numel(c)
u(1,i)= c(i) / ((A/(c(i)+1))-(d*c(i)/(c(i)+c2))) ;
u(2,i)= B*c(i) /(c(i)+c1)-s;
end

hold on
plot(c,u(1,:),'r');
plot(c,u(2,:),'g');
hold off

A: Since you are evaluating at discrete points, you have not hit a point where u_1==u_2. You can see the point where they are closest with
>> [diff_min, diff_min_index] = min(abs(u(1,:)-u(2,:)))

diff_min =

    0.0046

diff_min_index =

    65
>> hold on
>> plot(c(diff_min_index),u(1,diff_min_index))
>> hold off

Perhaps more helpfully, you can find the indices when u_1-u_2 changes sign:
>> find(diff(sign(u(1,:)-u(2,:)))~=0)

ans =

     4    65

To find the intersection, you could define a function as the difference of your two functions f=u_1 - u_2 and search for roots using the MATLAB function fzero:
You could do this by defining your original functions as anonymous functions:
>> f1 = @(c) c./((A./(c+1)) - d*c./(c+c2));
>> f2 = @(c) B*c./(c+c1) - s;
>> f_diff = @(c) f1(c) - f2(c);
>> fzero(f_diff,0)

ans =

    0.0488

>> fzero(f_diff,1)

ans =

    0.9729

If the original functions are not available, one could use griddedInterpolant.

A: The low-cost version:
With this method I'm just looking at the nearest point before/after the intersection:
ind = find(diff([u(1,:)-u(2,:)]>0))
interx = c(ind);

The best option (IMO) is to use this method to approximate the intersection points and then use the @Steve's solution to determine a more precise solution.
for i = 1:length(interx)
fzero(f_diff,interx(i))
end


text:
Q: Does the sign of $a(x-x_0)+b(y-y_0)+c(z-z_0)$ represent which side of the plane $M$ is? For $P(x_0, y_0, z_0)$ on a plane of normal vector $N(a, b, c)$ and a random point $M(x, y, z)$
does the sign of $a(x-x_0)+b(y-y_0)+c(z-z_0)$ represent which side of the plane $M$ is on (and is null if $M$ is on the plane)?

A: Answer is yes, as your product is $ \vec N \cdot \vec{PM} $
To see it, set your plane as $ \mathcal P : z = 0 $ ; your normal vector would be $\vec N (a=0,b=0,c=1)$, your point $P$ would have coordinates $(x_0,y_0,0)$ and your product would be $a(x-x_0)+b(y-y_0)+c(z-z_0) = z$, which obviously is positive or negative depending on which side of the plane you're on.
That's an illustration more than a demonstration, but given that scalar product is invariant by isometric transformation we're not that far...
PS: please use Mathjax on M.SE : Should MathJaX be pointed out to new users?


text:
Q: Avoid checkbox captions from wrapping in Windows Vista dialogs For a software project I need to align two additional personalized checkboxes in a microsoft windows vista dialog. I learned about adding checkboxes using Visual-Components and Visualgroups on a CustomizeInterface in delphi.
My Question: What do I need to do with those checkboxes' captions in order to avoid them from wrapping?
1st solution (showing the checkboxes one next to each other):
Dialog.QueryInterface(IFileDialogCustomize, lCustomizeInterface);
if getCheckBox1Caption <> '' then
  lCustomizeInterface.AddCheckButton(DWORD(CheckBox1ID), pWideChar(getCheckBox1Caption), Checked1);
if getCheckBox2Caption <> '' then
  lCustomizeInterface.AddCheckButton(DWORD(CheckBox2ID), pWideChar(getCheckBox2Caption), Checked2);

2nd solution (showing the checkboxes one below the other):
Dialog.QueryInterface(IFileDialogCustomize, lCustomizeInterface);
lCustomizeInterface.StartVisualGroup(DWORD(1005), pWideChar('Test'));
if getCheckBox1Caption <> '' then
  lCustomizeInterface.AddCheckButton(DWORD(CheckBox1ID), pWideChar(getCheckBox1Caption), Checked1);
if getCheckBox2Caption <> '' then
  lCustomizeInterface.AddCheckButton(DWORD(CheckBox2ID), pWideChar(getCheckBox2Caption), Checked2);
lCustomizeInterface.EndVisualGroup;

A: You cannot avoid them wrapping. The IFileDialogCustomize interface offers no functionality to control layout. The control does all of that.
The best you can do is to use a shorter caption if you wish to avoid wrapping onto multiple lines. Or add some extra spaces to avoid the rather nasty mid-word breaks. For instance if you use this text 'Generate expandable / collapsible Excel export' then the outcome is:


text:
Q: How can pure leptonic interactions be mediated by the weak force? $\mu^+ \rightarrow e^+ + \nu_e + \bar \nu_\mu$
Consider the above decay, it is given in my lecture notes as a weak force interaction. I thought the weak force was only involved when quarks change flavours. Here we have no quarks. Why are pure leptonic decays a weak force interaction?

A: "Only the weak force can change quark flavours" is probably what you heard. This is not the same as "the weak force is only involved when quark flavours change". All fermions couple to the weak force. In fact, neutrinos only couple to the weak force. If an interaction involves neutrinos, then the weak force has to be involved.


text:
Q: Can I change my application's name? The catch is that an application with the same name already exists on my account I have two applications live in the iTunes Store named A and B. Now I want to rename B to A. Is that possible? I can remove the current application A and only have B (which should use A's name) once A is removed.

A: I had a similar problem the other day and contacted support. You cannot use an app name that has already been used. Even deleting the app won't help, because the name remains stored in the developer account as used. Another developer account could use it.


text:
Q: On what kind of data (simple example) will KNN outperform linear regression Linear regression outperforms KNN in simple dataset like a line or a polynomial (say quadratic)
I am looking for a simple example where KNN would outperform linear regression.
I tried sin and cosine function but they linear regression performs better as compared to KNN.
For comparison I am using the metrics RMSE and cross correlation.

A: One situation where $k$-NN can easily outperform regression is when you are trying to approximate a function with some structure, but you don't know what that structure is. For example, suppose your data looks like this function $f(x)$:

A nearest-neighbor predictor will be able to fit this function very well, except perhaps right around the transition points.
Now consider trying to fit this with an explicit regression model. If you knew that that $f(x)$ had six transitions and they were all steps, you could write down a model and fit it. However, suppose we didn't know that a priori, and the data might really have 7--or 70 steps! It's still potentially possible to fit this (e.g, by doing some model selection), but it may not be easy and may require a lot of data to distinguish between similar possibilities.
A second advantage of $k$-NN is that its performance scales with the number of data points. Suppose we have a second function $f'(x)$ (not shown), which is like $f(x)$, but has some fine structure: perhaps the values also oscillate slightly, so that $f'(x)=1.001 \textrm{ or } f'(x)=0.001$ for odd $x$ values. You could explicitly incorporate this into your regression model--if you noticed it--but you would need to observe it and realize that it requires yet another degree of freedom in your model. In contrast, you'll get this "for free" with a $k-$NN model.
The major disadvantage of $k$-NN is that there is not much of a model to interpret. A regression model would tell you that there are transition points here and there (with this much uncertainty about their positions), which might be of interest. The $k$-NN model just tells you that the $k$-nearest points are (or are not) similar.


text:
Q: Find the formula of the sum of the first n members of the following sequence: Find the formula of the sum of the first n members of the following sequence:
$ 1; 5 \times 3^2; 9 \times 3^4; ...; (4n-3)\times 3^{2n-2} $

A: $$\begin{align}
\sum_{k=1}^n(4k-3)3^{2k-2}&=\sum_{k=1}^n(2k-1)3^{2k-2}+3\sum_{k=1}^n(2k-2)3^{2k-3}\\&=\left[\frac{d}{dx}\left(\sum_{k=1}^{n}x^{2k-1}\right)\right]_{x=3}+3\left[\frac{d}{dx}\left(\sum_{k=1}^{n}x^{2k-2}\right)\right]_{x=3}\\&=\left[\frac{d}{dx}\left(\frac{1-x^{2n+1}}{1-x^2}\right)\right]_{x=3}+3\left[\frac{d}{dx}\left(\frac{1-x^{2n}}{1-x^2}\right)\right]_{x=3}\end{align}$$
Now differentiate the expressions and evaluate the derivative at $x=3$.


text:
Q: Is there a performance improvement with new border properties for ContentPresenter, Grid, and StackPanel that are introduced in windows 10 Is there a performance improvement with new border properties for ContentPresenter, Grid,and StackPanel are introduced in windows 10 uwp(universal apps), if yes how can we measure it? I tried tocheck the process memory after modifying the existing styles using the diagnostics tool in visual studio 2015, but it remains the same.The size of the control in memory remains the same, irrespective of, if you remove the extra border from visual tree or keep it. I observed this from the heap snapshot in the memory profiler of visual studio.

A: If you want to analyze the time spent by your application preparing UI frames (layout and render), , you can use  "the Application Timeline profiler"  in scenarios like Application Startup, Page Load and Windows resize.
Application Timeline is one of the tools you can start with the Debug / Start Diagnostics Tools Without Debugging command.
For detailed introduction about this tool, you can find on MSDN.


text:
Q: How to convert below api response which is in xml format to c# class? I had posted a question regarding how to call api which is in xml format.
Calling api in xml format in c# - Getting error "Remote certificate is invalid according to the validation procedure"
Now I am getting a response from the api.  But now I want to convert the response  to c# object. The attributes of xml changes in case of success and failure.
Below response if everything is success..
<FIXML xsi:schemaLocation="http://www.finacle.com/fixml BalInq.xsd" xmlns="http://www.finacle.com/fixml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  <ResponseHeader> <RequestMessageKey> <RequestUUID>Req_1560515797477</RequestUUID> <ServiceRequestId>BalInq</ServiceRequestId> <ServiceRequestVersion>10.2</ServiceRequestVersion> <ChannelId>COR</ChannelId> </RequestMessageKey> <ResponseMessageInfo> <BankId>01</BankId> <TimeZone>GMT+05:30</TimeZone> <MessageDateTime>2020-05-29T12:39:13.379</MessageDateTime> </ResponseMessageInfo><UBUSTransaction> <Id/> <Status/> </UBUSTransaction> <HostTransaction> <Id/> <Status>SUCCESS</Status> </HostTransaction> <HostParentTransaction> <Id/> <Status/> </HostParentTransaction> <CustomInfo/> </ResponseHeader>   <BalInqResponse> <BalInqRs> <AcctId> <AcctId>4362500100484501</AcctId> <AcctType> <SchmCode></SchmCode> <SchmType></SchmType> </AcctType> <AcctCurr>INR</AcctCurr> <BankInfo> <BankId></BankId> <Name></Name> <BranchId>436</BranchId> <BranchName></BranchName> <PostAddr> <Addr1></Addr1> <Addr2></Addr2> <Addr3></Addr3> <City></City> <StateProv></StateProv> <PostalCode></PostalCode> <Country></Country> <AddrType></AddrType> </PostAddr> </BankInfo> </AcctId> <AcctBal> <BalType>CLRBAL</BalType> <BalAmt> <amountValue>2.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>SANLIM</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>UTLAMT</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>DRWPWR</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>ADHOC</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>SINTRN</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>CLNADH</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>DACC</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>LIEN</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>SYSRES</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>OVDFUT</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>DAFALM</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>FUTBAL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>FLOAT</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>AVAIL</BalType> <BalAmt> <amountValue>2.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>FFDAVL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>EFFAVL</BalType> <BalAmt> <amountValue>2.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>EFUAVL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode></currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>EMRADV</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>CLNEMR</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>CLNSTR</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>SYSGENLM</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>UNCLRBAL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>POOLAVL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>HOMAVL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>FUTCR</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>UTILFUTBAL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>USEDOC</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>DAFAWITHDRAWL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode></currencyCode> </BalAmt> </AcctBal> </BalInqRs><BalInq_CustomData/> </BalInqResponse></FIXML>

Below response in case of failure
<FIXML xsi:schemaLocation="http://www.finacle.com/fixml BalInq.xsd" xmlns="http://www.finacle.com/fixml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<ResponseHeader>
<RequestMessageKey>
<RequestUUID>Req_1560515797477</RequestUUID>
<ServiceRequestId>BalInq</ServiceRequestId>
<ServiceRequestVersion>10.2</ServiceRequestVersion>
<ChannelId>COR</ChannelId>
</RequestMessageKey>
<ResponseMessageInfo>
<BankId>01</BankId>
<TimeZone></TimeZone>
<MessageDateTime>2020-05-29T07:28:59.421</MessageDateTime>
</ResponseMessageInfo>
<UBUSTransaction>
<Id>null</Id>
<Status>FAILED</Status>
</UBUSTransaction>
<HostTransaction>
<Id>0000</Id>
<Status>FAILURE</Status>
</HostTransaction>
<HostParentTransaction>
<Id>null</Id>
<Status>null</Status>
</HostParentTransaction>
<CustomInfo/>
</ResponseHeader>

<Error>
<FIBusinessException>
<ErrorDetail><ErrorCode>162</ErrorCode><ErrorDesc>Account does not exist</ErrorDesc><ErrorSource>acct.foracid</ErrorSource><ErrorType>BE</ErrorType></ErrorDetail>
</FIBusinessException>
</Error>
</FIXML>

How do I convert it c# objects?.  Because attribute changes.

A: Create two classes, one for Success and one for Failed message. Depending on Status Code parse the response to corresponding class.
If you're thinking to create a dynamical class(es), well you could try using dynamic keyword, but C# is strong type language.
Also, there is a small tool who can help you create the class from the response, give it a try, here is  the link.
So the glue between your statuses is the header part, so I have separated it in one class.
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
   public class HeaderDto
   {

       [XmlRoot(ElementName = "RequestMessageKey", Namespace = "http://www.finacle.com/fixml")]
       public class RequestMessageKey
       {
           [XmlElement(ElementName = "RequestUUID", Namespace = "http://www.finacle.com/fixml")]
           public string RequestUUID { get; set; }
           [XmlElement(ElementName = "ServiceRequestId", Namespace = "http://www.finacle.com/fixml")]
           public string ServiceRequestId { get; set; }
           [XmlElement(ElementName = "ServiceRequestVersion", Namespace = "http://www.finacle.com/fixml")]
           public string ServiceRequestVersion { get; set; }
           [XmlElement(ElementName = "ChannelId", Namespace = "http://www.finacle.com/fixml")]
           public string ChannelId { get; set; }
       }

       [XmlRoot(ElementName = "ResponseMessageInfo", Namespace = "http://www.finacle.com/fixml")]
       public class ResponseMessageInfo
       {
           [XmlElement(ElementName = "BankId", Namespace = "http://www.finacle.com/fixml")]
           public string BankId { get; set; }
           [XmlElement(ElementName = "TimeZone", Namespace = "http://www.finacle.com/fixml")]
           public string TimeZone { get; set; }
           [XmlElement(ElementName = "MessageDateTime", Namespace = "http://www.finacle.com/fixml")]
           public string MessageDateTime { get; set; }
       }

       [XmlRoot(ElementName = "UBUSTransaction", Namespace = "http://www.finacle.com/fixml")]
       public class UBUSTransaction
       {
           [XmlElement(ElementName = "Id", Namespace = "http://www.finacle.com/fixml")]
           public string Id { get; set; }
           [XmlElement(ElementName = "Status", Namespace = "http://www.finacle.com/fixml")]
           public string Status { get; set; }
       }

       [XmlRoot(ElementName = "HostTransaction", Namespace = "http://www.finacle.com/fixml")]
       public class HostTransaction
       {
           [XmlElement(ElementName = "Id", Namespace = "http://www.finacle.com/fixml")]
           public string Id { get; set; }
           [XmlElement(ElementName = "Status", Namespace = "http://www.finacle.com/fixml")]
           public string Status { get; set; }
       }

       [XmlRoot(ElementName = "HostParentTransaction", Namespace = "http://www.finacle.com/fixml")]
       public class HostParentTransaction
       {
           [XmlElement(ElementName = "Id", Namespace = "http://www.finacle.com/fixml")]
           public string Id { get; set; }
           [XmlElement(ElementName = "Status", Namespace = "http://www.finacle.com/fixml")]
           public string Status { get; set; }
       }

       [XmlRoot(ElementName = "ResponseHeader", Namespace = "http://www.finacle.com/fixml")]
       public class ResponseHeader
       {
           [XmlElement(ElementName = "RequestMessageKey", Namespace = "http://www.finacle.com/fixml")]
           public RequestMessageKey RequestMessageKey { get; set; }
           [XmlElement(ElementName = "ResponseMessageInfo", Namespace = "http://www.finacle.com/fixml")]
           public ResponseMessageInfo ResponseMessageInfo { get; set; }
           [XmlElement(ElementName = "UBUSTransaction", Namespace = "http://www.finacle.com/fixml")]
           public UBUSTransaction UBUSTransaction { get; set; }
           [XmlElement(ElementName = "HostTransaction", Namespace = "http://www.finacle.com/fixml")]
           public HostTransaction HostTransaction { get; set; }
           [XmlElement(ElementName = "HostParentTransaction", Namespace = "http://www.finacle.com/fixml")]
           public HostParentTransaction HostParentTransaction { get; set; }
           [XmlElement(ElementName = "CustomInfo", Namespace = "http://www.finacle.com/fixml")]
           public string CustomInfo { get; set; }
       }

       [XmlRoot(ElementName = "Header", Namespace = "http://www.finacle.com/fixml")]
       public class Header
       {
           [XmlElement(ElementName = "ResponseHeader", Namespace = "http://www.finacle.com/fixml")]
           public ResponseHeader ResponseHeader { get; set; }
       }
   }
}

The Success response class would look something like this...
/*
 Licensed under the Apache License, Version 2.0

 http://www.apache.org/licenses/LICENSE-2.0
 */
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
using static Xml2CSharp.HeaderDto;

namespace Xml2CSharp
{
    public class SuccessDto
    {
        public RequestMessageKey RequestMessageKey { get; set; }
        public ResponseMessageInfo ResponseMessageInfo { get; set; }
        public UBUSTransaction UBUSTransaction { get; set; }
        public HostTransaction HostTransaction { get; set; }
        public HostParentTransaction HostParentTransaction { get; set; }
        public ResponseHeader ResponseHeader { get; set; }
        public Header Header { get; set; }

        [XmlRoot(ElementName = "AcctType", Namespace = "http://www.finacle.com/fixml")]
        public class AcctType
        {
            [XmlElement(ElementName = "SchmCode", Namespace = "http://www.finacle.com/fixml")]
            public string SchmCode { get; set; }
            [XmlElement(ElementName = "SchmType", Namespace = "http://www.finacle.com/fixml")]
            public string SchmType { get; set; }
        }

        [XmlRoot(ElementName = "PostAddr", Namespace = "http://www.finacle.com/fixml")]
        public class PostAddr
        {
            [XmlElement(ElementName = "Addr1", Namespace = "http://www.finacle.com/fixml")]
            public string Addr1 { get; set; }
            [XmlElement(ElementName = "Addr2", Namespace = "http://www.finacle.com/fixml")]
            public string Addr2 { get; set; }
            [XmlElement(ElementName = "Addr3", Namespace = "http://www.finacle.com/fixml")]
            public string Addr3 { get; set; }
            [XmlElement(ElementName = "City", Namespace = "http://www.finacle.com/fixml")]
            public string City { get; set; }
            [XmlElement(ElementName = "StateProv", Namespace = "http://www.finacle.com/fixml")]
            public string StateProv { get; set; }
            [XmlElement(ElementName = "PostalCode", Namespace = "http://www.finacle.com/fixml")]
            public string PostalCode { get; set; }
            [XmlElement(ElementName = "Country", Namespace = "http://www.finacle.com/fixml")]
            public string Country { get; set; }
            [XmlElement(ElementName = "AddrType", Namespace = "http://www.finacle.com/fixml")]
            public string AddrType { get; set; }
        }

        [XmlRoot(ElementName = "BankInfo", Namespace = "http://www.finacle.com/fixml")]
        public class BankInfo
        {
            [XmlElement(ElementName = "BankId", Namespace = "http://www.finacle.com/fixml")]
            public string BankId { get; set; }
            [XmlElement(ElementName = "Name", Namespace = "http://www.finacle.com/fixml")]
            public string Name { get; set; }
            [XmlElement(ElementName = "BranchId", Namespace = "http://www.finacle.com/fixml")]
            public string BranchId { get; set; }
            [XmlElement(ElementName = "BranchName", Namespace = "http://www.finacle.com/fixml")]
            public string BranchName { get; set; }
            [XmlElement(ElementName = "PostAddr", Namespace = "http://www.finacle.com/fixml")]
            public PostAddr PostAddr { get; set; }
        }

        [XmlRoot(ElementName = "AcctId", Namespace = "http://www.finacle.com/fixml")]
        public class AcctId
        {
            [XmlElement(ElementName = "AcctId", Namespace = "http://www.finacle.com/fixml")]
            public string AcctId { get; set; }
            [XmlElement(ElementName = "AcctType", Namespace = "http://www.finacle.com/fixml")]
            public AcctType AcctType { get; set; }
            [XmlElement(ElementName = "AcctCurr", Namespace = "http://www.finacle.com/fixml")]
            public string AcctCurr { get; set; }
            [XmlElement(ElementName = "BankInfo", Namespace = "http://www.finacle.com/fixml")]
            public BankInfo BankInfo { get; set; }
        }

        [XmlRoot(ElementName = "BalAmt", Namespace = "http://www.finacle.com/fixml")]
        public class BalAmt
        {
            [XmlElement(ElementName = "amountValue", Namespace = "http://www.finacle.com/fixml")]
            public string AmountValue { get; set; }
            [XmlElement(ElementName = "currencyCode", Namespace = "http://www.finacle.com/fixml")]
            public string CurrencyCode { get; set; }
        }

        [XmlRoot(ElementName = "AcctBal", Namespace = "http://www.finacle.com/fixml")]
        public class AcctBal
        {
            [XmlElement(ElementName = "BalType", Namespace = "http://www.finacle.com/fixml")]
            public string BalType { get; set; }
            [XmlElement(ElementName = "BalAmt", Namespace = "http://www.finacle.com/fixml")]
            public BalAmt BalAmt { get; set; }
        }

        [XmlRoot(ElementName = "BalInqRs", Namespace = "http://www.finacle.com/fixml")]
        public class BalInqRs
        {
            [XmlElement(ElementName = "AcctId", Namespace = "http://www.finacle.com/fixml")]
            public AcctId AcctId { get; set; }
            [XmlElement(ElementName = "AcctBal", Namespace = "http://www.finacle.com/fixml")]
            public List<AcctBal> AcctBal { get; set; }
        }

        [XmlRoot(ElementName = "BalInqResponse", Namespace = "http://www.finacle.com/fixml")]
        public class BalInqResponse
        {
            [XmlElement(ElementName = "BalInqRs", Namespace = "http://www.finacle.com/fixml")]
            public BalInqRs BalInqRs { get; set; }
            [XmlElement(ElementName = "BalInq_CustomData", Namespace = "http://www.finacle.com/fixml")]
            public string BalInq_CustomData { get; set; }
        }

        [XmlRoot(ElementName = "Body", Namespace = "http://www.finacle.com/fixml")]
        public class Body
        {
            [XmlElement(ElementName = "BalInqResponse", Namespace = "http://www.finacle.com/fixml")]
            public BalInqResponse BalInqResponse { get; set; }
        }

        [XmlRoot(ElementName = "FIXML", Namespace = "http://www.finacle.com/fixml")]
        public class FIXML
        {
            [XmlElement(ElementName = "Header", Namespace = "http://www.finacle.com/fixml")]
            public Header Header { get; set; }
            [XmlElement(ElementName = "Body", Namespace = "http://www.finacle.com/fixml")]
            public Body Body { get; set; }
            [XmlAttribute(AttributeName = "schemaLocation", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
            public string SchemaLocation { get; set; }
            [XmlAttribute(AttributeName = "xmlns")]
            public string Xmlns { get; set; }
            [XmlAttribute(AttributeName = "xsi", Namespace = "http://www.w3.org/2000/xmlns/")]
            public string Xsi { get; set; }
        }
    }

}

And Failed class would be like this
/*
 Licensed under the Apache License, Version 2.0

 http://www.apache.org/licenses/LICENSE-2.0
 */
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
using static Xml2CSharp.HeaderDto;

namespace Xml2CSharp
{
    public class FailedDto
    {
        public RequestMessageKey RequestMessageKey { get; set; }
        public ResponseMessageInfo ResponseMessageInfo { get; set; }
        public UBUSTransaction UBUSTransaction { get; set; }
        public HostTransaction HostTransaction { get; set; }
        public HostParentTransaction HostParentTransaction { get; set; }
        public ResponseHeader ResponseHeader { get; set; }
        public Header Header { get; set; }

        [XmlRoot(ElementName = "ErrorDetail", Namespace = "http://www.finacle.com/fixml")]
        public class ErrorDetail
        {
            [XmlElement(ElementName = "ErrorCode", Namespace = "http://www.finacle.com/fixml")]
            public string ErrorCode { get; set; }
            [XmlElement(ElementName = "ErrorDesc", Namespace = "http://www.finacle.com/fixml")]
            public string ErrorDesc { get; set; }
            [XmlElement(ElementName = "ErrorSource", Namespace = "http://www.finacle.com/fixml")]
            public string ErrorSource { get; set; }
            [XmlElement(ElementName = "ErrorType", Namespace = "http://www.finacle.com/fixml")]
            public string ErrorType { get; set; }
        }

        [XmlRoot(ElementName = "FIBusinessException", Namespace = "http://www.finacle.com/fixml")]
        public class FIBusinessException
        {
            [XmlElement(ElementName = "ErrorDetail", Namespace = "http://www.finacle.com/fixml")]
            public ErrorDetail ErrorDetail { get; set; }
        }

        [XmlRoot(ElementName = "Error", Namespace = "http://www.finacle.com/fixml")]
        public class Error
        {
            [XmlElement(ElementName = "FIBusinessException", Namespace = "http://www.finacle.com/fixml")]
            public FIBusinessException FIBusinessException { get; set; }
        }

        [XmlRoot(ElementName = "Body", Namespace = "http://www.finacle.com/fixml")]
        public class Body
        {
            [XmlElement(ElementName = "Error", Namespace = "http://www.finacle.com/fixml")]
            public Error Error { get; set; }
        }

        [XmlRoot(ElementName = "FIXML", Namespace = "http://www.finacle.com/fixml")]
        public class FIXML
        {
            [XmlElement(ElementName = "Header", Namespace = "http://www.finacle.com/fixml")]
            public Header Header { get; set; }
            [XmlElement(ElementName = "Body", Namespace = "http://www.finacle.com/fixml")]
            public Body Body { get; set; }
            [XmlAttribute(AttributeName = "schemaLocation", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
            public string SchemaLocation { get; set; }
            [XmlAttribute(AttributeName = "xmlns")]
            public string Xmlns { get; set; }
            [XmlAttribute(AttributeName = "xsi", Namespace = "http://www.w3.org/2000/xmlns/")]
            public string Xsi { get; set; }
        }
    }
}

Please consider this as pseudo code, since it's not tested.
So when you get the response, parse the header, and read the node you need to validate if its Success or Failed message, then just parse it as that object.


text:
Q: Notify my application when a folder is modified in Windows? I want the ownership of folders created by my application to remain only with my application.
This is because I am linking my application's data to the folders path.
So either of these 2 solutions are fine with me:

*

*Do not allow anybody to modify the folder created by my application.
Only my application can delete/rename the folder. Modifying it
through windows explorer should require admin rights.

*If above solution is not possible, at least my application should be notified of the change so that my application's links are updated.

The question is that whether it is possible to do this in Windows?
I feel language does not play a role, but still if required, I am using Qt in C++ for developing my application.
EDIT: Now there are 2 cases of being notified:
a. When my application is running and the folder is modified.
b. When my application is NOT running and the folder is modified (This may be achieved if Windows maintains a log file for changes to a folder. My application can read this log file and understand the changes in the folder).
Actually, I meant to ask specifically for case b, but now reading the answers makes me feel that it may not be possible to get notified for case b.

A: Security in Windows is account-based, not application-based. A folder isn't "created by your application"; it's created by the user running your application.
As for being notified, just keep an open handle. That will prevent the folder to be changed while you're running. Obviously, when you're not running, you couldn't even be notified.
[edit]
When your app is not running, you need NTFS change journals.

A: You can use QFileSystemWatcher class to monitoring files and directories for modifications.
QFileSystemWatcher *watcher = new QFileSystemWatcher();
watcher->addPath(QStringLiteral("C:\\Folder"));
QObject::connect(watcher,&QFileSystemWatcher::directoryChanged,[](QString folder) {
    qDebug() << folder;
});

A: You can certainly be notified upon dirctory changes - there's a specific API for it:
https://msdn.microsoft.com/en-us/library/windows/desktop/aa365465%28v=vs.85%29.aspx
It's common to run such monitoring calls in a threads of their own in order to reduce the chance of missing bursts of notifications, and the way you handle that, and any subsequent buffering/signaling to other threads, is a bit broad for SO.
Asynchronous overlapped operation seems to be supported, but I have not tried/tested it.


text:
Q: How will a page with two Html elements that have the same ID affect Google Indexing? I have the following code:

    An image, or another div with some text... Lore ipsum ...

    Other divs images... and other content...

I know that the id of a html element must be unique. I am aware that W3C attribute description but my client wants to keep the DIVs without changing the id to a class or without changing the second id to have a unique name.
I was wandering, is this unusual way of writing html code affecting the way Google is crawling the page? Is Google indexing this as any regular page or is skipping content or lowering the rank because of this issue?
I can't find official documentation on how Google works on this issue and I am afraid this is affecting a dozen of pages that I will then need fixing.

A: Violating the unique ID won't necessarily cause problems for web spiders, but it may stop your markup from validating and will also have implications for anything that relies on the "there can be only one" nature of the ID attribute, such as a CSS selector or Javascript.
Your client is misguided.  You're the expert.  Pull rank.

A: For some pages, Google displays anchor links in the search result, so that visitors can directly jump to a section of the page.
If the page of your client would be one of those sites where Google thinks it would be useful, this would not be possible, because you'd need different ids for that, obviously.
However, Google will add these links probably only for pages with some kind of ToC (like Wikipedia). So this wouldn't work for your site anyway, because you wouldn't be able to jump to both of these div elements.


text:
Q: Run Gradle task on the basis of Build Variant I have been struggling on this for past 2 days. There are several solutions on stack overflow which didn't work for me.
I am trying to ignore gradle task for prod environment.
To execute my task i.e. dokkaHtml on build, I am using this command -

tasks.named('preBuild') { finalizedBy(dokkaHtml) }

Is there a way to disable dokkaHtml task when running on different build variant(eg - ignore the task for production builds)?

A: You could try to connect dokka task to a flavor-specific preBuild, so in your case, it would be something like this:
tasks.named('preDevDebugBuild') { finalizedBy(dokkaHtml) }
tasks.named('preDevReleaseBuild') { finalizedBy(dokkaHtml) }
tasks.named('preTestDebugBuild') { finalizedBy(dokkaHtml) }
tasks.named('preTestReleaseBuild') { finalizedBy(dokkaHtml) }

This way you omit dokka for the prod flavor.

A: I am checking the current product flavor and based on the result, enabling the gradle task. This solution is working for me -

def getCurrentFlavor() {
    Gradle gradle = getGradle()
    String  tskReqStr = gradle.getStartParameter().getTaskRequests().toString()
    Pattern pattern
    if( tskReqStr.contains( "assemble" ) )
        pattern = Pattern.compile("assemble(\\w+)(Release|Debug)")
    else
        pattern = Pattern.compile("generate(\\w+)(Release|Debug)")

    Matcher matcher = pattern.matcher( tskReqStr )
    if( matcher.find() )
        return matcher.group(1).toLowerCase()
    else
        return ""
}

var currentFlavor = getCurrentFlavor().toString()
//disable dokka for prod environment
if(!currentFlavor.contains("production")){
    tasks.preBuild.finalizedBy(dokkaHtml)
}


text:
Q: Hide specific \item I have thousands of math tasks, which sometimes consist of several sub-questions. The subtasks are separated in an \enumerate environment with \item. I would like to be able to hide individual \item with the following macro
\long\def\itema#1\itemb{%
    \ifthenelse{\boolean{Aufgabea}}{\item#1\itemb}{\itemb}}

\long\def\itemb#1\itemc{%
\ifthenelse{\boolean{Aufgabeb}}{\item#1\itemc}{\itemc}}

\long\def\itemc#1\end{%
    \ifthenelse{\boolean{Aufgabec}}{\item#1\end}{\end}}

an example code:
\documentclass{article}

\usepackage{ifthen}
\newboolean{Taska}
\setboolean{Taska}{false}
\newboolean{Taskb}
\setboolean{Taskb}{true}
\newboolean{Taskc}
\setboolean{Taskc}{false}

\long\def\itema#1\itemb{%
    \ifthenelse{\boolean{Taska}}{\item#1\itemb}{\itemb}}

\long\def\itemb#1\itemc{%
\ifthenelse{\boolean{Taskb}}{\item#1\itemc}{\itemc}}

\long\def\itemc#1\end{%
    \ifthenelse{\boolean{Taskc}}{\item#1\end}{\end}}

\begin{document}

    \begin{enumerate}
        \itema itema
        \itemb itemb
        \itemc itemc

    \end{enumerate}

\end{document}

my problem is now if a task only consists of two \item commands (\itema and \itemb) it doesn't work. I would have to somehow add to the \itema, \itemb .. macros that they can either end with the next \item or with \end but don't know how. It would be good if the macros stayed in this style.

A: I'm not sure if I understand what you want. Give a try to package dbshow to filter the questions with labels.

\documentclass{article}
\usepackage{dbshow}

\dbNewDatabase{math}{labels=clist, ques=tl}
\begin{dbFilters}{math}
  \dbNewConditional{select}{labels}{label-a, label-b}
\end{dbFilters}
\dbNewStyle{base}{math}{
  before-code = {\dbIfEmptyF{\begin{enumerate}}},
  after-code = {\dbIfEmptyF{\end{enumerate}}},
  item-code = {\item\dbuse{ques}},
}
\dbNewStyle[base]{filter}{math}{raw-filter = {!select}}
\NewDocumentCommand \savemath { O{} m } {%
  \begin{dbitem}{math}[labels={#1}, ques=#2]%
  \end{dbitem}%
}

\begin{document}
\savemath[label-a]{Question 1 with label a.}
\savemath[label-b]{Question 2 with label b.}
\savemath[label-c]{Question 3 with label c.}
\savemath[label-b]{Question 4 with label b.}
\savemath[label-d]{Question 5 with label d.}

\section{Original}
\dbshow{base}{math}
\section{Hide question with label a and b}
\dbshow{filter}{math}
\end{document}


text:
Q: Call class A method from within class B in class A's object property Given class A instance with a property object which contains class B instance, can I call A's method from within B?
For example this class represents a cart:
class jsCart {
  constructor() {
    this.products = {};
  }

  addProduct(product){
    this.products[product.id] = product;
  }

  removeProduct(id) {
    delete this.products[id];
  }
}

And this class represents a product:
class jsProduct {
  constructor(id, price, quantity) {
    this.id = id;
    this.price = price;
    this.quantity = quantity;
  }

  set _quantity(n) {
    this.quantity = n;
  }
}

After adding an instance of jsProduct in jsCart as such:
let cart = new jsCart;
cart.addProduct(new jsProduct('bananas', 23, 1));

Can I call cart.removeProduct() from within the 'bananas' instance of jsProduct without knowing in advance the jsCart instance's var name ?
In other words, is there any way to generally refer to a containing jsCart instance from within jsProduct 'bananas' instance?
Thank you


text:
Q: How to avoid duplication of scheduler tasks when deployed in multiple instances Have a spring Boot application through which i am able to create a cron and schedule the tasks . However when the multiple instances of the app are deployed , the cron gets triggered in all the instances and results in duplication. Is there any configuration which needs to be done in spring level?
We are using redis and using a flag this can be controlled in other instances  but need a better approach for resolving this issue. Tried even the redisson library which didnt help much.
Need to even consider the failover cases whenever a instance is down.Please help.
Thanks

A: Check out this article
Include in your pom.xml schedlock dependencies:
<dependency>
    <groupId>net.javacrumbs.shedlock</groupId>
    <artifactId>shedlock-spring</artifactId>
    <version>2.2.0</version>
</dependency>

<dependency>
    <groupId>net.javacrumbs.shedlock</groupId>
    <artifactId>shedlock-provider-jdbc-template</artifactId>
    <version>2.1.0</version>
</dependency>

Create shedlock table
CREATE TABLE shedlock(
  name VARCHAR(64),
  lock_until TIMESTAMP(3) NULL,
  locked_at TIMESTAMP(3) NULL,
  locked_by  VARCHAR(255),
  PRIMARY KEY (name)
)

And don't forget to add a name to each job you create.
@SchedulerLock(name = "job_name")

This way, when this job will be executed on multiple instances, job record will be added to shedlock table by the first instance, and all other instances will check shedlock table for existing records with needed job name. This way the job will be executed only once.