text:
Q: correct use of getContextPath() on jsp I have a problem using getContextPath() on jsp.
I want to add an image to the JSP, a logo.
I have read that is better to use getContextPath().
In my browser´s address bar I see de URL:
http://local.host:9080/Cold/start/Result.jsp
So I have assumed my getContextPath() is:
http://local.host:9080/Cold/
Next, I found the Result.jsp file at:
**C:\Users\myname\IBM\rationalsdp\workspace\Cold_WEB\WebContent\start**
So I have created the next path:
**C:\Users\myname\IBM\rationalsdp\workspace\Cold_WEB\WebContent\images**
And I have put the logo file there.
So, I have added next code:
<img src='<%=request.getContextPath()%>/images/SuperlineaPF.gif' border="0">

But, I still can not see the logo at the page on the browser.
What is wrong?
Thank you.

A: I find the following graphic from HttpServletRequest Path Decoding  helpful:

A: Use the EL expression ${pageContext.request.contextPath}

A: You can do it following way in your JSP
<c:set var="context" value="${pageContext.request.contextPath}/images/SuperlineaPF.gif"/>

At the top of the page put an uri for JSTL as
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

Note: You'll require JSTL library for it. This is for best practice.
Since your JSPs are placed under start in WebContent you can simply refer to your images following way.

You do not require page context for that.


text:
Q: Find all unique values in column separated by comma I have multiple observations of one species with different observers / groups of observers and want to create a list of all unique observers. My data look like this:
data <- read.table(text="species observer
1 A,B
1 A,B
1 B,E
1 B,E
1 D,E,A,C,C
1 F"               , header = TRUE, stringsAsFactors = FALSE)

My output should return a list of all unique observers - so:
A,B,C,E,F

I tried to substring the data in column C using the following command  but that only returns the unique combinations of observers.
all_observers <- unique(strsplit(as.character(data$observer), ","))

all_observers
[[1]]
[1] "A" "B"

[[2]]
[1] "B" "E"

[[3]]
[1] "D" "E" "A" "C" "C"

[[4]]
[1] "F"

A: You're almost there, you just need to unlist before you do the unique:
all_observers <- unique(unlist(strsplit(as.character(data$observer), ",")))

A: We can use separate_rows on the 'observer', get the distinct rows, grouped by 'species', and paste the 'observer'
library(tidyverse)
data %>%
   separate_rows(observer) %>%
   distinct %>%
   group_by(species) %>%
   summarise(observer = toString(observer))

A: You could also use scan()
unique(scan(text=data$observer, what="", sep=","))
# Read 14 items
# [1] "A" "B" "E" "D" "C" "F"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mongoose get objects which match an object item from an array of objects I would like to find a single document matching the courseID but inside the document only objects from the materials array whose moduleNo matches the one I give. But the query I currently use seems to return the correct document but also returns all the objects in materials array. Any help would be appreciated.
My schema,
const materialSchema = new mongoose.Schema({
  courseID: String,
  materials: [
    {
      moduleNo: Number,
      moduleMaterial: String,
    },
  ],
});

My code/query,
 exports.getMaterials = (req, res) => {
  const { courseID, moduleNo } = req.query;
  Material.findOne(
    { courseID, "materials.moduleNo": moduleNo },
    (err, result) => {
      if (err) {
        console.error(err);
      } else {
        res.json(result);
      }
    }
  );
};

A: Use the $elemMatch operator, something lik this:
exports.getMaterials = (req, res) => {
  const { courseID, moduleNo } = req.query;
  Material.findOne(
    { courseID },
    {"materials": { $elemMatch: {moduleNo: moduleNo}},
    (err, result) => {
      if (err) {
        console.error(err);
      } else {
        res.json(result);
      }
    }
  );
};

Update: To return all matching elements in the array, you will have to use an aggregation pipeline, having $filter stage, to filter out array elements. Like this:
exports.getMaterials = (req, res) => {
  const { courseID, moduleNo } = req.query;
  Material.aggregate(
    [
  {
    $match: {
      courseID: courseID
    }
  },
  {
    "$project": {
      courseID: 1,
      materials: {
        "$filter": {
          "input": "$materials",
          "as": "material",
          "cond": {
            "$eq": [
              "$$material.moduleNo",
              moduleNo
            ]
          }
        }
      }
    }
  }
]
  );
};

Here's the playground link.

A: Way 1 : Use $elemMatch operator in project field

The $elemMatch operator limits the contents of an array field from
the query results to contain only the first element matching the
$elemMatch condition

Result : Returns only one matching array element

syntax :
db.collection.find(query,projection)

db.collection.find({
     "field": field_value
  },{
    "array_name":{
       $elemMatch:{"key_name": value }
    },
    field:1,
    field_2:1,
    field_3:0
})

https://mongoplayground.net/p/HKT1Gop32Pq
Way 2 : Array Field Limitations array.$ in project field
*

Result : Returns only one matching array element

db.collection.find({
     "field": field_value,
     "array_name.key_name": value
  },{
        "array_name.$":1,
        field:1,
        field_2:1,
        field_3:0
 });

https://mongoplayground.net/p/Db0azCakQg9
Update : Using MongoDB Aggregation

Result : Returns multiple matching array elements

db.collection.aggregate([
  {
    "$unwind": "$materials"
  },
  {
    "$match": {
      "courseID": "Demo",
      "materials.moduleNo": 1
    }
  }
])

will return output as :
[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "courseID": "Demo",
    "materials": {
      "moduleMaterial": "A",
      "moduleNo": 1
    }
  },
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "courseID": "Demo",
    "materials": {
      "moduleMaterial": "B",
      "moduleNo": 1
    }
  }
]

And If you want to format output :
db.collection.aggregate([
  {
    "$unwind": "$materials"
  },
  {
    "$match": {
      "courseID": "Demo",
      "materials.moduleNo": 1
    }
  },
  {
    "$group": {
      "_id": {
        "courseID": "$courseID",
        "moduleNo": "$materials.moduleNo"
      },
      "materials": {
        "$push": "$materials.moduleMaterial"
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "courseID": "$_id.courseID",
      "moduleNo": "$_id.moduleNo",
      "materials": "$materials"
    }
  }
])

will return result as :
[
  {
    "courseID": "Demo",
    "materials": [
      "A",
      "B"
    ],
    "moduleNo": 1
  }
]

https://mongoplayground.net/p/vdPVbce6WkX


text:
Q: Include parent node using XML::Parser I am trying to modify a Perl script that I found online that uses XML::Parser to identify the unique elements of an XML document and the number of times that each element occurs. The Perl script and its documentation can be found here:
use strict;
use warnings;

use XML::Parser;
use File::Find;

@ARGV or die "usage: xmlelements DIR [DIR ...]\n";

my %element_count;

my $parser = XML::Parser->new(
    Handlers => {
        Start => \&start_element,
    },
);

find \&process_xml, @ARGV;
print "$_ ($element_count{ $_ })\n"
    for sort keys %element_count;
exit;

sub process_xml {
    $parser->parsefile( $_ )
        if substr( $_, -4 ) eq '.xml' and -f;
}

sub start_element {
    my ( $expat, $element, @attrval ) = @_;
    $element_count{ $element }++;
}

This generates an output such as this:
Account (15614)
Account_No (15504)
Active (15614)
Activity (6658)
Address (28098)
Address_1 (27548)
Address_2 (2033)
Address_3 (62)
Address_City (15)

My question is how can I also include the parent node in the output?

A: The parent node name is given by current_element so do $name= $expat->current_element . '/' . $element and voilà! If you want to avoid the warnings for empty parent names, use my $parent= $expat->current_element || ''; $name = "$parent/$element";
So the handler becomes this:
sub start_element {
   my ( $expat, $element, @attrval ) = @_;
   my $parent= $expat->current_element || '';
   my $name= "$parent/$element";
   $element_count{$name}++;
}


text:
Q: Magick::ImageMagickError: non-conforming drawing primitive definition `text' @ error/draw.c/RenderMVGContent/4404 This error happened to me using Docker, but production on Heroku was fine.
Here is my Dockerfile
FROM ruby:3.2.0

RUN curl -sL https://deb.nodesource.com/setup_16.x | bash -

RUN apt update -q && apt install -y \
    build-essential \
    libpq-dev \
    postgresql-client \
    nodejs \
    nano \
    libvips > /dev/null

A: The problem was that you were getting an error in RMagick, and this was due to missing fonts on my system. Specifically, the default font that RMagick was trying to use was not available.
To fix the problem, you needed to install the gsfonts package, which contains several common fonts used in graphics applications.
To install gsfonts, you can use the following command on Ubuntu:
sudo apt-get install gsfonts


text:
Q: задача на комбинаторику: Сколькими способами можно выбрать из интервала от 1 до 300 три числа такие чтобы их сумма делилась на 3? Попалась одна задача на тесте - вопервых не пойму из какой области, толи из комбинаторики, толи динамического программирования ... (но больше склоняюсь что комбинаторная)
есть числа от 1, 2, 3 ... 300
Сколькими способами можно выбрать из них 3 числа такие чтобы их сумма делилась на 3 ?
мои мысли:
кол-во способов выбрать любые 3 числа из 300 понятное дело, что это сочетания по 3 из 300 - C(3, 300)
Но как теперь посчитать кол-во выборок только для тех сумма которых делится на 3 ??
ну такие числа имеют вид 3*(i + j + k) например, а что делать дальше ??
правильно ли я выбрал направление в решении ?

A: Раз с повторениями - то все просто:
первое число - 300 способов. Второе число - еще 300. Итого - 90000. Третье число - 100 способов - тех, которые имеют нужный остаток при делении на 3. Итого - 9000000 способов.
Непосредственным перебором подтверждается :)
Вот этот код
int main(int argc, const char * argv[])
{
    int total = 0;
    for(int i = 1; i <= 300; ++i)
        for(int j = 1; j <= 300; ++j)
            for(int k = 1; k <= 300; ++k)
                if ((i+j+k)%3 == 0) ++total;

    cout << total << endl;
}

дает положенные 9000000
Без повторов - просто чтоб разрешить споры -
int main(int argc, const char * argv[])
{
    int total = 0;
    for(int i = 1; i <= 300; ++i)
        for(int j = i+1; j <= 300; ++j)
            for(int k = j+1; k <= 300; ++k)
                if ((i+j+k)%3 == 0) ++total;

    cout << total << endl;
}

дает 1485100. Можно это число оценить - 3 числа выбрать можно 300*299*298/6! = 455100 способами, из которых примерно треть будет нужной - 1485033 (еще раз, это - оценка, а не точный ответ.
P.S. Надо только уточнить - повторы одинаковых чисел считаются одинаковыми или нет? Я считал разными. Т.е. у меня фактически оценивается вероятность того, что при выборке трех чисел с возвратом в выборку будет число, делящееся на 3.

A: Если считать, что повторения слагаемых разрешены, но при этом варианты, получающиеся перестановкой слагаемых, не считаются разными, то составить сумму, делящуюся на 3, из трех слагаемых можно только одним из следующих способов

*

*Все слагаемые дают остаток 0 при делении на 3

*Все слагаемые дают остаток 1 при делении на 3

*Все слагаемые дают остаток 2 при делении на 3

*Слагаемые дают остатки 0, 1, 2 при делении на 3

Количество вариантов в каждой из первых трех групп - количество сочетаний с повторениями по 3 из 100 = (100 + 3 - 1)!/(3! * 99!) = 171700
Количество вариантов четвертой группы = 100 * 100 * 100 = 1000000
Итого: 1515100
Проверка "в лоб" дает тот же результат: http://coliru.stacked-crooked.com/a/1578d2a7db5da0d9


text:
Q: Vertically aligning spans next to an image I'm trying to build an
 entry structure like the one depicted here:

As pointed in the picture, the red box is a
.
Also, if I dynamically remove the bottom  that's situated next to the image, I'd like the top  to be vertically centered (next to the image, of course).
I've had my attempts turning everything into block and playing with widths and heights but I wonder if there's a 'cleaner' version out there.
Thanks a lot!
EDIT:
My current code:
HTML:

    Text1
    Text2
    Text3

CSS:
li{
    border: 1px solid red;
    padding: 20px;
}
span:first-child{
    display: inline-block;
    width: 120px;
    height: 120px; /* width and height of the image*/
    vertical-align: middle;
}
span{
    border: 1px dashed green;
}

A: As much as I know only TD element support vertical alignment nothing else. If you want vertical alignment (positioning SPAN in the middle of LI) I suggest you two way:
Do it with JS or convert your LI to a TD.


text:
Q: how to show that there is no surjective function from a set to the set of natural numbers. So if I had a set $ A=\{1,...n\}$ where n is a positive integer how would I  show there is no surjective function from $A\rightarrow \mathbb{ N }$
I know that to show a function $f:X\rightarrow Y$ is surjective you take an element $y$ where $y\in Y$ and show that $y=f(x)$ for some $x \in X$.
So I tried something like a proof my lecturer did, saying there was a set $D = \{a \in A | a\notin f(a) \}$
Then saying if $a\in D $  then $a\notin f(a)$ so $f(a) \neq D$ and doing something simmilar for $a\notin D$,
 and concluding that f is not a surjective function.
But this seamed very wrong looking at what I wrote thanks for the help.

A: It can't be surjective since it can't reach more than $n$ elements.
To prove that you can consider any $$f:A\rightarrow \mathbb{ N }$$
then consider $max(f)$ which exists since f has a finite number of elements, then consider $m=max(f)+1\in \mathbb{N}$ which is not reached by $f$, thus f is not surjective.


text:
Q: Scraping Hidden Data using Python I have written the following code to scrape data:
import requests
from bs4 import BeautifulSoup
import pandas as pd

url = 'https://buyacp.com/parts/bumper-rear-primered-finish-fk-bb004/'

r = requests.get(url)

soup = BeautifulSoup(r.text, 'html.parser')

Product_Data = {
'SKU': soup.dd.text,

'name': soup.h1.text,

'description': soup.find('div', {"class":"tabs-contents"}),

}
url_list.append(Product_Data)
return`

I have tried many variations of the code to be able to scrape the description data however I only get the data from the last tab (warranty info) which is not what I am after.  The data for Description and Fitment seems to be hidden and I can't figure out what to do to be able to scrape this information.
Can someone point me in the right direction to be able to make this possible?
Thanks!

A: The reason you cannot access that data, as hinted at, is because that information is not loaded on page load, but is actually loaded into the tab elements from the JavaScript. This is why, like Andrej said, that information is in the script tags.
To resolve this, you can either pull that information from those script tags (again, like Andrej said) or use a Python library that allows you to load those tags. My library of choice is "Requests-HTML".
The below code will pull the information you want, although I am not sure what you want to do with the tab information so I provide no filtering:
# Will need to install 'requests-html'
from requests_html import HTMLSession

# Assign the URL,
# create the HTMLSession object,
# and run the "get" method to retrieve information from the URL
url = 'https://buyacp.com/parts/bumper-rear-primered-finish-fk-bb004/'
session = HTMLSession()
response = session.get(url)

# Check that the resolution code was 200
# (successfully retrieved info from URL)
res_code = response.status_code
if res_code == 200:
    response.html.render() # This is the critical line. This render method runs the script tags to turn them into HTML

    # Get the item SKU and Name from the html
    # Note: the "html.find()" method takes CSS selectors
    item_sku = response.html.find("dd[itemprop='sku']", first=True).text
    item_name = response.html.find("h1[itemprop='name']", first=True).text

    # Get the tab content and put it into a dictionary
    tabs = {}
    for tab in response.html.find("div.tab-content"):
        tab_name = tab.find("h4", first=True).text
        tab_text = tab.find(".collapsibleMobile-content ", first=True).text

        tabs[tab_name] = tab_text

    item_info = {
        'SKU': item_sku,
        'Name': item_name,
        "Tabs": tabs
    }

    print(item_info)

else:
    print("Could not reach web page!")

A: The data you see on the page is stored inside HTML in <script> tag. To decode it you can use next example:
import re
import json
import requests

url = "https://buyacp.com/parts/bumper-rear-primered-finish-fk-bb004/"

data = re.search(
    r'window\.stencilBootstrap\("product", (".*")', requests.get(url).text
).group(1)
data = json.loads(json.loads(data))

# uncomment this to print all data:
# print(json.dumps(data, indent=4))

for f in data["productCustomFields"]:
    print("{:<20} {}".format(f["name"], f["value"]))

Prints:
Oem#                 D0DZ-17906-A
Part Type            Bumper
Bullet 1             Replaces a rusted, damaged, or missing bumper to restore original appearance
Bullet 2             Constructed from steel; Primer finish allows for easy paint prep - color matched bumpers give the car a modern look
Bullet 3             Made to replicate the factory's original bumper fitment
Bullet 4             Direct fit for 70-73 cars
Bullet 5             Can be adapted to fit 74-77 using earlier model Maverick bumper brackets, lower valance, and quarter panel extensions as well as inner trunk brackets from a 69-70 Mustang (some welding required)
Brand Title 1        Quality Guarantee
Brand Copy 1         All of ACP's products are precisely crafted with high grade materials and all-new advanced tooling. Each item is tested and quality checked for accurate appearance and functionality before it reaches you.
Brand Title 2        Expertly Crafted
Brand Copy 2         ACP's exclusive control over manufacturing ensures that all of our products are designed and crafted with thorough precision and expertise.
Brand Title 3        Exact OE Specifications
Brand Copy 3         ACP strives to match or exceed OE Correct standards for each of our products to maintain the original factory look.
Partlocation         Rear
Material             Steel
Color Finish         Primer
Spec Size            Null
Prop 65              Yes
Plpymm 1             1970-1973 Ford Maverick, 1971-1973 Mercury Comet
Categories           Body
Part Group           Bumper
Make                 Mercury
Make                 Ford
Model                Comet
Model                Maverick
Year                 1973
Year                 1972
Year                 1971
Year                 1970


text:
Q: Astroturfer can get their profile link to stay on the main page - let's stop that Low volume sites have relatively static main pages. Consider this scenario:

*

*A user with a name that describes their services  (Everest Tour Guides for example) answers a question with a subject line like How Do I Find a Tour Guide to Everest Base Camp?

*the answer has a link in it and not enough disclaimers, and isn't very useful. It's flagged, or a moderator comes across it

*the answer is deleted, but the account is not

Result: the last activity on the main page still shows the user's name, and is a working link to their profile. Go to Travel today to see it in action.

I don't think I like this. Could the "last activity" somehow show the last activity that stuck? Or list the moderator who deleted the answer as the author of the last activity?

A: The correct thing here is to just delete this user, who was obviously only created for spamming. I just did this, and now the Community user shows up as the user who "last modified".


text:
Q: Adding 'x' lines to a SQL Table based on user input I have an application that has editable table rows through Vue that are displayed from a database. As of right now there is a button (add line) that when clicked calls a query to insert a row into a database. Is there a way to take user input to automatically add x number of lines without having to click the (add line) button many times?
This is the front end button:
input(style="margin-right: 50px;" type="submit" value="Add Line  " @click="addLine(query_number)")

This is Vue function that calls the backend query
addLine(query_number) {
  let line = {
    "quote_number": this.query_number
  }

  this.$http.post(`/api/quote/line/?quote_number=${query_number}`, line).then(res => {
    if(res.data.error) {
      this.$root.updateError(res.data.error)
    } else {
      this.$router.go(`/quote/line/?quote_number=${query_number}`), this.$root.updateSuccess(res.data.message)
    }
  }).catch(error => {
    this.$root.updateError(error)
  })
},

And finally the post call:
.post(checkAuthentication, (req, res) => {
  let request = new sql.Request(pool)
  let add_newLine = `
  insert into quote_line (
    quote_number,
    line_number,
    item_id,
    created_at
  )
  output Inserted.*
  Values (
    ${req.query.quote_number},
    ((select count(quote_number) as [count]
      from quote_line
      where quote_number = ${req.query.quote_number || ''}) + 1),
    'new item line',
    getDate()
  )`

  request.query(add_newLine, (error, result) => {
    if(error) {
      throw new Error(error)
      res.json({"error": `${error}`})
    }
    res.json({"message": `Successfully added a new line to ${req.query.quote_number}`})
  })
})

A: Create a UI element where the user can input the number of rows to add, and either modify the function that currently adds a row to add multiple, or call it in a loop, based on that input.
As Dale said, we'd probably need to see code to help further.


text:
Q: Implicit Wait in Robot Framework I am using below code to implement implicit wait in robot framework in PyCharm , it does not seem to work.
*** Settings ***
Resource        resource.robot
Test Setup      open admin portal url
Test Teardown   Close Browser Session
Library     Collections
Library     SeleniumLibrary

*** Test Cases ***

Usergroup Creation

    Login       ${username}   ${validpassword}
    Create Group

*** Keywords ***
Create Group
    #Set Selenium Implicit Wait          10 seconds
    Sleep               3
    Click Element       xpath://span[contains(text(),'User Groups')]

    Click Element       xpath://*[@class='row']/div[2]/div/a[1]/i[1]

    Input Text          id:displayName      TestGroup2
    Double Click Element    xpath://span[contains(text(),'suraj.morye@forcepoint.com')]
    Click Element       xpath://button[contains(text(),'Confirm')]

    Click Element       xpath://button[contains(text(),'Save')]

    Wait Until Page Contains        User Group created

I tried multiple library and stuff but to no use.


text:
Q: how to align absolute child's vertical position to parent div I'm trying to make the child divs (option-info) stay just below the parent div but also give them 100% width.
Now the children are centered and have 100% but aren't positioned relative to the parent div. Is there a way to give the child div absolute width but relative positioning vertically in CSS and HTML? Thanks in advance!
Here's the HTML:

hardware

test

design

test

software

test

gaming

test

Here's the CSS:
.header {
display: inline-block;
position: relative;
background-color: rgb(81, 154, 226);
font-size: 2.3em;
height: 100px;
color: white;
font-family: 'saira', arial;
text-shadow: 2px 2px #2280dd;
width: 250px;
text-align: center;
text-transform: uppercase;
margin: auto;
top: 70px;
-webkit-box-shadow: 0px 12px 60px -17px rgba(0,0,0,0.75);
-moz-box-shadow: 0px 12px 60px -17px rgba(0,0,0,0.75);
box-shadow: 0px 12px 60px -17px rgba(0,0,0,0.75);
z-index: 1;
line-height: 100px;
}

#container {
text-align: center;
width: 100%;
}

.option-container {
display: inline-block;
width: 250px;
margin: 22px 22px 100px 22px;
}

.option-info {
display: inline-block;
position: absolute;
width: 100%;
font-family: 'roboto', arial;
font-size: 1.3em;
text-align:  center;
right: 0;
left: 0;
}

A: Would something like this work for you? I took the option-info element out of the HTML and used the :after pseudo to insert the text in the desired (if I understood correctly) location.

.header {
display: inline-block;
position: relative;
background-color: rgb(81, 154, 226);
font-size: 2.3em;
height: 100px;
color: white;
font-family: 'saira', arial;
text-shadow: 2px 2px #2280dd;
width: 250px;
text-align: center;
text-transform: uppercase;
margin: auto;
top: 70px;
-webkit-box-shadow: 0px 12px 60px -17px rgba(0,0,0,0.75);
-moz-box-shadow: 0px 12px 60px -17px rgba(0,0,0,0.75);
box-shadow: 0px 12px 60px -17px rgba(0,0,0,0.75);
z-index: 1;
line-height: 100px;
}

#container {
text-align: center;
width: 100%;
}

.option-container {
display: inline-block;
width: 250px;
margin: 22px 22px 100px 22px;
  position: relative;
}

.option-container:after {
  width: 100%;
  position: absolute;
  padding: 10px 0;
  content: 'test';
  bottom: -120px;
  left: 0;
  z-index: 9999;
  font-family: 'roboto', arial;
  font-size: 1.3em;
  text-align:  center;
  }

hardware

design

software

gaming

A: So I tried restructuring the HTML and this is what I came up with, and this is exactly what I was looking for!

hardware

test

design

test

software

test

gaming

test

And I just changed two things with the CSS:
.info-container {
position: absolute;
width: 100%;
right: 0;
left: 0;
height: 100%;
}

.option-info {
display: inline-block;
position: relative;
width: 100%;
font-family: 'roboto', arial;
font-size: 1.3em;
text-align:  center;
color: black;
color: rgba(0, 0, 0, 0.9);
margin: auto;
top: 100px;
}

EDIT: I appreciate the answers, but it seems I fixed my own problem.


text:
Q: Google Play Store is missing in Android Things Did anyone successfully build location service into Android Things? I am trying to use LocationServices, but it cannot connect with Google Play.
It complains "W/GooglePlayServicesUtil: Google Play Store is missing." and ConnectionResult is {statusCode=SERVICE_INVALID, resolution=null, message=null}
I have setup wifi on Android Things (Intel Edison) and it can fetch a webpage successfully.
The following is my gradle file.
apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'

    defaultConfig {
        applicationId "com.example.androidthings.myproject"
        minSdkVersion 24
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
                    'proguard-rules.pro'
        }
    }
}

dependencies {
    compile 'com.google.android.gms:play-services:10.2.6'
    provided 'com.google.android.things:androidthings:0.4-devpreview'
}

My first ever question on stackoverflow. Many thinks for your help!

A: compile 'com.google.android.gms:play-services:10.2.6'

Android Things Developer Preview 4 does not support 10.2.6. It supports 10.0.0, as is noted in the release notes. My guess is that your Java code (which is not shown in your question) is going through a code path that is trying to upgrade Play Services to match your 10.2.6, and that is where you are getting your error.

A: Android Things does not include the Google Play Store, which is responsible for automatically updating Play Services on the device. Because the Play Services version on the device is static, apps cannot target a client SDK greater than the version bundled with the target release.  Source :- https://developer.android.com/things/sdk/index.html


text:
Q: SBT sub projects depending on each other I have a multi-project SBT build. There is a root which does not have anything, it just aggregates all sub projects.
lazy val aaRoot = (project in file(".")).settings(commonSettings: _*).settings(
  libraryDependencies ++= appDependencies
).enablePlugins(PlayJava).aggregate(foo, bar)

lazy val foo: Project = (project in file("modules/foo")).settings(commonSettings: _*).settings(
  libraryDependencies ++= appDependencies
).enablePlugins(PlayJava).dependsOn(bar)

lazy val bar = (project in file("modules/bar")).settings(commonSettings: _*).settings(
  libraryDependencies ++= appDependencies
).enablePlugins(PlayJava).dependsOn(foo)

It is clearly a cyclic dependency here (foo depends on bar and bar depends on foo). What are the possible approaches to avoid these kinds of dependencies or is there an SBT way of handling this.

A: None of the build tools I know allow for cyclic dependencies... and in my experience that is a symptom of a issue with the design of the application or modules, rather than a 'missing' feature from the tools. It's even seen as something bad when this happens at the package level in the same module/jar.
Can you merge those 2 modules? or reshufle the classes so the cyclic dependency disappears?

A: As @Augusto suggested, I have re-organized my classes into three different sub-modules and using my Dependency Injection little more wisely. This solved my problem and gave much more abstraction than what I initially had.
Three sub-projects:

*

*api (Just interfaces)

*foo (depends on api)

*bar (depends on api)

*aaRoot (which aggregates all of the above)

In FooModule (in my case Guice module), I am binding FooInterface from api module to FooImplementation (foo module). While calling the bar module, I just use BarInterface (from api) by passing FooInterface.
Same as the case with bar module.
At runtime they all will be available and it can easily resolve.


text:
Q: How to change boolean value within json file using a button in angular & typescript? My question is, how do I write a function in my table-viewer.component.ts file to change the value from false to true within the JSON file based on whether the user clicks the cancelled button?
I have a JSON file containing the following details.
db.json
"firstName": "Hamza",
"lastName": "Gallagher",
"carReg": "FG67 POI",
"parkingNumber": "00003",
"date": "2021-01-04",
"cancelled": false

etc ..
And I am displaying them in a table with angular, which shows the following:
Image of table
Table-viewer.component.html

    First Name
    Last Name
    Car Registration
    Parking Number
    Date
    Status

   {{booking.firstName}}
   {{booking.lastName}}
   {{booking.carReg}}
   {{booking.parkingNumber}}
   {{booking.date}}

Cancelled

Booked

     <button class="btn btn-danger mr-2" (click)="cancelBooking()">Cancel</button>

table-viewer.component.ts
export class TableViewerComponent implements OnInit {
  bookings: Booking[] = [];

  getBookings(): void {
    this.bookingService.getAll().subscribe((book: Booking[]) => {
      this.bookings = book;
    });
  }

  constructor(private bookingService: BookingService) {
  }

  ngOnInit(): void {
    this.getBookings();
  }

  cancelBooking(): void {
  //  Help
  }

}

booking.ts
export interface Booking {
  'firstName': string;
  'lastName': string;
  'carReg': string;
  'parkingNumber': string;
  'date': string;
  'cancelled': boolean;
}

A: Table-viewer.component.html

     ...

       <button class="btn btn-danger mr-2" (click)="cancelBooking(booking: Booking)">Cancel</button>

table-viewer.component.ts
export class TableViewerComponent implements OnInit {
   ...

  cancelBooking(booking): void {
     booking.cancelled = !booking.cancelled
     // or booking.cancelled = false; or whatever you want to do
   }
  }

Now, you have the change in the bookings array.
Next, you should implement a service to rewrite a json file.
https://stackoverflow.com/a/52242184/11218448

A: I think it is as simple as:
    cancelBooking(booking:Booking){
 booking.cancelled = true;
}

And just pass it in the view to the method

A: Please use this code in your componenet.ts
cancelBooking(index): void {
  //  Help
  this.bookings[index].cancelled = true;
  }

Template :
Change the loop code with below code:

   {{booking.firstName}}
   {{booking.lastName}}
   {{booking.carReg}}
   {{booking.parkingNumber}}
   {{booking.date}}

Cancelled

Booked

     <button class="btn btn-danger mr-2" (click)="cancelBooking(i)">Cancel</button>


text:
Q: I have a query in Spark-Scala I have tried the following in spark-scala.
Logic:
If Code in Data1 = Code in Data2 the record has to be written to the output file. so based on this condition 4*2; 8 rows are getting written.
Is there any way to optimize the below piece of code to group data?
.join(Data1,
 col("Code") === col("Code"), "inner")
 .selectExpr("Id" ,
            "Date",
            "Code"
             ).as[OutData]

Data1
+---------------+------------
|Id             |Code
+---------------+------------
|0839           |06869242986
|4395           |06869242986
|3796           |06869242986
|3592           |06869242986
+---------------+------------

Data2
+---------------+------------
|Date           |Code
+---------------+------------
|202050         |06869242986
|202051         |06869242986
+---------------+------------

OutData
+---------------+-------+------------
|Id             |Date   |Code
+---------------+-------+------------
|0839           |202050 |06869242986
|4395           |202050 |06869242986
|3796           |202050 |06869242986
|3592           |202050 |06869242986
|0839           |202051 |06869242986
|4395           |202051 |06869242986
|3796           |202051 |06869242986
|3592           |202051 |06869242986
+---------------+-------+------------


text:
Q: Detect type of string and create new variable accordingly to it So i have a dataset of passwords and i would like to create a new column if the password matches one of the following strings (im working with R)
id password   year     lenght
1  1 12345      2001       5
2  2 pass4      2002       5
3  3 angel      2003       5
4  4 pizza      2004       5

pattern for passwords with only letters: "^[a-zA-Z]+$"
pattern for passwords with only numbers: "^[0-9]*$"
pattern for passwords with BOTH numbers and letters : '([0-9].[a-zA-Z])|([a-zA-Z].[0-9])'
So basically i would need a new column named : TYPE with 3 levels (numbers, letters or both)
what I need is this :
id password   year     lenght   Type
1  1 12345      2001       5.   numbers only
2  2 pass4      2002       5.   both
3  3 angel      2003       5.   letters only
4  4 pizza      2004       5.   letters only

A: You can use the following solution. Just bear in mind that we put our conditions from the most specific (both) to the most general (either of the two other conditions):
library(dplyr)

df %>%
  mutate(Type = case_when(
    grepl("[A-Za-z]+", password) & grepl("[1-9]+", password) ~ "Both",
    grepl("[A-Za-z]+", password) ~ "Letters Only",
    grepl("[1-9]+", password) ~ "Numbers Only",
    TRUE ~ as.character(password)
  ))

  id password year lenght         Type
1  1    12345 2001      5 Numbers Only
2  2    pass4 2002      5         Both
3  3    angel 2003      5 Letters Only
4  4    pizza 2004      5 Letters Only


text:
Q: How to invert a condition in Bash I want to check if a directory exists on Android.
From an answer to Check if a file exists with a wildcard in a shell script, I get an idea. So I use ADB like below.
if [ adb shell ls ${test_dir}  2> /dev/null ] ;
then
   echo "files exist"
else
   echo "files do not exist"

fi

I am new to Bash scripting. I know adb shell ls will return all file names. But what's meaning of 2> /dev/null?
And I only care about files do not exist condition. So how do I  invert the condition?
Second version
if [ ! adb shell ls ${test_dir}  2> /dev/null ] ;
then
   echo "files exist"
else
   echo "files do not exist"

fi

Adding ! cannot work for me.

A: In the expression:
if [ adb shell ls ${test_dir}  2> /dev/null ]

The redirection 2> /dev/null redirects any message on stderr (any error resulting from abd shell ls ${test_dir} to /dev/null quaintly known as the bit bucket. In essence the bit bucket is a system device node that goes nowhere. So you can copy or redirect any output you like to /dev/null and it simply goes away (meaning it isn't copied anywhere and isn't redirected any further -- it just goes into the bit bucket -- a black-hole for convenience) This has the effect of suppressing any output from the test itself.
The second part of your question asks how to negate (invert) a test clause. The simple answer is to put a '!' at the front of the test.
Let me know if you have further questions.

After further discussion and sorting out that adb is a android tool, the solution was to simply check the return following the execution of the command itself, e.g.
$ adb shell ls ${test_dir}  2> /dev/null

and then test the return with
if [ "$?" -ne '0' ]; then
    # handle error
fi

If you have further questions on this issue, just let me know.


text:
Q: Assign Home and End to Fn+arrows Is is possible to assign Home/End/PgUp/PgDown to combinations of Fn+arrow keys in Windows 8.1 (I have HP Elitebook 8540p if that matters)?
Motivation: in particular I like keyboard of my current laptop a lot, but it's time to move on - and there are quite some offers of new laptops that don't have separate Home/End buttons, which I tend to use a lot, even when typing this question. Instead, I am supposed to use Fn+arrow keys as Home, End, PgUp and PgDown. Before buying such laptop, I wanted to try whether I can live with it, or whether I should only focus on laptops with these keys separate.

A: Fn is not a key that generates a scan code so no one knows about its existence except for the keyboard controller. If you press Fn along with another key that has the Fn function symbol on it then the keyboard controller will convert that combination to the real scan code and send to the OS.
As a result if on the keyboard Fn+arrow does have some function, like changing brightness or volume then you can assign Fn+arrow to Home/End/PgUp/PgDown by remapping the brightness ☀ or volume  keys to them. But the HP Elitebook 8540p's keyboard isn't one of them. And I believe HP never puts any Fn functions to the arrow keys

However it does have Home/End/PgUp/PgDown at the top row like any laptops with a numpad (the red rectangle above). It also has those keys in the numpad (the green rectangle)
In fact what you said "there are quite some offers of new laptops that don't have separate Home/End buttons" is incorrect. All the laptops I've ever seen have those keys, just at different locations. Personally I despise any keyboards that require me to use 2 keys for Home/End/PgUp/PgDown because I use them extensively, so I've always tried to look for laptops with them on single separate keys. However, it's time to move on - and there are quite some good deals for laptops without those on separate keys so I tried the ones with a numpad and was quite happy with that, just turn off numlock by default and I can navigate with single key presses. I don't like to reach the keys on the top row which requires me to move my hand a lot. It's also lucky that I hate laptops smaller than 15.4", and a lot of new big laptops have a numpad
If you really just want to use Fn+arrow then you're out of luck, unless those generate some hidden scan codes that doesn't show on the key label. You can use AutoHotkey or various other tools to check. See Finding the scan code of FN Key. If they don't then you have to choose another combination, like Ctrl+Alt+arrow, Win+Alt+arrow or CapsLock+arrow
There are a lot of questions about this on this site

*

*Remap laptop brightness keys to Fn + Arrow keys

*How To Map Fn+Key (Multiple Keys) To Other Key in Windows?

*Is it possible to create your own Fn+Key combinations on Windows 8.1?

*Remap "Windows key + Ctrl + Left or Right arrow" to "Fn key + Ctrl + Left or Right arrow"

*Remap FN to another key

*Mapping Ctrl+Arrow for Home/End/PageUp/Down

*Can I configure my windows key to act like a fn key?

*How can i map Fn+[keys] to emulate multimedia keys (prev, pause, next song...) in a laptop?

A: As far as I know the fn key on laptops is not reported as a keystroke - rather the keyboard has specific keys which you can use with the fn key to produce a different keycode. I discovered this by checking what was reported when the key was pressed, which was nothing, as opposed to other modifier keys like Alt or Shift which have a scancode of their own.
In summary: No, it's not possible because the fn key isn't a key in its own right and is only valid in combination with the specific keys (as printed usually in blue on the keytop for those specific keys).
Hope this helps!


text:
Q: Delete data from database using row action I have little problem how implement deleting data from database using row actions. I have my custom list which includes data from database table.

 function column_name( $item ) {
    $delete_nonce = wp_create_nonce();
    $title = '' . $item['article_name'] . '';
    $actions = [
        'edit' => sprintf('Edit', 'edytuj-artykul', $item['article_id']),
        'delete' => sprintf('Delete', esc_attr( $_REQUEST['page'] ), 'delete', absint($item['article_id']), $delete_nonce)
    ];
    return $title. $this->row_actions( $actions );
}

function delete_article($item){
    $article_id = $item['article_id'];
    global $wpdb;
     $table = 'wp_copywriter_articles';
     $wpdb->query("DELETE FROM $table WHERE article_id = %d", $article_id);
}

In the same file I added
add_action( 'admin_action_delete', 'delete_article' );

When I click Delete action, nothing happend. I got link
http://localhost/wordpress/wp-admin/admin.php?page=Artykuly&action=delete&article_id=26&_wpnonce=60a01b82d7
but record is not deleted from database.
For testing, I added a specific ID number of article to the delete_article method in the SQL query but still not works, so this method is not used by WP, when I click delete button.
Someone can give me any tip what am I doing wrong, because I spent on this few few hours :)
Best Regards,
Bartek
@EDIT
SOLVED
My mistake was put delete_article() method to my custom list class. When I put my method to functions.php, everything works! :)

A: I think it's better to use the $wpdb->delete() function to remove a row.
$article_id = $item['article_id'];
$table = 'wp_copywriter_articles';
$wpdb->delete( $table, array( 'id' => $article_id ) );

A: The "admin_action_{$_REQUEST['action']}" hook does not pass any arguments. You would need to get the article_id from the $_REQUEST array. There are also a few other concerns such as:

*

*You're not assigning an action when you call wp_create_nonce().

*As Mafnah suggets in their ansewr, you should use $wpdb::delete() as a shortcut for using $wpdb::prepare().

Here's how you could rewrite this:
function column_name( $item ) {
    $delete_nonce = wp_create_nonce( 'delete_article' );
    $actions = [
        'delete' => add_query_arg( array(
            'action'        => 'delete',
            'article_id'    => $item['article_id'],
            '_wpnonce'      => $delete_nonce,
        ), admin_url( 'admin.php' ) ),
    ];
    /* Etc... */
}

function delete_article() {

    global $wpdb;

    // Ensure we can verify our nonce.
    if( ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'delete_article' ) ) {
        wp_die( esc_html__( 'Could not verify request. Please try again.' ) );

    // Ensure we have an article ID provided.
    } else if( ! isset( $_REQUEST['article_id'] ) ) {
        wp_die( esc_html__( 'Could not find provided article ID. Please try again.' ) );

    // Ensure we're able to delete the actual article.
    } else if( false === $wpdb->delete( 'wp_copywriter_articles', array( 'article_id' => $_REQUEST['article_id'] ) ) ) {
        wp_die( esc_html__( 'Could not delete the provided article. Please try again.' ) );
    }

    // Redirect back to original page with 'success' $_GET
    wp_safe_redirect( add_query_arg( array(
        'page' => ( isset( $_REQUEST['page'] ) ) ? $_REQUEST['page'] : '404',
        'success' => 1,
    ), admin_url( 'admin.php' ) ) );
    exit();

}


text:
Q: Jetpack Compose: What exactly is 'remember' if mutableState does the job? I started learning Compose just recently. So far I had no difficulty implementing different Composables and controlling them around, but there are some terminologies that I am struggling to understand !
One of them is remember { } which returns the same type as mutableState(Both are snapshots). Here's an example:
        val myItems = mutableStateListOf<Int>()

        //then I call the composable here for example, and pass the items as a param:
        DropdownMenuCustomizedByMe(... items = myItems) { ... }

My Composable gets recomposed everytime the above variable changes, so that's the functionality I wanted, I am not sure what exactly is the purpose behind rememberif the latter does the job. I tried reading docs and people's explanations around stackoverflow but I really couldn't come to a practical conclusion as to why I'd use it.


text:
Q: Prevent user registration with ServiceStack.OpenId Is it possible to prevent ServiceStack from registering new users with the OpenId providers? (Registration Module disabled)
I only want to enable OpenId for users that already exists in the IUserAuthRepository, but ServiceStack adds every unknown user automatically.


text:
Q: PyCharm raw_input() and map() work differently Python newbie here. While running .py files or using the python command line in PyCharm, I see that built-in functions don't seem to work:
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32
>>> range(5, 30, 5)
range(5, 30, 5)

Similarly, when I try to use raw_input():
>>> x = raw_input('please enter a number')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'raw_input' is not defined

I can use map but can't seem to see the result - just the 'map object':
>>> def cube(x): return x*x*x
>>> map(cube, range(1, 11))
<map object at 0x03021F50>
>>> g = map(cube, range(1,11))
>>> g
<map object at 0x03027190>
>>> g[1]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'map' object is not subscriptable

If I run Python from my windows command line, these commands run fine. Any tips to figure out what's going wrong here?

A: Python 3 does not have raw_input only input.
How do I use raw_input in Python 3
Maybe you are confusing different Python interpreter versions here.


text:
Q: MySQL - Using ORDER BY equals very poor performance Using a MariaDB database containing a table with 1.7M UK postcodes, I am trying to determine the nearest postcode to a given set of latitude and longitude as follows:
MariaDB [dev]> SELECT COUNT(*) as total, postcode, ( 3959 * acos( cos( radians( 53.18526 ) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(-3.01984) ) + sin( radians(53.18526) ) * sin( radians( latitude ) ) ) ) AS distance FROM uk_postcodes LIMIT 1;
+---------+----------+--------------------+
| total   | postcode | distance           |
+---------+----------+--------------------+
| 1751331 | AB10 1AA | 276.23821854757585 |
+---------+----------+--------------------+
1 row in set (0.35 sec)

For the purpose of this example, I included COUNT(*) to show how many records are in the table to start with. Discounting COUNT(*) results in the query executing in 0.01 seconds.
I need to get the nearest postcode, so I add the ORDER BY statement:
MariaDB [dev]> SELECT postcode, ( 3959 * acos( cos( radians( 53.18526 ) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(-3.01984) ) + sin( radians(53.18526) ) * sin( radians( latitude ) ) ) ) AS distance FROM uk_postcodes ORDER BY distance LIMIT 1;
+----------+---------------------+
| postcode | distance            |
+----------+---------------------+
| CH5 3PF  | 0.13513453795504218 |
+----------+---------------------+
1 row in set (2.33 sec)

The correct result is returned but it takes a very long time.
The Google Geocode API is able to return the nearest postcode in what seems like instantly: https://maps.googleapis.com/maps/api/geocode/json?latlng=53.18526,-3.01984
What can I do to return a result from my database instantly?

A: Here's my suggestion above in the comments in a sql code, just in case it improves the performance a bit:
    SELECT postcode
, min(( 3959 * acos( cos( radians( 53.18526 ) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(-3.01984) ) + sin( radians(53.18526) ) * sin( radians( latitude ) ) ) )) AS distance
FROM uk_postcodes GROUP BY postcode;

A: I have managed to solve the performance problem!
TABLE STRUCTURE
+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| postcode    | varchar(8)   | NO   | PRI | NULL    |       |
| district    | varchar(4)   | YES  |     | NULL    |       |
| postal_town | varchar(35)  | YES  | MUL | NULL    |       |
| county      | varchar(37)  | YES  |     | NULL    |       |
| country     | varchar(16)  | YES  |     | NULL    |       |
| easting     | int(11)      | YES  |     | NULL    |       |
| northing    | int(11)      | YES  |     | NULL    |       |
| latitude    | decimal(7,5) | YES  |     | NULL    |       |
| longitude   | decimal(7,5) | YES  |     | NULL    |       |
| type        | varchar(14)  | YES  |     | NULL    |       |
| id          | varchar(32)  | YES  |     | NULL    |       |
| latlng      | geometry     | NO   | MUL | NULL    |       |
+-------------+--------------+------+-----+---------+-------+

SPATIAL INDEX
The latlng field has the spatial index and has been populated as follows:
UPDATE uk_postcodes SET latlng = GeomFromText(CONCAT('POINT(',latitude,' ', longitude, ')'));

SQL QUERY
SELECT postcode, ( 3959 * acos( cos( radians( 53.18526 ) ) * cos( radians( X(latlng) ) ) * cos( radians( Y(latlng) ) - radians(-3.01984) ) + sin( radians(53.18526) ) * sin( radians( X(latlng) ) ) ) ) AS distance
FROM uk_postcodes
WHERE MBRContains
(LineString
  (
    Point (53.18526 + 10 / (111.1 / COS(RADIANS(53.18526))), -3.01984 + 10 / 111.1),
    Point (53.18526 - 10 / (111.1 / COS(RADIANS(53.18526))), -3.01984 - 10 / 111.1)
  ),
  latlng
)
ORDER BY distance
LIMIT 1;

RESULT
+----------+---------------------+
| postcode | distance            |
+----------+---------------------+
| CH5 3PF  | 0.13513453795504218 |
+----------+---------------------+
1 row in set (0.00 sec)


text:
Q: MySql - How to get rid of the No Data : Zero Rows Fetched So i have written this small stored function which is supposed to return the cost of a juiceorder to me. However, i am having some trouble figuring out why specifically it isnt working. Any help would be appreciated
DELIMITER $$

CREATE DEFINER=`root`@`localhost` FUNCTION `juiceOrderCost`(p_id INT) RETURNS double
BEGIN
DECLARE cost DOUBLE;
DECLARE i INT DEFAULT 0;
DECLARE numRows INT;
DECLARE numDone INT DEFAULT 1;
DECLARE cup_id INT DEFAULT 0;

DECLARE myCursor CURSOR for
    SELECT cupId FROM hasJuice WHERE orderID = p_id;

OPEN myCursor;
SELECT FOUND_ROWS() INTO numRows;

FETCH myCursor INTO cup_id;
WHILE numDone <= numRows DO

SET cost =  cost + juiceCupCost(cup_id);

FETCH myCursor INTO cup_id;

SET numDone = numDone + 1;

END WHILE;

CLOSE myCursor;

RETURN cost;
END

A: Use DECLARE CONTINUE HANDLER FOR NOT FOUND
Visit https://dev.mysql.com/doc/refman/5.5/en/condition-handling.html


text:
Q: Nginx PHP Page downloads instead of displaying This has been a struggle for the past two days. I've done a lot of searching, couldn't find anything to fix it.
Here's my nginx.conf:
 user www-data;
    worker_processes 4;
    pid /run/nginx.pid;

    events {
            worker_connections 768;
            # multi_accept on;
    }

    http {

            ##
            # Basic Settings
            ##

            sendfile on;
            tcp_nopush on;
            tcp_nodelay on;
            keepalive_timeout 65;
            types_hash_max_size 2048;
            # server_tokens off;

            # server_names_hash_bucket_size 64;
            # server_name_in_redirect off;

            include /etc/nginx/mime.types;
            default_type application/octet-stream;

            ##
            # Logging Settings
            ##

            access_log /var/log/nginx/access.log;
            error_log /var/log/nginx/error.log;

            ##
            # Gzip Settings
            ##

            gzip on;
            gzip_disable "msie6";

            # gzip_vary on;
            # gzip_proxied any;
            # gzip_comp_level 6;
            # gzip_buffers 16 8k;
            # gzip_http_version 1.1;
            # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

            ##
            # Virtual Host Configs
            ##

            include /etc/nginx/conf.d/*.conf;
            include /etc/nginx/sites-enabled/*;
    }

Here's my default file in /etc/nginx/sites-enabled:
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html/;
    index index.php index.html index.htm;

    server_name [redacted server IP];

    location / {
        try_files $uri $uri/ =404;
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    location ~ /admin/ {
        auth_basic "Restricted";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

}

The page is stored in /usr/share/nginx/html/admin/index.php -- it prompts for the username/password (which works fine), but as soon as I login, it downloads instead of showing the php webpage.
If I put the 'location ~ /admin/' block after the 'location ~ .php$' block, it works, but doesn't authenticate.
There are scripts I wrote in another folder that work fine when called 'in the folder /usr/share/nginx/html/api/XXX.php' (which inserts stuff into the MySQL database), but it just returns JSON stuff.
You are awesome for helping me out, I really do appreciate it.

A: You are commenting the php5-fpm sock, delete the comment from the following line:
fastcgi_pass unix:/var/run/php5-fpm.sock;

Change your admin path configuration to use the php5-fpm sock:
location ~ /admin/.+\.php$ {
  auth_basic "Restricted";
  auth_basic_user_file /etc/nginx/.htpasswd;
  fastcgi_split_path_info ^(.+\.php)(/.+)$;
  fastcgi_pass unix:/var/run/php5-fpm.sock;
  include fastcgi_params;
  fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  fastcgi_index index.php;
 }

OR move your admin configuration path AFTER the ~\.php$ {} rule
(both worked for me)
make sure the php5-fpm service is running and you've restarted nginx
sudo service php5-fpm restart && sudo service nginx restart

A: Try adding the default PHP block into your conf.
location ~ \.php$ {
    fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        if (!-f $document_root$fastcgi_script_name) {
            return 404;
    }

   fastcgi_pass 127.0.0.1:9000;
   fastcgi_index index.php;
   include fastcgi_params;
}

Without this block the expected behavior is to show the file. You need to have PHP FPM running and configured to make this work. Instructions are available at http://wiki.nginx.org/PHPFcgiExample


text:
Q: How is it possible to deliver email from qmail to a LMTP server? I have a qmail server, which cannot be changed into anything else, because it is part of a much larger system. It should route all emails to a Zarafa server, which only uses the LMTP protocol and to which I don't have physical access.
How is it possible to make qmail deliver the emails to the LMTP server?

A: I don't see any indication that qmail supports LMTP.  Could you redirect to an exim process which runs the LMTP delivery.  This could be configured as a pipe delivery target.  Alternatively, exim could run on another port or server.


text:
Q: Propagation speed of air humidity I'm currently playing with relative air humidity and temperature sensor that makes measurements in my living room once every 60s. When plotted the data on a chart I noticed that spikes and dips of humidity very closely correlate with events in the room: i can clearly see a spike when I wake up in the morning and do myself a cup of tea or take shower. Similarly, the chart line plummets when i leave the house. On the other hand temp data doesn't seem to show any response to the events in the room.
The question is: how the speed of moisture traveling in air is defined?
When a kettle in one corner of a room starts to boil, how soon will this be detected by a sensor in the opposite corner?

A: if there is fan-forced heating in your room or convection moving the air around, the time constant for sharing humidity is on the order of minutes. if diffusion (no bulk air movement) is the only mechanism available, the answer is on the order of hours.

A: In a closed window envirinment in a room the fastest way of moving air is convection.
And convection depends on the geometry of the room, the walls, and even furniture. The trace of dust over walls and furniture in rooms not dusted for a while will be kind of an indicator of the flow of air.
If there is draft in the room especially from lower to higher part the flow of convection will be faster.
Depending on the gradient of humidity and temeratur in the absence of ventilation the air will stratify and stagnate in a few hours.
An explanation for your sensor not being sensitive to local fast chenges in temps could be the way it is set up. If it reads infrared readiation, it is possible it'looks' at some distance.


text:
Q: Tangent vector and sequence of points Let $M$ be the graph of a $C^1$ function $f: X \rightarrow \mathbb{R}$, where $X$ is open. Suppose there is a sequence $s_k$ converging to $p \in M$ such that $$\lim_{k}\frac{s_k-p}{|s_k-p|}=v$$ for some vector $v \in \mathbb{R}^{n+1}$.

Show that $v$ is tangent to $M$ at $p$, i.e. $v=(w ,df_xw)=(w, \nabla f (x) \cdot w)$, where $w=(v_1,...,v_n)\in \mathbb{R}^n$ and $(x,f(x))=p$

Here is my try. We have $s_k=(x_k,f(x_k))$ for some $x_k \in X$ and therefore $v=\displaystyle \lim_{k}\frac{s_k-p}{|s_k-p|}=\lim_k\frac{1}{|s_k-p|}\left(x_k-x,f(x_k)-f(x) \right )=\lim_k\frac{|x_k-x|}{|s_k-p|}\left(\frac{x_k-x}{|x_k-x|},\frac{f(x_k)-f(x)}{|x_k-x|} \right )$.
But $\displaystyle \frac{|x_k-x|}{|s_k-p|}=\frac{|x_k-x|}{\sqrt{|x_k-x|^2+|f(x_k)-f(x)|^2}}\in \left [\frac{|x_k-x|}{\sqrt{|x_k-x|^2(1+|\nabla f(x)|^2o(|x_k-x|)^2)}},1\right]$ because $f$ is differentiable, so $v=\displaystyle \lim_k\left(\frac{x_k-x}{|x_k-x|},\frac{f(x_k)-f(x)}{|x_k-x|} \right )$.
Calling $w:=\displaystyle \lim_k\left(\frac{x_k-x}{|x_k-x|}\right )$ I would be done, if I knew that this limit existed. Do you have any suggestion for this? Is the above correct?


text:
Q: How to import components correctly in react app? I found the following code. What does the @ stand for, is this a standard in react? What is a better way to import a component?
a)
import Box from '../../../components/Box '

b)
import Box from '@components/Box '

A: If you are using Typescript (which the tag suggests you are) it's possible to setup "path mapping" in your tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@": ["./src"],
      "@/*": ["./src/*"],
      "@components": ["./src/components"]
    }
  }
}

reference: https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping
So, it is difficult to update all paths in tsconfig.json so i would suggest to use 1st option

A: @components is an alias for the components folder.
See how the example a you have to go down a bunch of folders so that you can reach the components one, relative to wherever that statement is being used? Well, the secondary option makes that a log simpler by considering everything being imported from the components folder as @components, so you no longer need to worry about figuring out where one folder is when comparing to where you are.
This does usually require more configuration with webpack if it's how you chose to do so. Here is a blogpost I found explaining how and why
Also, to answer the original question, they are both correct. a is just the more traditional and default way of doing it, and b is an alternative that may require some extra setup, but will keep your imports more organized and easier to figure out.

A: Both are correct, no real benefit other than both won't always work depending on what you need imported.
You would use a) for when you need to import component(s) that exist in the source code of your project.
For b), you typically see this syntax when working with NPM packages that exist as dependencies in your project. Some of them are prefixed with an organization/library others are just the name of the library. For example: import React from 'react';


text:
Q: RuntimeError: Binary 'sox' could not be found I am playing with google speech library as follows:
from google_speech import Speech

# say "Hello World"
text = "Hello World"
lang = "en"
speech = Speech(text, lang)
speech.play()

getting this error:
RuntimeError

    Traceback (most recent call last)
<ipython-input-2-4daa3294f636> in <module>()
----> 1 from google_speech import Speech
      2
      3 # say "Hello World"
      4 text = "Hello World"
      5 lang = "en"

D:\soft\Ins\anac\lib\site-packages\google_speech\__init__.py in <module>()
    321
    322 # check deps
--> 323 bin_dep.check_bin_dependency(("sox",))
    324
    325

D:\soft\Ins\anac\lib\site-packages\google_speech\bin_dep.py in check_bin_dependency(bins)
      5   for bin in bins:
      6     if shutil.which(bin) is None:
----> 7       raise RuntimeError("Binary '%s' could not be found" % (bin))

RuntimeError: Binary 'sox' could not be found

i am working on windows, and i did all instructions:
If you don't already have it, install pip for Python 3
Install Google Speech: pip3 install google_speech
Install SoX, with MP3 support. On Ubuntu and other Debian derivatives: sudo apt-get install sox libsox-fmt-mp3. Windows users can download binaries on the SoX website, once installed you also need to copy libmad DLL in the directory where you have installed SoX, and to add this directory to your PATH environment variable.

A: You can find binaries and installers for SoX on its sourceforge downloads page:
    Get it from here
Adding SoX to your path
First, find the directory where SoX is installed. By default, this is probably C:\Program Files (x86)\sox-14-4-1 or C:\Program Files\sox-14-4-1
This directory needs to be added to your PATH environment variable. Open a command prompt by pressing the Windows key and typing cmd.exe (on Vista or later), or by choosing "Run" from the Start Menu and type cmd (on earlier versions).
Type path into the command prompt and it should return your PATH variable (PATH= followed by a list of directories). To temporarily add SoX to your PATH variable, type the following command (replace the C:\Program Files (x86)\sox-14-4-1 with your SoX directory if necessary):
set PATH=%PATH%;C:\Program Files (x86)\sox-14-4-1

Type path again, and it should return the same list of directories as before, but with the string ;C:\Program Files (x86)\sox-14-4-1 added to the very end. If it returns anything else (e.g., if it only returns the SoX directory), don't proceed to the next step (close the command prompt window and start over). If it returns the same list plus SoX, you can add SoX permanently by using the setx command instead of set:
setx PATH %PATH%;C:\Program Files (x86)\sox-14-4-1

On Windows XP, you'll need to install the Windows XP SP2 Support Tools before you can do this.
Checking for success
To check that this worked, open a new command prompt and type sox. If this is successful, it will return information on using SoX, but otherwise it should return "sox is not recognized".


text:
Q: Mongo for each not doing the funtcion I want to create a log document for each task that is late.
const dte = new Date();
  Task.find()
    .where("status")
    .ne("Done", "Stuck", "Late")
    .where("date")
    .lt(dte)
    .updateMany({ status: "Late" })
    .map(task => {
      const newLog = new Log({
        message: `${moment(dte).format("LT")}: The task: ${
          department.name
        } is delayed`,
        type: "late"
      });

      newLog.save();
    });

I expect to have the logs created at the db, the error message that I got is .map() is not a function.

A: You can do this.
const dte = new Date();
Task.find({
  status: {
  $ne: ["Done", "Stuck", "Late"]
},
 date: {
   $lt: dte
 }
}).then((tasks) => {

   // loop through tasks
   tasks.forEach(async (task) => {
      const newLog = new Log({
        message: `${moment(dte).format("LT")}: The task: ${
        department.name
        } is delayed`,
        type: "late"
      });

      await newLog.save();

      // update task
      task.set({ status: "Late" });
      await task.save();
 });
})


text:
Q: Hibernate 4 - Calling DAO and Initializing sessionFactory bean I'm in the middle of updating my old program to Spring 3.2 and Hibernate 4 and am running into a couple of difficulties with sessionFactory (I was using hibernateTemplate before).

*

*I don't think the way I am accessing the DAO is the best way to do it, but I don't see how else to make it work.  If I do a simple creation of the DAO object (CSSDAO d = new CSSDAOImpl();), the sessionFactory is always null.  If I have it the way I do below, it works.  What is the proper way to call the DAO methods? (please ignore the MVC portion of the controller, I know that needs its own work)

*I'm opening a new session in every method in the DAO.  I know this isn't correct, as I should be getting the current session.  But everytime I try to get the current session, it says one doesn't exist.  How does the session get "initialized" the first time?  I thought it would inject it based on the XML configuration, but that doesn't seem to be doing anything here.  Any thoughts?
hibernate-cfg.xml
    <?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

    <bean id="myDataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver"></property>
        <property name="url" value="jdbc:derby:C:\Users\Steven\MyDB"></property>
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="packagesToScan" value="net.form" />
        <property name="dataSource" ref="myDataSource"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.DerbyTenSevenDialect
                </prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>net.form.StyleChooser</value>
            </list>
        </property>
    </bean>

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean id="CSSDAO" class="dao.CSSDAOImpl">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

</beans>

DAO:
package dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import net.form.StyleChooser;

public class CSSDAOImpl implements CSSDAO {

    private SessionFactory sessionFactory;

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Transactional
    public List selectAllCSS() {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        List l = session.createCriteria(StyleChooser.class).list();
        session.flush();
        tx.commit();
        return l;
    }

    @Transactional
    public StyleChooser selectCSSById(Integer ID) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        StyleChooser sc = (StyleChooser) session.get(StyleChooser.class, ID);
        session.flush();
        tx.commit();
        return sc;
    }

    @Transactional
    public Integer insertCSS(StyleChooser insertCSS) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        Integer id = (Integer) session.save(insertCSS);
        session.flush();
        tx.commit();
        return id;
    }

    @Transactional
    public void deleteCSS(Integer CSSId) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        StyleChooser sc = (StyleChooser) session.get(StyleChooser.class, CSSId);
        session.delete(sc);
        session.flush();
        tx.commit();
    }

    @Transactional
    public void updateCSS(StyleChooser cssWithNewValues) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        session.update(cssWithNewValues);
        session.flush();
        tx.commit();
    }
}

Accessing DAO...
package net.controllers;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import net.form.StyleChooser;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import dao.CSSDAOImpl;

@Controller
@RequestMapping("/stylechoosertable.html")
public class IndexController extends MultiActionController {

    Resource resource = new FileSystemResource(
            "C:/Users/Steven/Desktop/Programming/workspace/CSSGeneratorHibernate4/WebContent/WEB-INF/hibernate.cfg.xml");
    BeanFactory beanFactory = new XmlBeanFactory(resource);
    CSSDAOImpl dao = (CSSDAOImpl) beanFactory.getBean("CSSDAO");

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView showIndex(HttpServletRequest request) throws Exception {
        List<StyleChooser> styleChooser = dao.selectAllCSS();
        return new ModelAndView("stylechoosertable", "styleChooser", styleChooser);
    }
}

A: Few observation:

*

*In your retrieve methods, transaction shouldn't be used i.e. they should be non-transactional.

*Add <tx:annotation-driven transaction-manager="transactionManager"/> in your configuration to recognize the transactional annotations.

*If you use @Transactional annotation then don't need to use programmatic transactions. Add the propagation attribute in the @Transactional annotation as @Transactional(propagation=Propagation.REQUIRED) and leave the transaction management to Hibernate.

*For first time you need to open the session and if not closed you may use the same session next time. For getting the session,  better to use an utility method as below:
private Session getSession(SessionFactory sessionFactory){
 Session session = null;
 try{
     session = sessionFactory.getCurrentSession();
 }catch(HibernateException hex){
     hex.printStackTrace();
 }
 if(session == null && !session.isClosed()){
     session = sessionFactory.openSession();
 }
}

This way, you will get the session if available and open otherwise open a new session.


text:
Q: Popup with scrollable area In my game, I planned to use show the IAP items in a pop up. The pop up area should be scrollable so that I can show the next items.
I am new to the scroll feature available in LibGdx. Could you please point me the right tutorial / Sample ?
Just a note - I have developed the game without using Scen2D.


text:
Q: How do I integrate logging into .NET code contract I am trying to wrap my head around .NET's code contract. When using code contract, how do I log the assert causing the method in question to fail. For example, look at this code:
  Public IsMatch(string x, string, y)
{

    Contract.Assert(!string.IsNullOrWhiteSpace(x));
     Contract.Assert(!String.IsNullOrWhitespace(y));

       return x == y;
 }

Let say x = string.Empty. This will cause the method to fail. How do I log that the assert cause the method above to fail. I can have many asserts such as this in a large app and it would be nice to know which one is the trouble-maker.

A: Look at: http://msdn.microsoft.com/en-us/library/system.diagnostics.contracts.contract.aspx
Basically as a second parameter you can specify a message.
That said, Contract.Assert is farely primitive. Post conditions can better be checked using Contract.Requires since its a requirement for your method.
Edit: Post conditions should ofcourse be pre conditions

A:
When using code contract, how do I log the assert causing the method in question to fail?

If you're talking about logging, I assume you mean at runtime rather than static verification.
The asserts raise exceptions when they fail.  You can write a try/catch block to log exceptions:
try
{
    bool result = SomeClass.IsMatch(x, y);
}
catch(Exception e)
{
    logger.Error(e.ToString()); // Use whatever logging mechanism here
    throw; // Note: Make sure you rethrow if you catch "Exception e"
}

This will get you the stack trace of the exception, which will point to the line where the assertion failed.
As Polity mentioned, you can also include a userMessage parameter on each assertion.  That way your logs will contain custom error messages in addition to the stack trace.
If you need a good logger class, look at the NLog library.


text:
Q: Producer/consumer problem with 2 mutexes? The setup
Let us consider a variant of the classical multithreaded programming problem: the producer/consumer problem. We have some finite number of resources (for simplicity, let there be just a single resource). The producer thread continuously creates new resource units, until the resource buffer is full (in our case, it can only produce one resource unit before blocking). The consumer thread fetches resources from the buffer and performs some work with them.
The problem
The trick is to use some sort of a synchronisation primitive (or several primitives) to prevent the buffer from entering an inconsistent state as a result of race conditions, etc.
The question
As far as I know, the problem could be solved using any of the following:

*

*monitors

*a mutex and a condition variable

*two semaphores

*three mutexes

I could use the algorithm from the semaphore solution to solve the problem using just two mutexes, but since the thread is only allowed to unlock its own mutexes, this algorithm cannot be applied here. I have not been able to come up with another one so far.
Thus, my question is:
Is it possible to solve the described variant of producer/consumer problem using just a pair of mutexes, without any other synchronisation primitive?
If it is not, why? Could you provide a formal proof?

A: Basically the producer/consumer architectures use a queue that is fed by the producer(s) and read by the consumer(s):

The concurrency and racing conditions are all related to the management of the queue.
The simplest way to proceed would be to protect every queue access with a single mutex, held and released either by producer or the consumer.  The problem in your scenario, is that the producer writes continuously new items until buffer is full, so there is a risk of letting the consumers starve until buffer is full, thus arriving de facto at a sequentialization of the processing.
The variants that you propose avoid starvation by ensuring a more balanced access to the shared queue (as for example the condition variable with the mutex).
But it is also possible to share a queue using two mutexes !  One such example consist of using a mutex for the head and a mutex for the tail (a so-called fine grained lock as implemented here)


text:
Q: How to select 'product' rows instead of 'sale' rows In my LINQ query below I want to select the 'product' rows and add the 'sale' rows data into it but the opposite is happening, it's selecting the 'sale' rows and adding the 'product' rows
var query = (from product in SampleProductTable
from sale in SampleSalesTable
where (sale.ProductId == product.Id)
select new
{
    Id = product.Id,
    TotalSales = product.TotalSales + ((product.Id == sale.ProductId) ? sale.Amount : 0)
})

Sample Product Table
+-------+------------+---------+-----------------+-------+------------+
|  Id   | CategoryId | BrandId |      Name       | Price | TotalSales |
+-------+------------+---------+-----------------+-------+------------+
| mlk3  | MLK        | BRND1   | Creamy Milk     |     5 |         10 |
| snck2 | SNCK       | BRND2   | Chocolate Snack |     2 |         24 |
+-------+------------+---------+-----------------+-------+------------+

Sample Sales Table
+-----+-----------+--------+
| Id  | ProductId | Amount |
+-----+-----------+--------+
| 120 | mlk3      |     55 |
| 121 | mlk3      |     15 |
| 122 | snck2     |     12 |
| 123 | mlk3      |      5 |
| 124 | mlk3      |     10 |
| 125 | snck2     |      2 |
| 126 | mlk3      |    115 |
| 127 | snck2     |      6 |
| 128 | snck2     |     34 |
+-----+-----------+--------+

Desired Output
+-------+------------+
|  Id   | TotalSales |
+-------+------------+
| mlk3  |        210 |
| snck2 |         78 |
+-------+------------+

A: var answer = (from product in SampleProductTable
              join sale in SampleSalesTable on product.Id == sale.ProductId into subSales
              from subSale in subSales.DefaultIfEmpty()
              group subSale by new { product.Id, product.TotalSales } into gr
              select new
              {
                  gr.Key.Id,
                  TotalSales = gr.Sum(x => x == null ? 0 : x.Amount) + gr.Key.TotalSales
              }).ToList();

Approximate T-SQL:
select p.Id, p.TotalSales + sum(coalesce(s.Amount, 0)) TotalSales
from SampleProductTable p
left outer join SampleSalesTable s on p.Id = s.ProductId
group by p.Id, p.TotalSales

A: In your example you join two collections the way that the result will have as many rows as there are distinct child records (sales in this case) and create a new object for each record (similar to INNER JOIN). That's why the result is "sales-based".
If I understand your intent correctly, I would approach it like:
SampleProductTable.Select(p => new
{
    Id = p.Id,
    TotalSales = p.Sales.Sum(s => s.Amount)
}

please note that for this approach you will need to map "Sales" collection on a product.

A: First of all it would be better to use the join statement instead, and then, it seems you need to group your Sales tables based on the ProductId:
 var query = (from product in SampleProductTable
              join sale in SampleSalesTable.GroupBy(c => c.ProductId)
              on product.Id equals sale.Key
              select new
              {
                  Id = product.Id,
                  TotalSales = product.TotalSales + sale.Sum(c=>c.Amount)
              }).ToList();

Also please note: since you used a where statement in your code, you don't need to use this condition (product.Id == sale.ProductId) ? in your select anymore. Same as mine, because I used the join statement with on keyword, there is no need to use the condition in the select area.
You can see your desired result in the following link:
https://dotnetfiddle.net/RFTtrv

A: In general LINQ terms the query shape you are looking for is called grouped join:

The group join is useful for producing hierarchical data structures. It pairs each element from the first collection with a set of correlated elements from the second collection.

In your case, it will produce a collection of correlated Sales for each Product. Then all you need is to apply aggregate (Sum) inside the final projection (select):
var query =
    from product in SampleProductTable
    join sale in SampleSalesTable on product.Id equals sale.ProductId into productSales
    select new
    {
        Id = product.Id,
        TotalSales = product.TotalSales + productSales.Sum(sale => sale.Amount)
    };

But since in some of the comments you mentioned converting to SQL, most likely you are using some ORM like LinqToSQL, EF or EF Core. In such case the things are even simpler. These ORMs support a so called navigation properties which represent the relationships, and when used inside queries are translated to SQL with all the                                                                                necessary joins, so you don't need to be bothered with such details and can concentrate on the logic needed to produce the desired result.
If that's the case, the Product class would normally have something like
public ICollection<Sale> Sales { get; set; }

and the query in question would be simple Select like this:
var query = db.Products
    .Select(product => new
    {
        Id = product.Id,
        TotalSales = product.TotalSales + product.Sales.Sum(sale => sale.Amount)
    });

A: LEFT JOIN with grouping looks like
        var query =
            from product in SampleProductTable
            join sale in SampleSalesTable.GroupBy(c => c.ProductId)
                 on product.Id equals sale.Key into join1
            from lj in join1.DefaultIfEmpty() // left join
            select new
            {
                Id = product.Id,
                TotalSales = product.TotalSales + (lj == null ? 0 : lj.Sum(c => c.Amount))
            };

Left join may return null, so check the potential group, lj before trying to sum it. For later c# versions null check could be abbreviated to
            TotalSales = product.TotalSales + (lj?.Sum(c => c.Amount) ?? 0)

Fiddle

A: In query syntax, Slava's solution should return with the result you're looking for i.e.
var querySyntax = (from product in SampleProductTable
    join sale in SampleSalesTable on product.Id equals sale.ProductId into sales
    from subSales in sales.DefaultIfEmpty()
    group subSales by new { product.Id, product.TotalSales }
    into grp
    select new
    {
        grp.Key.Id,
        TotalSales = grp.Sum(s => s.Amount) + grp.Key.TotalSales
    }).ToList();

If you have a burning desire to use method syntax for whatever reason, this equivalent LINQ query will also work:
var methodSyntax = (SampleProductTable
    .GroupJoin(SampleSalesTable, product => product.Id, sale => sale.ProductId,
        (product, sales) => new {product, sales})
    .SelectMany(s => s.sales.DefaultIfEmpty(), (s, subSales) => new {s, subSales})
    .GroupBy(ss => new {ss.s.product.Id, ss.s.product.TotalSales}, ss => ss.subSales)
    .Select(grp => new {grp.Key.Id, TotalSales = grp.Sum(s => s.Amount) + grp.Key.TotalSales})).ToList();


text:
Q: Showing that the base space is homeomorphic to the total space through an equivalence relation Question:

Let $(E,M ,\mathcal P, F)$ a locally trivial bundle. Define an equivalence relation $\sim$ on $E$ that identifies points in the same fiber of $\mathcal P$, i.e., $p_1 \sim p_2$ iff $\mathcal P(p_1) = \mathcal P(p_2)$. Show that $M$ is homeomorphic to $E/\sim$.

Attempt: Results I have used so far
Lemma 1: Let $(E,M ,\mathcal P, F)$ be a locally trivial bundle. Then $\mathcal P : E \to M$ is a continuous, open surjection.
Lemma 2: Let $\mathcal Q : X \to Y$ be a quotient map, $Z$ e topological space and $f : X \to Z$ a continuous map constant on each fiber of $\mathcal Q$. Then there exists a unique continuous map $\bar f : Y \to Z$ such that $\bar f \circ \mathcal Q = f$.
Consider $\mathcal Q : E \to E/\sim $ the quotient map with respect to $\sim$ given.Since $$[p_1] = [p_2] \iff p_1 \sim p_2 \iff \mathcal P (p_1) = \mathcal P(p_2)$$ then $\mathcal P$ is constant on each fiber of $\mathcal Q$. By Lemma 1 $\mathcal P$ is continuous then it follows from Lemma 2 that there exists a unique continuous map $\bar {\mathcal P}$ such that $\bar {\mathcal P} \circ \mathcal Q = \mathcal P$. As $\mathcal P$ (again Lemma 1) is surjective then $\bar {\mathcal P}$ is a bijection.
It is left to prove that $\bar {\mathcal P}^{-1}$ is continuous.
1) It seems I need to show that $\bar {\mathcal P}$ is an open mapping.
Any ideas?

A: I believe this proves the result. I will write it here for future reference.
Let $U \subseteq E/\sim$ be any open set in $E/\sim$. Since  $\mathcal Q$ is continuous, $\mathcal Q^{-1} (U)$ is open. Now by Lemma 1 we have that $\mathcal P$ is an open maping then $\bar{\mathcal P}(U) =\mathcal P(\mathcal Q^{-1}(U))$ is open, showing that $\bar {\mathcal P}$ is an open maping. As $\bar{\mathcal P}$ is continuous and surjective we may conclude that $\bar {\mathcal P}^{-1}$ is continuous.  Thus showing that $M$ is homeomorphic to $E/\sim$.


text:
Q: C# Winforms Application Failure in sending Email: The remote name could not be resolved: 'smtp.gmail.com ; Operation Timed out My WinForms C# program sends email. I've used MailMessage and SmtpClient.
In the constructor of SmtpClient I passed smtp.gmail.com and port 587.
This is working on my friend's computer, however when I try it I get this error:
System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: The remote name could not be resolved: 'smtp.gmail.com'

System.Net.Mail.SmtpException: Operation Timed out

How do I fix this error? Why is it specific to my computer?
If i use port 25 i get exception : Operation Timed out

If i use port 587 i get exception : The remote name could not be resolved: 'smtp.gmail.com'

if i use port 465 i get exception : Operation Timed out

A: Try some basic network troubleshooting. First, ensure you can ping something by IP address, this does not need DNS to work, so try ping 173.194.41.86 and see if you get some replies.
Then ping www.gmail.com from your machine with ping www.gmail.com. This should tell you if your network can resolve any names to IP addresses. You should get four IP address pings in the response the same as above.
If it does not, then your DNS configuration is bad. If you have a static IP address then you will need to check with a network admin or set the DNS servers the same as the working machine. If its dynamic then you might try ipconfig /renew to get the latest settings from the DHCP server.
If pinging www.gmail.com worked then try ping smtp.gmail.com to see if the smtp host is resolving. If it does not, then there's still a DNS issue but one that is effecting only the smtp hostname.
Try ipconfig /flushdns to clear the local DNS cache and try again. Try rebooting, if not on a prod server.
You can also use nslookup to check DNS name resolution and also Resolve-DnsName in PowerShell, possibly only in 3.0 though.
Also, check any firewall settings.

A: Mark EnableSsl in your SmtpClient to true.
smtpClient.EnableSsl = true;


text:
Q: Multi-threaded downloading files with Guzzle HTTP client: EachPromises vs Pool objects for testing purposes, I have an array of 2000 image URIs (strings) with I download asynchronously with this functions. After some googling & testing & trying I've come up with 2 functions that both of them work (well to be honest downloadFilesAsync2 throws a InvalidArgumentException at the last line).
The function downloadFilesAsync2 is based on the class GuzzleHttp\Promise\EachPromise and downloadFilesAsync1 is based on the GuzzleHttp\Pool class.
Both functions download pretty well the 2000 files asynchronously, with the limit of 10 threads at the same time.
I know that they work, but nothing else. I wonder if someone could explain both aproaches, if one is better than the other, implications, etc.
// for the purpose of this question i've reduced the array to 5 files!
$uris = array /
  "https://cdn.enchufix.com/media/catalog/product/u/n/unix-48120.jpg",
  "https://cdn.enchufix.com/media/catalog/product/u/n/unix-48120-01.jpg",
  "https://cdn.enchufix.com/media/catalog/product/u/n/unix-48120-02.jpg",
  "https://cdn.enchufix.com/media/catalog/product/u/n/unix-48120-03.jpg",
  "https://cdn.enchufix.com/media/catalog/product/u/n/unix-48120-04.jpg",
);

function downloadFilesAsync2(array $uris, string $dir, $overwrite=true) {
    $client   = new \GuzzleHttp\Client();
    $requests = array();
    foreach ($uris as $i => $uri) {
        $loc = $dir . DIRECTORY_SEPARATOR . basename($uri);
        if ($overwrite && file_exists($loc)) unlink($loc);
        $requests[] = new GuzzleHttp\Psr7\Request('GET', $uri, ['sink' => $loc]);
        echo "Downloading $uri to $loc" . PHP_EOL;
    }
    $pool = new \GuzzleHttp\Pool($client, $requests, [
        'concurrency' => 10,
        'fulfilled' => function (\Psr\Http\Message\ResponseInterface $response, $index) {
            // this is delivered each successful response
            echo 'success: '.$response->getStatusCode().PHP_EOL;
        },
        'rejected' => function ($reason, $index) {
            // this is delivered each failed request
            echo 'failed: '.$reason.PHP_EOL;
        },
    ]);
    $promise = $pool->promise();  // Start transfers and create a promise
    $promise->wait();   // Force the pool of requests to complete.
}

function downloadFilesAsync1(array $uris, string $dir, $overwrite=true) {
    $client = new \GuzzleHttp\Client();
    $promises = (function () use ($client, $uris, $dir, $overwrite) {
        foreach ($uris as $uri) {
            $loc = $dir . DIRECTORY_SEPARATOR . basename($uri);
            if ($overwrite && file_exists($loc)) unlink($loc);
            yield $client->requestAsync('GET', $uri, ['sink' => $loc]);
            echo "Downloading $uri to $loc" . PHP_EOL;
        }
    })();
    (new \GuzzleHttp\Promise\EachPromise(
        $promises, [
        'concurrency' => 10,
        'fulfilled'   => function (\Psr\Http\Message\ResponseInterface $response) {
            //            echo "\t=>\tDONE! status:" . $response->getStatusCode() . PHP_EOL;
        },
        'rejected'    => function ($reason, $index) {
            echo 'ERROR => ' . strtok($reason->getMessage(), "\n") . PHP_EOL;
        },
    ])
    )->promise()->wait();
}

A: First, I will address the InvalidArgumentException within the downloadFilesAsync2 method.  There are actually a pair of issues with this method.  Both relate to this:

$requests[] = $client->request('GET', $uri, ['sink' => $loc]);

The first issue is the fact that Client::request() is a synchronous utility method which wraps $client->requestAsync()->wait().  $client->request() will return an instance of Psr\Http\Message\ResponseInterface, as a result $requests[] will actually be populated with ResponseInterface implementations.  This is what, ultimately causes the InvalidArgumentException as the $requests does not contain any Psr\Http\Message\RequestInterface's, and the exception is thrown from within Pool::__construct().
A corrected version of this method should contain code which looks more like:
$requests = [
    new Request('GET', 'www.google.com', [], null, 1.1),
    new Request('GET', 'www.ebay.com', [], null, 1.1),
    new Request('GET', 'www.cnn.com', [], null, 1.1),
    new Request('GET', 'www.red.com', [], null, 1.1),
];

$pool = new Pool($client, $requests, [
    'concurrency' => 10,
    'fulfilled' => function(ResponseInterface $response) {
        // do something
    },
    'rejected' => function($reason, $index) {
        // do something error handling
    },
    'options' => ['sink' => $some_location,],
]);

$promise = $pool->promise();
$promise->wait();

To answer your second question, "What is the difference between these two methods", the answer is simply, there is none.  To explain this, let me copy and paste Pool::__construct():
/**
 * @param ClientInterface $client   Client used to send the requests.
 * @param array|\Iterator $requests Requests or functions that return
 *                                  requests to send concurrently.
 * @param array           $config   Associative array of options
 *     - concurrency: (int) Maximum number of requests to send concurrently
 *     - options: Array of request options to apply to each request.
 *     - fulfilled: (callable) Function to invoke when a request completes.
 *     - rejected: (callable) Function to invoke when a request is rejected.
 */
public function __construct(
    ClientInterface $client,
    $requests,
    array $config = []
) {
    // Backwards compatibility.
    if (isset($config['pool_size'])) {
        $config['concurrency'] = $config['pool_size'];
    } elseif (!isset($config['concurrency'])) {
        $config['concurrency'] = 25;
    }

    if (isset($config['options'])) {
        $opts = $config['options'];
        unset($config['options']);
    } else {
        $opts = [];
    }

    $iterable = \GuzzleHttp\Promise\iter_for($requests);
    $requests = function () use ($iterable, $client, $opts) {
        foreach ($iterable as $key => $rfn) {
            if ($rfn instanceof RequestInterface) {
                yield $key => $client->sendAsync($rfn, $opts);
            } elseif (is_callable($rfn)) {
                yield $key => $rfn($opts);
            } else {
                throw new \InvalidArgumentException('Each value yielded by '
                    . 'the iterator must be a Psr7\Http\Message\RequestInterface '
                    . 'or a callable that returns a promise that fulfills '
                    . 'with a Psr7\Message\Http\ResponseInterface object.');
            }
        }
    };

    $this->each = new EachPromise($requests(), $config);
}

now if we compare that to an a simplified version of the code within the downloadFilesAsync1 method:
$promises = (function () use ($client, $uris) {
    foreach ($uris as $uri) {
        yield $client->requestAsync('GET', $uri, ['sink' => $some_location]);
    }
})();
(new \GuzzleHttp\Promise\EachPromise(
    $promises, [
    'concurrency' => 10,
    'fulfilled'   => function (\Psr\Http\Message\ResponseInterface $response) {
        // do something
    },
    'rejected'    => function ($reason, $index) {
        // do something
    },
])
)->promise()->wait();

In both examples, there is a generator which yields promises that resolve to instances of ResponseInterface and that generator along with the configuration array (fulfilled callable, rejected callable, concurrency) is also fed into a new instance of EachPromise.
In summary:

*

*downloadFilesAsync1 is functionally the same thing as using Pool only without the error checking that has been built into Pool::__construct().

*There are a few errors within downloadFilesAsync2 which will cause the files to be downloaded in a synchronous fashion prior to receiving an InvalidArgumentException when the Pool is instantiated.
My only recommendation is: use whichever feels more intuitive for you to use.


text:
Q: Why won't the buttons show in Tkinter I am trying to place buttons on a chessboard, with the board being an image, but the queen, king and bishop buttons don't show. How would I fix this?
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
root.geometry("1200x1200")
img = Image.open("s8XND.png")

resized = img.resize((1200, 900), Image.ANTIALIAS)
chessboard = ImageTk.PhotoImage(resized)
canvas = Canvas(root, width = 1200, height = 900)
canvas.place( relheight = 1, relwidth = 1)
canvas.create_image(0, 0, image = chessboard, anchor = "new")

label = Label(root, bg = chessboard)
label.place(pady = 10, padx = 20)
#Black Rook
blackRook = Button(root, text = "Castle", fg = "white", bg = "black")
blackRook.grid(row = 1, column = 0)

#Black Knight
blackHorse = Button(root, text = "Horse", fg = "white", bg = "black")
blackHorse.grid(row = 1, column = 1)

#Black Bishop
blackBishop = Button(root, text = "Bishop", fg = "white", bg = "black")
blackHorse.grid(row = 1, column = 2)

#Black Queen
blackQueen= Button(root, text = "Queen", fg = "white", bg = "black")
blackQueen.grid(row = 1, column = 3)

#Black King
blackKing= Button(root, text = "King", fg = "white", bg = "black")
blackQueen.grid(row = 1, column = 4)

root.mainloop()

A: This code works for me. Note that I removed the Label and fixed several errors in your code:
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
root.geometry("1200x1200")
img = Image.open("s8XND.png")

resized = img.resize((1200, 900), Image.ANTIALIAS)
chessboard = ImageTk.PhotoImage(resized)
canvas = Canvas(root, width=1200, height=900)
canvas.place(relheight=1, relwidth=1)
canvas.create_image(0, 0, image=chessboard, anchor="nw")

# Black Rook
blackRook = Button(root, text="Castle", fg="white", bg="black")
blackRook.grid(row=1, column=0)

# Black Knight
blackHorse = Button(root, text="Horse", fg="white", bg="black")
blackHorse.grid(row=1, column=1)

# Black Bishop
blackBishop = Button(root, text="Bishop", fg="white", bg="black")
blackBishop.grid(row=1, column=2)

# Black Queen
blackQueen = Button(root, text="Queen", fg="white", bg="black")
blackQueen.grid(row=1, column=3)

# Black King
blackKing = Button(root, text="King", fg="white", bg="black")
blackKing.grid(row=1, column=4)

root.mainloop()

Also note that you made some copy-paste errors with blackHorse and blackKing.