text:
Q: Selecting something that isn't a div or other standard selector? Update: selecting the "roll" is now working, but I'm still stuck on grabbing the image.
I'm trying to select every item on a website (not mine) that are labeled as roll="article". I can find tutorials online about selecting divs, images, etc. but I can't find anything for "rolls" (might be a label made up by the website, but I'm not sure.)
var article_block = jNode.closest("roll.article");
article_block.css("border", "2px solid red");

This simply doesn't work. No errors, but I don't get the red border.
Then within the "roll" items, I'm trying to select the image that starts with "https://external". It's within a ton of divs, but I'd rather not try and deal with children if possible because the site uses React and the div structure changes. Right now I've got:
var image = article_block.querySelector("[name^=https://external]");

For that, I get "DOMException: Failed to execute 'querySelector': '[name^=https://external]' is not a valid selector."
When I Google this error, I find that a querySelector can't start with a number. But mine doesn't start with a number, so I don't understand.
Here's my code:
function callAttentionToX(jNode) {

    var article_block = jNode.closest("roll.article");
    article_block.css("border", "2px solid red");
    try {

    var image = article_block.querySelector("[name^=https://external]");
    console.log(image);

    ...

    waitForKeyElements("[class$='roll.article']", callAttentionToX);

Here's the HTML I'm working with.

                        <a aria-hidden="true" class="oajrlxb2 g5ia77u1 qu0x051f esr5mh6w e9989ue4 r7d6kgcz rq0escxv nhd2j8a9 nc684nl6 p7hjln8o kvgmc6g5 cxmmr5t8 oygrvhab hcukyx3x jb3vyjys rz4wbd8a qt6c0cv9 a8nywdso i1ao9s8h esuyzwwr f1sip0of lzcic4wl oo9gr5id gpro0wi8" href="https://www.facebook.com/chelsey.sprengeler?__cft__[0]=AZVEpYRntgGV9-kMb1SONRfDQ_Hm6nOFozBDqAmsSWnGw0yyDHdp3Cy6_8hXet_ritlMwr2KTWwQ_Rs_Vvl8d8DGdmU2VBWt8n2uqGq0PW94961HR0UVmom1hKG8HAQOy0ksiLaPFDOtj4fmmxTao6fMD2DZfwO0w2PrIChsFvZ-LQ&__tn__=%3C%2CP-R" role="link" tabindex="-1">

                                            <a class="oajrlxb2 g5ia77u1 qu0x051f esr5mh6w e9989ue4 r7d6kgcz rq0escxv nhd2j8a9 nc684nl6 p7hjln8o kvgmc6g5 cxmmr5t8 oygrvhab hcukyx3x jb3vyjys rz4wbd8a qt6c0cv9 a8nywdso i1ao9s8h esuyzwwr f1sip0of lzcic4wl oo9gr5id gpro0wi8 lrazzd5p" href="https://www.facebook.com/chelsey.sprengeler?__cft__[0]=AZVEpYRntgGV9-kMb1SONRfDQ_Hm6nOFozBDqAmsSWnGw0yyDHdp3Cy6_8hXet_ritlMwr2KTWwQ_Rs_Vvl8d8DGdmU2VBWt8n2uqGq0PW94961HR0UVmom1hKG8HAQOy0ksiLaPFDOtj4fmmxTao6fMD2DZfwO0w2PrIChsFvZ-LQ&__tn__=-UC%2CP-R" role="link" tabindex="0">
                                                Chelsey Sprengeler

                                         ·

                                        <a class="oajrlxb2 g5ia77u1 qu0x051f esr5mh6w e9989ue4 r7d6kgcz rq0escxv nhd2j8a9 nc684nl6 p7hjln8o kvgmc6g5 cxmmr5t8 oygrvhab hcukyx3x jb3vyjys rz4wbd8a qt6c0cv9 a8nywdso i1ao9s8h esuyzwwr f1sip0of lzcic4wl gmql0nx0 gpro0wi8 b1v8xokw" href="https://www.facebook.com/chelsey.sprengeler/posts/10218030275250892?__cft__[0]=AZVEpYRntgGV9-kMb1SONRfDQ_Hm6nOFozBDqAmsSWnGw0yyDHdp3Cy6_8hXet_ritlMwr2KTWwQ_Rs_Vvl8d8DGdmU2VBWt8n2uqGq0PW94961HR0UVmom1hKG8HAQOy0ksiLaPFDOtj4fmmxTao6fMD2DZfwO0w2PrIChsFvZ-LQ&__tn__=%2CO%2CP-R" role="link" tabindex="0">
                                            Yesterday at 11:44 AM

                                         ·

                            <div aria-expanded="false" aria-haspopup="menu" aria-label="More" class="oajrlxb2 gs1a9yip g5ia77u1 mtkw9kbi tlpljxtp qensuy8j ppp5ayq2 goun2846 ccm00jje s44p3ltw mk2mc5f4 rt8b4zig n8ej3o3l agehan2d sk4xxmp2 rq0escxv nhd2j8a9 pq6dq46d mg4g778l btwxx1t3 pfnyh3mw p7hjln8o kvgmc6g5 cxmmr5t8 oygrvhab hcukyx3x tgvbjcpo hpfvmrgz jb3vyjys rz4wbd8a qt6c0cv9 a8nywdso l9j0dhe7 i1ao9s8h esuyzwwr f1sip0of du4w35lb lzcic4wl abiwlrkh p8dawk7l dwo3fsh8 pzggbiyp pkj7ub1o bqnlxs5p kkg9azqs c24pa1uk ln9iyx3p fe6kdd0r ar1oviwq l10q8mi9 sq40qgkc s8quxz6p pdjglbur" role="button" tabindex="0">

1% of food consumed in the U.S is made here on small family farms. In the event of an economic collapse, who do you think will fare better?

Large US farms are currently euthanizing millions of "excess" animals for factory farming because slaughterhouse workers are victims of the virus and processing has slowed.

In Russia:…

See More

                                            <a class="oajrlxb2 g5ia77u1 qu0x051f esr5mh6w e9989ue4 r7d6kgcz rq0escxv nhd2j8a9 nc684nl6 p7hjln8o kvgmc6g5 cxmmr5t8 oygrvhab hcukyx3x jb3vyjys rz4wbd8a qt6c0cv9 a8nywdso i1ao9s8h esuyzwwr f1sip0of lzcic4wl gmql0nx0 gpro0wi8 datstx6m k4urcfbm" href="https://l.facebook.com/l.php?u=https%3A%2F%2Freturntonow.net%2F2020%2F02%2F13%2Fnearly-40-of-russias-food-comes-from-small-family-gardens%2F%3Ffbclid%3DIwAR3GpoDKK2tTrnqyruN3IMptK1bXEthDLOAuhGPpag_8l_-y9T8WkKFaKYk&h=AT2WE1zOdASEzXsLYfttOJ-A6c3FxBVxTEkBz1P96QjMhIBYr21_AbywUgZRJ4MgqkeEIfdxAKzhxIWLQTtKs19Igv_3FDFWc0GubnlMYzzqbHDcZRUgTU0ov7ODeEM3IovrUy7R5icDcf2jCT7hANM&__tn__=H-R&c[0]=AT3DKWTElvH8PY2xklr03tGI6MzhkJ4OP5_UXdDt1C54et1RMKpxZetnJHBV-Cij__tq7ahkBal_zD8ZhNObNCRoBUQYEQDicxZk4VUOHWaX2KI_8UIZIIFcWOJKxHgGoLqUMualNdmAHY92uhpHDWscvJOoV4Nj3FYhyMDOeZ-VNhhtyw" rel="nofollow noopener" role="link" tabindex="0" target="_blank">

A: You can use some thing like to select attribute. Than you can add style attribute with key style and value your css style.
var article = document.querySelectorAll("[roll='article']")[0];
article.setAttribute("style", "border: 2px solid red;")

A: Based on your html you can do something like this (I added notes inside):
const rollArticle = document.querySelector('[role="article"]'); // select the article with roll
const imgArticle = rollArticle.querySelectorAll('img'); // select images inside this article
for (var i=0; i < imgArticle.length; i++) { // iterate over images
  let imgEl = imgArticle[i]; // helper
  if (imgEl.src && imgEl.src.search('https://external') > -1) { // if one of the images src has https://external then:
    imgEl.setAttribute('style', 'outline: 1px solid red;'); // do whatever you want
  }
}

Hope that helps!


text:
Q: Summation involving the integer nearest to $\sqrt n$.
Let $\langle n\rangle$ denote the integer nearest to $\sqrt n$. Evaluate $$\sum_{n=1}^{\infty} \frac{2^{\langle n\rangle}+2^{-\langle n\rangle}}{2^n}.$$

I tried writing down a few terms but I couldn't get any idea of how the sum progress. Any ideas? Thanks.

A: Here is my solution
I bet you are preparing for indian statistical institute exam. (Im also preparing so best of luck)
First of all notice that there are 2i integers whose nearest integer to square root is i.It can be seen by taking a few examples.
So now write down a few terms $$S=\frac{2^1+2^{-1}}{2^1}+\frac{2^1+2^{-1}}{2^2}+\frac{2^{2}+2^{-2}}{2^3} \text{so on}$$

Now consider the sequence $1,3,7,...$ The nth term of this sequence can be written as $n^2-n+1$ You can now convert the sum as $$\sum_{1}^{\infty} \frac{2^i+2^{-i}}{2^{i^2-i+1}}[1/2+1/2^2+...\text{2i terms}]$$ which after simplification van be shown to telescope yielding $3$ as answer.It can be seen from the attached picture.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Double thumbnails after adding custom wallpapers to /usr/share/backgrounds I have followed the advice in various posts to this forum on how to get 12.04 to display my own wallpapers in /usr/share/backgrounds. None worked I have subsequently established that 12.04 uses file precise-wallpapers.xml to read its' wallpapers.
This file is locacted in /usr/share/gnome-background-properties. I have added mine to this file. My issue is that when I right click and select 'change background' I now have two thumbnails for my wallpapers. Does anyone know why this is happening and how to fix it?


text:
Q: How to trigger an event without it happening in JavaFX So, what I want to do is to trigger a setOnMouseClicked event, which I created with lambda expression, without it happening, like a method call in the method start of the main class.

A: You need to specify object that will receive the fired event; the target is an object where the event starts and then propagates upwards through a component hierarchy:
MouseEvent mouseEvent = new MouseEvent(
  MouseEvent.MOUSE_CLICKED, 1, 2, 3, 4, MouseButton.PRIMARY, 5, true, true, true, true, true, true, true, true, true, true, null);
target.fireEvent(mouseEvent);

See the javadoc for details, but seriously, don't do this.


text:
Q: Calculate the values of counters after applying all alternating operations I was trying to solve a problem from the Codility with a given solution. The problem is provided below:
You are given N counters, initially set to 0, and you have two possible operations on them:

increase(X) − counter X is increased by 1,
max counter − all counters are set to the maximum value of any counter.
A non-empty array A of M integers is given. This array represents consecutive operations:

if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
if A[K] = N + 1 then operation K is max counter.
For example, given integer N = 5 and array A such that:

A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4
the values of the counters after each consecutive operation will be:

(0, 0, 1, 0, 0)
(0, 0, 1, 1, 0)
(0, 0, 1, 2, 0)
(2, 2, 2, 2, 2)
(3, 2, 2, 2, 2)
(3, 2, 2, 3, 2)
(3, 2, 2, 4, 2)

The goal is to calculate the value of every counter after all operations.

Write a function:

class Solution { public int[] solution(int N, int[] A); }

that, given an integer N and a non-empty array A consisting of M integers, returns a sequence of integers representing the values of the counters.

The sequence should be returned as:

a structure Results (in C), or
a vector of integers (in C++), or
a record Results (in Pascal), or
an array of integers (in any other programming language).
For example, given:

    A[0] = 3
    A[1] = 4
    A[2] = 4
    A[3] = 6
    A[4] = 1
    A[5] = 4
    A[6] = 4
the function should return [3, 2, 2, 4, 2], as explained above.

Assume that:

N and M are integers within the range [1..100,000];
each element of array A is an integer within the range [1..N + 1].
Complexity:

    expected worst-case time complexity is O(N+M);
    expected worst-case space complexity is O(N) (not counting the storage required for input arguments).

I have a solution provided,
public static int[] solution(int N, int[] A) {

        int[] counters = new int[N];

        int currMax = 0;
        int currMin = 0;

        for (int i = 0; i < A.length; i++) {

            if (A[i] <= N) {

                counters[A[i] - 1] = Math.max(currMin, counters[A[i] - 1]);
                counters[A[i] - 1]++;

                currMax = Math.max(currMax, counters[A[i] - 1]);
            } else if (A[i] == N + 1) {
                currMin = currMax;
            }
        }

        for (int i = 0; i < counters.length; i++) {
            counters[i] = Math.max(counters[i], currMin);
        }

        return counters;
    }

It seems they use 2 storage to hold and update the min/max values and use them inside the algorithm. Obviously, there is a more direct way to solve the problem ie. increase the value by 1 or set all the values to max as suggested and I can do that. The drawback will be to lower perfromance and increased time complexity.
However, I would like to understand what is going on here. I spend times debugging with the example array but the algorithm is still little confusing.
Anyone understand it and can explain to me briefly?

A: It is quite simple, they do lazy update. You keep track at all times of what is the value of the counter that has the highest value (currMax). Then, when you get a command to increase all counters to that maxValue, as that is too expensive, you just save that the last time you had to increase all counters to maxValue, that value was currMin.
So, when do you update a counter value to that value? You do it lazily, you just update it when you get a command to update that counter (increase it). So when you need to increase a counter, you update the counter to the max between its old value and currMin. If this was the first update on this counter since a N + 1 command, the correct value it should have is actually currMin, and that will be higher (or equal) to its old value. One you updated it, you add 1 to it. If now another increase happens, currMin doesn't actually matter, as the max will take its old value until another N + 1 command happens.
The second for is to account for counters that did not get an increase command after the last N + 1 command.
Note that there can be any number of N + 1 commands between 2 increase operations on a counter. It still follows that the value it should have is the maxValue at the time of the last N + 1 command, it doesn't really matter that we didn't update it before with the other maxValue from a previous N + 1, we only care about latest.


text:
Q: Issue with WiFiNINA to get JSON data I'm trying to do a GET request to my weather forecast API service with an Arduino nano 33 IoT but I can't parse JSON data because the code output also other information inside the string, is there a way to "clean" the string with only the JSON data?
Here's my code
#include <ArduinoJson.h>
#include <SPI.h>
#include <WiFiNINA.h>
#include "arduino_secrets.h"

char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;            // your network key index number (needed only for WEP)

int status = WL_IDLE_STATUS;

char server[] = "api.weatherapi.com";    // name address for Google (using DNS)

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
WiFiClient client;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to WiFi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }
  Serial.println("Connected to WiFi");
  printWifiStatus();

  Serial.println("\nStarting connection to server...");
  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected to server");
    // Make a HTTP request:
    client.println("GET /v1/forecast.json?key=9c5df5870ht454gsd0fdd8194739211006&q=Rimini&days=2&aqi=no&alerts=no HTTP/1.0");
    client.println("Host: api.weatherapi.com");
    client.println("Connection: close");
    client.println();
  }
}
void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  while (client.available()) {
    String payload = client.readString();
    Serial.println(payload);

    DynamicJsonDocument doc(4000);
    DeserializationError error = deserializeJson(doc, payload);
    if (error) {
      Serial.print(F("deserializeJson() failed: "));
      Serial.println(error.f_str());
      client.stop();
      return;
    }
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting from server.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

The output:
Starting connection to server...
connected to server
HTTP/1.1 200 OK
Date: Wed, 14 Jul 2021 16:58:42 GMT
Content-Type: application/json
Connection: close
Vary: Accept-Encoding
Server: BunnyCDN-IT1-555
CDN-PullZone: 93447
CDN-Uid: 8fa3a04a-75d9-4707-8056-b7b33c8ac7fe
CDN-RequestCountryCode: IT
CDN-EdgeStorageId: 555
CDN-CachedAt: 2021-07-14 18:58:42
CDN-RequestPullSuccess: True
CDN-RequestPullCode: 200
Cache-Control: public, max-age=180
CDN-RequestId: d6bc580dc2a234693a1ad59cb34aabcb
CDN-Cache: EXPIRED

{"location":{"name":"Rimini","region":"Emilia-Romagna","country":"Italy","lat":44.06,"lon":12.58,"tz_id":"Europe/Rome","localtime_epoch":1626281922,"localtime":"2021-07-14 18:58"},"current":{"condition":{},"uv":7.0},"forecast":{"forecastday":[{"date":"2021-07-14","day":{"daily_will_it_rain":0,"daily_chance_of_rain":"67","daily_will_it_snow":0,"daily_chance_of_snow":"0","condition":{}},"astro":{},"hour":[{"condition":{},"chance_of_rain":"45"},{"condition":{},"chance_of_rain":"67"},{"condition":{},"chance_of_rain":"45"},{"condition":{},"chance_of_rain":"22"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"29"},{"condition":{},"chance_of_rain":"58"},{"condition":{},"chance_of_rain":"87"},{"condition":{},"chance_of_rain":"84"},{"condition":{},"chance_of_rain":"81"},{"condition":{},"chance_of_rain":"78"},{"condition":{},"chance_of_rain":"52"},{"condition":{},"chance_of_rain":"26"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"}]},{"date":"2021-07-15","day":{"daily_will_it_rain":0,"daily_chance_of_rain":"0","daily_will_it_snow":0,"daily_chance_of_snow":"0","condition":{}},"astro":{},"hour":[{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"},{"condition":{},"chance_of_rain":"0"}]}]}}
deserializeJson() failed: InvalidInput

disconnecting from server.

The string "payload" start from 'HTTP/1.1 200 OK' and it should start from '{"location"....'
Thanks to all who will help me.

A: A simple solution is to modify the string.
Looking at the Arduino documentation for String, it seems you have several functions available to you that can help solve this.
For example, you could use indexOf, lastIndexOf and substring to get everything between the first '{' and last '}':
int start = payload.indexOf('{');
int end = payload.lastIndexOf('}');
String body = payload.substring(start, end + 1);

This is not necessarily the most robust solution (e.g. you should check whether it is possible for '{' and '}' to appear in the HTTP header), but this should give you some hints towards a solution. Then again, if this is a small project, this may well be good enough for your use case.
Alternatively, you could cut cut the string up based on the newline:
int start = payload.indexOf('\n');
int body = payload.substring(start + 1);

Again, this makes assumptions about the payload format and you may wish to do some testing to verify those assumptions.
(I can't test this code, so you may need to debug this and make corrections.)


text:
Q: While loop does not allow me parse an string correctly I am writing a program which gets the user's string input and parses it by white spaces.
Since the program needs to repeatedly receive user input until the user enters "exit", I put all my codes in a while loop as below:
while(cont == true)
{
    cin>>command;
    string parsedStr[3];
    parsedStr[0] = "";
    parsedStr[1] = "";
    parsedStr[2] = "";
    int j = 0;

    for(i=0; i<command.size(); i++)
    {
        if (command[i] == ' ')
        {
            ++j;
        }
        parsedStr[j] += command[i];
    }

    cout<<"Command: "<<parsedStr[0]<<"\n";
    cout<<"Argument 1: "<<parsedStr[1]<<"\n";
    cout<<"Argument 2: "<<parsedStr[2]<<"\n";

    /* do my desired operations according to the received command */
}

This is however when I enter a command such as "execute 12 345", it will show the below result and doesn't parse the argument:
Command: execute
Argument 1:
Argument 2:
Command: 12
Argument 1:
Argument 2:
Command: 345
Argument 1:
Argument 2:

But when I move the parser out of the while loop, it works perfectly and prints out the followings:
Command: execute
Argument 1: 12
Argument 2: 345

What should I do?

A: This is because you are reading a string using
cin >> command;

The >> operator stops at the space, so your command ends up with no spaces in it. The next iteration of the loop picks up the first argument and tries to parse it; then the next iteration does the same with the last argument.
You can make your code work by using std::getline instead:
getline(cin, command);

But an easier way to do the same thing is to use >> operator correctly:
cin >> parsedStr[0];
cin >> parsedStr[1];
cin >> parsedStr[2];


text:
Q: Calling Raspberry Pi temp sensor, invalid syntax when calling driver as bash script I'm currently putting together a temperature sensor for my Raspberry Pi and ran into this issue. In order to run the driver designated in the code, I had to run it was a shell command. I'm having a difficult time figuring out why my syntax is incorrect.
Code:
def read_dht22( PiPin ):
        output = subprocess.check_output([shell=True], ['/home/pi/Adafruit-Raspberry-Pi-Python-Code/Adafruit__DHT_Driver", "2302", str(PiPin)])

Error:
sudo python scr6.py
  File "scr6.py", line 31
    output = subprocess.check_output([shell=True], ['/home/pi/Adafruit-Raspberry-Pi-Python-Code/Adafruit_DHT_Driver', '2302', str(PiPin)])
                                           ^
SyntaxError: invalid syntax

Error Prior to Adding shell=True
sudo python scr5.py
Traceback (most recent call last):
  File "scr5.py", line 46, in <module>
    temp_c, temp_f = read_dht22(4)
  File "scr5.py", line 31, in read_dht22
    output = subprocess.check_output(["/home/pi/Adafruit-Raspberry-Pi-Python-Code/Adafruit_DHT_Driver", "2302", str(PiPin)])
  File "/usr/lib/python2.7/subprocess.py", line 537, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child
    raise child_exception
OSError: [Errno 13] Permission denied

A: This should fix your syntax error:
def read_dht22( PiPin ):
    output = subprocess.check_output(["/home/pi/Adafruit-Raspberry-Pi-Python-Code/Adafruit__DHT_Driver", "2302", str(PiPin)], shell=True)


text:
Q: Push Services in blackberry Hi friends I am developing an application to display push notification.I would Like to know weather it is Chargeable Push Notification Essential.

A: RIM charges based on the frequency and size of the push data, and the number of clients being pushed to. When you apply for push credetials the limitations and cost of each type of account are explained. Current information is available from the Push Service site.


text:
Q: Modelica Programming: fixed constraint in 'for loop' -- for Multistage Constant Current Battery Charging I want to perform Multistage Constant Current Battery Charging in Modelica.
Could anyone help me? Thanks in advance.
model BatteryCharge
constant Real Voltage0 = 3;
parameter Real Current_vec[5] = {0.01,0.005,0.004,0.003,0.002};
Real Voltage;
Real Current;
// Integer k;
// algorithm
// k := 1;
// Current := Current_vec[k];
// Voltage := Voltage0 + Current * time;
//
// if Voltage > 4 then
//    k := k+1;
// end if;

algorithm
for k in 1:5 loop
Current := Current_vec[k];
Voltage := Voltage0 + Current * time;

if Voltage > 4 then
   break;
end if;

end for;

end BatteryCharge

I do really need help.
Pls do not ask me to do this in matlab since this is only one simple case of a part of my programming code.

A: It looks like you are mixing units of current, voltage and time.  So, it is not very clear what you are trying to accomplish.
However, if you are trying to just generate voltage as a function of time, you could just use a Modelica.Blocks.Sources.TimeTable to give you voltage.


text:
Q: SQL questions - Medium difficulty I am working through this link and I am stuck on Q7 and Q8 on this website: http://sqlzoo.net/a3m.htm
My attempt for Q7 is:
SELECT tprod.dscr, sum(qnty), max(tpurcd.recv)
FROM tprod, tpurcd
WHERE tprod.code = tpurcd.prod
GROUP BY tprod.dscr, tpurcd.recv

Q8 attempt:
SELECT tpurcd.cust, tpurcd.recv, qnty
FROM tpurcd, tprod
WHERE tprod.code = tpurcd.prod
AND tpurcd.qnty * tprod.pric

Table info is listed here: http://sqlzoo.net/a3.htm
Any help would be appreciated!

A: .7. For each product show the description and the total number ordered and the date of the most recent order.
(you shouldn't group by tpurcd.recv)
SELECT tprod.dscr, sum(qnty), max(tpurcd.recv)
FROM tprod
INNER JOIN tpurcd ON tprod.code = tpurcd.prod
GROUP BY tprod.dscr

.8. Show the customer code, the received date and the total value of all purchase orders with a total value of at least £475.
(the expression tpurcd.qnty * tprod.pric was hanging)
SELECT tpurcd.cust, tpurcd.recv, sum(tpurcd.qnty * tprod.pric)
FROM tpurcd
INNER JOIN tprod ON tprod.code = tpurcd.prod
GROUP BY tpurcd.cust, tpurcd.recv
HAVING sum(tpurcd.qnty * tprod.pric) >= 475

A: Using mysql
7
SELECT tprod.dscr as Description, sum(tpurcd.qnty) as Quantity, max(tpurcd.recv) as 'Most Recent Order'
FROM tprod
INNER JOIN tpurcd ON tprod.code = tpurcd.prod
GROUP BY tprod.dscr

8
SELECT tpurcd.cust as 'Customer Code', tpurcd.recv as 'Received Date', sum(tpurcd.qnty * tprod.pric) as 'Total Value'
FROM tprod
INNER JOIN tpurcd ON tprod.code = tpurcd.prod
group by tpurcd.cust, tpurcd.recv
having sum(tpurcd.qnty * tprod.pric) > 475


text:
Q: Angular Momentum Addition Theorem If I have, for example a particle with $s = 3/2$ and $\ell = 2$, what are the allowed values of $j$?
I'm slightly confused because I know that $j = \ell + s$, so surely there is only one allowed value?

A: The problem is that $\ell$ and $s$ are the eigenvalues of the angular momentum, but each value of them corresponds to multiple underlying states (unless the eigenvalue is zero). In effect the eigenvalue represents the magnitude of a vector angular momentum, but not it's direction, and the various different underlying states represent different possible values of direction.
If the spin and orbital angular momenta point in the same direction then you would expect them to add, but if they point in opposite direction you would expect them to subtract.
The addition rules for angular momentum reflect the vector nature of the quantity.


text: Q: Grayed out settings in Home app for HomePod Not sure if this is ios 15 thing. A lot of setting for my Homepod inside the Home app are grayed out, including 'Personal requests'. I can't change them. What's causing that? How do I change them?


text:
Q: Decomposition of $S^2(\wedge^2 E)$ Consider bianchi map $$ b(T)(x,y,z,t) = \frac{1}{3}(T(x,y,z,t)+T(y,z,x,t) + T(z,x,y,t))$$ where $T\in S^2(\wedge^2 E)$
I already checked that $b(b(T))=b(T)\in S^2(\wedge^2 E)$
But how can we derive the following ?
$$ S^2(\wedge^2 E) = {\rm Ker}\ b \oplus {\rm Im}\ b$$ and
$${\rm Im}\ b = \wedge^4 E$$

A: The splitting $V = \mathrm{ker\ } T \oplus \mathrm{im\ } T$ occurs for any projection operator (i.e. idempotent) $b$ on a finite-dimensional vector space $V$. To see this note that any $v\in V$ can be written $v = (v-b v) + b v$ and apply the rank-nullity theorem.
To show that $\mathrm{im\ }b = \bigwedge^4 E$, you just need to show that $3b(T)_{ijkl} = T_{ijkl} + T_{jkil} + T_{kijl}$ is completely antisymmetric when $T \in S^2 \bigwedge^2 E$. Since you already know $b(T)$ has some antisymmetries (it is still in $S^2 \bigwedge^2 E$), you really just need to check that you pick up a sign change when you swap one of the first two indices with one of the last two. (This shows $\mathrm{im\ }b \subset \bigwedge^4 E$; for the other direction just show that $b$ acts as the identity on $\bigwedge^4 E$.)


text:
Q: Obtaining a prediction in Keras I have successfully trained a simple model in Keras to classify images:
model = Sequential()

model.add(Convolution2D(32, 3, 3, border_mode='valid', input_shape=(img_channels, img_rows, img_cols),
                        activation='relu', name='conv1_1'))
model.add(Convolution2D(32, 3, 3, activation='relu', name='conv1_2'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Convolution2D(64, 3, 3, border_mode='valid', activation='relu', name='conv2_1'))
model.add(Convolution2D(64, 3, 3, activation='relu', name='conv2_2'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.5))

model.add(Dense(nb_classes, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])

I can also predict the image classes using
y_pred = model.predict_classes(img, 1, verbose=0)

However the output of y_pred is always binary. This also seems to be the case when using predict_proba and predict. My outputs are in this form
[[ 1.  0.  0.  0.]]
[[ 0.  1.  0.  0.]]

This works OK, but I'd like to have a probability percent for each classification, for example
[[ 0.8  0.1  0.1  0.4]]

How do I get this in Keras?

A: Softmax might yield "one-hot" like output. Consider the following example:
# Input; Exponent; Softmax value
20    485165195  0.99994
 9         8103  0.00002
 5          148  0.00000
10        22026  0.00005
------------------------
# Sum 485195473  1

Since the exponential function grows very fast softmax starts yielding one-hot like output starting from order of magnitude 1. In Keras implementation of the softmax function the maximum value is subtracted from the input, but in the stated above case it won't make any difference.
Possible ways to fix this:

*

*Make sure that input images are rescaled, so that pixels values are between 0 and 1.

*Add some regularizers to your model.


text:
Q: Minimal $k$ so that the sum of two nilpotent elements in a commutative ring is 0 Let $R$ be a commutative ring, $a,b\in R$ such that $a^n=0$ and $b^m=0$ $(n,m\in\mathbb{N})$.
I proved that there exist some $k$ such that $(a+b)^k=0$ (using binomial theorem with $k=n+m$) but such derivation is not very enlightening because take $n=3,m=2$ then $(a+b)^4=a^4+4a^3b+6a^2b^2+4ab^3+b^4=0$ and $4\neq 5$.
So there's something else going on and I can't see what.
The question would be:

What is the minimal $k$ such that $(a+b)^k=0$?

A: Yeah, $n+m-1$ is the minimum.
You can take the case $R=\mathbb Z[x,y]/\langle x^n,y^m\rangle.$
Then $$(x+y)^{n+m-2}=\binom{n+m-2}{n-1}x^{n-1}y^{m-1}\neq 0$$
Of course, it is possible in some cases for it to be smaller. If $ab=0$ then you can use $k=\max(m,n).$
If $a=-b$ then $n=m$ and $k=1.$
But the smallest $k$ which works for all rings is $n+m-1.$


text:
Q: Automatically add helm repos to new clusters As the title says, is it possible to configure clusters/templates to automatically provision with custom helm repos?
In case there's confusion, I'm talking about the Apps > Repositories menu in rancher when you're "Exploring" a cluster.
It defaults with these two repos for new clusters:
https://git.rancher.io/partner-charts
https://git.rancher.io/charts


text:
Q: Looping through individual dicts and inserting into a nested dict I'm looking to loop through individual nested dictionaries being pulled in from a database and update a single new dictionary with all the nested dictionaries. I'm using a counter to assign key values to the dictionaries being pulled in but the logic is off and I'm having trouble getting my desired output.
My CursorByName assigns the proper keys and values to the data.
Code:
counter = 1
newdict = {}
dictofdict = {}
for row in CursorByName(cursor):
    while counter < 4:
        dictofdict = {counter : row}
        newdict.update(dictofdict)
        print(newdict)
        counter += 1

Output:
{1: {key1:value1}}
{1: {key1:value1}, 2: {key2:value2}}
{1: {key1:value1}, 2: {key2:value2}, 3: {key3:value3}}

Target Output:
{1: {key1:value1}, 2: {key2:value2}, 3: {key3:value3}, 4: {key4:value4}, etc}

A: Use dict comprehension:
In [1]: d = {i: {'key{}'.format(i): 'value{}'.format(i)} for i in range(1, 4)}

In [2]: d
Out[2]: {1: {'key1': 'value1'}, 2: {'key2': 'value2'}, 3: {'key3': 'value3'}}


text:
Q: jQuery count how many divs with a class there are and put into string Is there a way in jQuery to count how many divs you have and put that number into a string

SOME TEXT

SOME OTHER TEXT

DIFFERENT TEXT

So count the divs with class name and then put that into a string so the output would be this
var strNoDivs = 2

Any ideas?
Thanks
Jamie

A: First option is:
var count= $('div.name').length;

or filter() function can be used too.
var count= $('div').filter('.aaa').length;

A: var strNoDivs = $('div.name').length;
Done.
jQuery's selector syntax is based on the CSS selector syntax (which, I suppose, is only helpful information if you're already familiar with CSS selectors).

A: var strNoDivs = $('div.name').length.toString();

A: var nb = $('div.name').length;

A: var noOfDivs = $('div.name').length?
Using the Length property.

A: Like this...
var divisions = $("div.name");
var strNoDivs = divisings.length.toString();
alert(strNoDivs);

A: According to the reference of jQuery Forum it can be done this way.
$('input[id*="name"]').length;


text:
Q: Adding null values to array in Objective-C In a swift project I was able to do this easily. I have an array of CLLocationCoordinate2D's and CLLocationDistances
Here is the swift code (inside a PFQuery) It works just fine
if let returnedLocation = object["location"] as? PFGeoPoint
{
    let requestLocation = CLLocationCoordinate2DMake(returnedLocation.latitude, returnedLocation.longitude)
    self.locations.append(requestLocation)
    let requestCLLocation = CLLocation(latitude: requestLocation.latitude, longitude: requestLocation.longitude)
    let driverCLLocation = CLLocation(latitude: location.latitude, longitude: location.longitude)
    let distance = driverCLLocation.distanceFromLocation(requestCLLocation)
    self.distances.append(distance/1000)
}

When I try to add them in Objective C to the locations and distance arrays I get an error because I'm adding an object without a pointer. What would be the best way to get around this? Thank you
Objective C code (they're both NSMutableArrays)
if (object[@"driverResponded"] == nil) {
    NSString *username = object[@"username"];
    [self.usernames addObject:username];
    PFGeoPoint *returnedLocation = object[@"location"];
    CLLocationCoordinate2D requestLocation = CLLocationCoordinate2DMake(returnedLocation.latitude, returnedLocation.longitude);
    //FIX!
    [self.locations addObject:requestLocation];
    CLLocation *requestCLLocation = [[CLLocation alloc]initWithLatitude:requestLocation.latitude longitude:requestLocation.longitude];
    CLLocation *driverCLLocation = [[CLLocation alloc]initWithLatitude:location.latitude longitude:location.longitude];
    CLLocationDistance distance = [driverCLLocation distanceFromLocation:requestCLLocation];
    [self.distances addObject:distance/1000];
}

A: You can do this to store it as a CLLocationCoordinate doing this:
CLLocationCoordinate2D new_coordinate = CLLocationCoordinate2DMake(returnedLocation.latitude, returnedLocation.longitude);
[self.locations addObject:[NSValue valueWithMKCoordinate:new_coordinate]];

Pull it back out like this:
CLLocationCoordinate2D coordinate = [[self.locations objectAtIndex:0] MKCoordinateValue];


text:
Q: Why this program doesn't consume memory? It's bothering me what delete [] actually does, so I just tried some code and I was shocked with the results
Test #1:
int main()
{
    int *d;
    while(true)
    {
        d = new int[10];
        delete []d;
    }
}

The program doesn't consume any memory at all, as expected.
Test #2:
int main()
{
    int *d;
    while(true)
    {
        d = new int[10];
        delete [](d + 5);
    }
}

Though in every loop there should be at least 20 bytes (for the five ints it reserves at the beginning of array) reserved which are not deleted this program also doesn't consume any memory!
Test #3:
int main()
{
    int *d;
    while(true)
    {
        d = new int[10];
        delete []d;
        *d=1;
    }
}

This one caused access violation as expected (seems all the memory is deleted after delete []d).
Test #4:
int main()
{
    int *d;
    while(true)
    {
        d = new int[10];
        delete [](d+5);
        *d=1;
    }
}

This one was the most amazing, though the while doesn't consume any memory the program doesn't produce any access violations either, I'm just wondering where *d is storing it's data?
(By the way all programs are compiled using no-optimization!)
Now the main question :
What if I allocated an array and I've done working with half of it, can't I by any chance release that half and keep the other half?

A:
it's bothering me what delete []
  actually does

You're not supposed to worry about what delete[] actually does. It's for all intents and purposes a black box with certain rules on how to use it properly. The only time you need to worry about what it needs to actually do is if you're writing a compiler or a C++ runtime (e.g. operating systems, etc.)
With respect to those "certain rules on how to use it properly", Test #2 and #4 invokes undefined behavior:

ISO C++ 2003 Standard 5.3.5 Delete [expr.delete]
1 The delete-expression operator destroys a most derived object (1.8) or array created by a new-expression.

    delete-expression:
        ::opt delete cast-expression
        ::opt delete [ ] cast-expression

The first alternative is for non-array
  objects, and the second is for arrays.
  The operand shall have a pointer type,
  or a class type having a single
  conversion function (12.3.2) to a
  pointer type. The result has type
  void.
2 If the operand has a class type, the
  operand is converted to a pointer type
  by calling the above-mentioned
  conversion function, and the converted
  operand is used in place of the
  original operand for the remainder of
  this section. In either alternative,
  if the value of the operand of delete
  is the null pointer the operation has
  no effect. In the first alternative
  (delete object), the value of the
  operand of delete shall be a pointer
  to a non-array object or a pointer to
  a sub-object (1.8) representing a base
  class of such an object (clause 10).
  If not, the behavior is undefined.
  In the second alternative (delete array), the value of the operand of
  delete shall be the pointer value
  which resulted from a previous array
  new-expression. If not, the
  behavior is undefined. [Note: this
  means that the syntax of the
  delete-expression must match the type
  of the object allocated by new, not
  the syntax of the new-expression. ]

"Undefined Behavior" means that anything can happen, including the behavior you just described.
These expressions that you have in Tests #2 and #4 are in violation of 5.3.5/2 and will cause undefined behavior (Test #3 will also cause undefined behavior, but for a different reason).
d = new int[10];
delete [](d + 5);

The delete[] line violates 5.3.5/2 because pointer value you pass to delete[] wasn't the same value that was given to you from new int[].
So if the new int[] command gives you 0xA01D2CE9 and you pass in 0xA01D2CE9 + 5 to delete[], you cannot possibly reason about or predict what will happen because you have broken the rules of the language. What will actually happen will be dependent on how the compiler and/or the operating system handles new[] and delete[]. That can range from nothing wrong happening to completely crashing your system, and everywhere in between.
In other words, just don't write things like delete [](d + 5);.

A: When you say "doesn't consume any memory", are you talking about when viewed inside of a "task-manager" style performance monitor?  Because if-so, 40-bytes will not show up as "memory usage" ... you're going to have to allocate a lot more memory for it to show up in most standard process performance monitors.

A: delete [](d + 5);

(from your test #2) is definitively something you should not do, this will corrupt the memory if not segfault. It actually segfaults on my platform.
The outcome of your tests will depend on many things, among other things the platform your run these tests on, the internals of new/delete etc.

A: delete [](d + 5);

It sounds like you are expecting this to free just part of the memory allocated by new int[10].
This is not the case, it causes undefined behavior and could cause anything to happen.
On some memory managers, if you ask them to free a block by passing a pointer, if you don't pass a pointer to the beginning of the block then they may free the entire block that contains the pointer that you pass. This may well be happening in your case.
Another consideration is that new int[10] does not initialize the memory allocated so the operating system can just allocate some address space and doesn't need to back the allocation with any physical storage. This means that even if you call new int[10] in a loop without any delete[] you may see no rising memory usage in many memory monitoring tools, even up to the point when new[] throws a std::bad_alloc exception when you exhaust the logicalbvg address space. (This is likely to take some time just allocating 10 bytes at a time.)

A: Are you running these tests under a release build?  Have you looked at the generated assembly instructions?  How are you measuring memory consumption?  You're ony allocating 40 bytes and then immediately clearing it.
Also, doing something like delete [](d + 5) is invoking undefined behavior.  You need to pass in the pointer returned by operator new in order for delete to work correctly.


text:
Q: Check and run correct Tensorflow Version (v2.0) i was using the previous version of tensorflow, but i wanna use tensorflow 2.0.0 alpha and i've installed it with pip using
    pip install tensorflow==2.0.0-alpha0

than i run the simple code to check what version
    import tensorflow as tf
    print(tf.__version__)

but this is the result:
1.13.0-rc1

so i check with pip
    pip3 show tensorflow

and i got:
Name: tensorflow
Version: 2.0.0a0
Summary: TensorFlow is an open source machine learning framework for
everyone.
Home-page: https://www.tensorflow.org/
Author: Google Inc.
Author-email: packages@tensorflow.org
License: Apache 2.0
Location:
c:\users\massimo\appdata\local\programs\python\python37\lib\site-packages
Requires: gast, six, protobuf, google-pasta, absl-py, astor, tb-nightly,
termcolor, grpcio, keras-applications, keras-preprocessing, tf-estimator-
nightly, wheel, numpy
Required-by:

is there something wrong? i'm expecting with tf.version something like 2.0.0
what i'm missing?
Thank you all
Max
UPDATE
while the command
python -m site

sys.path = [
'C:\\Users\\Massimo\\AppVisualCode',
 'C:\\Users\\Massimo\\AppData\\Local\\Programs\\Python\\Python37\\python37.
  zip',
'C:\\Users\\Massimo\\AppData\\Local\\Programs\\Python\\Python37\\DLLs',
'C:\\Users\\Massimo\\AppData\\Local\\Programs\\Python\\Python37\\lib',
'C:\\Users\\Massimo\\AppData\\Local\\Programs\\Python\\Python37',
'C:\\Users\\Massimo\\AppData\\Roaming\\Python\\Python37\\site-packages',
'C:\\Users\\Massimo\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-
   packages',
  ]
  USER_BASE: 'C:\\Users\\Massimo\\AppData\\Roaming\\Python' (exists)
  USER_SITE:
   'C:\\Users\\Massimo\\AppData\\Roaming\\Python\\Python37\\site-packages'
  (exists)
  ENABLE_USER_SITE: True

A: if you have two interpreters both with python version 3+ upgrade your pip to version 0.8 or above for both the interpreters and then you can also do this
pip3.5 install package1
pip3.6 install package2
pip3.7 install package3

I was about to write the same answer as what Vlad wrote in the comment but because it didn't work for you & since you are already using multiple python interpreters,
another possible suggestion could be to use them in a different virtual environment (interpreters with different or same python versions) for all your new projects (it's also highly recommended by most of the Data Scientists).
After that install the packages with exact version that you want to use and you'll be good to go. You'll never have to worry about for which interpreter/environment you installed which package.


text:
Q: Google map, autocomplete show state name for select country Is it possible to get only list of states in autocomplete for selected country using google maps.
Currently am getting city,street,state in autocomplete for  selected country,
ScreenShot:

Code:
   var map, places, infoWindow;
    var markers = [];
    var autocomplete;
    var countryRestrict = { 'country': 'in' };
    var MARKER_PATH = 'https://maps.gstatic.com/intl/en_us/mapfiles/marker_green';
    var hostnameRegexp = new RegExp('^https?://.+?/');

    var countries = {
        'in': {
            center: new google.maps.LatLng(21.76, 78.87),
            zoom: 4
        },
        'au': {
            center: new google.maps.LatLng(-25.3, 133.8),
            zoom: 4
        },
        'br': {
            center: new google.maps.LatLng(-14.2, -51.9),
            zoom: 3
        },
        'ca': {
            center: new google.maps.LatLng(62, -110.0),
            zoom: 3
        },
        'fr': {
            center: new google.maps.LatLng(46.2, 2.2),
            zoom: 5
        },
        'de': {
            center: new google.maps.LatLng(51.2, 10.4),
            zoom: 5
        },
        'mx': {
            center: new google.maps.LatLng(23.6, -102.5),
            zoom: 4
        },
        'nz': {
            center: new google.maps.LatLng(-40.9, 174.9),
            zoom: 5
        },
        'it': {
            center: new google.maps.LatLng(41.9, 12.6),
            zoom: 5
        },
        'za': {
            center: new google.maps.LatLng(-30.6, 22.9),
            zoom: 5
        },
        'es': {
            center: new google.maps.LatLng(40.5, -3.7),
            zoom: 5
        },
        'pt': {
            center: new google.maps.LatLng(39.4, -8.2),
            zoom: 6
        },
        'us': {
            center: new google.maps.LatLng(37.1, -95.7),
            zoom: 3
        },
        'uk': {
            center: new google.maps.LatLng(54.8, -4.6),
            zoom: 5
        }
    };

    function initialize() {
        var myOptions = {
            zoom: countries['us'].zoom,
            center: countries['us'].center,
            mapTypeControl: false,
            panControl: false,
            zoomControl: false,
            streetViewControl: false
        };

        map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);

        infoWindow = new google.maps.InfoWindow({
            content: document.getElementById('info-content')
        });

        // Create the autocomplete object and associate it with the UI input control.
        // Restrict the search to the default country, and to place type "cities".
        autocomplete = new google.maps.places.Autocomplete(
        /** @type {HTMLInputElement} */(document.getElementById('autocomplete')),
  {
      //types: ['(cities)'],
      // types: ['(regions)'],
      types: ['(regions)'],

      componentRestrictions: countryRestrict
  });
        places = new google.maps.places.PlacesService(map);

        google.maps.event.addListener(autocomplete, 'place_changed', onPlaceChanged);

        // Add a DOM event listener to react when the user selects a country.
        google.maps.event.addDomListener(document.getElementById('country'), 'change',
  setAutocompleteCountry);
    }

    // When the user selects a city, get the place details for the city and
    // zoom the map in on the city.
    function onPlaceChanged() {
        var place = autocomplete.getPlace();
        if (place.geometry) {
            map.panTo(place.geometry.location);
            map.setZoom(15);
            search();
        } else {
            document.getElementById('autocomplete').placeholder = 'Enter a city';
        }

    }

    // Search for hotels in the selected city, within the viewport of the map.
    function search() {
        var search = {
            bounds: map.getBounds(),
            types: ['lodging']
        };

        places.nearbySearch(search, function (results, status) {
            if (status == google.maps.places.PlacesServiceStatus.OK) {
                clearResults();
                clearMarkers();
                // Create a marker for each hotel found, and
                // assign a letter of the alphabetic to each marker icon.
                for (var i = 0; i < results.length; i++) {
                    var markerLetter = String.fromCharCode('A'.charCodeAt(0) + i);
                    var markerIcon = MARKER_PATH + markerLetter + '.png';
                    // Use marker animation to drop the icons incrementally on the map.
                    markers[i] = new google.maps.Marker({
                        position: results[i].geometry.location,
                        animation: google.maps.Animation.DROP,
                        icon: markerIcon
                    });
                    // If the user clicks a hotel marker, show the details of that hotel
                    // in an info window.
                    markers[i].placeResult = results[i];
                    google.maps.event.addListener(markers[i], 'click', showInfoWindow);
                    setTimeout(dropMarker(i), i * 100);
                    addResult(results[i], i);
                }
            }
        });
    }

    function clearMarkers() {
        for (var i = 0; i < markers.length; i++) {
            if (markers[i]) {
                markers[i].setMap(null);
            }
        }
        markers = [];
    }

    // Set the country restriction based on user input.
    // Also center and zoom the map on the given country.
    function setAutocompleteCountry() {
        var country = document.getElementById('country').value;
        if (country == 'all') {
            autocomplete.setComponentRestrictions([]);
            map.setCenter(new google.maps.LatLng(15, 0));
            map.setZoom(2);
        } else {
            autocomplete.setComponentRestrictions({ 'country': country });
            map.setCenter(countries[country].center);
            map.setZoom(countries[country].zoom);
        }
        clearResults();
        clearMarkers();
    }

    function dropMarker(i) {
        return function () {
            markers[i].setMap(map);
        };
    }

    function addResult(result, i) {
        var results = document.getElementById('results');
        var markerLetter = String.fromCharCode('A'.charCodeAt(0) + i);
        var markerIcon = MARKER_PATH + markerLetter + '.png';

        var tr = document.createElement('tr');
        tr.style.backgroundColor = (i % 2 == 0 ? '#F0F0F0' : '#FFFFFF');
        tr.onclick = function () {
            google.maps.event.trigger(markers[i], 'click');
        };

        var iconTd = document.createElement('td');
        var nameTd = document.createElement('td');
        var icon = document.createElement('img');
        icon.src = markerIcon;
        icon.setAttribute('class', 'placeIcon');
        icon.setAttribute('className', 'placeIcon');
        var name = document.createTextNode(result.name);
        iconTd.appendChild(icon);
        nameTd.appendChild(name);
        tr.appendChild(iconTd);
        tr.appendChild(nameTd);
        results.appendChild(tr);
    }

    function clearResults() {
        var results = document.getElementById('results');
        while (results.childNodes[0]) {
            results.removeChild(results.childNodes[0]);
        }
    }

    // Get the place details for a hotel. Show the information in an info window,
    // anchored on the marker for the hotel that the user selected.
    function showInfoWindow() {
        var marker = this;
        places.getDetails({ reference: marker.placeResult.reference },
  function (place, status) {
      if (status != google.maps.places.PlacesServiceStatus.OK) {
          return;
      }
      infoWindow.open(map, marker);
      buildIWContent(place);
  });
    }

    // Load the place information into the HTML elements used by the info window.
    function buildIWContent(place) {
        document.getElementById('iw-icon').innerHTML = '';
        document.getElementById('iw-url').innerHTML = '' + place.name + '';
        document.getElementById('iw-address').textContent = place.vicinity;

        if (place.formatted_phone_number) {
            document.getElementById('iw-phone-row').style.display = '';
            document.getElementById('iw-phone').textContent =
    place.formatted_phone_number;
        } else {
            document.getElementById('iw-phone-row').style.display = 'none';
        }

        // Assign a five-star rating to the hotel, using a black star ('✭')
        // to indicate the rating the hotel has earned, and a white star ('✩')
        // for the rating points not achieved.
        if (place.rating) {
            var ratingHtml = '';
            for (var i = 0; i < 5; i++) {
                if (place.rating < (i + 0.5)) {
                    ratingHtml += '✩';
                } else {
                    ratingHtml += '✭';
                }
                document.getElementById('iw-rating-row').style.display = '';
                document.getElementById('iw-rating').innerHTML = ratingHtml;
            }
        } else {
            document.getElementById('iw-rating-row').style.display = 'none';
        }

        // The regexp isolates the first part of the URL (domain plus subdomain)
        // to give a short URL for displaying in the info window.
        if (place.website) {
            var fullUrl = place.website;
            var website = hostnameRegexp.exec(place.website);
            if (website == null) {
                website = 'http://' + place.website + '/';
                fullUrl = website;
            }
            document.getElementById('iw-website-row').style.display = '';
            document.getElementById('iw-website').textContent = website;
        } else {
            document.getElementById('iw-website-row').style.display = 'none';
        }
    }

A: No it's not possible. According to Google Maps API Autocomplete Library Documentation,
you can only restrict results up to regions level which in some results it is returned city or even street name.
In Autocomplete() function, you have four types to expect in results as mentioned in docs and you have already known I think: geocode, establishment, (regions), (cities).
However, if you can use another autocomplete plugin or built yours and feed it with autocomplete.getPlace() object values, it is sure possible.


text:
Q: Implementation of Stack in SWI-Prolog So I have to implement an ADT, in this case a Stack in SWI-Prolog. I need help, because I'm new in this programming language, and don know how to start.
This started as an implementation in python(3) where I defined a class and added functions to work with (push, is_empty?,pop, peak). But now, I need to do something similar in prolog.
I have visited some other stackoverflow questions similar to mine, but I'm still helpless.
I think that is not only to define a list in SWI-Prolog,  Pls help.

A: Since you mention ADTs, I will use Logtalk (which you can run with most Prolog systems) to first define a stack protocol/interface:
:- protocol(stack_protocol).

    :- public(new/1).
    :- mode(new(--stack), one).
    :- info(new/1, [
        comment is 'Creates a new empty stack.',
        argnames is ['Stack']
    ]).

    :- public(empty/1).
    :- mode(empty(@stack), one).
    :- info(empty/1, [
        comment is 'True if the stack is empty.',
        argnames is ['Stack']
    ]).

    :- public(top/2).
    :- mode(top(?stack, ?element), zero_or_one).
    :- info(top/2, [
        comment is 'True if Top is the top element of the stack.',
        argnames is ['Stack', 'Top']
    ]).

    :- public(push/3).
    :- mode(push(?stack, ?element, ?stack), zero_or_one).
    :- info(push/3, [
        comment is 'Adds an element to the stack.',
        argnames is ['Stack0', 'Element', 'Stack']
    ]).

    :- public(pop/3).
    :- mode(pop(?stack, ?element, ?stack), zero_or_one).
    :- info(pop/3, [
        comment is 'Removes an element from the stack.',
        argnames is ['Stack0', 'Element', 'Stack']
    ]).

:- end_protocol.

We can now define an implementation for the stack ADT. The obvious choice is simply to use a list:
:- object(stack,
    implements(stack_protocol)).

    new([]).

    empty(Stack) :-
        Stack == [].

    top([Top| _], Top).

    push(Stack, Element, [Element| Stack]).

    pop([Element| Stack], Element, Stack).

:- end_object.

Assuming both protocol and object defined in a stack.lgt source file, a sample call would be:
| ?- {stack}.
...
% (0 warnings)

(4 ms) yes
| ?- stack::(
         new(S0),
         push(S0, 1, S1),
         push(S1, 2, S2),
         push(S2, 3, S3),
         top(S3, T),
         pop(S3, E, S)
     ).

E = 3
S = [2,1]
S0 = []
S1 = [1]
S2 = [2,1]
S3 = [3,2,1]
T = 3

yes

Is it worthy defining the protocol? Protocols are specially useful when several different implementations are expected (e.g. a dictionary or a random number generator). But, in this case, a list is such a natural candidate to implement a stack that the usefulness of defining a protocol is mainly for its educational value. In most cases, when a stack is required, programmers simply use a list directly.


text:
Q: Android - Finish latest Intent from parent My activities sends long-term requests to slow server, so after sends they show "Loading, please wait" activity (with cute pinkish progressbar, white rabbits, etc) this way:
@Override
public void onClick(View v) {
    ~sendRequestThroughRunnable();
    startActivity(new Intent(Activity.this, LoadingActivity.class));
}

Afterward parent activity get exact notification about end of requests through callback functions (from other thread), so my question is, how can i finish (or stop, etc) LoadingActivity from parent activity and get back control?

A: Replace startActivity() with startActivityForResult(intent, requestCode). When it's time to finish the LoadingActivity call finishActivity(requestCode).


text:
Q: Cannot "print" random forest model when loaded into R I seem to have ran into a problem recently when I load a random forest model into R. Normally when I generate a random forest model using the randomForest package, I am able to call on the model itself or use the print function to have a nice summary of the model, such as coefficient of determination, number of trees, etc.
For example:
test = na.omit(airquality)

RF = randomForest(Ozone ~ Temp + Month + Day, data = test)
RF #or print(RF)

The output is:
Call:
  randomForest(formula = Ozone ~ Temp + Month + Day, data = test)
          Type of random forest: regression
                 Number of trees: 500
No. of variables tried at each split: 1

      Mean of squared residuals: 479.4724
                % Var explained: 56.3

However, when I save my model RF in R as an .RData file and load it into R,  I can no longer call on the function and get the summary as above. Instead I print out every single list member contained in str(RF).
Any ideas on how to fix this?

A: One must load the randomForest package with the library() function prior to printing the model once you've read it from disk in order to have it use the specialized version of print() that works with a random forest model object.
data(airquality)
library(randomForest)
test <- na.omit(airquality)

rfModel <- randomForest (Ozone ~ Temp + Month + Day, data = test)
rfModel
saveRDS(rfModel,"./data/rfModel.rds")

At this point if you exit R and restart, the following sequence of commands will print the object as a list.
rfModel2 <- readRDS("./data/rfModel.rds")
rfModel2

After loading the randomForest package, the model will print as expected.
library(randomForest)
rfModel2


text:
Q: Question about multiplicity of eigenvalue = 0 for singular matrix For an $n\times n$ matrix $A$ of rank $r$, for $\lambda = 0$, I think the dimension of the eigenspace (equal to the null space of $A$) is always $n-r$. Is it possible to show whether the multiplicity of $\lambda = 0$ can exceed $n-r$?
If the multiplicity of $\lambda = 0$ always equal the dimension of its eigenspace ($n-r$), why is this true yet for a matrix like $\begin{bmatrix}3&1\\0&3\end{bmatrix}$, we have $\lambda = 3$ with a multiplicity of 2 but only one eigenvector?

A: You may be under the impression that R^n  is spanned by the eigenvectors of a matrix this is actually not true however see  https://en.wikipedia.org/wiki/Jordan_normal_form
It is typically true however one can think of large blocks in the JOrdan normal form as a "degeneracy" so to speak.
For a simple counter example to your claim consider the  right shift operator where the right most element is deleted one can easily see any eigenvalue must be 0 but the dimension of the nullspace is merely one
you may also want to look up idempotent and nilpotent operators

A: The multiplicity of an eigenvalue known as algebraic multiplicity is $\ge $  than the geometric multiplicity (geometric multiplicity is $n-r$ for your exemple of $\lambda=0$). A classic fact.


text:
Q: Flutter build failure: MainActivity cannot be converted to FlutterEngine I am facing an error please help me to solve it out, I am completely new here.
error: incompatible types: MainActivity cannot be converted to FlutterEngine

    GeneratedPluginRegistrant.registerWith(this);
* What went wrong:
MainActivity.java uses or overrides a deprecated API.

Execution failed for task ':app:compileDebugJavaWithJavac'.
Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.


text:
Q: Trying to add separators to numbers (the comma's and the .) So far I have:
var addSeparators = function (input, thousandSep, fractionSep) {
  if (!input) {
    return '';
  }
  return (input + '').replace(/(\d)(?=(\d{3})+$)/g, '$1' + thousandSep);
};

If I call addSeparators('1000', ',', '.'); I get 1,000 back.
If I call addSeparators('1000.0234', ',', '.'); I get 1000.0,234 back but I would like 1,000.0234.

A:   var addSeparators = function (input, thousandSep, fractionSep) {
  if (!input) {
    return '';
  }
  fraction=input.toString().split('.')[1];
  fraction=fraction?fractionSep+fraction:'';
  return parseInt(input).toString().replace(/(\d)(?=(\d{3})+$)/g,'$1'+thousandSep)+fraction;
};

A: try this
function thousandSeparator(num) {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

thousandSeparator(1000.0234);


text:
Q: WPF Datagrid Column Width Issue I have columns in a DataGrid that are being set by an ObservableCollection that is the type of a simple data object that I created. The first column has a width set to "Auto" and the second column as a width set to "1*".
I am currently using the method in the answer here to autoupdate the width of my column that is set to "Auto" when the ItemsSource changes. This seems to work most of the time:

This looks great, and works all of the time
Although, when the ItemsSource is a little bit larger (lets say about 30-35 records), the "Auto" width (first) column will shrink down only when the DataGrid (including the scroll bar) is clicked:
 This will be resized properly if it hasn't been clicked
My XAML looks like this:
 <my:DataGrid CanUserSortColumns="false" CanUserResizeRows="false" CanUserResizeColumns="false" CanUserReorderColumns="false" CanUserDeleteRows="false" CanUserAddRows="false" AutoGenerateColumns ="False" SelectionMode="Single" SelectionUnit="Cell" Height="113" HorizontalAlignment="Left" Margin="11,22,0,0" Name="dataGrid" VerticalAlignment="Top" Width="226" Background="#FFE2E2E2" AlternatingRowBackground="#FFA4CFF2" BorderBrush="#FF7C7C7C" HorizontalGridLinesBrush="White" PreviewKeyDown="dataGrid_PreviewKeyDown" CellEditEnding="dataGrid_CellEditEnding" BeginningEdit="dataGrid_BeginningEdit" PreparingCellForEdit="dataGrid_PreparingCellForEdit" SelectedCellsChanged="dataGrid_SelectedCellsChanged" Loaded="dataGrid_Loaded" TargetUpdated="dataGrid_TargetUpdated">
        <my:DataGrid.Columns>
        <my:DataGridTextColumn Binding="{Binding Path=Name, NotifyOnTargetUpdated=True}" Width="Auto">
                <my:DataGridTextColumn.CellStyle>
                    <Style TargetType="{x:Type my:DataGridCell}">
                        <Setter Property="KeyboardNavigation.IsTabStop" Value="False"></Setter>
                        <Setter Property="IsHitTestVisible" Value="False"></Setter>
                        <Setter Property="Focusable" Value="False"></Setter>
                        <Setter Property="Background" Value="WhiteSmoke"></Setter>
                        <Setter Property="BorderBrush" Value="LightGray"></Setter>
                    </Style>
                 </my:DataGridTextColumn.CellStyle>
              </my:DataGridTextColumn>
        <my:DataGridTextColumn Binding="{Binding Path=Value}" Width="1*"></my:DataGridTextColumn>
   </my:DataGrid.Columns>
 </my:DataGrid>

The code to assure the updating of the column:
 private void dataGrid_TargetUpdated(object sender, DataTransferEventArgs e)
    {
        dataGrid.Columns[0].Width = 0;
        dataGrid.UpdateLayout();
        dataGrid.Columns[0].Width = new DataGridLength(0, DataGridLengthUnitType.Auto);
        dataGrid.UpdateLayout();
    }

Is there any reason this may be happening only when the list is longer like this?

A: DataGrid's TargetUpdated might not get called in a few scenarios. For example, when you have more rows coming in but they are not visible then the datagrid doesn't have to "waste cycles on" re-rendering something that is not visible. The initial TargetUpdated is fine, but you might have to find an additional hook, and do similar thing there, such as hooking into the CollectionChanged of the object that's bound to ItemsSource of your datagrid, your  observableCollection has the event CollectionChanged, subscribe and try your logic there.


text:
Q: JSONFormatting on JSP I have JSON data stored in a DB table in string format.
Requirement is to show this on JSP page may be in some basic readable format(A table with two coloums-Name,value).
Please help.
Thank You.

A: Convert jsonString to jsonObject using json or gson parser API. Once you've objects then you can easily format the data and show them on web-page via EL, JSTL.

A: See http://flexjson.sourceforge.net/javadoc/flexjson/JSONDeserializer.html
You this flexJson api to deserialize your JSON String and assign to the corresponding Object.
Now use your object to display whatever u want!


text:
Q: Lightning aura If is not working I am trying to render 2 text according to change in button Menu select. I am able to get the value of the selected menu but the auro:if condition is not getting reRender properly. My code below
<aura:component >
<aura:attribute name="selectedVal" type="boolean" default="false"/>
<lightning:buttonMenu value="{!selectedVal}" class="slds-dropdown-trigger " alternativeText="Settings" onselect="{!c.handleMenuSelect}">
    <lightning:menuItem label="Panal 1" value="true" />
    <lightning:menuItem label="Panal 2" value="false"/>
</lightning:buttonMenu>

{!v.selectedVal}

{!v.selectedVal == true}

{!v.selectedVal == false}
    <aura:If istrue="{!v.selectedVal}">

p1

    </aura:If >

    <aura:if istrue="{!!v.selectedVal}">
            testing
    </aura:if>
</aura:component>

Controller
({
handleMenuSelect : function(component, event, helper) {
    var selectedMenuItemValue = event.getParam("value");
    var selected = selectedMenuItemValue;
     console.log(selectedMenuItemValue);
    component.set("v.selectedVal", selectedMenuItemValue);
} })

My text is not getting renderd when the selected value is changed. i used if and else auro:set condition even if it is not working. Do anyone have any idea.

Above is the screenshot of what i am getting after selecting panel 1 from button option.

A: This is actually because "true" and "false" are rendering as String values, even though your attribute is a Boolean. I'm not sure why Lightning allows this, but the easiest fix is to use the true and false global providers:
    <lightning:menuItem label="Panal 1" value="{!true}" />
    <lightning:menuItem label="Panal 2" value="{!false}"/>

Or, compare as strings:
{!v.selectedVal}

{!v.selectedVal == 'true'}

{!v.selectedVal == 'false'}

Also, please be aware that Lightning is case sensitive, and may have undesirable side effects if you ignore it. aura:if won't work if you use istrue, but will work if you use isTrue. Mind your capitalization.

<aura:if istrue="{!!v.selectedVal}">
    testing
</aura:if>

<aura:if isTrue="{!!v.selectedVal}">
    testing
</aura:if>

A: The bug in your code is at lightning:buttonmenu  value="{!selectedVal}" ,you must append with using value provider v ( This value provider enables you to access the value of a component's attribute in the component's markup) eg:
value="{!v.selectedVal}" refer this for more details Value Providers
and Lightning is case sensitive use isTrue not istrue
<aura:if isTrue="{!v.selectedVal}">

p1

</aura:if >

<aura:if isTrue="{!!v.selectedVal}">
        testing
</aura:if>
<lightning:buttonMenu value="{!v.selectedVal}" class="slds-dropdown-trigger " alternativeText="Settings" onselect="{!c.handleMenuSelect}">


text:
Q: Programmatically launch the Mac's System Preferences screen -> Sound Is there a programmatic way to launch the system settings on Mac and have it focus on the sound pane?
If so, is there a programmatic way to have it default on the "Output" tab?

A: You can applescript it:
tell application "System Preferences"
    activate
    set the current pane to pane id "com.apple.preference.sound"
    reveal anchor "Output" of pane id "com.apple.preference.sound"
end tell

Adapted from this link.

A: There is an easier way:
NSURL * url = [NSURL fileURLWithPath:@"/System/Library/PreferencePanes/Speech.prefPane"];
[[NSWorkspace sharedWorkspace] openURL:url];

A: I had a simular problem:
I wanted to open the "privacy" tab in the "security & privacy" system preferences pane.
You can achieve this from a terminal using this command:
open x-apple.systempreferences:com.apple.preference.security?Privacy

Therefore I tried the following in my app which did not work:
// does not work!!!
[[NSWorkspace sharedWorkspace] openURL:[NSURL fileURLWithPath:@"x-apple.systempreferences:com.apple.preference.security?Privacy"]];

So I implemented this kind of hacky solution:
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/bin/sh";
task.arguments = @[@"-c" , @"open x-apple.systempreferences:com.apple.preference.security?Privacy"];
[task launch];

Tested on macOS 10.14.6.


text:
Q: How can I make an account/tag sort of variable which stores my users input? I would like to know how you can make a function that would make a tag/account in discord that will store information about the users participation in the server and/or see how much money they have in they're fake virtual bank. This is a command sort of like dank memer. What I have now looks like this:
var cards = [];
var money = 0;
var buildings = [];

var account = [`${cards}`, `${money}`, `${buildings}`];

if(!message.author.account) {
        message.channel.send(`If you want to use MR. HONI CHAN, then start by doing \`gimme start\``);
    }

I want to have something like:
if(!message.author.have.account) {
       message.channel.send(`If you want to use MR. HONI CHAN, then start by doing \`gimme start\``);
}

but that is not proper code. Another thing that I need to do is the gimme start command. Here is what I have now:
if(message.content === 'gimme start') {

}

and that is it because I don't know how to create a variable when a certain function is ran.

A: You would have to have a database for storage. Would recommend enmap or other similar databases. For temporary storage, you can use
const tempDb = Discord.Collection();

For downloading the module:
npm i enmap

Using the db:
const enmap = require('enmap');
const db = new enmap({
  name: "db",
  cloneLevel: "deep",
  fetchAll: true,
  autoFetch: true
});
db.set('foo', 'bar');
await db.get('foo'); // returns bar
db.delete('foo');


text:
Q: RCurl and self-signed certificate issues I am having problems getting RCurl function getURL to access an HTTPS URL on a server that is using a self-signed certificate. I'm running R 3.0.2 on Mac OS X 10.9.2.
I have read the FAQ and the curl page on the subject. So this is where I stand:

*

*I have saved a copy of the certificate to disk (~/cert.pem).

*I have been able to use this very same file to connect to the server using python-requests and the 'verify' option, and succeeded.

*curl on the command-line seems to be ignoring the --cacert option. I succeeded in accessing the website with it after I flagged the certificate as trusted using the Mac OS X 'Keychain Access' app.

*RCurl stubbornly refuses to connect to the website with the following code:
getURL("https://somesite.tld", verbose=T, cainfo=normalizePath("~/cert.pem"))
This is the output I get:
* Adding handle: conn: 0x7f92771b0400
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 38 (0x7f92771b0400) send_pipe: 1, recv_pipe: 0
* About to connect() to somesite.tld port 443 (#38)
*   Trying 42.42.42.42...
* Connected to somesite.tld (42.42.42.42) port 443 (#38)
* SSL certificate problem: Invalid certificate chain
* Closing connection 38

When I tested both curl with the --cacert option and the RCurl code above in a Linux VM with the same cert.pem file and exact same URL, it worked perfectly.
So equal tests on Linux and Mac OS X, and only on Mac OS X do they fail. Even adding the certificate to the keychain didn't work.
The only thing that does work is using ssl.verifypeer=FALSE, but I don't want to do that for security reasons.
I'm out of ideas here. Anyone else have any suggestions on how to get this to work?

A: You can try:
library ("RCurl")
URL1 <- "https://data.mexbt.com/ticker/btcusd"
getURL(URL1,cainfo=system.file("CurlSSL","cacert.pem",package="RCurl"))

A: Coming back to this issue I just wanted to point out that if you are still using RCurl, you should be using httr (which uses curl) instead.
I have confirmed that using config(cainfo="/path/to/certificate") with httr connections will work as intended.


text:
Q: Binding as a formatted string I have a ListBox which hold a set of objects (linked via ItemsSource bind to an ObservableCollection). I haven't used Dynamic binding yet. It currently use the ToString() method of the object. The ToString() method shows a string this way : name (someOtherProperty)
However, even if the INotifyPropertyChanged is implemented and that i use an ObservableCollection, if i change an item property this string won't be updated.
I believe that this is because it only calls ToString once. instead i guess i have to use data binding but how i can form such a string with it ? << name (someOtherProperty) >>
Thanks.

A: You can use a multibinding, e.g. something like this:
<MultiBinding StringFormat="{}{0} ({1})">
    <Binding Path="name"/>
    <Binding Path="someOtherProperty"/>
</MultiBinding>

If you just let it execute ToString there is no proper binding at all, any notifications will have no effect.
You use it like this:
<ListBox ...>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock>
                <TextBlock.Text>
                    <!-- The above binding here -->
                </TextBlock.Text>
            </TextBlock>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>


text:
Q: pyspark sum of rows to get one new row based on values in another column in groupby Have a dataframe which has user, location, values. Currently US related location are in different rows for one user:
user     location   values
209       OH_US          45
O09       PA_US          30
O09       AQ             10
209       CA_US          50
209       UK             10
....

For each user want to generate a new row to replace US related locations with a  sum and location name is 'US'.Remove those rows in different states in US.
Expected result looks like this:
user     location   values
209       US          200
209       UK          10
O09       US          300
O09       AQ          10
...

Currently I'm thinking to pull all  US  related rows to a separate  dataframe to do a sum in groupby, then drop all the rows related to US in original dataframe to join with the US sum dataframe.
Is there a more efficient way to do this?

A: Hi there can we multiple approach to solve this in pyspark

*

*Using spark.sql -

df.createOrReplaceTempView("SAMPLE_TABLE")

df.createOrReplaceTempView("SAMPLE_TABLE")

df2=spark.sql("SELECT user , case when location like '%_US' then 'US' else location end Location , SUM(VALUES) VALUES  from SAMPLE_TABLE group by user , case when location like '%_US' then 'US' else location end ")

df2.show()

*Using pyspark api
import pyspark.sql.functions as F

df.groupby(F.when(F.col('location').\
like("%_US"),"US").\
otherwise(F.col("location")).\
alias('location'))\
.agg(F.sum('values').alias("values"))\
.show()


text:
Q: Why doesn't $2\pi\int_{-1}^1\sqrt{1-x^2}dx$ give the surface area of a sphere of radius $1$?
Possible Duplicate:
Areas versus volumes of revolution

For fun I decided to derive the surface area of a sphere of radius $1$ from the formula for the perimeter of a circle.  This integral is what I came up with:
$$2\pi\int_{-1}^1\sqrt{1-x^2}dx = \pi^2$$
Unfortunately the desired value is $4\pi$.  My rationale was simply to stack infinitely thin 'hula-hoops' whose radii followed the curvature of the sphere.  I can't readily see where my conceptual misunderstandings are, can someone help elucidate them for me? Thanks.

A: You need to use the surface area for a surface of revolution formula
$$2\pi\int \rho\,ds,$$
where $ds$ is an element of arc length.  The smart way to go is to parametrize the
semicircle as follows, $x(t) = \cos(t)$, $y(t) = \sin(t)$.
We have
$$ds = \sqrt{x'(t)^2 + y'(t)^2} = 1. $$
The quantity $\rho$ is the radius of the surface of revolution, which, in this case, is
$y = \sin(t)$.
For the circle
$$\sigma = 2\pi\int_0^\pi \sin(t)\,dt = 2\pi(2) = 4\pi.$$

A: Check if this helps : Surface area $S$ is given by $$ S= \int_{0}^{\pi}2\pi rdt$$ Where $$dt=Rd\theta$$ and $$ r=Rsin\theta$$ $\theta$ being the angle of the circle in question . So we get $$ S= \int_{0}^{\pi}2\pi R^2sin\theta d\theta $$ $$S= 4\pi$$


text:
Q: Structural Verilog) creating a mod-12 counter with 4 D-FF - no outputs from some FFs I'm trying to make a mod-12 counter in Verilog using 4 D-FFs. I've actually come up with two implementations, one of which works as intended (but is really bad practice IRL), and the other does not work as intended. The following is the ideal(correct) output generated from my "bad" implementation.

And the following is what's generated from the module I'm having trouble with.

Here is the module that generated the top image:
module Mod12Counter(q, clk, rstIn0);
    output [3:0] q;
    input  clk, rstIn0;

    DF DF0(q[0], qBar0, qBar0, clk, rst),
       DF1(q[1], qBar1, qBar1, qBar0, rst),
       DF2(q[2], qBar2, qBar2, qBar1, rst),
       DF3(q[3], qBar3, qBar3, qBar2, rst);

    and and0(test, q[2], q[3]);
    or  or0 (rst, rstIn0, test);

endmodule

And here is the module that generated the bottom image:
module Mod12Counter(q, clk, rst);
    output [3:0] q;
    input  clk, rst;

    and and0(d1In0, q[1], qBar0),
        and1(d1In1, qBar1, q[0]),
        and2(d2In0, q[2], qBar1),
        and3(d2In1, qBar3, qBar2, q[1], q[0]),
        and4(d2In2, q[2], qBar0),
        and5(d3In0, q[3], qBar1),
        and6(d3In1, q[2], q[1], q[0]),
        and7(d3In2, q[3], qBar0);

    or or0(d1, d1In0, d1In1),
       or1(d2, d2In0, d2In1, d2In2),
       or2(d3, d3In0, d3In1, d3In2);

    DF DF0(q[0], qBar0, qBar0, clk, rst),
       DF1(q[1], qBar1, d1, qBar0, rst),
       DF2(q[2], qBar2, d2, qBar1, rst),
       DF3(q[3], qBar3, d3, qBar2, rst);
endmodule

What's really weird is these two modules should behave exactly the same way. The only difference is one is just made using my gut feelings and the other one is generated by deriving equations from state tables. From what I know, the bottom module is much more preferable to use IRL.
So far the problem I'm seeing is q[2] and q[3] don't get triggered at all in the bottom module. I've tried using BUS assignment as you see now and I've also tried not using BUS assignment.
I've spent MANY hours on this, and I would really appreciate it if you could help me debug the module, point at the right direction, or tell me a better place to go for things like this.

A: If q[2] is never going high, the first thing you should look at is to understand why the input to DF2 is not ever going high at the point when the clock rises.
Looking at the inputs to see what drives d2, I see these three lines:
    and2(d2In0, q[2], qBar1),
    and3(d2In1, qBar3, qBar2, q[1], q[0]),
    and4(d2In2, q[2], qBar0),

Obviously and2 and and4 cannot help you here, because they require q[2] to be true in order to be true, so we can throw those out, leaving just these lines to look at:
    and3(d2In1, qBar3, qBar2, q[1], q[0]),
    or1(d2, d2In0, d2In1, d2In2),
    DF2(q[2], qBar2, d2, qBar1, rst),

d2In1 should be high when q is equal to 0011, which then means that d2 will be high at the same time. However you are triggering the clock to DF2 on the rising edge of qBar1, which means that at whenever qBar1 goes high, q[1] is going low, thus causing d2In1 to go low as well. So you have a race condition where the input to the flip flop is falling at the same time the clock edge is rising, which is not good!
Instead of clocking your flip flops on outputs of flip flops (which can give you nasty race conditions), you should let all your flip flops be based on just a single clock, and generate your next state based on the previous value of the flip flops.
Alternatively, here is a very simple solution (you don't always have to design the gates yourself!):
reg [3:0] q;
always @(posedge clk) begin
    q <= (q == 4'd11 || rst) ? 0 : q + 1;
end


text:
Q: Is it possible to boot into an UEFI EDK2 shell version > 2 on mac hardware? Is it possible to boot into an UEFI EDK2 shell version > 2 on any mac hardware?
I know the older version (1.0 I think) of UEFI EDK shell works, at least on some mac models. But I have not been able to boot version greater than 2.
For example when you boot from arch installer media, it has an an option to enter an EFI shell. I am speaking of that type of shell.


text:
Q: Missing icons and error message when running gnome-terminator (built from sources) I just installed terminator from sources that I got here.
It appears there is a dev version that works better but I just could not find it (launchpad is so messy).
When I launched a terminal I'm getting:
Warning: python-keybinder is not installed. This means the hide_window shortcut will be unavailable
Unable to bind hide_window key, another instance/window has it.
/home/me/programs/terminator/lib/python2.6/site-packages/terminatorlib/window.py:185: GtkWarning: Could not find the icon 'terminator'. The 'hicolor' theme
was not found either, perhaps you need to install it.
You can get a copy from:
    http://icon-theme.freedesktop.org/releases
  if icon_theme.lookup_icon(icon_name, 48, 0):
ActivityWatch plugin unavailable: please install python-notify
PluginRegistry::load_plugins: Importing plugin activitywatch.py failed: 'module' object has no attribute 'AVAILABLE

EDIT2:
The build and install went OK, with no message or warning. But when I launch the terminator from another terminal app, then this message appear.
And indeed most icons on the terminator are messed up (replaced by ugly X)
I tried to install icon-theme-hicolor, I had to build it, it went ok but I do not see ant icon in its (many) directories.
How can I get terminator working correctly ?
EDIT: I use a CentOS6.6


text:
Q: Prove a Limit Using the $\varepsilon - N$ definition I'm having trouble proving the following limit using the $\varepsilon-N$ definition:
$$\lim_{n \to \infty} \frac{3n}{\sqrt{9n^2 + 11n + 4}} = 1.$$
Here is my work so far.
Take arbitrary $\varepsilon$. We need to prove the existence of a natural number, $N$, such that for all $n \ge N$, $$ | x_n - 1| < \varepsilon.$$
$x_n = \frac{3n}{\sqrt{9n^2 + 11n + 4}}$ and since $x_n < \frac{3n}{\sqrt{9n^2}} = 1$, the equation becomes: $$1 - \frac{3n}{\sqrt{9n^2 + 11n + 4}} < \varepsilon.$$
Rewriting gives: $$\frac{3n}{\sqrt{9n^2 + 11n + 4}} > 1 - \varepsilon.$$
Clearly, when $\varepsilon \ge 1$, the statement is true since the RHS of the inequality becomes non-positive and obviously, the RHS must be positive.
However, I'm having trouble proving the statement when $0 < \varepsilon < 1$.
My idea so far has been to take the square:
$$\frac{9n^2}{9n^2 + 11n + 4} > 1 - 2\varepsilon + \varepsilon^2.$$Then, by taking the reciprocal of both sides, we obtain:
$$\frac{9n^2 + 11n + 4}{9n^2} < \frac{1}{1 - 2\varepsilon + \varepsilon^2}.$$
From here, I thought it might be smart to use the idea that for any real number, $x$, there exists a natural number, $m$, such that $\frac{1}{m} < x$.
Specifially, this would give us $m$ such that: $$\frac{1}{m} < \frac{1}{1 - 2\varepsilon + \varepsilon^2}$$ in which we case we could try to solve for $n$ in terms of $m$.
However, this solution is very complicated and long and bashy. There has to be a more elegant way to prove this limit right?
A pattern I've seen in a lot of limit problems involving square roots is the usage of $$a -b = \frac{a^2 - b^2}{a+b}$$ but I can't see how to apply that here either.
Any ideas or tips for a better solution would be greatly appreciated!

A: Let us assume that $n\geq n_{\varepsilon}$. Then it results that
\begin{align*}
\left|\frac{3n}{\sqrt{9n^{2} + 11n + 4}} - 1\right| & = \left|\frac{3n - \sqrt{9n^{2} + 11n +  4}}{\sqrt{9n^{2} + 11n + 4}}\right|\\\\
& \leq\left|\frac{3n - \sqrt{9n^{2} + 11n + 4}}{3n}\right|\\\\
& = \left|\frac{11n + 4}{3n[3n + \sqrt{9n^{2} + 11n + 4}]}\right|\\\\
& \leq\left|\frac{11n + 4}{3n(3n + 3n)}\right|\\\\
& = \frac{11n + 4}{18n^{2}}\\\\
& = \frac{11}{18n} + \frac{2}{9n^{2}}\\\\
& \leq \frac{11}{18n_{\varepsilon}} + \frac{2}{9n^{2}_{\varepsilon}} := \varepsilon
\end{align*}
Then you can take the ceiling function of the corresponding solution.


text:
Q: Sort two columns of datagrid with checkbox flex I have 5-6 columns in DataGrid in flex application.
<s:DataGrid id="recordGrid" dataProvider="{dxList}">

Grid:
Selected  Name   field2   field2   field3

In first column has CheckBox.
Second column contains Name. and So on...
Currently No checkbox is selected.   Now, user select multiple checkbox randomly and Click on header(selected). then it will sort checkbox first.(I Done it).
But, My problem is Second field is also sort alphabetically.
All selected records come top with their Name alphabetically. Then after unchecked Record will be display in alphabetically sorted.
I Do following to sort record by checkbox selected:
<s:GridColumn dataField="selected" sortDescending="true">

Thanks.

A: Make sure you're using the sort api of the dataProvider.
Example taken from: http://www.java2s.com/Code/Flex/Grid/SortingaDataGridonmultiplecolumns.htm
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    initialize="initDP();" width="550" height="400">
    <mx:Script>

        import mx.events.DataGridEvent;
        import mx.collections.*;
        private var myDPColl:ArrayCollection;

        [Bindable]
        private var sortA:Sort;
        private var sortByColumn1:SortField;
        private var sortByColumn2:SortField;
        private var sortByColumn3:SortField;
        private var myDP:Array = [{Column1:'A', Column2:'AA',Column3:11.99, Column4: true},
                                  {Column1:'B', Column2:'BB',Column3:10.99, Column4: false},
                                  {Column1:'C', Column2:'CC',Column3:12.99, Column4: true},
                                  {Column1:'D', Column2:'VV',Column3:11.99, Column4: false},
                                  {Column1:'E', Column2:'EE',Column3:11.99, Column4: true},
                                  {Column1:'F', Column2:'FF',Column3:14.99, Column4: true},
                                  {Column1:'G', Column2:'GG',Column3:5.99,  Column4: true}
        ];
        private function initDP():void {
            myDPColl = new ArrayCollection(myDP);
            sortA = new Sort();
            sortByColumn1 = new SortField("Column1", true, true);
            sortByColumn2 = new SortField("Column2", true);
            sortByColumn3 = new SortField("Column3", true);
            sortA.fields=[sortByColumn1, sortByColumn2];
            myDPColl.sort=sortA;
            myDPColl.refresh();
            myGrid.dataProvider = myDPColl;
            myGrid.rowCount = myDPColl.length +1;
        }
        private function headRelEvt(event:DataGridEvent):void {
            sortA.fields[2] = sortA.fields[1];
            sortA.fields[1] = sortA.fields[0];
            if (event.columnIndex==0) {
                sortA.fields[0] = sortByColumn1;
            } else if (event.columnIndex==1) {
                sortA.fields[0] = sortByColumn2;
            } else {
                sortA.fields[0] = sortByColumn3;}
                myDPColl.sort = sortA;
                myDPColl.refresh();
                event.preventDefault();
        }

    </mx:Script>
    <mx:DataGrid id="myGrid" width="100%" headerRelease="headRelEvt(event);">
        <mx:columns>
            <mx:DataGridColumn minWidth="120" dataField="Column1"/>
            <mx:DataGridColumn minWidth="200" dataField="Column2"/>
            <mx:DataGridColumn width="75" dataField="Column3"/>
        </mx:columns>
    </mx:DataGrid>

</mx:Application>


text:
Q: Connection problems or burned chip? I am assembling a board for a wireless charger based on this evaluation module (see here)
I own a preheat bed, a hot air gun and a quality soldering iron.
I am afraid that after soldering the chip and all its accessories, I have burned it.
I took the chance at verifying every input of the chip (using a microscope and oscilloscope) to determine if I have the correct values.
Here's a diagram:

The red question marks are outputs that should show some voltage, but show 0.
The green checkmarks or x are valid inputs or the part is not needed.
I made sure all the inputs were correct, but I get nothing for output. I should see some PWM signal through PWM_A and PWM_B and also LED_A, LED_B, and LED_C
I also checked the stability of the 3.3V line, and it sits within 10mV

I used the following technique to solder the chip:

*

*I applied solder paste to the chip

*Placed the board on top of the preheating bed and turned the device to heat up to 280 celsius

*I applied some flux and then I started using the hot air tool at 360 degrees for about 20 seconds

*When the chip looked stable on the board, I turned off the heat bed and waited for it to cool.

*Finally, I used a soldering iron at 370 (with a wide tip) to remove excess solder

Do you have any thoughts on this? Did I kill it?.
Later Edit:
Photos of the chip itself from three different angles so you have an idea:

To me it looks fairly well soldered. I took the pictures using my 1500x microscope (the same one I used to test the pins themselves with the oscilloscope)
Another argument here would be that I tried to "feel the resistance" of the lead with the tip of the oscilloscope probe and the visible lead tears formed between the pads and the chip pins were there.
Still, any idea?
Later Edit 2:

Photo of the chip in PCB design

A: *

*You applied solder paste by hand and soldered with hot air.

*The chip has a large thermal pad underneath that is connected to ground.

*You have pins reading 0 V when there should be some higher voltage present.

I think you've got short circuits between the thermal pad and some of the pins.  The shorts will be under the chip where you can't see them.
Measure the resistance between your anomalous zero volt pins and ground.  I think you will find things are shorted.

*

*Remove the chip with your hot air station.

*Install a new chip. I think you'll want to replace the old one because there's no telling what damage may have been caused by the short circuits.

*Use less solder paste on the thermal pad than you did the first time.

Next time, measure the resistance between all pins and ground before you apply power to the circuit.

If you have time and resources enough (moola to have a new PCB made,) then you can make it easier to install the chip.
Place a large plated through hole under the chip.  You want it as big as possible, but still smaller than the thermal pad.
Install the chip as usual from the top side any way you like (I'd solder it by hand with a small tipped iron, but I'm weird that way.)  Do not put solder paste on the PCB pad for the thermal pad.
Once all the pins are soldered and there are no short circuits, flip the board over.
Put a drop of liquid flux in the plated through hole for the thermal pad.
Use a large tip on your soldering iron, and solder the thermal pad to the plated through hole.  Keep feeding in solder as long as it'll go in.
The solder should wick its way in under the chip and make a good connection between the thermal pad and the PCB.


text:
Q: Confusion concerning the Sokhotski–Plemelj theorem: two different values for the same real integral A very well-known formula in complex analysis is
$
\lim_{\epsilon\to0^+}\int_{-\infty}^\infty\frac{f(x)}{x-x_0\pm i\epsilon}dx = P\int_{-\infty}^\infty \frac{f(x)}{x-x_0}dx \mp i\pi f(x_0),
$
known as Sokhotski–Plemelj theorem. I am really puzzled by the meaning of the integral on the left hand side. I understand that this integral comes from an integral over an infinite arc of radius $R$ on the upper-half plane (where the integral goes to zero for $R\to\infty$) plus the real line (after taking the limit $\epsilon\to 0$). Assuming the integrand goes to zero faster than $x^{-1}$ and considering the residue theorem, we get the result:
$
\lim_{\epsilon\to0^+}\int_{-\infty}^\infty\frac{f(x)}{x-x_0\pm i\epsilon}dx=2\pi i \text{Res}[f;x_0].
$
Now, if we take the minus sign for $i\epsilon$ and send $\epsilon$ to 0 (without calculating the integral) the above equation yields $2\pi if(x_0)$, while the plus sign yields 0. What is the problem here? Is this related to the fact I can't commute the limit with the integral sign in this case, i.e.
$
\lim_{\epsilon\to0^+}\int_{-\infty}^\infty\frac{f(x)}{x-x_0\pm i\epsilon}dx\neq\int_{-\infty}^\infty\frac{f(x)}{x-x_0}dx?
$

A: Taking $x_0=0$:
"I understand that this integral comes from an integral over an infinite arc on the upper-half plane plus the real line": No, the integral on the left is the integral over a horizontal line. For the one with the plus sign, that's the same as the integral over $(-\infty,-r)$ plus the integral over a small semicircle with center at the origin and radius $r$, plus the integral over $(r,\infty)$. The limit of the integrals over the two intervals is exactly the principal-value integral on the right, by definition. And the integral over that small semicircle is asymptotic to half the integral over a full circle of radius $r$, which would be $2\pi if(0)$.