text:
Q: scrape data from interactive chart using selenium, bs4 or requests I want to scrape data from charts on this page: http://188.166.44.172/match/live-stats/100941310
I tried requests and bs4, but failed to get any data, I also tried with selenium and no data as well.
Here's the code using requests:
import requests
from bs4 import BeautifulSoup

headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0'}

session = requests.Session()
r = session.get(u, timeout=30, headers=headers)

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

for i in soup.find_all('rect'):
    if i.has_attr("onmouseover"):
        text = i.get('onmouseover')
        print(text)

And the code using selenium:
from selenium import webdriver
from bs4 import BeautifulSoup
u = "http://188.166.44.172/match/live-stats/100941310"

driver = webdriver.Chrome(executable_path=r"C:/chromedriver.exe", options=options)

driver.get(url)

soup = BeautifulSoup(driver.page_source, 'html.parser')

for i in soup.find_all('rect'):   #I also tried soup.select('*')
    if i.has_attr("onmouseover"):
        text = i.get('onmouseover')
        print(text)

Is there's any way to scrape data from those charts using python ?

A: The reason you're not getting anything back is because all the charts are generated dynamically by JavaScript and with, for example, bs4 you won't read any of this.
However, the data for the charts is embedded in the HTML. You could parse that and plot.
Here's how:
import ast
import re

import requests
import matplotlib.pyplot as plt

target_url = "http://188.166.44.172/match/live-stats/100941310"
page_source = requests.get(target_url).text

raw_attack_data = ast.literal_eval(
    re.search(r"var all_attack = (\[.*\])", page_source).group(1),
)
all_attack = [i[1] for i in raw_attack_data if isinstance(i, list)]

plt.plot(all_attack, label="attack")
plt.legend(loc="lower right")
plt.show()

This should give you a plot like this:

As I've said, eveyrthing you need is in the source code, so you'd have to play around with the values.
The source looks like this:

Where the first value of the inner list is the game time and the second value is the stat that's plotted on the charts.
Note that some arrays have values in {}. These' are those icon markers on the charts. You can filter them out with isistance(i, list) since these can be easily parsed as dicts, as I've shown above.
EDIT:
Yes, it's possible to get division and team info, as everything is in the HTML. I've reworked the initial answer a bit and came up with this:
import ast
import re

import requests
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt

target_url = "http://188.166.44.172/match/live-stats/100941310"
page_source = requests.get(target_url).text

def get_match_info(html_source: str) -> list:
    return [
        i.getText(strip=True) for i
        in BeautifulSoup(html_source, "lxml").select("h1 a")
    ]

def get_stats(html_source: str, search_str: str) -> tuple:
    raw_data = ast.literal_eval(
        re.search(fr"var {search_str} = (\[.*\])", html_source).group(1),
    )
    filtered = [i[1] for i in raw_data if isinstance(i, list)]
    game_time = [i[0] for i in raw_data if isinstance(i, list)]
    return game_time, filtered

division, home, away = get_match_info(page_source)

time_, attack_home = get_stats(page_source, "dangerous_home")
_, attack_away = get_stats(page_source, "dangerous_away")

plt.suptitle(f"{division} - {home} v {away}")
plt.ylabel("Attack")
plt.xlabel("Game time")
plt.plot(time_, attack_home, color="blue", label=home)
plt.plot(time_, attack_away, color="black", label=away)
plt.legend(loc="lower right")
plt.show()

This produces a plot:


text:
Q: getRequestDispatcher(.).forward(req,res) throws java.io.FileNotFoundException I have upgraded my Servlet from 2.4 to 3.0 and deployed my application on Websphere 8.5.5.8. Application Server starts properly.
When I try to access my home.jsp page in browser it throws:

Controller Main Error OG1000SRVE0190E: File not found: /servlet/com.platform7.affina.operations.servlet.ValidateLoginUser

When I try to debug, code hits my Main Controller Servlet (which is in same package) but inside Controller servlet class I am calling:
this.getServletContext().getRequestDispatcher("Servlet/com.platform7.affina.operations.servlet.ValidateLoginUser").forward(request, response);

Which throws:

FileNotFoundException for  Servlet/com.platform7.affina.operations.servlet.ValidateLoginUser.

But ValidateLoginUser is in the same package and classes folder location!
Folder structure:
\NEED4SPEEDCell02\operations_1.ear\OperationsWeb.war\WEB-INF\classes\com\platform7\affina\operations\servlet

ControllerMain.class and ValidateLoginUser.class are in same servlet package.
my Web.xml file:
<servlet>
    <servlet-name>servletMain</servlet-name>
    <servlet-class>com.platform7.affina.operations.servlet.ControllerMain</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>servletMain</servlet-name>
    <url-pattern>/controllerMain</url-pattern>
</servlet-mapping>

So when I access my URL: it hits ControllerMain.class but inside this class I am calling another servlet which is not part of web.xml but is located in same package of ControllerMain.class.
When I print realpath: this.getServletContext().getRealPath("/"));
I get:

C:\WebSphere858\AppServer\profiles\AppSrv01\installedApps\NEED4SPEEDCell02\operations_1.ear\OperationsWeb.war

I tried using getNamedDispatcher(..) too but throws: null.
Same code works fine on Websphere 7 and even works on Websphere 8.5.5.5

A: Due to security reasons the default setting for com.ibm.ws.webcontainer.disallowServeServletsByClassname property has been changed.

Please Note:This APAR has changed the default value of the
  WebContainer custom property
  com.ibm.ws.webcontainer.disallowServeServletsByClassname from false to
  true so that no security threat could occur. Prior to this change, it
  was up to the developer to remember to change the custom property to
  true before deploying into production.
Property Name:
  com.ibm.ws.webcontainer.disallowServeServletsByClassname Description:
  If set to true, disallows the use of serveServletsByClassnameEnabled
  at the application server level, overriding any setting of
  serveServletsByClassnameEnabled at the application level. This
  property affects all applications. Values: true(default)/false

You will need to add that custom property to the Web Container and set it to false for serving servlets by class name.
But as BalusC suggested, you should add your servlet to web.xml in the form:
<servlet>
    <servlet-name>servletMain</servlet-name>
    <servlet-class>com.platform7.affina.operations.servlet.ValidateLoginUser</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>servletMain</servlet-name>
    <url-pattern>/validateLoginUser</url-pattern>
</servlet-mapping>

and change that forward to:
this.getServletContext().getRequestDispatcher("/validateLoginUser").forward(request, response);

And do the same with your other class from the same package.

A: You seem to be relying on the legacy InvokerServlet which is known to have major security holes. This was deprecated in Tomcat 5 and clones (WebSphere 4) and removed in Tomcat 7 and clones (WebSphere 6).
You're not supposed to use it anymore. Just map the servlet on a normal URL pattern and invoke it. Assuming that the servlet is mapped on an URL pattern of /validateLoginUser via @WebServlet("/validateLoginUser") annotation on the servlet class, or via <url-pattern>/validateLoginUser</url-pattern> in web.xml mapping on the servlet, then you can get a request dispatcher on it as below:
request.getRequestDispatcher("/validateLoginUser");

Or, just refactor shared code to a plain Java class with a method and invoke it the usual Java way. It's these days kind of weird to have shared validation logic tight coupled in a servlet.
See also:

*

*How to invoke a servlet without mapping in web.xml?

A: To make above upgrade working, I did few other changes as below for future references.
Mainly, I have to change binding files for websphere.
Previously, I had two bindings ibm-web-bnd.xmi and ibm-web-ext.xmi
ibm-web-bnd.xmi
<?xml version="1.0" encoding="UTF-8"?>
<com.ibm.ejs.models.base.bindings.webappbnd:WebAppBinding xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:com.ibm.ejs.models.base.bindings.webappbnd="webappbnd.xmi" xmi:id="WebAppBinding_1226331113121" virtualHostName="default_host">
  <webapp href="WEB-INF/web.xml#WebApp"/>
    <resRefBindings xmi:id="ResourceRefBinding_1226331113121" jndiName="AffinaDataSource_pma">
      <bindingResourceRef href="WEB-INF/web.xml#ResourceRef_AffinaDataSource_pma"/>
    </resRefBindings>
</com.ibm.ejs.models.base.bindings.webappbnd:WebAppBinding>

ibm-web-ext.xmi
<?xml version="1.0" encoding="UTF-8"?>
<com.ibm.ejs.models.base.extensions.webappext:WebAppExtension
    xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI"
    xmlns:com.ibm.ejs.models.base.extensions.webappext="webappext.xmi"
    xmi:id="WebAppExtension_1226331113121"
    serveServletsByClassnameEnabled="true">
  <webApp href="WEB-INF/web.xml#WebApp"/>
  <jspAttributes xmi:id="JSPAttribute_1226331113121" name="reloadEnabled" value="true"/>
  <jspAttributes xmi:id="JSPAttribute_1226331113122" name="reloadInterval" value="10"/>
</com.ibm.ejs.models.base.extensions.webappext:WebAppExtension>

So as per servlet3 and Websphere 8.5.5.8, I change to replace above two .xmi files with ibm-web-bnd.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-bnd xmlns="http://websphere.ibm.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee http://websphere.ibm.com/xml/ns/javaee/ibm-web-bnd_1_0.xsd" version="1.0">

  <virtual-host name="default_host"/>
  <resource-ref name="AffinaDataSourceAlias_pma" binding-name="AffinaDataSource_pma"/>

</web-bnd>

and then while installing application on Websphere 8.5.5.8, it use to throw outofmemmory error, so to fix that I change below max memory parameter from 256m to 512m in wsadmin.bat
C:\WebSphere858\AppServer\bin\wsadmin.bat
set PERFJAVAOPTION=-Xms256m -Xmx512m -Xquickstart

Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: In R, Sift Through a Dataframe for N Consecutive Rows of Data (a "Window"), Then do a Function I am looking to read a raw data output .csv file containing 10's of thousands of rows. The rows are mostly not filled with meaningful data, but every once in a while, a cluster of N (usually 5 or so) rows shows up that contains the meaningful data. I want to sift through the rows, and when I encounter these clusters, write the maximum of the cluster to a file that is continuously updated with these maximums.
Here's an example of the data:
screen cap
The second column is what I'm interested in.

A: The rle function lets you scan a vector and get lengths of sequences. The hand-waving answer is to scan for sequences of rle(vector>0)$values associated with  rle(vector>0)$lengths is > 5.
We cannot do very much with pictures of object viewers. So to give a tested, code-containing answer we need code-produced data that can be pasted into a console session. In this case you probably what sequences of values that age non-zeroFind a section of your dataframe that I'm assuming is named dfrm that appears interesting to you and post the output of dput(dfrm[ rownames(dfrm) %in% i:j , ]) where i and j are rownames several rows above and belwo the area of interest. We can then show you how to use rle and cumsum and seq to build a selection vector for the rows of interest.


text:
Q: How to do a pie chart with two factor variables and % inside the plot How can I transform this bar plot into a pie chart?
This is the bar plot I have:

This is the code I use to make the bar plot:
dados_gráfico_distrito <- dados_desde_2015 %>%
  filter(!is.na(qsd_distrito_nascimento_rec)) %>%
  group_by(anoletivo_cat) %>%
  count(anoletivo_cat, qsd_distrito_nascimento_rec) %>%
  mutate(pct = n / sum(n), pct_label = scales::percent(pct, accuracy=1))

dados_gráfico_distrito$qsd_distrito_nascimento_rec <- factor(dados_gráfico_distrito$qsd_distrito_nascimento_rec, levels = c("Other", "Porto", "Braga"))

ggplot(dados_gráfico_distrito, aes(x= anoletivo_cat, fill = qsd_distrito_nascimento_rec, y = pct)) +
  geom_bar(position = "fill", stat="identity", width = 0.5) +
  geom_text(aes(label = paste(pct_label), y = pct), position = position_fill(vjust = 0.5), colour = "black", size = 3.2) +
  scale_y_continuous(labels = scales::percent) +
  labs(y = " ", x = " ", fill=" ") +
  theme_void() + scale_fill_brewer(palette="Paired") +
  theme(legend.text = element_text(size = 8, colour = "black")) +
  theme(axis.text = element_text(size = 8, colour = "black")) +
  theme(legend.position = "bottom", legend.direction = "horizontal") +
  guides(fill = guide_legend(reverse=TRUE)) +
  theme(plot.margin = unit(c(1, 1, 1, 1), "cm")) +
  theme(panel.grid = element_line(colour="grey90")) +
  theme(panel.grid.minor.y = element_line(color = "white"), panel.grid.major.x = element_line(color = "white"))

When I try to transform it in a pie chart, adding the code line coord_polar () I get this chart:

This is what I pretend:

Thank you!

A: As you did not provide sample data, I have used some other sample data.  Perhaps this will meet your needs.  Please modify as necessary.
library(ggrepel)
library (ggplot2)

df = read.csv("https://www.dropbox.com/s/lc3xyuvjjkyeacv/inputpie.csv?dl=1")

df <- df %>% group_by(fac)  %>%
  mutate(
    facc = ifelse(fac=="f1", "15/16 to 19/20", "20/21"),
    cs = rev(cumsum(rev(per))),
    text_yp = per/2 + lead(cs, 1),
    text_yp = if_else(is.na(text_yp), per/2, text_yp)
  )  %>%  data.frame()

df$type <- factor(df$type, levels=unique(df$type))

ggplot(df, aes(x="", y=per, fill=type )) +
  geom_bar(stat="identity", width=1) +
  coord_polar("y", start=0)   +
  facet_grid(facc~.  ) +
  scale_fill_brewer(palette="Paired") +
  theme_void()   +
  geom_label_repel(
    aes(label = text_y, y = text_yp), show.legend = FALSE
  ) +
  scale_y_continuous(labels = scales::percent) +
  labs(y = " ", x = " ", fill=" ") +
  theme(legend.text = element_text(size = 8, colour = "black")) +
  #theme(axis.text = element_text(size = 8, colour = "black")) +
  #theme(legend.position = "bottom", legend.direction = "horizontal") +
  guides(fill = guide_legend(reverse=TRUE)) +
  theme(plot.margin = unit(c(1, 1, 1, 1), "cm")) +
  theme(panel.grid = element_line(colour="grey90")) +
  theme(panel.grid.minor.y = element_line(color = "white"), panel.grid.major.x = element_line(color = "white"))


text:
Q: I would like to change Rails default redirect code I'm modifying an existing project, and I want my app to have only status: 301 redirects instead of Rails default 302. As there is a lot of places in the app where redirect_to is used, I would like to skip modifying all of them and adding status: 301 as a parameter, so I would like if possible to change default rails redirect code for my app to be 301, or if that's not possible then somehow "hijack" 302 redirect and change it to 301.
Thanks in advance

A: You could monkeypatch the redirect_to method:
class ApplicationController < ActionController::Base
  def redirect_to_with_permanence(options = {}, response_status = {})
    response_status.reverse_merge! status: :moved_permanently
    redirect_to_without_permanence options, response_status
  end
  alias_method_chain :redirect_to, :permanence
end


text:
Q: Firebase Database get children of specific level android I have the following database structure in Firebase:

In my app when I launch an activity. I want to get all the level0Node's nodes only once when the activity is started. This I achieve like this:
rootNode.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Iterable<DataSnapshot> level0Nodes = dataSnapshot.getChildren();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {}
        });

But the problem I am facing is that if any updates occur on the level1Node's, onDataChanged is invoked again which I do not want. How can I achieve this?

A: You're looking for a SingleValueListener.
Replace your ValueEventListener with one, the code would look like this:
rootNode.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Iterable<DataSnapshot> level0Nodes = dataSnapshot.getChildren();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });

For more info refer to the Official Docs

A: you have two methods for getting total data in one go from a particular reference.

*

*rootNode.addValueEventListener(new ValueEventListener(){}
// this you are using and according to documentation this is triggered when ever the data is change at this node- rootNode.  if you want to use it only once your can remove  your listner by calling
rootNode.removeEventListener()  method for removing further updates.

*use rootNode.addListenerForSingleValueEvent(new ValueEventListener() {}

according to documentation this is only triggered once so when ever there is a change in your child this listner will not trigger and your problem will be solve.
plus i just want to suggest you to read full documentation on firebase as your question was very basic.


text:
Q: Match two columns, and bring along values in the corresponding columns - Microsoft Excel for Mac 2011 v. 14.4.1 I need to match two columns (B and C) and move down the values (C and D) inserting an empty line where there's no match.

into this

Is there a formula that can do this?

A: You should have the tables structured so that the leftmost column is the key, i.e. the unique identifier. In this case, that would be their names. After that, you can simply use VLOOKUP to look up a key in a second table. You can wrap that VLOOKUP in an IFERROR to hide errors by making them equal empty strings (i.e. "")
In your example, column C is redundant, so here's how I'd structure it:

For copy-and-paste purposes, the formula in C1 is =IFERROR(VLOOKUP($A1,$A$7:$B$9,2,0),"") -- then just drag down


text:
Q: Show that lim of the sequence is $\ell$ Given the sequence defined as :
$\displaystyle{u_{n + 1} = {u_{n}^{2} \over 1 - 2u_{n}^{2}}}\quad\forall\ n \in \mathbb{N}$
And $u_{0} =a $ such that $a \in \left(0,{1 \over 4}\right)$
Let's take $s_{n} = \sum_{k = 0}^{n}\,\left(-1\right)^{k}\,u_{k}$
$w_{n} = s_{2n + 1}$
$v_{n} = s_{2n}$
Let $\lim v_{n} = \lim w_{n} = \ell$
How can one prove that $\lim s_{n} = \ell$
I see that we need to majorate the expression of $s_{n}$ by $v_{n}$ or $w_{n}$ to find that $\lim s_{n} = \ell$ but it seems difficult since i don't see a direct relation between $s_{n}$ and $s_{2n}$ and $s_{2n + 1}$.

A: Notice that if $0 < x < \frac{1}{4}$, then
$$ \frac{x^2}{1-2x^2} < \frac{\frac{1}{4}x}{1-\frac{1}{8}} = \frac{2}{7}x. $$
Then by a simple induction, we find that $0 < u_n < (2/7)^n u_0$. This proves that $ \sum_{n=0}^{\infty} (-1)^n u_n$ converges absolutely, and if we denote the value of this series by $\ell$, then both $v_n$ and $w_n$ also converge to $\ell$ since they are subsequences of the convergent sequence $(s_n)$.


text:
Q: Strength of atomic update in Firestore increment I'm Firestore user recently diving into a concept of "atomic" update, especially Firestore documents' increment update. There is a classic article on Firestore increment in context of atomic update. And here comes my question.
Q, How strong is this atomic increment(number) update? Does this operation really have no limitation when it comes to operating truly atomically?
Let me explain a bit of details with an example case. We know that Firestore has a write limitation of 10,000 (up to 10 MiB per second) per db instance, and we also know that Firestore's increment method updates documents atomically. So, I hope to know if the below extreme example case would work perfectly atomically.

This Firestore instance only has a single document, and numerous users-maybe 10000 users maximum- update a single document using increment method, which increments a same field value as much as a random double number between 0 and 1 each, WITHIN a single second: 10000 updates in 1 second;

Above case makes use of Firestore write rate limit per second as much as possible, and all operations are updating a single field of same document. If increment method deals with update requests truly atomically, we might say all 10000 details will be calculated correctly into a single field.
But, this is only theoretic and conceptual idea, and it seems really hard for Firestore(or even any other db systems) to make no exception when it performs such an extreme set of increment operations when it has to deal with other upcoming operations linearly. It means that the Firestore instance would keep going on with upcoming API requests. This is a real world problem, actually. Let's say a lovely singer, Ariana Grande's Instagram post is just uploaded. If we deal with the event with Firestore document, we would have to deal with thousands of increment requests for likes per a single second.
So, i hope to know if there is truly no limitations for atomic increment method even there comes a set of high number of extremely concurrent increment requests to very few number of target documents. Hope this question reach to firebase gurus in the community! Comments are really welcomed! Thanks in advance [:

A: I'm not sure I understand your question completely, but I'll try to help anyway by explaining how Firestore and its increment operation work.
Firestore's main write limits come from the fact that data needs to be synchronized between data centers for each write operation. This is not a quota-type limit, but a physical limit of how fast data can be pushed across the wires.
Since you talk about frequent writes to a single document, you're going to sooner hit the soft limit of 1 sustained write per second per document. This is also caused by the physical nature of how the database works, and needs to synchronize the documents and indexes between servers/data centers.
While using the increment() operation means that no roundtrip is needed between the client and the server, it makes no difference to the data that needs to be read/written on the servers themselves. Therefore it makes no difference to the documented throughput limits.
If you need to perform counts beyond the documented throughput limits, have a look at the documentation on using a distributed counter.


text:
Q: tsql to know when a database was last shrunk In SQL 2000, 2005 and 2008, how can  I know when databases were last shrunk on a MS SQL server?
I want to do this using TSQL.
Regards
Manjot

A: Because for shrinking of database one uses DBCC SHRINKDATABASE or DBCC SHRINKFILE, you can try to solve your problem with server audits from the group DBCC_GROUP (see http://technet.microsoft.com/en-us/library/cc280663.aspx and http://msdn.microsoft.com/en-us/library/cc280386.aspx)


text:
Q: Shell generate random adjective clause I want generate random directory name. But name must be adjective clause. Also, created name must not be created again. I have two arrays:
names=("phone" "book" "pencil" "bag" "bed")
adjectives=("good" "bad" "thin" "short")

and i want this:
randomdir 2

good book, thin pencil directories has been created
randomdir 3

bad pencil, good bag, good phone directories has been created


text:
Q: Problem combining two tuples into dictionary I have a list of sorted integer IDs like
[1, 2, 10, 15, 16, 17, 20, 34, ...]

I have a tuple (tuple1) of tuples of codes next to an ID sorted by ID like
((1, "A"), (2, "A"), (15, "B"), (16, "A"), (17, "B"), (34, "B"), ...)

I have another tuple (tuple2) of tuples in the same format like
((1, "B"), (2, "B"), (10, "B"), (16, "A"), (17, "B"), (34, "B"), ...)

I want to combine the tuples into a dictionary whereby the key is the ID and the value is a list containing their code from tuple1 and their code from tuple2 in that order. If the ID exists in the ID list but not in the tuple then the value should be "N/A".
Therefore, using the above data the following should be produced:
{1: ["A", "B"], 2: ["A", "B"], 10: ["N/A", "B"], 15: ["B", "N/A"],
 16: ["A", "A"], 17: ["B", "B"], 20: ["N/A", "N/A"], 34: ["B", "B"]}

I have spent quite a while thinking about this problem but I cannot come up with a solution. If someone could help me figure out how to get it working in Python then that would be extremely helpful.
Thanks.
EDIT: It is not a duplicate, this problem is considerably more complex.

A: Here is one possible solution to this:
from collections import defaultdict

keys = [1, 2, 10, 15, 16, 17, 20, 34]

t1 = ((1, "A"), (2, "A"), (15, "B"), (16, "A"), (17, "B"), (34, "B"))
t2 = ((1, "B"), (2, "B"), (10, "B"), (16, "A"), (17, "B"), (34, "B"))

merge_d = defaultdict(list)
for d in map(dict, (t1, t2)):
    for k in keys:
        merge_d[k].append(d.get(k, "N/A"))

The resulting dict will contain:
>>> merge_d
defaultdict(<class 'list'>, {1: ['A', 'B'], 2: ['A', 'B'], 10: ['N/A', 'B'], 15: ['B', 'N/A'], 16: ['A', 'A'], 17: ['B', 'B'], 20: ['N/A', 'N/A'], 34: ['B', 'B']})

A: If you make your tuple of tuples into a dictionary, it will be a lot easier. Use get to set a default value for your dictionary if the key is absent:
ids = [1, 2, 10, 15, 16, 17, 20, 34]
tup1 = ((1, "A"), (2, "A"), (15, "B"), (16, "A"), (17, "B"), (34, "B"))
tup2 = ((1, "B"), (2, "B"), (10, "B"), (16, "A"), (17, "B"), (34, "B"))

tup1 = dict(tup1)
tup2 = dict(tup2)
{k: [tup1.get(k, 'N/A'), tup2.get(k, 'N/A')] for k in ids}

A: It's a little gross, but you can do it without converting to a dictionary:
myList = [1, 2, 10, 15, 16, 17, 20, 34]
tuples1 = ((1, "A"), (2, "A"), (15, "B"), (16, "A"), (17, "B"), (34, "B"))
tuples2 = ((1, "B"), (2, "B"), (10, "B"), (16, "A"), (17, "B"), (34, "B"))

myDict = {}

for i in myList:
    myDict[i] = ["N/A","N/A"]

for t in tuples1:
    if(t[0]) in myList:
        for key in myDict:
            if key == t[0]:
                myDict[key][0] = t[1]

for t in tuples2:
    if(t[0]) in myList:
        for key in myDict:
            if key == t[0]:
                myDict[key][1] = t[1]

print(myDict)

Gives:

{1: ['A', 'B'], 2: ['A', 'B'], 10: ['N/A', 'B'], 15: ['B', 'N/A'], 16: ['A', 'A'], 17: ['B', 'B'], 20: ['N/A', 'N/A'], 34: ['B', 'B']}

A: This can be done another way!
lis=[1, 2, 10, 15, 16, 17, 20, 34]
tuple1=((1, "A"), (2, "A"), (15, "B"), (16, "A"), (17, "B"), (34, "B"))
tuple2=((1, "B"), (2, "B"), (10, "B"), (16, "A"), (17, "B"), (34, "B"))

z={**dict.fromkeys(lis,'N/A'), **dict(tuple1)}
y={**dict.fromkeys(lis, 'N/A'), **dict(tuple2)}

ds = [z, y]
d = {}
for k in y.keys():
    d[k] = list(d[k] for d in ds)

A: My two cents: a one-line solution, based on @busybear's answer, able to handle an arbitrary number of tuples:
ids = [1, 2, 10, 15, 16, 17, 20, 34]
vals = (
    ((1, "A"), (2, "A"), (15, "B"), (16, "A"), (17, "B"), (34, "B"),),
    ((1, "B"), (2, "B"), (10, "B"), (16, "A"), (17, "B"), (34, "B"),),
)

d = {i: [d.get(i, 'N/A') for d in map(dict, vals)] for i in ids}


text:
Q: DBus permission denied on an embedded hardware I'm new to DBus and I'm trying to call the following method within my own C++ application using the sdbus-cpp library:
org.freedesktop.login1.Manager.Suspend
The goal of the call is that the device switches to suspend mode.
The application works so far if the application runs as root user! But for security reasons I would like to run the application as a non-root user (lets say as 'embuser').
On the net I found out that DBus can be configure. So I put the following file in folder /etc/dbus-1/system.d/suspend.conf with this content:
root@colibri:/etc/dbus-1/system.d$ cat suspend.conf
<!DOCTYPE busconfig PUBLIC
          "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
          "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>

  <!-- Only root or user embuser can own the login1 service -->
  <policy user="embuser">
    <allow own="org.freedesktop.login1"/>
  </policy>
  <policy user="root">
    <allow own="org.freedesktop.login1"/>
  </policy>

  <!-- Allow anyone to invoke methods on login1 server -->
  <policy context="default">
    <allow send_destination="org.freedesktop.login1"/>
    <allow receive_sender="org.freedesktop.login1"/>
  </policy>
</busconfig>

I restarted the dbus daemon (systemctl restart dbus). Then, when I start my application (which is running as 'embuser') following gets printed out:
terminate called after throwing an instance of 'sdbus::Error'
what():  [org.freedesktop.DBus.Error.AccessDenied] Permission denied
Aborted
As stated above, when the application is started as root user, the application works as expected and the suspend mode gets activated. So there shouldn't be a issue with the C++ application itself.
What can I do in order to call the DBus method as non-root user? Did I miss something in the configuration file? Or what else can I do to be able to execute the DBus call?
The application is running on an embedded Linux device (Colibri module with an ARM iMX7d processor).
Here is the Linux kernel and systemd version of the embedded device:
$ uname -r
5.4.91-5.2.0-devel+git.c59b3c2da1e9

$ systemctl --version
systemd 244 (244.5+)
+PAM -AUDIT -SELINUX +IMA -APPARMOR -SMACK +SYSVINIT +UTMP -LIBCRYPTSETUP -GCRYPT -GNUTLS +ACL +XZ -LZ4 -SECCOMP +BLKID -ELFUTILS +KMOD -IDN2 -IDN -PCRE2 default-hierarchy=hybrid


text: Q: Does the verb "esquisser" mean anything in Latex terminology? Latex doesn't want me to write "esquisser". Does that mean something in Latex terminology and am I creating a command by using this word? How can I use it without creating any command?


text:
Q: jquery datatable sorting on multiple columns including one hidden column which is always by desc I have a jQuery datatable with multiple columns including one hidden column ("Updated Time"), and the requirement is:
when users click on one column such as "Type", the result will be sorted by "Type" + "Updated Time", and, no matter the "Type" is sorted by "asc" or "desc", the sorting direction for "Updated Time" must always be "desc". I have no issue with sorting by multiple columns as following:
          "columnDefs": [ {
            "targets": [ 0 ],
            "orderData": [ 0, 6 ]
          }, {
            "targets": [ 1 ],
            "orderData": [ 1, 6 ]
          }, {
            "targets": [ 2 ],
            "orderData": [ 2, 6 ]
          }, {
            "targets": [ 3 ],
            "orderData": [ 3, 6 ]
          }, {
            "targets": [ 4 ],
            "orderData": [ 4, 6 ]
          } ],

The above column #6 is the hidden column "Updated Time". This solution only satisfy sorting by the 2 columns at the same time with the same direction, which is either both "asc" or both "desc". Is there any way to keep the sorting direction for "Updated Time" always "desc", and can chang the clicked column to sort by "asc" or "desc"?
Your help will be really appreciated!

A: Found the solution:
Add:
     "orderFixed": {
         "post": [ 6, 'desc' ]
     },

And the following is NOT needed:
"columnDefs": [ {
            "targets": [ 0 ],
            "orderData": [ 0, 6 ]
          }, {
            "targets": [ 1 ],
            "orderData": [ 1, 6 ]
          }, {
            "targets": [ 2 ],
            "orderData": [ 2, 6 ]
          }, {
            "targets": [ 3 ],
            "orderData": [ 3, 6 ]
          }, {
            "targets": [ 4 ],
            "orderData": [ 4, 6 ]
          } ],


text:
Q: Optimizing queries for the next and previous element I am looking for the best way to retrieve the next and previous records of a record without running a full query. I have a fully implemented solution in place, and would like to know whether there are any better approaches to do this out there.
Let's say we are building a web site for a fictitious greengrocer. In addition to his HTML pages, every week, he wants to publish a list of special offers on his site. He wants those offers to reside in an actual database table, and users have to be able to sort the offers in three ways.
Every item also has to have a detail page with more, textual information on the offer and "previous" and "next" buttons. The "previous" and "next" buttons need to point to the neighboring entries depending on the sorting the user had chosen for the list.

(source: pekkagaiser.com)
Obviously, the "next" button for "Tomatoes, Class I" has to be "Apples, class 1" in the first example, "Pears, class I" in the second, and none in the third.
The task in the detail view is to determine the next and previous items without running a query every time, with the sort order of the list as the only available information (Let's say we get that through a GET parameter ?sort=offeroftheweek_price, and ignore the security implications).
Obviously, simply passing the IDs of the next and previous elements as a parameter is the first solution that comes to mind. After all, we already know the ID's at this point. But, this is not an option here - it would work in this simplified example, but not in many of my real world use cases.
My current approach in my CMS is using something I have named "sorting cache". When a list is loaded, I store the item positions in records in a table named sortingcache.
name (VARCHAR)             items (TEXT)

offeroftheweek_unsorted    Lettuce; Tomatoes; Apples I; Apples II; Pears
offeroftheweek_price       Tomatoes;Pears;Apples I; Apples II; Lettuce
offeroftheweek_class_asc   Apples II;Lettuce;Apples;Pears;Tomatoes

obviously, the items column is really populated with numeric IDs.
In the detail page, I now access the appropriate sortingcache record, fetch the items column, explode it, search for the current item ID, and return the previous and next neighbour.
array("current"   => "Tomatoes",
      "next"      => "Pears",
      "previous"  => null
      );

This is obviously expensive, works for a limited number of records only and creates redundant data, but let's assume that in the real world, the query to create the lists is very expensive (it is), running it in every detail view is out of the question, and some caching is needed.
My questions:

*

*Do you think this is a good practice to find out the neighbouring records for varying query orders?

*Do you know better practices in terms of performance and simplicity? Do you know something that makes this completely obsolete?

*In programming theory, is there a name for this problem?

*Is the name "Sorting cache" is appropriate and understandable for this technique?

*Are there any recognized, common patterns to solve this problem? What are they called?

Note: My question is not about building the list, or how to display the detail view. Those are just examples. My question is the basic functionality of determining the neighbors of a record when a re-query is impossible, and the fastest and cheapest way to get there.

If something is unclear, please leave a comment and I will clarify.

Starting a bounty - maybe there is some more info on this out there.

A: I have an idea somewhat similar to Jessica's.  However, instead of storing links to the next and previous sort items, you store the sort order for each sort type.  To find the previous or next record, just get the row with SortX=currentSort++ or SortX=currentSort--.
Example:
Type     Class Price Sort1  Sort2 Sort3
Lettuce  2     0.89  0      4     0
Tomatoes 1     1.50  1      0     4
Apples   1     1.10  2      2     2
Apples   2     0.95  3      3     1
Pears    1     1.25  4      1     3

This solution would yield very short query times, and would take up less disk space than Jessica's idea.  However, as I'm sure you realize, the cost of updating one row of data is notably higher, since you have to recalculate and store all sort orders.  But still, depending on your situation, if data updates are rare and especially if they always happen in bulk, then this solution might be the best.
i.e.
once_per_day
  add/delete/update all records
  recalculate sort orders

Hope this is useful.

A: I've had nightmares with this one as well. Your current approach seems to be the best solution even for lists of 10k items. Caching the IDs of the list view in the http session and then using that for displaying the (personalized to current user) previous/next. This works well especially when there are too many ways to filter and sort the initial list of items instead of just 3.
Also, by storing the whole IDs list you get to display a "you are at X out of Y" usability enhancing text.

By the way, this is what JIRA does as well.
To directly answer your questions:

*

*Yes it's good practice because it scales without any added code complexity when your filter/sorting and item types crow more complex. I'm using it in a production system with 250k articles with "infinite" filter/sort variations. Trimming the cacheable IDs to 1000 is also a possibility since the user will most probably never click on prev or next more than 500 times (He'll most probably go back and refine the search or paginate).

*I don't know of a better way. But if the sorts where limited and this was a public site (with no http session) then I'd most probably denormalize.

*Dunno.

*Yes, sorting cache sounds good. In my project I call it "previous/next on search results" or "navigation on search results".

*Dunno.

A: In general, I denormalize the data from the indexes. They may be stored in the same rows, but I almost always retrieve my result IDs, then make a separate trip for the data. This makes caching the data very simple. It's not so important in PHP where the latency is low and the bandwidth high, but such a strategy is very useful when you have a high latency, low bandwidth application, such as an AJAX website where much of the site is rendered in JavaScript.
I always cache the lists of results, and the results themselves separately. If anything affects the results of a list query, the cache of the list results is refreshed. If anything affects the results themselves, those particular results are refreshed. This allows me to update either one without having to regenerate everything, resulting in effective caching.
Since my lists of results rarely change, I generate all the lists at the same time. This may make the initial response slightly slower, but it simplifies cache refreshing (all the lists get stored in a single cache entry).
Because I have the entire list cached, it's trivial to find neighbouring items without revisiting the database. With luck, the data for those items will also be cached. This is especially handy when sorting data in JavaScript. If I already have a copy cached on the client, I can resort instantly.
To answer your questions specifically:

*

*Yes, it's a fantastic idea to find out the neighbours ahead of time, or whatever information the client is likely to access next, especially if the cost is low now and the cost to recalculate is high. Then it's simply a trade off of extra pre-calculation and storage versus speed.

*In terms of performance and simplicity, avoid tying things together that are logically different things. Indexes and data are different, are likely to be changed at different times (e.g. adding a new datum will affect the indexes, but not the existing data), and thus should be accessed separately. This may be slightly less efficient from a single-threaded standpoint, but every time you tie something together, you lose caching effectiveness and asychronosity (the key to scaling is asychronosity).

*The term for getting data ahead of time is pre-fetching. Pre-fetching can happen at the time of access or in the background, but before the pre-fetched data is actually needed. Likewise with pre-calculation. It's a trade-off of cost now, storage cost, and cost to get when needed.

*"Sorting cache" is an apt name.

*I don't know.

Also, when you cache things, cache them at the most generic level possible. Some stuff might be user specific (such as results for a search query), where others might be user agnostic, such as browsing a catalog. Both can benefit from caching. The catalog query might be frequent and save a little each time, and the search query may be expensive and save a lot a few times.

A: Here is an idea. You could offload the expensive operations to an update when the grocer inserts/updates new offers rather than when the end user selects the data to view. This may seem like a non-dynamic way to handle the sort data, but it may increase speed. And, as we know, there is always a trade off between performance and other coding factors.
Create a table to hold next and previous for each offer and each sort option. (Alternatively, you could store this in the offer table if you will always have three sort options -- query speed is a good reason to denormalize your database)
So you would have these columns:

*

*Sort Type (Unsorted, Price, Class and Price Desc)

*Offer ID

*Prev ID

*Next ID

When the detail information for the offer detail page is queried from the database, the NextID and PrevID would be part of the results. So you would only need one query for each detail page.
Each time an offer is inserted, updated or deleted, you would need to run a process which validates the integrity/accuracy of the sorttype table.

A: I'm not sure whether I understood right, so if not, just tell me ;)
Let's say, that the givens are the query for the sorted list and the current offset in that list, i.e. we have a $query and an $n.
A very obvious solution to minimize the queries, would be to fetch all the data at once:
list($prev, $current, $next) = DB::q($query . ' LIMIT ?i, 3', $n - 1)->fetchAll(PDO::FETCH_NUM);

That statement fetches the previous, the current and the next elements from the database in the current sorting order and puts the associated information into the corresponding variables.
But as this solution is too simple, I assume I misunderstood something.

A: There are as many ways to do this as to skin the proverbial cat. So here are a couple of mine.
If your original query is expensive, which you say it is, then create another table possibly a memory table populating it with the results of your expensive and seldom run main query.
This second table could then be queried on every view and the sorting is as simple as setting the appropriate sort order.
As is required repopulate the second table with results from the first table, thus keeping the data fresh, but minimising the use of the expensive query.
Alternately, If you want to avoid even connecting to the db then you could store all the data in a php array and store it using memcached. this would be very fast and provided your lists weren't too huge would be resource efficient. and can be easily sorted.
DC

A: Basic assumptions:

*

*Specials are weekly

*We can expect the site to change infrequently... probably daily?

*We can control updates to the database with ether an API or respond via triggers

If the site changes on a daily basis, I suggest that all the pages are statically generated overnight. One query for each sort-order iterates through and makes all the related pages. Even if there are dynamic elements, odds are that you can address them by including the static page elements. This would provide optimal page service and no database load. In fact, you could possibly generate separate pages and prev / next elements that are included into the pages. This may be crazier with 200 ways to sort, but with 3 I'm a big fan of it.
?sort=price
include(/sorts/$sort/tomatoes_class_1)
/*tomatoes_class_1 is probably a numeric id; sanitize your sort key... use numerics?*/

If for some reason this isn't feasible, I'd resort to memorization. Memcache is popular for this sort of thing (pun!). When something is pushed to the database, you can issue a trigger to update your cache with the correct values. Do this in the same way you would if as if your updated item existed in 3 linked lists -- relink as appropriate (this.next.prev = this.prev, etc). From that, as long as your cache doesn't overfill, you'll be pulling simple values from memory in a primary key fashion.
This method will take some extra coding on the select and update / insert methods, but it should be fairly minimal. In the end, you'll be looking up [id of tomatoes class 1].price.next. If that key is in your cache, golden. If not, insert into cache and display.

*

*Do you think this is a good practice to find out the neighboring records for varying query orders? Yes. It is wise to perform look-aheads on expected upcoming requests.

*Do you know better practices in terms of performance and simplicity? Do you know something that makes this completely obsolete? Hopefully the above

*In programming theory, is there a name for this problem? Optimization?

*Is the name "Sorting cache" is appropriate and understandable for this technique? I'm not sure of a specific appropriate name. It is caching, it is a cache of sorts, but I'm not sure that telling me you have a "sorting cache" would convey instant understanding.

*Are there any recognized, common patterns to solve this problem? What are they called? Caching?
Sorry my tailing answers are kind of useless, but I think my narrative solutions should be quite useful.

A: You could save the row numbers of the ordered lists into views, and you could reach the previous and next items in the list under (current_rownum-1) and (current_rownum+1) row numbers.

A: The problem / datastructur is named bi-directional graph or you could say you've got several linked lists.
If you think of it as a linked list, you could just add fields to the items table for every sorting and prev / next key. But the DB Person will kill you for that, it's like GOTO.
If you think of it as a (bi-)directional graph, you go with Jessica's answer. The main problem there is that order updates are expensive operations.
 Item Next Prev
   A   B     -
   B   C     A
   C   D     B
   ...

If you change one items position to the new order A, C, B, D, you will have to update 4 rows.

A: Apologies if I have misunderstood, but I think you want to retain the ordered list between user accesses to the server. If so, your answer may well lie in your caching strategy and technologies rather than in database query/ schema optimization.
My approach would be to serialize() the array once its first retrieved, and then cache that in to a separate storage area; whether that's memcached/ APC/ hard-drive/ mongoDb/ etc. and retain its cache location details for each user individually through their session data. The actual storage backend would naturally be dependent upon the size of the array, which you don't go into much detail about, but memcached scales great over multiple servers and mongo even further at a slightly greater latency cost.
You also don't indicate how many sort permutations there are in the real-world; e.g. do you  need to cache separate lists per user, or can you globally cache per sort permutation and then filter out what you don't need via PHP?. In the example you give, I'd simply cache both permutations and store which of the two I needed to unserialize() in the session data.
When the user returns to the site, check the Time To Live value of the cached data and re-use it if still valid. I'd also have a trigger running on INSERT/ UPDATE/ DELETE for the special offers that simply sets a timestamp field in a separate table. This would immediately indicate whether the cache was stale and the query needed to be re-run for a very low query cost. The great thing about only using the trigger to set a single field is that there's no need to worry about pruning old/ redundant values out of that table.
Whether this is suitable would depend upon the size of the data being returned, how frequently it was modified, and what caching technologies are available on your server.

A: So you have two tasks:

*

*build sorted list of items (SELECTs with different ORDER BY)

*show details about each item (SELECT details from database with possible caching).

What is the problem?
PS: if ordered list may be too big you just need PAGER functionality implemented. There could be different implementations, e.g. you may wish to add "LIMIT 5" into query and provide "Show next 5" button. When this button is pressed, condition like "WHERE price < 0.89 LIMIT 5" is added.


text:
Q: Android SQLite: table user has no column named Here's part of my SQLiteHandler class code.
public class SQLiteHandler extends SQLiteOpenHelper implements DataKeyLists {

    private static final String TAG = SQLiteHandler.class.getSimpleName();

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "users";

    // Login table name
    private static final String TABLE_USER = "user";

    // query to create a login table
    private static final String QUERY_CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_USER
            + "("
            + KEY_ID + " INTEGER PRIMARY KEY,"
            + KEY_UID + " TEXT UNIQUE,"
            + KEY_NAME + " TEXT,"
            + KEY_STATUS + " TEXT,"
            + KEY_EMAIL + " TEXT UNIQUE,"
            + KEY_GENDER + " TEXT,"
            + KEY_BIRTHDAY + " TEXT,"
            + KEY_RELIGION + " TEXT,"
            + KEY_NATIONALITY + " TEXT,"
            + KEY_COUNTRY_OF_RESIDENCE + " TEXT,"
            + KEY_CREATED_AT + " TEXT"
            + KEY_UPDATED_AT + " TEXT"
            + ")";

    public SQLiteHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(QUERY_CREATE_LOGIN_TABLE);

        Log.d(TAG, "Database tables created");
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);

        // Create tables again
        onCreate(db);
    }

    /**
     * Storing user details in database
     * */
    public void addUserIntoSQLite(String uid, String name, String status, String email, String gender, String birthday, String created_at, String updated_at) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_UID, uid);
        values.put(KEY_NAME, name);
        values.put(KEY_STATUS, status);
        values.put(KEY_EMAIL, email);
        values.put(KEY_GENDER, gender);
        values.put(KEY_BIRTHDAY, birthday);
        values.put(KEY_CREATED_AT, created_at);
        values.put(KEY_UPDATED_AT, updated_at);

        long id = db.insert(TABLE_USER, null, values);
        db.close();

        Log.d(TAG, "New user is added into sqlite: " + id);
    }
}

I later added a new column KEY_UPDATED_AT the QUERY_CREATE_LOGIN_TABLE query and restarted the application.
Now I get the following message on the Logcat.
Error inserting uid=564ef4c43388d0.82002082 birthday=1982-07-27 updated_at=null email=learn@android.com status=user name=learnandroid created_at=2015-11-20 05:24:04 gender=Male
11-20 15:41:42.976 8659-8852/? E/SQLiteDatabase: android.database.sqlite.SQLiteException: table user has no column named updated_at (code 1): , while compiling: INSERT INTO user(uid,birthday,updated_at,email,status,name,created_at,gender) VALUES (?,?,?,?,?,?,?,?)

It seems like the table is dropped and newly created if there is a version difference.
I think the onUpgrade() takes that part, but why am I still getting that error message?
I also uninstalled the app on my device, cleaned and rebuilt the project on Android Studio and re-ran the application.
This didn't work either.

A: You miss a comma here:
+ KEY_CREATED_AT + " TEXT"
+ KEY_UPDATED_AT + " TEXT"

It has to be
+ KEY_CREATED_AT + " TEXT, "
+ KEY_UPDATED_AT + " TEXT"

Then uninstall and reinstall your app (in order for the database to be recreated).
Or simply increase the DATABASE_VERSION constant value (i.e.: set it to 3).


text:
Q: How to get local time from web server I have set up an AJAX server with these settings:

    let express = require('express');
    let server = express();

    server.use('/MyWebApp', express.static(__dirname + '/public'));

    server.get('/MyWebApp/dateService', function(request, response){
        response.send({'dateTime' : new Date()});
    });

    server.listen(2019);
    console.log('server running on port 2019 ...')

I want to get the local time and have this function in my HTML:
function getDateTime(){

                $.get({

                    url: "http://localhost:2019/MyWebApp/dateService",
                    dataType: "json",
                    success: function(result){
                        document.getElementById("timer").innerHTML = result;
                    }
                });
            }

But when I click the button, it doesn't work and I don't know why.

Random Text

<input type="button" value="Server-Request" onclick="getDateTime()"/>

The div is suppose to change to the local time but I get error

jquery.min.js:6 GET http://localhost:2019/MyWebApp/[object%20Object] 404 (Not Found)

If I change the function into this, it works perfectly!
function getTime(){
                $.ajax({
                    type: 'GET',
                    url: "http://localhost:2019/MyWebApp/dateService",
                    async: true,
                    dataType: 'text',
                    success: function(data, textStatus, jqXHR){
                    document.getElementById('timer').innerHTML = "Current Time:" + data + " Status: " + textStatus;
                    }
                });

            }

And this Endpoint:
server.get('/MyWebApp/dateService', function(request, response){
    response.send(new Date(Date.now()).toISOString());
});

But my point is that I want to send JSON.

A: You can't send a working object via JSON like you're trying to with
response.send({'dateTime' : new Date()});

HTML responses like this are strings.  If you try to send an object, it will attempt to make a string out of it.
And, since the client-side looks like it expects a string that you can insert directly into your HTML, what I'd suggest you do on the server is this:
server.get('/MyWebApp/dateService', function(request, response){
    let now = new Date();
    res.send(now.toGMTString());     // or pick your favorite string format
});

Or, look at the various ways the current date can be formatted and pick a different string format.
and, then change your ajax call to expect a string back:
       function getDateTime(){
            $.get({url: "http://localhost:2019/MyWebApp/dateService"}).then(function(result) {
                  document.getElementById("timer").innerHTML = result;
            }).catch(function(err) {
                  // decide what to do if you get an error
                  console.log(err);
            });
        }

Note: this gets the time on the server.  If you just want the current time for the user, you don't need to ask the server for that.  You can use a Date object in your local browser Javascript to get the client computer's time.


text:
Q: Coordinates of the truncated 120 cell I'm looking for the coordinates of the truncated 120 cell. They are given at the bottom of this page: http://eusebeia.dyndns.org/4d/trunc120cell
However when I use these coordinates I don't get the expected result. More likely I did a mistake, but I'd like to double check with another reference.

A: They seem correct here. When I construct a polytope with the specified permutations of the given coordinates in polymake, I get a polytope which is isomorphic to the truncated 120-cell produced by wythoff("H4", range(0,1)). Polymake reports that they are not congruent, but I think they are similar, up to rounding errors. All the edges are of uniform length (2 with the coordinates given at your link, as compared to $\sqrt{2}$ with Wythoff's construction in polymake).
Make sure you're getting all the right permutations. You will get $4\cdot 16 = 64$ vertices each from the first three points given, $12\cdot8=96$ vertices each from the next five points (the ones including 0), and $12\cdot16=192$ vertices each from the remaining nine points, for a total of 2400 vertices.


text:
Q: Group-by with multiple variables I have a df that looks a bit like this:
Date   Animal   Height   Weight
Jan-00   Cat      102      56
Jan-00   Cat      98       75
Jan-00   Cat      50       100
Jan-00   Cat      46       46
Jan-00   Cat      100      50

I am trying to find the average weight of cats in Jan-00 that are more than the median height of Cats in Jan-00. So in this example, the median height is 98; and the average weight of cats more than the median height is 53 (avg of 50, 56). I have a variable number of different animal types so I don't want to have to manually specify the animal types. In time there will be other things I want to measure over and above the weight of the cats (so I'm trying to future proof my code somewhat).
From scouring StackOverflow, my approach has been:
(1) Write a function which tells the rest of the code which things I want to measure:
def column_index(df, query_cols):
    cols = df.columns.values
    sidx = np.argsort(cols)
    return sidx[np.searchsorted(cols,query_cols,sorter=sidx)]

cols = (column_index(df, ["Weight"]))

Then (2), write some code that splits my original df between dates and animal type, split by the median height, and then return the things I want to measure:
x = (df["Height"]
     .gt(df.groupby(["Date","Animal"])["Height"]
     .transform('median')))

df_Tall = df[x].mean(level = 0)[df.columns[cols]]

However, when I do this, it is only returning a single series of data for the weight; I'm trying to get multiple columns, each of which represent a different animal - ie my intended output should look like:
       Weight
Date   Cat   Animal_x   Animal_y   Animal_z
Jan-00  53     xx          xx         xx

I think my error likes in the line
.gt(df.groupby(["Date","Animal"])["Height"]

But I can't figure out how to fix it. Any thoughts would be really appreciated!
Thanks

A: Your approach was almost correct. I just added another groupby of the median-filtered height data to group the mean weight (and height) by the Animal and Date columns:
df.loc[
    df['Height'].gt(df.groupby(['Date', 'Animal'])['Height'].transform('median')), :
].groupby(['Date', 'Animal']).mean().unstack()

Of course you can get the mean of the Weight by selecting the Weight column after (or also before) the second groupby, f.i. by changing the last line to: ].groupby(['Date', 'Animal'])[['Weight']].mean().unstack(), with the double brackets around 'Weight' retaining the df dimensions/structure.
step-by-step:

*

*groupby Date and Animal, get median and select where Height is greater (same as in your question)

*.loc explicit first axis indexing over your df[x] is just my personal preference. both work well to filter the data by the median height.

*second groupby on height-filtered data, selecting Weight before or after groupby is optional.

*get the mean of each animal and date group

*unstack transforms the dataframe into multiindex-columns with Animal as the second level

The second groupby could afaik only be avoided, if groupby.median() supported a level-argument. But since level is not supported by (most or all?) groupby methods, a second groupby is required.


text:
Q: Como definir uma imagem, vinda do banco de dados e que está armazenada em binário, como background-image de uma div? Tenho uma imagem que é armazenada no banco de dados de forma binária. Eu resgatei essa imagem (através de um select) e gostaria de inseri-la como background-image de uma div. Eu só consigo inseri-la como src de uma img.
Como Armazeno no banco de dados

$foto = $_FILES['foto']['name'];

if($this->__get('foto') != "")
{
  $binario = file_get_contents($this->__get('foto'));
  $query = "UPDATE usuarios SET foto = :foto, nome = :nome, usuario = :usuario, telefone = :telefone, email = :email, email_alternativo = :email_alternativo, frase = :frase, senha = :senha, lembrete = :lembrete, biografia = :biografia ";
  $query .= "WHERE id = :id";

  $stmt = $this->db->prepare($query);
  $stmt->bindValue(':foto', $binario);
  $stmt->bindValue(':nome', $this->__get('nome'));
  $stmt->bindValue(':usuario', $this->__get('usuario'));
  $stmt->bindValue(':telefone', $this->__get('telefone'));
  $stmt->bindValue(':email', $this->__get('email'));
  $stmt->bindValue(':email_alternativo', $this->__get('email_alternativo'));
  $stmt->bindValue(':frase', $this->__get('frase'));
  $stmt->bindValue(':senha', $this->__get('senha'));
  $stmt->bindValue(':lembrete', $this->__get('lembrete'));
  $stmt->bindValue(':biografia', $this->__get('biografia'));
  $stmt->bindValue(':id', $this->__get('id'));
  $stmt->execute();
}

Parte que eu insiro como src de um img.

<?php

function dataURI($bin)
{
  return 'data: image/gif;base64,'.base64_encode( $bin );
}

?>

      <?php
  if(!empty($this->view->info_usuario['foto']))
  {

   $foto = dataURI($this->view->info_usuario['foto']);

   echo "";
  }
  else
  {
   echo "";
  }
 ?>

Eu gostaria de inserir no background-image da div abaixo:

  <div class="col-lg-12" style="background-image: url(<?php echo $foto; ?>);">

*

*Tentei, no desespero, dar um echo da variável que contém a imagem dentro do url(), porém não deu certo.

*Código HTML gerado da página: Fiddle

A: Se fosse uma URL normal, o valor de url no background-image não necessitaria ser delimitado por aspas, mas no caso de base64, é preciso.
Como os valores da style da div estão delimitados por aspas duplas, basta você delimitar o valor da url com aspas simples:
background-image: url('<?php echo $foto; ?>');


text:
Q: I cannot enable ASP Classic on Windows 8.1 I am trying to enable ASP Classic on my local PC windows 8.1. I have followed the steps to enable ASP in this Windows KB > https://learn.microsoft.com/en-gb/iis/application-frameworks/running-classic-asp-applications-on-iis-7-and-iis-8/classic-asp-not-installed-by-default-on-iis#installing-classic-asp-on-windows-8-or-windows-81
However when I go to the simple ASP Classic page I have created in a folder under inetpub/wwwroot/test/test.asp which just tries to do a simple Response.Write("TEST") on the page when I go to file:///C:/inetpub/wwwroot/test/test.asp all I see is my ASP code in text on the page. I enabled ASP, ISAPI filters and anything else that seemed relevant but it doesn't seem to run.
Is there not a VBScript DLL that needs to be enabled somewhere that isn't present in the Application Development Features under World Wide Web Services as I thought both VBScript and the ASP DLLS were needed to run ASP Classic?
Anyway I followed the KB article and still all I see are the text of the ASP page when I go to the local URL.
I also have WAMPServer installed on my PC but I have that under a different port 8888 so that I can toggle between the two. I have no problems starting WAMP and running PHP code it is just the IIS I am having issues with.
If I just enable IIS and go to localhost I get the default IIS page e.g file:///C:/inetpub/wwwroot/iis-85.png but I cannot get the ASP code to actually execute, it just shows up as text on the page.
How can I get this to work? I never used to have problems switching between the two servers ASP and WAMP but after a factory reset on this laptop I am having issues.


text:
Q: How do I embed javascript in clojure Hiccup? I'm writing a webserver app in clojure with Hiccup (and other things).
I'm trying to have a check-box enable and disable two drop-down fields with a little JS but I can't make it work.
[:head
[:script "function toggleText(cb, t1, t2) {
    document.getElementById(t1).disabled = !cb.checked;
    document.getElementById(t2).disabled = !cb.checked;
}"]]

[:td (hf/check-box {:on-change (str "toggleText(" (name endtag) "," (name tytag) "," (name tmtag) ")")} endtag)]
[:td (hf/drop-down tytag (range 2013 2031) 2017)]
[:td (hf/drop-down tmtag (range 1 13) 6)]

A: on-change is a React handler and won't work in server-side HTML.
If you don't want to create a separate JS file, you can use the onclick attribute: the below should work (provided that the hf/check-box function creates an element with the given properties):
[:td (hf/check-box
      {:onclick (str "toggleText(" (name endtag) ","
                     (name tytag) "," (name tmtag) ")")}
      endtag)]

A: Thanks Aleph, your fix together with adding getElementById for the cb parameter in the function did the trick!
The function now looks like this
[:script "function toggleText(cb, t1, t2) {
    document.getElementById(t1).disabled = !document.getElementById(cb).checked;
    document.getElementById(t2).disabled = !document.getElementById(cb).checked;}"]

And I simplified the Hiccup code too (not passing the tags as parameters) so it looks like this
[:td (hf/check-box {:onclick (str "toggleText('endtag','toyear','tomonth')")} :endtag (some? (:toyear m)))]
[:td (hf/drop-down :toyear (range 2013 2031))]
[:td (hf/drop-down :tomonth (range 1 13))]


text:
Q: Do threads continue to run after service is closed by android? A service is called on the onCreate in my Main Activity.
The service extends from Service class (not IntentService) - in that service, a thread is called, which has an infinite loop - if the thread throws any Exception, it closes the service, and recalls the service (Handled by a try catch block).
Eventually, for any reason, the service is closed by android.
Please answer the following questions:
A) Does my thread continue to run?
.....If so, if a Exception is thrown at any time in the future, will it recall the service?
....If not, will an Exception be thrown to cause the service to start again?
B) Will android just turn of my thread when it turns off my service?
I'm just trying to understand what happens to my application when Android decides to clear my service.

A: As long as the thread is running it is considered "garbage collection root". Therefore, the thread itself and any other object reachable from that thread will not be garbage collected. If Android framework will not interfere, a thread having infinite loop will continue to run indefinitely. Since your thread can "close" the service, I assume that it has a reference to the service (either implicit or explicit), therefore the entire service will remain in memory.
However, Android do have some means for monitoring apps' memory consumption, and can kill apps in order to free memory. When Android kills an app, it kills the entire process of the app. When the process is killed, all threads are stopped and the memory associated with them is freed, therefore no further activity will take place.
It seems like this is the end of your service, but Android provides additional mechanism to control what happens in that case: you can designate the service as STICKY, and Android will attempt to restart the service as soon as possible. It is discussed in details in this answer.
References:
Most of the information provided in this answer is covered in official Services page and javadoc of service class.
For the more complicated scenario of Service running in a another process there is almost no documentation, but there are many blogs out there. I also wrote a post on the subject: How to establish a reliable (crash and kill tolerant) connection to bound IPC (e.g. AIDL) Service in Android


text:
Q: React native base64 to pdf expo print I want to print a pdf file on react native mobile app, I receive a base64 code from api and by using it I want to show customer his/her invoice pdf. I tried using Expo Print but I couldnt handle it, I keep getting
Error: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of children, use an array instead.]
I would appreciate any help!
import React, { Component } from 'react';
import { View, Text, Button, StyleSheet,TouchableHighlight } from 'react-native';
import RNHTMLtoPDF from 'react-native-html-to-pdf';
import * as Print from 'expo-print';

const InvoiceScreen = async({ route, navigation }) => {
  const { invoice} = route.params;
  const my_uri = "data:application/pdf;base64"+invoice
  console.log("DID INVIOCE COMEEE",invoice)
  await   Print.printAsync(
    {uri:my_uri,
      width: 595, height: 842 })
    return (
      <View></View>
      );
};

export default InvoiceScreen;

A: replace your code with this:
const InvoiceScreen = async({ route, navigation }) => {
  const { invoice } = route.params;
  const my_uri = `data:application/pdf;base64,${invoice}`;
  await Print.printAsync({uri:my_uri});
};

export default InvoiceScreen;

A: Maybe the problem is the data type of the "invoice" parameter, this must be a string which must be the base64 of the pdf file. Reference
If you are using Expo - Managed workflow (Expo CLI / Tool), to view pdf I recommend that you use https://www.npmjs.com/package/rn-pdf-reader-js
I also leave a simple implementation in view:
import React from "react";
import { View, StyleSheet, Dimensions } from "react-native";
import { globalStyles } from "../../constants/globalStyles";
import PDFReader from "rn-pdf-reader-js";

export default function XScreen({ navigation, route }) {

  return (
    <View style={globalStyles.backGround}>
      <PDFReader
        source={{
          base64: route.params.source,
        }}
        style={styles.pdf}
      />
    </View>
  );
}
const styles = StyleSheet.create({
  pdf: {
    flex: 1,
    width: Dimensions.get("window").width,
    height: Dimensions.get("window").height,
  },
});

Note:

route.params.source =
data:application/pdf;base64,${response.data.data};
response.data.data = string base64 pdf


text:
Q: Query to stuff duplicate records in SQL Server? I have this table:
   +----------+----------+---------+-----------------------------------+
| Class A  | Class  B | Class C | Result_XML                        |
+----------+----------+---------+-----------------------------------+
| SUPER    | PREMIUM  | A       | <Array> <Ser ref="RF124" r="200"> |
| ECONOMIC | SEMI     | A       | <Array> <Ser ref="RF124" r="200"> |
| SUPER    | PREMIUM  | A       | <Array> <Ser ref="RF144" r="500"> |
| SUPER    | NA       | B       | <Array> <Ser ref="RF124" r="200"> |
| ECONOMIC | SEMI     | A       | <Array> <Ser ref="RF154" r="200"> |
| SUPER    | PREMIUM  | C       | <Array> <Ser ref="RF124" r="100"> |
+----------+----------+---------+-----------------------------------+

And, what I've been trying to get is something like below:
+----------+---------+--------+---------+
|  ClassA  | ClassB  | ClassC | Result  |
+----------+---------+--------+---------+
| SUPER    | PREMIUM | A      | 200,500 |
| ECONOMIC | SEMI    | A      |     200 |
| SUPER    | NA      | B      |     200 |
| SUPER    | PREMIUM | C      |     100 |
+----------+---------+--------+---------+

Basically the above is distinct list of records from first table having same result in last column and if different then stuff the results in same row like first example. So far I come up with the following but is obviously not working. Thank you in advance for any help:
SELECT DISTINCT
    ClassA, ClassB, ClassC,
    Result = (STUFF((Select Distinct ',' + E1.RESULT_XML.value('(/Array/Ser/@r)[1]', 'varchar(max)')
                     From listtable E2
                     Where E1.ClassA = E2.ClassA
                       And E1.ClassB = E2.ClassB
                       And E1.ClassC = E2.ClassC
                     FOR XML PATH(''), TYPE, ROOT).value('root[1]','nvarchar(max)'),1,1,''))
FROM
    listtable E1

A: You should use E2.ResultXml instead of E1.ResultXml in the stuff query.
DECLARE @T TABLE (ClassA NVARCHAR(50), ClassB NVARCHAR(50), ClassC NVARCHAR(50), ResultXML NVARCHAR(300))

INSERT @T SELECT 'SUPER','PREMIUM'  ,'A','200'--'<Array> <Ser ref="RF124" r="200">'
INSERT @T SELECT 'ECONOMIC','SEMI'  ,'A','200'--'<Array> <Ser ref="RF124" r="200">'
INSERT @T SELECT 'SUPER','PREMIUM'  ,'A','500'--'<Array> <Ser ref="RF144" r="500">'
INSERT @T SELECT 'SUPER','NA'       ,'B','200'--'<Array> <Ser ref="RF124" r="200">'
INSERT @T SELECT 'ECONOMIC','SEMI'  ,'A','200'--'<Array> <Ser ref="RF154" r="200">'
INSERT @T SELECT 'SUPER','PREMIUM'  ,'C','100'--'<Array> <Ser ref="RF124" r="100">'

SELECT * FROM @T

SELECT
    ClassA,ClassB,ClassC,
    Result = (STUFF((Select  DISTINCT ',' + E2.RESULTXML
                     From @T E2
                     Where E1.ClassA = E2.ClassA
                       And E1.ClassB = E2.ClassB
                       And E1.ClassC = E2.ClassC
                     FOR XML PATH('')),1,1,''))
FROM
    @T E1
GROUP BY
    ClassA, ClassB, ClassC

Yields--->
ClassA      ClassB     ClassC  Result
ECONOMIC    SEMI       A       200
SUPER       NA         B       200
SUPER       PREMIUM    A       200,500
SUPER       PREMIUM    C       100

A: ;with cte( ClassA  , ClassB , ClassC , Result_XML)
AS
(
SELECT 'SUPER'    , 'PREMIUM'  , 'A'       , '<Array> <Ser ref="RF124" r="200">' Union all
SELECT 'ECONOMIC' , 'SEMI'     , 'A'       , '<Array> <Ser ref="RF124" r="200">' Union all
SELECT 'SUPER'    , 'PREMIUM'  , 'A'       , '<Array> <Ser ref="RF144" r="500">' Union all
SELECT 'SUPER'    , 'NA'       , 'B'       , '<Array> <Ser ref="RF124" r="200">' Union all
SELECT 'ECONOMIC' , 'SEMI'     , 'A'       , '<Array> <Ser ref="RF154" r="200">' Union all
SELECT 'SUPER'    , 'PREMIUM'  , 'C'       , '<Array> <Ser ref="RF124" r="100">'
)

,Result AS (
    SELECT ClassA
        ,ClassB
        ,ClassC
        ,CAST(REPLACE(RIGHT(Result_XML, 5), '">', '') AS INT) AS Result_XML
    FROM cte
    )

SELECT DISTINCT ClassA
    ,ClassB
    ,ClassC
    ,STUFF((
            SELECT DISTINCT ', ' + CAST(i.Result_XML AS VARCHAR(10))
            FROM Result i
            WHERE i.ClassA = o.ClassA
                AND i.ClassB = o.ClassB
                AND i.ClassC = o.ClassC
            FOR XML PATH('')
            ), 1, 1, '') AS Result
FROM Result o
ORDER BY ClassC
    ,Result DESC

OutPut
+----------+---------+--------+---------+
|  ClassA  | ClassB  | ClassC | Result  |
+----------+---------+--------+---------+
| SUPER    | PREMIUM | A      | 200,500 |
| ECONOMIC | SEMI    | A      |     200 |
| SUPER    | NA      | B      |     200 |
| SUPER    | PREMIUM | C      |     100 |
+----------+---------+--------+---------+

A: I have a solution to the problem, but I'm sure it can be solved more effectively.

SELECT
    ClassA
    ,ClassB
    ,ClassC
    ,Result = (STUFF((SELECT DISTINCT
            ',' + CAST(E1.Result AS XML).value('(/Array/Ser/@r)[1]', 'varchar(max)')
        FROM [OrchestratorNotifications].[dbo].[Kuko] E2
        WHERE E1.ClassA = E2.ClassA
        AND E1.ClassB = E2.ClassB
        AND E1.ClassC = E2.ClassC
        FOR XML PATH (''), TYPE, ROOT)
    .value('root[1]', 'nvarchar(max)'), 1, 1, '')) INTO #tmp1
FROM [OrchestratorNotifications].[dbo].[Kuko] E1
ORDER BY ClassA
    ,ClassB
    ,ClassC

SELECT ClassA
    ,ClassB
    ,ClassC
    ,Result FROM (
SELECT *,ROW_NUMBER() OVER( PARTITION BY ClassA,ClassB,ClassC ORDER BY ClassA,ClassB,ClassC,w DESC) AS r1 FROM(
SELECT
    ClassA
    ,ClassB
    ,ClassC
    ,o.Result,
    o.w,
    ROW_NUMBER() OVER( PARTITION BY ClassA,ClassB,ClassC,o.w  ORDER BY ClassA,ClassB,ClassC,o.w) AS rownum
FROM #tmp1 a
CROSS APPLY (SELECT
        CASE
            WHEN a.Result = b.Result THEN a.Result
            ELSE a.Result + ',' + b.Result
        END Result,
            CASE
            WHEN CAST( a.Result AS INT) = CAST( b.Result AS INT) THEN  CAST( a.Result AS INT)
            ELSE CAST( a.Result AS INT)  + CAST( b.Result AS INT)
        END w
    FROM #tmp1 b
    WHERE a.ClassA = b.ClassA
    AND a.ClassB = b.ClassB
    AND a.ClassC = b.ClassC) o
    )y
    where y.rownum=1
    )d
    WHERE d.r1=1
    ORDER BY d.ClassC

DROP TABLE #tmp1


text:
Q: Post Install Script not working How do I run postinstallscript from anonymous window to check if it is working or not?
I am trying to install a package to another org where it is failing with below error.
Unexpected Error    The package installation failed. Please provide the following information to the publisher: Organization Name: prime.com Organization ID: 00D6F000001GQCU Package: accpack Version: 1.0 Error Message: The post install script failed.
Scenario:
Created a custom field on contact object. Now I am trying to package and trying to install into another org.
In my post install script I am trying to assign this custom field to contact page layout in the installed org where it is failing.
Please help me on this.

A: You should get emails from package installs or upgrades, if subscriber didn't set Email Deliverability to No email. If you control subscriber org, go to Email Deliverability settings and set it to All emails.
Then you should be able to email the Email Stack Trace to yourself
public inherited sharing class InstallHandler implements System.InstallHandler {
    public void onInstall(InstallContext context) {
        try {
            methodCall();
        } catch (Exception e) {
            send(
                context.installerId(),
                'Installation Failure' + context.organizationId(),
                ' e: ' + e.getMessage() + ' stack trace ' + e.getStackTraceString()
            );
        }
    }
    ....
}


text:
Q: Proof-finding: Power iteration and complexity of the Rayleigh quotient I'm searching for a proof for this theorem:
\begin{align}
|\lambda^{(k)}-\lambda_1| = \mathcal{O}\Big(\Big|\frac{\lambda_2}{\lambda_1}\Big|^{2k}\Big)
\end{align}
where
\begin{align}
\lambda^{(k)} : = \frac{(x^k)^TAx^k}{(x^k)^Tx^k}
\end{align}
is the Rayleigh quotient iteration and $A \in \mathbb{R}^{n\times n}$, $A=A^T$, $|\lambda_1|\geq ... \geq |\lambda_n|$ eigenvalues of A.
I found one in a german book by Hanke-Bourgeois (Theorem 25.3) but it's very technical. Does any of you know where to find a simple proof for that?
Thank you!


text:
Q: android - setBackground with checking android version not working I want change the background drawable of a button. My min. SDK version is 14. Therefore I check the current version, which is installed on the device:
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
    buttonClubPublic.setBackgroundDrawable(buttonClubPublic.getContext().getResources().getDrawable(R.drawable.check_button));
    buttonClubPrivate.setBackgroundDrawable(buttonClubPrivate.getContext().getResources().getDrawable(R.drawable.uncheck_button));
} else {
    buttonClubPublic.setBackground(buttonClubPublic.getContext().getResources().getDrawable(R.drawable.check_button));
    buttonClubPrivate.setBackground(buttonClubPrivate.getContext().getResources().getDrawable(R.drawable.uncheck_button));
}

When the current version is equal or above 16 I use setBackground otherwise I use setBackgroundDrawable.
However, it seems that Eclipse doesn't recognize the if/else check of the version, because I get an error:

Error: Call requires API level 16 (current min is 14)

I set the button in XML:
<Button
    android:id="@+id/create_club3_club_privat"
    android:text="@string/create_club3_privat"
    android:textColor="#000000"
    android:textSize="@dimen/check_button_size"
    android:layout_width="@dimen/check_button_width"
    android:layout_height="wrap_content"
    android:background="@drawable/uncheck_button"
    android:layout_marginLeft="@dimen/create_team_check_button_margin"
/>


text:
Q: PHP - Translating cURL to PHP I am trying to upload PostGIS table from Postgres to GeoServer using php. However I am having issue translating cURL to its equivalent PHP.

I am getting Http code: 405

cURL:
curl -v -u admin:geoserver -X PUT-H "Content-type: text/xml" -T pgstores.xml \
http://localhost:9090/geoserver/rest/workspaces/testworkspace/datastores.xml

PHP:
$url = "http://localhost:9090/geoserver/rest/workspaces/testworkspace/datastores.xml";
                $headers = array('Content-Type: text/xml', 'Accept: text/xml');
                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_VERBOSE, true);
                curl_setopt($ch, CURLOPT_USERPWD, GEOSERVER_USER);

                $path = getcwd()."/uploads/pgstores.xml";
                $fp = fopen($path, "r");

                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_PUT, 1);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                curl_setopt($ch, CURLOPT_UPLOAD, true);
                curl_setopt($ch, CURLOPT_REFERER, true);
                curl_setopt($ch, CURLOPT_INFILE, $fp);
                curl_setopt($ch, CURLOPT_INFILESIZE, filesize($path));

Any help would be appreciated.


text:
Q: seperate Weight from Weight/bias vector neural network Matlab I have trained neural network by matlab nntraintool
i want to have weights and bias. i have tried these function to get them
wb = formwb(net,net.b,net.iw,net.lw)
[b,iw,lw] = separatewb(net,wb)
wb =
-28.5243
   26.1019
   10.2387
   23.7000
  -12.2929
   14.6831
   16.7075
  -26.4566
    9.4643
  -24.0166
  -26.8963 ...
b =
[20x1 double]
[     0.0411]

iw =
[20x1 double]
[]

lw =
           []    []
[1x20 double]    []

can some one help me how to read them

A: The easiest way is after executing these two commands:

wb = formwb(net,net.b,net.iw,net.lw);
[b,iw,lw] = separatewb(net,wb);

look inside your workspace, then double-click any of these variables (b, iw, lw) and then again double-click on those cells that say [# x # double]..


text:
Q: Finding column values for the first and last row in the previous year I have the price history for Google stock in a Google Colab doc, like this:
df = pd.DataReader('GOOG', data_source='yahoo', start='08-01-2004')

These are open, high, low, close and adjusted close prices for each trading day in the price history. I can create a new column in the DataFrame for the rate of return of the stock over the trailing 12 months like this:
df['Trailing 12 month return'] = (df['Adj Close'] -
  df['Adj Close'].shift(DAYS_TRADING_PER_YEAR)) /
  df['Adj Close'].shift(DAYS_TRADING_PER_YEAR)

But what if what I actually want is one value for rate of the return per year, looking at the return over the previous calendar year? So, for 2015, just find the first trading day (more correctly, the first day for which we have data) in 2014 and the last trading day in 2014 and get the percentage change over that period?

A: Assuming Date is a proper datetime column:

*

*groupby(df.Date.dt.year) to group by year

*apply() the yearly rates computed from first_valid_index() and last_valid_index()

*shift() the results to get the previous year

rates = df.groupby(df.Date.dt.year)['Adj Close'].apply(
    lambda g: (g.loc[g.last_valid_index()] - g.loc[g.first_valid_index()]) / g.loc[g.first_valid_index()]
).shift()

# Date
# 2014         NaN
# 2015    0.128019
# 2016    2.232232
# 2017    1.041269
# 2018    0.292042
# 2019    0.154558
# 2020   -0.136102
# 2021    0.396961
# Name: Adj Close, dtype: float64

*Then map() these rates with df.Date.dt.year to create the new column:

df['Previous year rate of return'] = df.Date.dt.year.map(rates)

#            Date   Adj Close  Previous year rate of return
# 0    2014-08-01  166.724074                           NaN
# 1    2014-08-02   69.634211                           NaN
# ...         ...         ...                           ...
# 999  2017-04-26  165.225121                      1.041269
# 1000 2017-04-27   40.165297                      1.041269
# ...         ...         ...                           ...
# 2433 2021-03-30   67.864861                      0.396961
# 2434 2021-03-31   31.408317                      0.396961


text:
Q: How to get value from result of asynctask to use in MainActivity I want to get the value of a and set to b,how can i do that?
    public class MainActivity extends AppCompatActivity {
    int a,b;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Task task=new Task();
    task.execute(5,6);
    b=a;
}

public class Task extends AsyncTask<Integer,Void,Integer>{

   @Override
   protected void onPostExecute(Integer integer) {
       super.onPostExecute(integer);
       a=integer;

   }

   @Override
   protected Integer doInBackground(Integer... integers) {
       return integers[0]+integers[1];
   }
}
}

A: in line b=a; run on time running other thread
best result is in method onPostExecute write b = a;
so b before than a be set

A: In your question you are already having the answer.
After executing this statement.
Task task=new Task();
task.execute(5,6);

After executing task.execute first doInBackground will be called and then it will return to onPostExecute then sum of a and b and your are assigning to a.
just write b=a in onPostExecute and it will work as your want.


text:
Q: Display approval sign/check mark (✓) on Kivy Label I am working on a Kivy(Python) Project and I need to display approval(✓) and cross(X) symbol in different scenario. I can display cross symbol but unable to display other one. Is there any way to do this ? Thanks.
Note: I have tried, writing text:'✓' and text:u'2713' under Label in .kv file but it doesn't work.

A: The font supplied with Kivy doesn't include the tick mark. You need to use fonts that include those symbols. Tick is available in fonts Arial Unicode MS, Wingdings and Wingdings 2. You can download the font ttf file and have it in the same folder with your script.
Link to download the font
https://www.download-free-fonts.com/details/88978/arial-unicode-ms
Then include the font and use it in the label as follow:
Label:
   font_name:'arial-unicode-ms.ttf'
   text: "This is the tick ✓"

A: Bro I was also troubling from same problem from morning but now I figured it out actually so I would like to share it with you.I used below code:
        def wrong_btn(self):
    self.ids.wrong_button.text =    u"⌫"       self.ids.wrong_button.font_name=r"C:\Users\95532\AppData\Local\Microsoft\Windows\Fonts\Arial-Unicode-MS.ttf"

I used this to specify the folder in which the font is stored so you can also download the font you want and just specify the path and don't forget use a r i.e raw string mark or else it wont work I wasted my whole day searching for that hope this helps you bro


text:
Q: How to Clear Adobe reader history programatically using C# I need to clear the recently opened documents history from Adobe reader in my windows application using C#.Is it possible?

A: Clear this registry hive
[-HKEY_CURRENT_USER\Software\Adobe\Acrobat Reader\10.0\AVGeneral\cRecentFiles]

var registrykeyHKLM = Registry.CurrentUser;
string keyPath = @"Software\Adobe\Acrobat Reader\10.0\AVGeneral\cRecentFiles";
registrykeyHKLM.DeleteValue(keyPath);
registrykeyHKLM.Close();


text:
Q: umount bind of stale NFS i've got a problem removing mounts created with mount -o bind from a locally mounted NFS folder. Assume the following mount structure:
NFS mounted directory:
$ mount -o rw,soft,tcp,intr,timeo=10,retrans=2,retry=1 \
 10.20.0.1:/srv/source /srv/nfs-source

Bound directory:
$ mount -o bind /srv/nfs-source/sub1 /srv/bind-target/sub1

Which results in this mount map
$ mount
/dev/sda1 on / type ext3 (rw,errors=remount-ro)
# ...
10.20.0.1:/srv/source on /srv/nfs-source type nfs (rw,soft,tcp,intr,timeo=10,retrans=2,retry=1,addr=10.20.0.100)
/srv/nfs-source/sub1 on /srv/bind-target/sub1 type none (rw,bind)

If the server (10.20.0.1) goes down (eg ifdown eth0), the handles become stale, which is expected.
I can now un-mount the NFS mount with force
$ umount -f /srv/nfs-source

This takes some seconds, but works without any problems. However, i cannot un-mount the bound directory in /srv/bind-target/sub1. The forced umount results in:
$ umount -f /srv/bind-target/sub1
umount2: Stale NFS file handle
umount: /srv/bind-target/sub1: Stale NFS file handle
umount2: Stale NFS file handle

Here is a trace http://pastebin.com/ipvvrVmB
I've tried umounting the sub-directories beforehand, find any processes accessing anything within the NFS or bind mounts (there are none).
lsof also complains:
$ lsof -n
lsof: WARNING: can't stat() nfs file system /srv/nfs-source
      Output information may be incomplete.
lsof: WARNING: can't stat() nfs file system /srv/bind-target/sub1 (deleted)
      Output information may be incomplete.
lsof: WARNING: can't stat() nfs file system /srv/bind-target/
      Output information may be incomplete.

I've tried with recent stable Linux kernels 3.2.17, 3.2.19 and 3.3.8 (cannot use 3.4.x, cause need the grsecurity patch, which is not, yet, supported - grsecurity is not patched in in the tests above!).
My nfs-utils are version 1.2.2 (debian stable).
Does anybody have an idea how i can either:

*

*force the un-mount some other way? (any dirty trick is welcome, data loss or damage neglible at this point)

*use something else instead of mount -o bind? (cannot use soft links, cause mounted directories will be used in chroot; bindfs via FUSE is far to slow to be an option)

Thanks,
Paul
Update 1

*

*With 2.6.32.59 the umount of the (stale) sub-mounts work just fine. It seems to be a kernel regression bug.

*The above tests where with NFSv3. Additional tests with NFSv4 showed no change.

Update 2

*

*We have tested now multiple 2.6 and 3.x kernels and are now sure, that this was introduced in 3.0.x. We will fille a bug report, hopefully they figure it out.

A: Something that worked for me in my particular setup, to get cleints working, was this:
I had an autofs tree with a mounted nfs fs on /fs/doom and another mounted on /fs/doom/localvol5. After server reboot it was possible to access /fs/doom and /fs/doom/localvol5/sub, but /fs/doom/localvol5 itself gave ESTALE on everything, including umount -f, -l, -fl.
What I did to get the client running without reboot was to move the whole /fs/doom hierarchy to another tree:
    mkdir /dev/shm/garbage-mount
    mount --move /fs/doom /dev/shm/garbage-mount

That moved the whole tree, and apparently works only because /fs/doom was accessible and a mountpoint. I sitll cannot unmount any of these filesystems, but I was able to restart autofs and get a fresh and working tree.
This should work with any autofs tree that has malfunctioning nfs subdirs.
Hope that helps.

A: You could simply mount the remote filesystem on /srv/bind-target/sub1.
If you're expecting this level of unavailability you should also specify the sync (although maybe defailt) option to NFS to lower the chance of having unwritten changes on your client

A: $ umount -l

Worked for me, before none of them were working:
$ mount -f ...


text:
Q: Starting up a Bluetooth server I implemented the Bluetooth server according to the example shown in http://www.codeproject.com/Articles/252882/Bluetooth-Server-Programming-on-Windows.
I modified it a bit to use AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM.
It works fine.
However, if I restart the computer, the program hangs at accept().
If I then un-pair the two devices and then re-pair them again, the program works.
Any clues as to why this is happening.

A: So the program hangs on accept, from what I know accept in windows bluetooth sockets and other Bluetooth sockets platforms, accept like functions are a blocking asynchronous call, it pretty much block/freezes the thread that is on, and waits a client to connect, now winsock2 handles one thread operations much better than other platforms yes i'm looking to you android ,but still the program might get unstable if two of those calls occur , furthermore the guy only checks for one error in accept , so try referring to this complete list of winsock errors
 (retrieved by winsockgetlasterror())  ,
also can you pls provide the client code and more info like on what platform, ide,devices  , you are using ?


text:
Q: An error occurred while attempting to decode the Jwt: Signed JWT rejected: Another algorithm expected, or no matching key(s) found I am trying setup OAuth2-OpenID Connect with ForgeRock OpenAM integrated with spring security and am getting the following error
2019-06-17 15:01:42.576 DEBUG 62255 --- [nio-8090-exec-2] .o.s.r.w.BearerTokenAuthenticationFilter :
Authentication request for failed: org.springframework.security.oauth2.core.OAuth2AuthenticationException:
An error occurred while attempting to decode the Jwt:
Signed JWT rejected: Another algorithm expected, or no matching key(s) found

The Jwk .well-known uri returns the following supported algorithms:
"id_token_signing_alg_values_supported": [
    "PS384",
    "ES384",
    "RS384",
    "HS256",
    "HS512",
    "ES256",
    "RS256",
    "HS384",
    "ES512",
    "PS256",
    "PS512",
    "RS512"
  ]

The decoded JWT shows the following header:
{
  "typ": "JWT",
  "zip": "NONE",
  "alg": "HS256"
}

Is there a way I can set a specific JwtDecoder based on the value coming from the header or enforce AM to use one particular algorithm?

A: The issue was with the configuration in the Access Management on the token encryption. It was blank but for some reason the JWT header showed HS256, that caused spring to look for the HS256 private key and fail. After I changed the setting to use RS256, everything started working.

A: In my case, by default NimbusJwtDecoder taking RS256 as JwsAlgo. So I configured JWTDecoder and provided RS512 algorithm which I found in my JWT header.

{   "alg": "RS512",   "typ": "JWT" }

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
    private String jwkSetUri;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated().and().oauth2ResourceServer().jwt().decoder(jwtDecoder());
    }

    @Bean
    public JwtDecoder jwtDecoder() {
        return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).jwsAlgorithm(SignatureAlgorithm.RS512).build();
    }
}

A: Yes you can tell AM to use a specific signature algorithm for OIDC id token signature (https://backstage.forgerock.com/docs/am/6.5/oidc1-guide/#configure-oauth2-oidc-client-signing), but I suspect the client is not able to verify the signature because of the missing key.
Just to make sure ... you are aware that OAuth2 and OIDC are different topics..


text:
Q: R function to compute deviation matrix I've writen a function to compute a matrix where each column is the corresponding input matrix column minus the column mean.
# compute the deviation matrix
deviation <- function(X) {
  one <- rep(1, nrow(X))
  n <- ncol(X)
  d <- matrix(data = NA, nrow = nrow(X), ncol = ncol(X))
  for(i in seq.int(from = 1, to = n)) {
    d[,i] <- X[,i] - mean(X[,i], na.rm = TRUE) * one
  }
  d
}

Could this function be written more idiomatically in R (using functional programming, perhaps)?

A: Use sweep and colMeans:
sweep(mat, 2, colMeans(mat))

By default, sweep uses - or the subtraction function, taking the column means as calculated by colMeans, from the values in each column (MARGIN=2). Gives the same result:
mat <- matrix(1:12,nrow=3)
deviation(mat)
#     [,1] [,2] [,3] [,4]
#[1,]   -1   -1   -1   -1
#[2,]    0    0    0    0
#[3,]    1    1    1    1

sweep(mat, 2, colMeans(mat))
#     [,1] [,2] [,3] [,4]
#[1,]   -1   -1   -1   -1
#[2,]    0    0    0    0
#[3,]    1    1    1    1


text:
Q: GeometryModel3D Area and Volume Is there a way to calculate the Area and Volume for a given GeometryModel3D?

A: There isn't for this class type.  You can solve this using general math, though.  See this stack overflow question:
Volume of a 3D closed mesh car object
It seems DarenW may have a useful answer for you.
Note that your mesh must be perfectly closed for this calculation to even make sense.
Also, what is "area" of a 3D object?  Surface area?  If so, just take every triangle, find the area, and sum them...


text:
Q: Python, why can't i override Popen.stdout Why is possibile to override sys.stdout but not subprocess.Popen.stdout, with my own class.
If it is possibile to override please show me how ...
I'm working on some GUI project, and i want to print output of some other program on text_view in "real_time", not when everything is done.
when i am overriding sys.stdout i do somthing like this :
class MyStdOut :
  def __init__(self) : self.text = ""
  def write(self, string) : self.text += string

here is some program 'pyscript.py'
import os

def main() :
  for i in range(10) :
    print i
    os.system('sleep 0.1') ## this is just to make some delay, i did also 3 loops

if __name__ == '__main__' : main()

and here is main program :
import subprocess as sub

def main() :
  popen = sub.Popen('./pyscript.py', stdout=sub.PIPE)
  for line in popen.stdout : print 'Line :', line
  print 'Main done'

if __name__ == '__main__' : main()

Still it is not 'real time', i get everything when it ends.
I also tried communicate, but get same result.
In my real program i have to print output of other program on text_view (GUI GTK+). I suspect that subprocess.stdout must be file, but when i tried to make some class that inherits from IOBase i got errors too.
Everybody say that it is possible, but still I tried many different ways with no success.

A: You can achieve the same by using:
p = Popen(args, ..., stdout=subprocess.PIPE)
for line in p.stdout:
   print line

where p.stdout behaves like PIPE, so you can read data from it as soon as it arrives. It is not strict realtime, because some buffering comes in play, but still this is a viable alternative.


text:
Q: chrome extension get data from web site im trying to get data from web pages. I read lot of documents but still i couldnt do anything. I want to get title from a youtube video.
Basiclly my extension has just a click function like this:
$(document).ready(function(){
    $("#btn").click(function(){
        alert("This youtube title: ");
    });
});

youtube image
How can i get this title when i clicked button ?
thanks for your help.

A: declare tabs permission in manifest file then on button click add following code snippet
 chrome.tabs.query({
        active: true,
        currentWindow: true
    }, function (tabs) {
       var current_tab = tabs[0];
       var url = current_tab.url;

})