text:
Q: Extract data from Json string and divide into multiple columns I have a column in a table that has Jsonstring text:
[
    {
        "PType":{"code":"9","name":"Hospitality"},
        "PSubType":{"code":"901","name":"Hotel"},
        "AType":{"code":"9","name":"Hospitality"},
        "ASubType":{"code":"901","name":"Hotel"}
    }
]

How can I divide that into multiple columns using sql server query?

A: With SQL-Server 2016+ there is native JSON support:
DECLARE @json NVARCHAR(MAX)=
N'[
    {
        "PType":{"code":"9","name":"Hospitality"},
        "PSubType":{"code":"901","name":"Hotel"},
        "AType":{"code":"9","name":"Hospitality"},
        "ASubType":{"code":"901","name":"Hotel"}
    }
]';

SELECT A.[key]
      ,JSON_VALUE(A.value,'$.code') AS Code
      ,JSON_VALUE(A.value,'$.name') AS [Name]
FROM OPENJSON(JSON_QUERY(@json,'$[0]')) A;

The result
key         Code    Name
---------------------------------
PType       9       Hospitality
PSubType    901     Hotel
AType       9       Hospitality
ASubType    901     Hotel

Some explanation:
With JSON_QUERY() you can get the element within the array, OPENJSON will find all objects within and return them as derived table.
JSON_VALUE will read the internals into columns.
Hint
with a version below v2016 you should use another tool or think about a CLR function...

A: In SQL Server 2016+ you can use a combination of openjson (more info here) and cross apply:
declare @json nvarchar(max) = '[ { "PType":{"code":"9","name":"Hospitality"}, "PSubType":{"code":"901","name":"Hotel"}, "AType":{"code":"9","name":"Hospitality"}, "ASubType":{"code":"901","name":"Hotel"} } ]'

select
 [PT].[code] as Ptype_Code
,[PT].[name] as Ptype_Name
,[PS].[code] as PSubType_Code
,[PS].[name] as PSubType_Name
,[AT].[code] as AType_Code
,[AT].[name] as AType_Name
,[AS].[code] as ASubType_Code
,[AS].[name] as ASubType_Name

from   openjson (@json)
with
(
    PType  nvarchar(max) as json,
    PSubType  nvarchar(max) as json,
    AType  nvarchar(max) as json,
    ASubType  nvarchar(max) as json
) as lev1
cross apply openjson (lev1.PType)
with
(
    code int,
    name nvarchar(100)
) as PT
cross apply openjson (lev1.PSubType)
with
(
    code int,
    name nvarchar(100)
) as PS
cross apply openjson (lev1.AType)
with
(
    code int,
    name nvarchar(100)
) as [AT]
cross apply openjson (lev1.ASubType)
with
(
    code int,
    name nvarchar(100)
) as [AS]

Result:


text:
Q: A join aggregate behaviour I can't understand Query 1:
 SELECT c.class_id,
       SUM
       (
        CASE
         WHEN s.student_id IS NULL THEN 0
         ELSE 1
        END
       ) as total_students
  FROM classes c LEFT JOIN students s ON c.class_id = s.class_id
GROUP BY c.class_id;

result:
453 100
461 10
462 19
464 0
471 0
499 133

great !
Query 2: (added where condition to filter student types)
 SELECT c.class_id,
       SUM
       (
        CASE
         WHEN s.student_id IS NULL THEN 0
         ELSE 1
        END
       ) as total_students
  FROM classes c LEFT JOIN students s ON c.class_id = s.class_id WHERE s.student_type='instate'
GROUP BY c.class_id;

result:
453 89
461 5
462 19
499 43

All the figures are right, except the ones with 0 counts vanish :!
why is that ?

A: The WHERE clause is checking s.student_type='instate'.
In a LEFT JOIN, everything on the right side is NULL, so the WHERE clause would not evaluate to anything.
If I may, I'd like to suggest a slight rewrite of your query:
Instead of this
SELECT c.class_id,
       SUM
       (
        CASE
         WHEN s.student_id IS NULL THEN 0
         ELSE 1
        END
       ) as total_students
  FROM classes c LEFT JOIN students s ON c.class_id = s.class_id
GROUP BY c.class_id;

write it more compact like this
SELECT c.class_id, SUM(1-ISNULL(s.student_id)) as total_students
FROM classes c LEFT JOIN students s USING (class_id)
GROUP BY c.class_id;

Now, if you would like to filter on student_type and have the zeros to come back, you must rewrite the query like this:
SELECT
    A.class_id,
    IFNULL(B.total_students,0) total_students
FROM classes A LEFT JOIN
(
    SELECT c.class_id, COUNT(s.student_id) as total_students
    FROM classes c INNER JOIN students s USING (class_id)
    WHERE s.student_type='instate'
    GROUP BY c.class_id
) B USING (class_id);

UPDATE 2012-03-08 13:11 EST
Now I am curious
This is your query
SELECT class_id,
(
    SELECT count(*) FROM students a
    WHERE a.class_id=e.class_id
    AND a.student_type='instate'
) FROM classes e WHERE class_account='92';

Please Try This One
SELECT
    COUNT(DISTINCT e.class_id)
FROM
    (SELECT class_id FROM classes WHERE class_account='92') e
    INNER JOIN
    (SELECT class_id FROM students WHERE student_type='instate') a
    USING (class_id)
;

Make sure you have the following indexes before running this new query:
ALTER TABLE classes ADD INDEX (class_account,class_id);
ALTER TABLE students ADD INDEX (student_type,class_id);

A: SELECT c.class_id,
       COUNT( s.student_id ) AS total_students
FROM classes c
  LEFT JOIN students s
    ON c.class_id = s.class_id AND s.student_type='instate'
GROUP BY c.class_id;

A: SELECT c.class_id,
 SUM(CASE
    WHEN s.student_id IS NULL THEN 0
    ELSE 1
    END
    ) as total_students
FROM classes c
LEFT JOIN students s ON c.class_id = s.class_id AND s.student_type='instate'
GROUP BY c.class_id;

You converted the join to an inner join by using the where clause.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is DPT in the context of a firewall log? I'm not a server admin, but I'm trying to work out why a colleague can't connect to the internet. The settings she's using are exactly the same as everyone else, but she can't connect. We're all Mac people and running OS X 10.5. One thing I noticed after looking at the firewall logs is that connections from everyone has a DPT of 137, wheras her machine has a number above 40000. Is this normal and what does it mean?

A: DPT=Destination PorT
UPD Port 137 is NETBIOS service port, but if you aren't an admin network...it will be hard to solve the problem.

A: DPT = Destination Port as lg mentions.
Port 137 typically is the NetBIOS Name Service which is not unusual in a firewall log, but I doubt that it's got anything to do with your user's problem.
What you want to look for in the firewall logs will vary depending on what services you're allowing through your firewall and what the firewall's logging configuration is.  It's possible to configure the firewall to not log things.
If you can post a little more about what exactly "connect to the Internet" means in your context then we'll be able to help a bit more.  Are you talking about web browsing, ftp, SSH, etc...?


text:
Q: Why do Nakajima and Watanabe claim the induced action of a finite linear group on the invariant subring of the reflection subgroup is linearizable? I just picked up the paper "The classification of quotient singularities which are complete intersections" by Haruhisa Nakajima and Kei-Ichi Watanabe, which is in the book

*

*Greco, Silvio, and Rosario Strano, eds. Complete intersections: lectures given at the 1st 1983 session of the Centro Internationale Matematico Estivo (CIME) held at Acireale (Catania), Italy, June 13-21, 1983. Vol. 1092. Springer, 2006.

Nakajima and Watanabe's paper is pp. 102-120. On p. 103, the authors make an assertion (without comment) that I find surprising or at least very non-obvious. (Here, $V$ is a complex finite-dimensional vector space, $G$ is a finite subgroup of $\mathrm{GL}(V)$, and $S$ is the symmetric algebra on $V$, i.e., a ring of polynomials whose degree 1 component is $V$.)

Theorem C: If $G$ does not contain pseudo-reflections, $S^G$ is a Gorenstein ring if and only if $G\subset \mathrm{SL}(V)$.
The condition "$G$ does not contain pseudo-reflections" is not so serious. If $G$ does contain pseudo-reflections, let $H$ be the subgroup of $G$ generated by all the pseudo-reflections of $G$. Then $S^H$ is a polynomial ring by Theorem A, and the action of $G/H$ is linear and does not contain pseudo-reflections. So we can apply Theorem C to this action.

Emphasis added. Theorem A here is the Chevalley-Shepard-Todd theorem. The assertion seems to be that there is a set $f_1,\dots,f_n$ of polynomial generators for $S^H$ (i.e., a set of algebraically independent generators) such that the action of the group $G/H$ on the ring $S^H$ is induced from a linear action of $G/H$ on the vector space $W=\langle f_1,\dots,f_n\rangle_{\mathbb{C}}$, so that $S^H$ can be seen as the symmetric algebra on $W$.
This is not at all clear to me. The degrees of the generators $f_1,\dots,f_n$ are determined by $H$, and it's possible that they're all distinct (e.g. if $H$ is the reflection group $A_n$). Meanwhile, the action of $G/H$ on $S^H$ is certainly graded. In this case, for the action of $G/H$ on $f_1,\dots,f_n$ to be linear in the above sense, it is necessarily diagonal. This seems like a lot to know for sure.

Question: Why do Nakajima and Watanabe feel sure that the action of $G/H$ on $S^H$ is linear?

Remark: Four years ago I asked a related question which is still unanswered as of today, but Nakajima and Watanabe's situation is more specific than the setting of this previous question. In particular, for them, the graded subring is always the invariant ring of a reflection group. (Also, the ground field is $\mathbb{C}$ as opposed to a general field of characteristic 0.)

A: I think one should consider the ideal $I = S^H_+$ of invariants with zero constant coefficient. To give algebra-generators for $S^H$ is the same as to give generators of $I/I^2$ as a vector space. So here dim$_K(I/I^2) = n$. $G/H$ acts linearly on $I$, $I^2$ and on $I/I^2$. Since we are working on the nonmodular case, $I^2$ has a complement $W$ in $I$ (as $G/H$-spaces). So a basis of $W$ yields suitable generators $f_i$. Now there is an isomorphism $S(W) \to S^H$ (with $S(W)$ the symmetric algebra). The isomorphism is $G/H$-equivariant, but NOT graded.
I hope this makes sense. I agree that Nakajima and Watanabe's comment raises a lot of questions, and I haven't answered them all. For instance, is there a problem with applying Theorem C to $S(W)$ since the isomorphism is not graded?
But Amiram Braun has answered them and carried this argument to the modular case by proving that if you assume that $S^H$ is a polynomial ring, then $S^G$ is quasi-Gorenstein iff $G/H$ acts on $I//I^2$ by transformations of determinant 1. See Corollary 3.9.12 in the book of Derksen and Kemper.


text:
Q: Infinite wait for reply from server using sockets in Python I'm trying to send a message to the API of a server in order to get a reply. I am using the following code:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('h68.p.ctrader.com',5211)
sock.connect(server_address)

message = "8=FIX.4.4|9=87|35=0|49=theBroker.12345|56=cServer|57=QUOTE|50=BVN's Message|34=1|52=20180322-21:26:01|10=101"

sock.send(bytes(message,'utf-8'))
data = sock.recv(3)
print(data)
sock.close()

However, when executing it, the message is sent to the server, but at the moment of receiving the reply from the server [data = sock.recv (3)], the program does not go on. It keeps the cursor blinking, like in an infinite loop. What is the cause of this problem? Was it the script? The message sent to the server? The server itself? How to solve the problem?
Note: This message is in a format required by the server API, which consists of "tag" = "value" | "tag" = "value" | "tag" = "value" ...

A: A quick look at the documentation for this API you're using turns up a couple of problems:

*

*You're missing a | at the very end of the message.

*You shouldn't actually be sending |s at all, that's just a human-readable translation of the actual message.  All of them need to be replaced with \x01 or \u0001 (depending on whether you're creating a byte string or a Unicode string), the actual tag separator character.


text:
Q: Can't Login to phpmyadmin without using password I would like to logging into phpmyadmin without using password.
However I changed AllowNoPassword to TRUE in /etc/webapps/phpmyadmin/config.inc.php :
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['AllowNoPassword'] = true;

But, phpmyadmin asks me for password again!
P.S:
MySQL root user has no password.

A: first, stop apache before editing this file with this:
/etc/init.d/apache stop

then, if you are trying to log in as root, you should have the following lines in your config:
$cfg['Servers'][$i]['user'] = 'root';# add this line
$cfg['Servers'][$i]['AllowNoPasswordRoot'] = true;

finally, start apache again:
/etc/init.d/apache start

A: as suggested at Archlinux BBS: add /etc/webapps to open_basedir in your php.ini


text:
Q: how do we retrive checkout session in stripe success page This is my server side code

<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

use Slim\Http\Request;
use Slim\Http\Response;
use Stripe\Stripe;

require 'vendor/autoload.php';

$dotenv = Dotenv\Dotenv::create(__DIR__);
$dotenv->load();

require './config.php';

$app = new \Slim\App;

$app->add(function ($request, $response, $next) {
    Stripe::setApiKey(getenv('STRIPE_SECRET_KEY'));
    return $next($request, $response);
});

$app->get('/', function (Request $request, Response $response, array $args) {
  return $response->write(file_get_contents(getenv('STATIC_DIR') . '/index.html'));
});

$app->post('/checkout_sessions', function(Request $request, Response $response) use ($app)  {
  $params = json_decode($request->getBody());
  $payment_method_types = [
    'usd' => ['card'],
    'eur' => ['card'],
    'cad' => ['card']
  ];
  $products = [
    'cause-a' => 'prod_KP3YP2a3IGYqsb',
    'cause-b' => 'prod_KP3iZRGcEjn5W8',
  ];

  $session = \Stripe\Checkout\Session::create([
    'success_url' => 'http://localhost:4242/success.html?session_id={CHECKOUT_SESSION_ID}',
    'cancel_url' => 'http://localhost:4242/?cancel=true',
    'mode' => 'payment',
    'payment_method_types' => $payment_method_types[$params->currency],
    'metadata' => [
      'cause' => $params->cause,
      'currency' => $params->currency,
    ],
    'submit_type' => 'donate',
    'line_items' => [[
      'price_data' => [
        'currency' => $params->currency,
        'product' => $products[$params->cause],
        'unit_amount' => $params->amount,
      ],
      'quantity' => 1,
    ]]
  ]);

  return $response->withJson([
    'id' => $session->id
  ]);
});

$app->get('/order', function (Request $request, Response $response) {
  $id = $_GET['sessionId'];
  $checkout_session = \Stripe\Checkout\Session::retrieve($id);

  echo json_encode($checkout_session);
});

$app->run();

this is the success page with javascript

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Order Confirm</title>

Success

                 payment status:

i need help with  product detail , customer name , amount on success page and if possible payment paid or not paid status on it.... cant find any tutorial on it or any detail step by step guide on it
i am close but cant get it to bullseyes please help me with it
yeah on success page all i get is payment status and blank

A: Looks like here is what happened:

*

*Your Checkout Session defined success_url to success.html

*Your success.html fired another request to "/success?session_id=xxx"

*Your backend handled this with $app->get('/success', function...

It could be confusing to name both HTML in step 2 and the handling URL in step 3 as "success". You may want to use a different name such as "success" and "get-checkout-session" like Stripe example on Github. After that, debug your server log on step 3 to see whether you got the session id correctly and have retrieved the Customer Id.
There is more information to extract from a CheckoutSession. See Stripe's API Reference on available properties. You probably want to expand its payment_intent to see the amount and payment status.


text:
Q: How can i use Google Analytics in my ASP.NET WebApp I created a Google Analytics Account and copied the tracking snippet into the head of my MasterPage in ASP.NET. But when i run the WebApp the Google Analytics Charts are still empty. Is it possible to use Google Analytics in ASP.NET when the WebApp runs on the localhost?

A: First of all assuming that no JavaScript error exist on your code - you just copy/paste the tracking code from google analytics and its run as expected.
Now, for google analytics to track your page, its must find the same url name that you see on your url on your browser.
Because you probably see http://localhost/, or http://192.168.1.1/ or something similar you need to change that name, to much the same name that you use on google analytics.
To do that you can use the host file, located on c:\[windows]\System32\drivers\ folder.
There open the host file, and add a line that reflect the local ip and use a url name close to the public one with different sub-domain and setup that one on google analytics.
for example something like
192.168.1.1 local.mypublicname.com

then setup that local.mypublicname.com on google analytics as a new view - a test view (example : https://www.directom.com/google-analytics-subdomain-tracking/)
call your local site as http://local.mypublicname.com and there you go - its works.
For working more easy, I suggest to setup the local ISS and not run the visual studio web server... but you can do both of them, just need an extra setup on visual studio to say where is the first page - in this case the local.mypublicname.com


text:
Q: Error when compile Squashfs tools from source I'm trying to compile modified squashfs tools from source code (GPL source). Installation 'readme' from original pack have notes that it can be built without needing to patch the kernel.(locally)
2. Building squashfs tools
The squashfs-tools directory contains the mksquashfs and unsquashfs programs. These can be made by typing make. The source files use a local copy of squashfs_fs.h (included in the kernel patches) allowing the tools to be made without needing to patch the kernel.
Executing make gives error: Makefile:2: *** Sqlzma is not defined.  Stop. The sqlzma files, iclude sqlzma.h are located in another folder, 'sqlzma-3.4-457'.
I assume, the problem may be related with links to those external files, but I'm not sure. I'm new to programming in general.
Makefile in 'squashfs-tools' folder:
ifndef Sqlzma
$(error Sqlzma is not defined)
endif

INSTALL_DIR = /usr/local/bin

INCLUDEDIR = .

CFLAGS := -I$(INCLUDEDIR) -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_GNU_SOURCE -O2
ifdef UseDebugFlags
DebugFlags = -g -Wall -Wno-unused-variable -O0 -UNDEBUG
endif
CFLAGS += -I${Sqlzma} -D_REENTRANT -DNDEBUG ${DebugFlags}
LDFLAGS += -L${LzmaAlone} -L${LzmaC}

all: mksquashfs unsquashfs

mksquashfs: mksquashfs.o read_fs.o sort.o
    #$(CC) $(LDFLAGS) mksquashfs.o read_fs.o sort.o -lz -lpthread -lm -lunlzma_r -llzma_r -lstdc++ -o $@
    g++ $(LDFLAGS) mksquashfs.o read_fs.o sort.o -lz -lpthread -lm -lunlzma_r -llzma_r -lstdc++ -o $@

mksquashfs.o: mksquashfs.c squashfs_fs.h mksquashfs.h global.h sort.h \
    ${Sqlzma}/sqlzma.h ${Sqlzma}/sqmagic.h \
    ${LzmaAlone}/liblzma_r.a ${LzmaC}/libunlzma_r.a

read_fs.o: read_fs.c squashfs_fs.h read_fs.h global.h \
    ${Sqlzma}/sqlzma.h ${Sqlzma}/sqmagic.h

sort.o: sort.c squashfs_fs.h global.h sort.h

unsquashfs: unsquashfs.o
    $(CC) $(LDFLAGS) unsquashfs.o -lpthread -lm -lunlzma -lz -o $@

unsquashfs.o: unsquashfs.c squashfs_fs.h read_fs.h global.h \
    ${Sqlzma}/sqlzma.h ${Sqlzma}/sqmagic.h ${LzmaC}/libunlzma.a

clean:
    -rm -f *.o mksquashfs unsquashfs

install: mksquashfs unsquashfs
    mkdir -p $(INSTALL_DIR)
    cp mksquashfs unsquashfs $(INSTALL_DIR)

Makefile in "sqlzma-3.4-457" folder:

# Copyright (C) 2006-2008 Junjiro Okajima
# Copyright (C) 2006-2008 Tomas Matejicek, slax.org
#
# LICENSE follows the described ones in lzma and squashfs.

# $Id: Makefile,v 1.1.1.1 2010/11/11 13:20:13 nash Exp $

# paths
Sqlzma = ${CURDIR}

LzmaVer = lzma457
Lzma = ${Sqlzma}/${LzmaVer}
SqVer = squashfs3.4
Squashfs = ${Sqlzma}/${SqVer}
KVer = linux-2.6.27.4
SqFs = ${Squashfs}/kernel-patches/${KVer}/fs/squashfs
#KDir = /lib/modules/$(shell uname -r)/build
#KDir = ${SqFs}/../..

ifeq (${LzmaVer}, lzma443)
LzmaC = ${Lzma}/C/7zip/Compress/LZMA_C
LzmaAlone = ${Lzma}/C/7zip/Compress/LZMA_Alone
else
LzmaC = ${Lzma}/C/Compress/Lzma
LzmaAlone = ${Lzma}/CPP/7zip/Compress/LZMA_Alone
endif
SqTools = ${Squashfs}/squashfs-tools

# enable it if you want to add -g option when compiling
#UseDebugFlags = 1
#MyDebugFlags = -DSQUASHFS_TRACE
# disable it if you don't want to compile squashfs kernel module here
#BuildSquashfs = 1

export

all:
    ${MAKE} -C ${LzmaC} -f sqlzma.mk $@
    ${MAKE} -C ${LzmaAlone} -f sqlzma.mk $@
    #${MAKE} -C ${SqTools} $@

clean:
    ${MAKE} -C ${LzmaC} -f sqlzma.mk $@
    ${MAKE} -C ${LzmaAlone} -f sqlzma.mk $@
    #${MAKE} -C ${SqTools} $@
    ${RM} *~

########################################

-include priv.mk

ifdef BuildSquashfs
CONFIG_SQUASHFS = m
CONFIG_SQUASHFS_EMBEDDED =
CONFIG_SQUASHFS_FRAGMENT_CACHE_SIZE = 3
EXTRA_CFLAGS = -I${Sqlzma} -I${SqFs}/../../include -Wall -Werror
EXTRA_CFLAGS += -DCONFIG_SQUASHFS_MODULE -UCONFIG_SQUASHFS
EXTRA_CFLAGS += -UCONFIG_SQUASHFS_EMBEDDED -DCONFIG_SQUASHFS_FRAGMENT_CACHE_SIZE=3
# if you enabled CONFIG_PREEMPT, but want CPU to try concentrating
# the uncompression, then define UnsquashNoPreempt.
# if you don't define UnsquashNoPreempt, the behaviour follows
# the CONFIG_PREEMPT.
EXTRA_CFLAGS += -DUnsquashNoPreempt
export

# the environment variables are not inherited since 2.6.23
MAKE += SQLZMA_EXTRA_CFLAGS="$(shell echo ${EXTRA_CFLAGS} | sed -e 's/\"/\\\\\\"/g')"

all: all_sq

FORCE:
all_sq:
    ${MAKE} -C ${KDir} M=${SqFs} modules

clean: clean_sq
clean_sq:
    ${MAKE} -C ${KDir} M=${SqFs} clean
endif

########################################

load:
    for i in ${LzmaC}/kmod/unlzma.ko ${LzmaC}/kmod/sqlzma.ko \
        ${SqFs}/squashfs.ko; \
    do sudo insmod $$i; done

unload:
    -sudo rmmod squashfs sqlzma unlzma

Links to squashfs and sqlzma folders.


text:
Q: Resizing WebView with window I have a NSView that houses about a dozen WebViews populated with HTML generated from the application. When I first init them, I wait for - (void)webView:didFinishLoadForFrame: to fire before laying them out and adding them to the view based on the documentView frame.
How would I go about resizing these WebViews along with the window? Is there a way to get the desired size of the WebView for a given width?

A: Since all you're using the web views for is rendering MarkDown, you should instead investigate  MacDown or MarkdownLive. These render MarkDown directly into an NSTextView. This will be MUCH more efficient than multiple WebView objects.
In future, you should ensure that your question includes what you're actually trying to achieve because there's often a simpler way to do what you want than the way you think it perhaps should be achieved.


text:
Q: Proving the inequality $ 1+\mathbb{S}<(1+a_1) \dot\ \dots \dot\ (1+a_n)<\frac{1}{1-\mathbb{S}} $
Given $a_1,a_2,\dots,a_n>0$ and $\mathbb{S}=a_1+\dots+a_n<1$ Prove: $$ 1+\mathbb{S}<(1+a_1) \dot\ \dots \dot\ (1+a_n)<\frac{1}{1-\mathbb{S}}   $$

I proved the left inequality, but I can't figure the right one.
Any help appreciated.

A: Let $S=\sum_{k=1}^n a_k<1$, where $a_k>0$ for all $k$.
METHODOLOGY $1$:  Use the AM-GM Inequality
Using the AM-GM Inequality revelas
$$\begin{align}
\prod_{k=1}^n(1+a_k)&\le \left(\frac{\sum_{k=1}^n(1+a_k))}{n}\right)^n\\\\
&=\left(1+\frac{S}{n}\right)^n\tag 1\\\\
\end{align}$$
Now, in THIS ANSWER, I showed using only the limit definition of the exponential function and Bernoulli's inequality that (i) the sequence $\left(1+\frac xn\right)^n$ monotonically increases to $e^x$ and (ii) that the exponential function satisfies the inequality $e^x\le \frac{1}{1-x}$ for $x<1$.
Therefore, we see that
$$\begin{align}
\prod_{k=1}^n(1+a_k)&\le e^S\\\\
&\le \frac{1}{1-S}
\end{align}$$
as was to be shown!

METHODOLOGY $2$:  Use a Standard Inequality for the Loagarithm Function
Again, in THIS ANSWER, I showed that the logarithm satisfies the inequality $\log(x)\le x-1$.
Hence, we have
$$\begin{align}
\log\left(\prod_{k=1}^n(1+a_k)\right)&=\sum_{k=1}^n\log(1+a_k)\\\\
&\le \sum_{k=1}^na_k\\\\
&=S
\end{align}$$
Therefore, we see that
$$\prod_{k=1}^n(1+a_k)\le e^S\le \frac{1}{1-S}$$
as expected!

A: As you proved the left one yourself, here is the proof of the right ineq. by induction:
$$(1+a_1)(1-a_1)=1-a_1^2<1 \Rightarrow 1+a_1<\frac{1}{1-a_1}$$
Suppose for some $n-1\in \Bbb N$, $$(1+a_1)...(1+a_{n-1})<\frac{1}{1-\Bbb S_{n-1}}$$
Then if $a_1,...,a_n>0$ and $\Bbb S<1$, we have
$$(1+a_1)...(1+a_n)<\frac{1+a_n}{1-\Bbb S_{n-1}}=\frac{1+a_n}{1-\Bbb S_{n-1}}\frac{1-a_n}{1-a_n}=\frac{1-a_n^2}{1-\Bbb S_n +a_n\Bbb S_{n-1}}<\frac{1}{1-\Bbb S_n}$$
where $\Bbb S_{j}=\sum_{i=1}^{j}a_i$
Result follows


text:
Q: How to deal with Chrome alerts with Selenium (Python) I am very new to Selenium and am trying to automate sending messages through WhatsApp Web through Google Chrome. I am using a different api which lets users write messages directly to the phone number specified: https://wa.me/. However, there is an alert box which pops up and my code is unable to accept it.
Alert box screenshot
I have tried
driver.switch_to_alert().accept()
 but this is resulted in a deprecation warning, so switched to:
alert_box = driver.switch_to.alert
alert_box.accept()

Both result in the following error:
Exception has occurred: NoAlertPresentException
Message: no such alert
  (Session info: chrome=105.0.5195.102)
  File "<hidden>", line 30, in <module>
    driver.switch_to.alert.accept()

Current code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)

# Ensure you are logged in to whatsapp web
num = "xxxxxxxxxxxxxxxxxxxxx" # hid the number
driver.get("https://wa.me/" + num)

# Allow time to load page
driver.implicitly_wait(3)

# Switch to alert window to accept the alert to open URL
driver.switch_to.alert.accept()

driver.find_element(By.XPATH, './/a[@class="_9vcv _advm _9scb"][@id="action-button"][@title="Share on WhatsApp"]').click()

# Switch to alert window to accept the alert to open URL
driver.switch_to_alert().accept()

driver.find_element(By.XPATH, '//*[@id="fallback_block"]/div/div/h4[2]/a').click()

Interestingly, no alert shows up if I manually go through the screens myself.
Thanks in advance!

A: You probably should add some code to wait for the alert to open.
Have a look a the following snipped.
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

try:
    wait = WebDriverWait(driver, 10)
    wait.until(EC.alert_is_present(), 'waiting for alert')
    alert = driver.switch_to.alert
    alert.accept()
except TimeoutException:
    print("timed out waiting for alert")


text:
Q: Axis2 Deployed vs Generated Service WSDL Differences I have a web service built with axis2. Also, I have used Java2WSDL utility provided by axis2 to generate a WSDL from my class (not the deployed services) at build time.
Then I generated a client via wsimport for both i.e. Deployed Web Service in Java EE Application Server and from generated WSDL file. The problem is that generated code is different in terms of packages and mamespaces and because of that the client generated from WSDL file is not working as it complains about the namespace mismatch....on jboss I see following exception;
13:46:04,524 ERROR [RPCMessageReceiver] Exception occurred while trying to invoke service method getLanguage
org.apache.axis2.AxisFault: namespace mismatch require http://CustomerServiceWs found http://customer.webservices.temenos.com
        at org.apache.axis2.rpc.receivers.RPCUtil.invokeServiceClass(RPCUtil.java:177)
        at org.apache.axis2.rpc.receivers.RPCMessageReceiver.invokeBusinessLogic(RPCMessageReceiver.java:102)
        at org.apache.axis2.receivers.AbstractInOutMessageReceiver.invokeBusinessLogic(AbstractInOutMessageReceiver.java:40)
        at org.apache.axis2.receivers.AbstractMessageReceiver.receive(AbstractMessageReceiver.java:114)
        at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:173)
        at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:173)
        at org.apache.axis2.transport.http.AxisServlet.doPost(AxisServlet.java:144)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
        at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
        at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
        at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
        at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
        at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
        at java.lang.Thread.run(Thread.java:619)

I used following command to generate my WSDL file from Class File;
java2wsdl.bat -o C:\Temp -tn http://CustomerServiceWs -cn com.temenos.webservices.customer.CustomerServiceWS

could you please help me sort out this problem or suggest a better way to approach this problem.
Thanks,
--
Sjunejo

A: Make Sure the namespace in your schema matches with the NameSpace of the WSDL, to frank enough i do not even like the idea of using Axis2 because of so many problems it has.. anyways try matching the namespace of your xsd with that of your wsdl and make sure all your names of the request and response are similar.


text:
Q: how does audio-video streaming server work and it's requirements I am a php mysql developer ... just an (below) average. and i am interested in the way television and radio are broadcasted over internet live. i want to know how it works and and what are its requirements. i must admit that i am a complete layman but i expect it do by next half month or year or so.

A: there're a couple of network protocols for multimedia streaming. most popular atm are RTSP and RTMP. typically you need to setup streaming server that takes audio/video from some source and streams to all connected clients. popular streaming servers are Adobe Flash Media Server, Wowza Media Server and others.
Streaming is done over TCP or UDP, depending on your requirements. TCP guarantees that no packets are lost but they can be significantly delayed. This can be smoothed by large enough jitter buffer. Streaming over TCP is often used for one-way streaming from server to client when that delay can be tolerated. UDP is used for "live" streaming, especially in chat/conference, when you cannot tolerate several seconds delay.
RTSP is open standard. You can receive and play RTSP streaming by VLC player (free). RTSP provides a "media session setup" and goes over TCP. Actual streaming is done by RTP/RTCP protocols over UDP or "interleaved" with RTSP packets over TCP.
RTMP is proprietary protocol of Adobe.


text:
Q: dumpsys cpuinfo in Android: Interpreting the results of this command I'm looking at the out of the following command "adb shell dumpsys cpuinfo" where I want to know if these reported values are averages over previous time ?
    D:\Android_Dev\Android_sdk\platform-tools>adb shell dumpsys cpuinfo
Load: 4.03 / 3.43 / 2.44
CPU usage from 23770ms to 16630ms ago:
  58% 1844/logd: 58% user + 0% kernel / faults: 3 minor
  50% 3895/com.google.android.wearable.app:ui: 41% user + 9.3% kernel / faults: 1798 minor
  26% 1864/adbd: 2.8% user + 23% kernel / faults: 1243 minor
  22% 4880/logcat: 7.8% user + 15% kernel
  9.7% 7834/kworker/0:2: 0% user + 9.7% kernel
  4.9% 2198/system_server: 2.6% user + 2.2% kernel / faults: 76 minor

My questions are as follows:

*

*what does faults represent here ?

*what does these percentage values represent because they don't add up to 100 ?

*are these percentage values averages of the respective processes such as as 58% for logd?

*CPU usage from 23770ms to 16630ms ago: what does this mean ? does it mean that these values are the average from last 23 to 16 seconds ?

A: adb shell dumpsys cpuinfo

shows info from /proc/stat and /proc/(pid)/stat

1.what does faults represent here ?

Page faults.
"minor" for minor faults.
from ProcessCpuTracker.java
collectStats(...) {
  ...
  final long[] procStats = mProcessStatsData;
  if (!Process.readProcFile(st.statFile.toString(),
  PROCESS_STATS_FORMAT, null, procStats, null)) {
  continue;
  }
  ...
  final long minfaults = procStats[PROCESS_STAT_MINOR_FAULTS];
  final long majfaults = procStats[PROCESS_STAT_MAJOR_FAULTS];
}

private static final int[] PROCESS_STATS_FORMAT = new int[] {
  ...
  PROC_SPACE_TERM|PROC_OUT_LONG,                  // 10: minor faults
  ...
  PROC_SPACE_TERM|PROC_OUT_LONG,                  // 12: major faults
  ...
};

They are /proc/(pid)/stat data[9] and data[11].

2.they don't add up to 100

http://blog.scoutapp.com/articles/2009/07/31/understanding-load-averages
(Linked page from interpreting dumpsys cpuinfo)
With multi-processor system, sum can be more than 100%.

3.are these percentage values averages of the respective processes

from ProcessCpuTracker.java
printProcessCPU(...) {
  ...
  printRatio(pw, user+system+iowait+irq+softIrq, totalTime);
  ...
}

2nd parameter(user+...) / 3rd parameter(totalTime) is printed.

4.CPU usage from 23770ms to 16630ms ago

Times are based on times when stat data cached by ProcessCpuTracker is updated.
from ProcessCpuTracker.java
update() {
  final long nowUptime = SystemClock.uptimeMillis();
  ...
  mLastSampleTime = mCurrentSampleTime;
  mCurrentSampleTime = nowUptime;
  ...
}

[Related sources]
https://android.googlesource.com/platform/frameworks/native/+/master/cmds/dumpsys/dumpsys.cpp
main() => service->dump()
https://github.com/android/platform_frameworks_base/blob/master/services/core/java/com/android/server/am/ActivityManagerService.java
CpuBinder.dump() is called
mProcessCpuThread updates stat cache. (updateCpuStatsNow() is called)
https://github.com/android/platform_frameworks_base/blob/master/core/java/com/android/internal/os/ProcessCpuTracker.java
printCurrentLoad() prints CPU load
printCurrentState() prints per process stats


text:
Q: When should I start learning Set Theory? I started to learn a few disciplines on my own over the break after my first year in college and one of them was Real Analysis. In the process I came across many issues in Analysis texts concerning the foundations of Mathematics. One issue was the construction of the real numbers and the other being the cardinality of sets. I read Landau's Foundations of Analysis and the first bit of Richard Dedekind's Essays on the Theory of Numbers to console myself about what I thought were naive developments in the first chapters of Analysis texts. For the life of me I still can't explain how numbers are constructed but at least after a first reading of these texts I now know that they can be constructed. And I'm happy.
Now, I was told that the best text for a first glimpse at formal set theory was Naive Set Theory by Paul Halmos. But I found that I was spending too much time on the foundations and the preface on this book hinted it was best to just keep learning your stuff and fill your gaps later so I abandoned Halmos after the first two chapters and have been following Analysis through The Elements Real Analysis by Robert Bartle.
BUT:
I posted this question today and it made me realise how important a decent footing on set theory actually is. Most of the answers are about axiomatic set theory and although some skimming on google helps me get a slight idea, I do not have a firm grasp on the subject. My question is,

I need some advice as to whether a deviation into learning Set Theory
  at this point is feasible? When should I, in general, pursue the foundations? Should I at all?

My journey so far in Mathematics is as follows.
I have just started my second year. Have taken courses on first year calculus, multi-variable calculus, Differential Equations, introductory Graph theory, a computational course on matrices, some elementary number theory and a tinge of group theory.
I will be taking another Calculus course, a Linear ALgebra course, another on Differential Equations and one on Linear Programming this semester.
I have also taken a small course on Naive Set Theory and Combinotrics in my first semester. But this just introduced set identities (Associative Laws, Idempotent Laws etc. ) and motivated the use of them in proving relationships between sets. No cardinality or anything beyond.
I am also in the middle of a self-learning project on Analysis and Elementary Number Theory.
Would love some advice. And any would be greatly appreciated.

A: Set theory is absolutely necessary to learn more advanced mathematics.  It is needed for just about every branch of mathematics, if not every branch.  In my opinion, it would be a good idea to start learning some basic set theory notions at least.  It will definitely show up in classes like real analysis, complex analysis, and probability just to name a few.  Most likely, those undergrad courses will introduce you to some of the theory but to start learning on your own definitely won't hurt.  There are numerous resources out there available for learning by yourself.  Good luck!


text:
Q: Xcode 11 not released simultaneously with iOS 13? Yesterday I installed the public release iOS 13 on my development iPhone, assuming that Xcode 11 was released as well.
This morning, I wanted to install the latest Xcode, only to find out that it was not released yet! So right now I cannot compile/test on my iOS 13 device (without switching over to Xcode beta).
I cannot remember that this has happened in the past. Again, I'm not interested in switching to Xcode beta/GM on this machine, as I'm in production environment. Does anyone has any insights on when Xcode 11 public release will be available? Was there ever a delay in Xcode release after public iOS release?

A: Public Xcode may come out later on Sept. 30th together with iPadOS (not confirmed ofc) since devs have a GM Seed 2 already and it seems to be pretty stable. So that's my guess..
Edit: Xcode 11 was released for the Mac AppStore one day after iOS 13, on Sept. 20th 2019
To the second part, about previous releases:

*

*(2018) iOS 11: September 17; Xcode 9.0: September 12

*(2014) iOS 8: September 17; Xcode 6.0: September 09

*(2013) iOS 7: September 18; Xcode 5.0: September 16

However, you're right in recent years Apple mostly released iOS and Xcode at the same time.. so it shouldn't take too long.
Hope this was helpful :)


text:
Q: How to create a two column list with random item heights I want to create a layout like this:

It is a ViewGroup with two columns. Item widths are fixed but each has random height.
How can I implement this? Should I use GridView, ListView, or ...?


text:
Q: MVC - TextAreaFor does not display box I have multiple projects in which this happens. I specify an TextBoxFor and I don't get a display of the text area box (i.e. no borders). I just get space of a row that looks like it is for the TextArea and if I hit return I get another. But no borders. This can't be the default. This happens for text boxes as well. Can anyone tell me why?
I have a ViewModel:
// Text Area - Whole Markup
        [Display(Name = "HTML Markup Code: ")]
        public string HTMLMarkupCode { get; set; }

And the markup:
<div class="col-xs-9">
                @Html.LabelFor(m =>  m.HTMLMarkupCode)
                @Html.TextAreaFor(m => m.HTMLMarkupCode)
            </div>

A: Sounds like a CSS issue. Using the Chrome developer tools (F12) you can inspect the element and you can look at the computed CSS for the element. Then you should see that the border is probably set to 0 or none. You can then look under the Styles tab to figure out which CSS file and which line of the CSS has removed the borders.
Have a look: https://developer.chrome.com/devtools
This is the quickest way to definitely find out what the issue is, otherwise you could go with a long trial and error approach, but you've got the tools to avoid it :)


text:
Q: Migration error(django.db.utils.OperationalError) I'm trying to migrate my custom user model and I run makemigrations command to make migrations for new models. But when I run migrate command it throws this error :

conn = _connect(dsn, connection_factory=connection_factory,
**kwasync) django.db.utils.OperationalError

Trace back:
    (venv_ruling) C:\Users\enosh\venv_ruling\ruling>python manage.py migrate
    Traceback (most recent call last):
      File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection
        self.connect()
      File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\asyncio.py", line 26, in inner
        return func(*args, **kwargs)
      File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 200, in connect
        self.connection = self.get_new_connection(conn_params)
      File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\asyncio.py", line 26, in inner
        return func(*args, **kwargs)
      File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection
        connection = Database.connect(**conn_params)
      File "C:\Users\enosh\venv_ruling\lib\site-packages\psycopg2\__init__.py", line 127, in connect
        conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
    psycopg2.OperationalError
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\enosh\venv_ruling\ruling\manage.py", line 22, in <module>
    main()
  File "C:\Users\enosh\venv_ruling\ruling\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\base.py", line 89, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle
    self.check(databases=[database])
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\management\base.py", line 419, in check
    all_issues = checks.run_checks(
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\core\checks\model_checks.py", line 34, in check_all_models
    errors.extend(model.check(**kwargs))
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\models\base.py", line 1290, in check
    *cls._check_indexes(databases),
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\models\base.py", line 1680, in _check_indexes
    connection.features.supports_covering_indexes or
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\postgresql\features.py", line 93, in is_postgresql_11
    return self.connection.pg_version >= 110000
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\postgresql\base.py", line 329, in pg_version
    with self.temporary_connection():
  File "C:\Users\enosh\AppData\Local\Programs\Python\Python39\lib\contextlib.py", line 117, in __enter__
    return next(self.gen)
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 603, in temporary_connection
    with self.cursor() as cursor:
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 259, in cursor
    return self._cursor()
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 235, in _cursor
    self.ensure_connection()
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection
    self.connect()
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection
    self.connect()
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\base\base.py", line 200, in connect
    self.connection = self.get_new_connection(conn_params)
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\utils\asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "C:\Users\enosh\venv_ruling\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection
    connection = Database.connect(**conn_params)
  File "C:\Users\enosh\venv_ruling\lib\site-packages\psycopg2\__init__.py", line 127, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError

models.py
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    """extend usermodel"""

    class Meta:
        verbose_name_plural = 'CustomUser'

settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'rulings',
        'USER': 'xxxxxxx',
        'PASSWORD': 'xxxxxxx',
        'HOST': '',
        'PORT': '',
    }
}

AUTH_USER_MODEL = 'accounts.CustomUser'

The postgresql's database is empty.(ver.12.6)
I just mentioned user model and settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you

A: I don't know if you have left the port empty for the question or it is actually empty, but try this in the console and see if the connection is successful.
conn=psycopg2.connect(database="rulings", user="xxx", password="xxx",port=5432)

Also this might not be your port(it is the default but yours might be changed) check your port number  \conninfo in the postgres shell. And let me know if it helps.

A: You have to check for the host_ip or the port number in the settings.py file of django.


text:
Q: Angular 12 to 14 upgrade error; __webpack_require__.h is not a function + angular material theming after upgrading angular 12  to 14  I'm getting this error at runtime in browser.
UI loads correctly, nothing is broken, it's just this error pops up in browser console before page loads.
Uncaught TypeError: __webpack_require__.h is not a function at 1211 (index.js:43:58) at __webpack_require__ (bootstrap:19:1) at __webpack_exec__ (auth-theming.scss?8317:1:1) at auth-theming.scss?8317:1:1 at webpackJsonpCallback (jsonp chunk loading:34:1) at styles.js:1:81
I'm using angular material and have custom theme as well.
I still get this error, replacing angular.json   build > options > styles
"styles": ["src/theme/auth-theme.scss", "src/styles.scss"],
with
"styles": [],
I've been googling for couple of days now... any help appreciated.


text:
Q: jQuery Validation with ASP.NET C# Web Forms I'm having a bit of an awkward problem with jquery validation (which is brilliant) and asp.net web forms. I presume its an issue with how the forms are used in this framework but anyway here's the issue.

*

*I have a page which has a number of fields for an employee to fill out, when he/she submits/saves the record (asp.net button control) the validation rules trigger and display relative errors if present (seems to work, rules need work but that irrelevant for the minute).

*The validations trigger correctly and list at the bottom of the screen, however if i click anywhere on the screen the jQuery seems to fire again and displays only the first error (same with any sort of key press/minimization of the screen). When that error is corrected the next in the list appears and so on...

Note:
My form is in the master page which has a content placeholder within it and the .net version is 3.5 (unfortunately limited by the servers I'm working on).
If anybody could help, that would be great :D.
    $(document).ready(function () {
        $('.txt')
        .focus(function () {
            $('.txt').removeClass('focused');
            $(this).addClass('focused');
        })
        .blur(function () {
            $(this).removeClass('focused');
        });

        //Fire validation events
        $("#aspnetForm").validate({
            //Setting validations rules like, Required, Minimum or Maximum Length, Data Type etc.
            rules:
            {
                //Set name of tag to validate: Name = UniqueID
                <%= txtPointCode.UniqueID %> : { required: true, minlength: 5, maxlength: 10 },
                <%= txtPointName.UniqueID %> : { required: true, minlength: 5, maxlength: 10 },
                <%= txtPointLocalName.UniqueID %> : { required: true, minlength: 5, maxlength: 10 },
                <%= txtPortCode.UniqueID %> : { required: true, minlength: 5, maxlength: 10 },
                <%= txtCountryCode.UniqueID %> : { required: true, minlength: 5, maxlength: 10 },
                <%= txtCountryName.UniqueID %> : { required: true, minlength: 5, maxlength: 10 },
                <%= txtAreaName.UniqueID %> : { required: true, minlength: 5, maxlength: 10 },
                <%= txtRegionName.UniqueID %> : { required: true, minlength: 5, maxlength: 10 },
                <%= txtContinentName.UniqueID %> : { required: true, minlength: 5, maxlength: 10 }
            },
            //Contextual error messages for each selected field
            messages:
            {
                <%= txtPointCode.UniqueID %> : "This field cannot be empty, please enter between 5 - 10 characters.",
                <%= txtPointName.UniqueID %> : "This field cannot be empty, please enter between 5 - 10 characters.",
                <%= txtPointLocalName.UniqueID %> : "This field cannot be empty, please enter between 5 - 10 characters.",
                <%= txtPortCode.UniqueID %> : "This field cannot be empty, please enter between 5 - 10 characters.",
                <%= txtCountryCode.UniqueID %> : "This field cannot be empty, please enter between 5 - 10 characters.",
                <%= txtCountryName.UniqueID %> : "This field cannot be empty, please enter between 5 - 10 characters.",
                <%= txtAreaName.UniqueID %> : "This field cannot be empty, please enter between 5 - 10 characters.",
                <%= txtRegionName.UniqueID %> : "This field cannot be empty, please enter between 5 - 10 characters.",
                <%= txtContinentName.UniqueID %> : "This field cannot be empty, please enter between 5 - 10 characters."
            },

            //A custom message display handler. Gets the map of errors as the first argument and and array of errors as the second,
            //called in the context of the validator object.
            showErrors: function (errorMap, errorList)
            {
                var messages = "";
                var errorCount = 0;

                //Error builder
                $.each(errorList, function (index, value) {
                    var id = $(value.element).attr('id');
                    var elementName = $(value.element).attr('name').split('txt'); //Strip out UniqueID obfuscation

                    messages += "" + (index + 1) + ". | [" + elementName[1] + "] | " + value.message + "
";
                    errorCount++;
                });

                messages = "

Please correct the following " + errorCount + " errors:

" + messages + "
";

                //Display error summary with slide animation
                $('#summary-validation').html(messages);
                $('#summary-validation').show("fast");
            },

            //If all validations are successfully validate then execute submitHandler function
            submitHandler: function ()
            {
                $('#summary-validation').empty();
                //alert("All fields are valid!");
                $("#aspnetForm").submit();
            },
            onkeyup: false, //Stops validation refresh on occurances of certain key presses
            onfocusout: false //Stops validation refresh when element loses focus
        });
        //-------------------------------------------------------------------------------
    });
    //If validation errors are occured in any field, it will display field name with link, clicking on link it will set focus of perticular field.
    function setFocus(ele)
    {
        document.getElementById(ele).focus();
        //$(ele).focus();
    }


text:
Q: How to sort contours from top to bottom : Opencv , Android I have found the contour but the problem is that the findcontours() returns contours in random order like at contour(0) it shows some sontour from middle of the page. How can I sort them vertically? From top to bottom and then left to right? Given the image below I connected the components horizontally and connected every MCQ with their choices and then applied findcontours() and Now I want to sort them in an order that they should be retrieved sequentially

A: I have the same problem and use the sort method of java.
//sort by y coordinates using the topleft point of every contour's bounding box
    Collections.sort(contourList, new Comparator<MatOfPoint>() {
        @Override
        public int compare(MatOfPoint o1, MatOfPoint o2) {
            Rect rect1 = Imgproc.boundingRect(o1);
            Rect rect2 = Imgproc.boundingRect(o2);
            int result = Double.compare(rect1.tl().y, rect2.tl().y);
            return result;
        }
    } );

//sort by x coordinates
Collections.sort(contourList, new Comparator<MatOfPoint>() {
        @Override
        public int compare(MatOfPoint o1, MatOfPoint o2) {
            Rect rect1 = Imgproc.boundingRect(o1);
            Rect rect2 = Imgproc.boundingRect(o2);
            int result = 0;
            double total = rect1.tl().y/rect2.tl().y;
            if (total>=0.9 && total<=1.4 ){
                result = Double.compare(rect1.tl().x, rect2.tl().x);
            }
            return result;
        }
    });

A: You have the function boundingRect: With that you can find the topleft point of a bounding rectangle around the points. Then you can define a sorting function that orders the contours based on the location of this point for each contour.

A: @user9876747 solution works great for small contour list but throws the below exception for larger contour list.
java.lang.IllegalArgumentException: Comparison method violates its general contract!

So i was able to tweak the solution to below and it works fine for large contour lists.
 Collections.sort(contours, new Comparator<MatOfPoint>() {
        public int compare(MatOfPoint o1, MatOfPoint o2) {
            org.opencv.core.Rect rect1 = Imgproc.boundingRect(o1);
            org.opencv.core.Rect rect2 = Imgproc.boundingRect(o2);

            int result = Double.compare(rect1.br().y, rect2.br().y);
            double total = rect1.br().y / rect2.br().y;

            if (total < 1.1 && total > 1/1.1) {
                result = Double.compare(rect1.tl().x, rect2.tl().x);
            }
            return result;
        }
    });


text:
Q: Azure DevOps Server Repos Is there a way to restrict users from pushing new branches?
Our management wants the Repo admin to control what branches get created, they don't want devs pushing branches to a repo from their desktops in order to create them.
Is there a way to lock branch creation/pushes?  I know you can lock an EXISTING branch, but how about a net new branch a dev pushes to ADS?

A:
Is there a way to lock branch creation/pushes?

To limit users to create new branches, you can set the permission of the users/group.
You can navigate to Project Settings -> Repositories-> Select Repository -> Security and set the permission: Create branch as Deny.
For example:

Then the users will have no access to create/push branch via UI or Git commnad.


text:
Q: KeyError: "Couldn't delete link (Can't delete self)" I'm trying to delete a dataset in a HDF5 file. To be specific, i'm trying to delete the optimizer layer from a keras deep learning model which i have previously trained and saved.
The code is as follows
f = h5py.File('model.h5', 'r+')
del f['optimizer_weights']
f.close()

And the error is
KeyError: "Couldn't delete link (Can't delete self)

Error message in detail
    del f['optimizer_weights']
  File "h5py\_objects.pyx", line 54, in h5py._objects.with_phil.wrapper (D:\Build\h5py\h5py-2.7.0\h5py\_objects.c:2853)
  File "h5py\_objects.pyx", line 55, in h5py._objects.with_phil.wrapper (D:\Build\h5py\h5py-2.7.0\h5py\_objects.c:2811)
  File "C:\Users\Anaconda3\envs\tensorflow-keras-gpu\lib\site-packages\h5py\_hl\group.py", line 297, in __delitem__
    self.id.unlink(self._e(name))
  File "h5py\_objects.pyx", line 54, in h5py._objects.with_phil.wrapper (D:\Build\h5py\h5py-2.7.0\h5py\_objects.c:2853)
  File "h5py\_objects.pyx", line 55, in h5py._objects.with_phil.wrapper (D:\Build\h5py\h5py-2.7.0\h5py\_objects.c:2811)
  File "h5py\h5g.pyx", line 294, in h5py.h5g.GroupID.unlink (D:\Build\h5py\h5py-2.7.0\h5py\h5g.c:4179)
KeyError: "Couldn't delete link (Can't delete self)"

Any suggestions on how to fix this ??
Thanks!

A: Are you sure the dataset actually made it in there? I've gotten this wrong looking error when trying to delete a non-existent dataset.
def printname(name):
    print(name)

f.visit(printname)

# list of datasets, should contain 'dataset_name'

In code you unfortunately need to include a check for existence every time prior to deleting. To 'overwrite' a possibly already existing dataset:
with h5py.File('/path/to/h5', 'a') as f:
    if f.get('dataset_name'):
        del f['dataset_name']
    f['dataset_name'] = 'new value'

A: Quite an old question, but try putting the file in write or append mode
f = h5py.File('model.h5', 'a')


text:
Q: Dynamically select all data when creating a pivot table I have created a VBA macro to create a pivot table on the fly. The source data changes everyday, so there are different number of records each day. In the macro the number of records to select is hard coded. Is there a way to select all the data in the source table each day - instead of a predefined number of records
Application.DisplayAlerts = False
Call DeleteAllPivotTablesInWorkbook
Sheets("ALL").Select
If CheckSheet("AllSummary") Then
    Sheets("AllSummary").Delete
End If
Sheets.Add.Name = "AllSummary"
Application.DisplayAlerts = True
Sheets("AllSummary").Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
    "All!R1C1:R26885C47", Version:=xlPivotTableVersion10).CreatePivotTable _
    TableDestination:="AllSummary!R3C1", TableName:="PivotTable3", DefaultVersion _
    :=xlPivotTableVersion10
Sheets("AllSummary").Select
Cells(3, 1).Select

As you can see the sourcdata value is hard coded. How can I select all the data regardless of the number of records?

A: you can also use
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
    "All!" & Sheets("All").Range("A1").CurrentRegion.Address(ReferenceStyle:=xlR1C1), Version:=xlPivotTableVersion10).CreatePivotTable _
    TableDestination:="AllSummary!R3C1", TableName:="PivotTable3", DefaultVersion _
    :=xlPivotTableVersion10

A: Or if you keep your data on a separate sheet than your pivot table destination you can just use a last row/column/cell type selection to select all the relevant data on your data sheet:
Sub Excel2010Syntax()
    Sheets("Sheet1").Select
    ActiveCell.SpecialCells(xlLastCell).Select
    Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        "Sheet1!R1C1:R16C4", Version:=xlPivotTableVersion14).CreatePivotTable _
        TableDestination:="Sheet2!R20C1", TableName:="PivotTable4", DefaultVersion _
        :=xlPivotTableVersion14
    Sheets("Sheet2").Select
    Cells(1, 1).Select
End Sub

This was recorded in excel 2010 ( I think you have an earlier version ) but you get the idea. Just have a dedicated data sheet and then select all the data on it to create your pivot table.
EDIT:
Or just run this macro:
Sub Answer()
Dim wb As Workbook
Dim ws As Worksheet
Dim rng1 As Range
Set wb = ActiveWorkbook
Set ws = wb.Sheets("All")
Set rng1 = ws.Cells.Find("*", ws.[a1], xlFormulas, , , xlPrevious)
Sheets("AllSummary").Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
    "All!R1C1:R" & CStr(rng1.Row) & "C" & CStr(rng1.Column), Version:=xlPivotTableVersion10).CreatePivotTable _
    TableDestination:="AllSummary!R3C1", TableName:="PivotTable3", DefaultVersion _
    :=xlPivotTableVersion10
Sheets("AllSummary").Select
Cells(3, 1).Select
End Sub

A: First, consider if you should be recreating the pivot table. If you just want to change where the pivot table points to, you can do that without deleting and creating it.
This sub finds the first pivot table on the AllSummary sheet and changes its PivotCache's SourceData property. The SourceData property is changed using the CurrentRegion property of the range object. When you're dealing with pivot tables, you usually have pretty well structured data and if that's the case, CurrentRegion will return the range that includes any new rows or columns added.
The Address property uses R1C1 because that's what SourceData expects and also uses True in the External argument to get the sheet's name in the address.
Sub AdjustPtSource()

    Dim pt As PivotTable

    With ActiveWorkbook
        Set pt = .Worksheets("AllSummary").PivotTables(1)
        pt.PivotCache.SourceData = .Worksheets("All").Range("A1").CurrentRegion.Address(, , xlR1C1, True)
    End With

End Sub

If you must delete and recreate, you can still use CurrentRegion to get the whole contiguous range.
Sub MakePT()

    Dim shSum As Worksheet
    Dim shAll As Worksheet
    Dim pc As PivotCache
    Dim pt As PivotTable

    Const sWSSUMMARY As String = "AllSummary"

    DeleteAllPivotTablesInWorkbook
    Set shAll = ActiveWorkbook.Worksheets("All")

    If CheckSheet(sWSSUMMARY) Then
        Sheets(sWSSUMMARY).Delete
    End If

    Set shSum = ThisWorkbook.Worksheets.Add
    shSum.Name = sWSSUMMARY

    Set pc = ActiveWorkbook.PivotCaches.Create(xlDatabase, shAll.Range("A1").CurrentRegion)
    Set pt = pc.CreatePivotTable(shSum.Cells(3, 1))

End Sub


text:
Q: Copy local dictionary into global dictionary I am having a problem where I create a dictionary in a method and then try to make a field equal to the dictionary!
So:
var theJson : NSDictionary!

func someMethod()
{
   if let theDictionary = valueFromGoogleDirections as? NSDictionary
   theJson = theDictionary
}

func fieldTest()
{
   print(theJson)
}

after calling someMethod and then fieldTest the fieldTest method always prints "{ }" which I figure means it is an empty dictionary. What is going on? I know that theDictionary is getting values because I am able to use its values from within the someMethod method.

A: try this:
theJson = theDictionary.copy()


text:
Q: How to get only values from a list of dictionary and put them in a list again in Python? I am running a query in the db and getting the output in a list of dict format. Each list of dict is associated with a id column.
Example:
[{'v_key':50},{'v_key':60}] # say here the id is 1
[{'r_key':10}] # here the id is 2 (the output go on like this and key in dict may not be same)

so to loop thru the output of the query i need something like below:
[50,60] # for id 1.(The values to be in a list and this will go on for all the id's)

A: [v for dct in lst for v in dct.values()]. This will have undefined order if dicts have more than one value.

A: If query_result = [{'v_key':50},{'v_key':60}], then:
[d['v_key'] for d in query_result]  # [50, 60]


text:
Q: How can I use paste add predictors into a penalized regression argument? Instead of specifying the predictors as regression arguments, I would like to just pass on a string and change it into the right syntax before it is used for penalized regression. It has been explained in Loop function to add large numbers of predictors in regression function or How to use paste to get formula how this can be done for lm but it does not work for penalized regression.
Here is my code:
df<-data.frame(date=seq(as.Date("2018-01-01"), as.Date("2018-10-01"), by="days"))
df$month<-format(as.Date(df$date), "%m")
df$y<-runif(nrow(df),1,100)
df$time<- -floor(nrow(df)/2):(ceiling(nrow(df)/2)-1)/1000
df$month<-as.factor(df$month)

yname<-"y"
xnames<-colnames(training)
xnames<-xnames[-which(xnames==yname)]
xnames<-xnames[-which(xnames=="date")]
yname<-paste(yname,",")
formula<-paste(yname,"~",paste(xnames,collapse="+"))

ens<-penalized(formula, ~ 0,lambda1=1, lambda2=1, positive =TRUE, data=training)

I tried using as.formula for the formula but it does not work with the comma. It is all working fine though if I put the variable names in manually and it is working for lm but not for penalized. Any ideas?
Please note that I have edited the question to make it more specific for penalized.

A: You are almost there, you just need to use the 'paste' function:
string <- paste("month", "time", sep = " + ")

I am not familiar with the 'penalized' function. However, if you are having further issues you might need to paste the entire formula. For example, for a linear regression, you would need to use something like:
string_variables <- paste("month", "time", sep = " + ")
string_formula <- paste("y ~ ", string_variables ,sep = " ")

# simple linear regression usage
ens <- lm(formula = string_formula, data=training)
summary(ens)


text:
Q: Why is random forest inconsistent in text mining? Earlier I've used SVM (rbf kernel) in text mining with success, and after that for similar text mining work with long texts I've used random forest with success as well. However in a recent kaggle competition when I used random forest with a word vector (after doing SVD and reducing the dimension to 200-400), the result was never close to the svm in terms of RMSE. Any idea why random forest is inconsistent in different text mining but SVM does it more consistently?

A: I have used random forest successfully in text mining applications, although SVM with linear kernel, for instance, had reached superior classification accuracy. SVM is a good start when you search for good classification algorithms without prior understanding.
Despite random forest runs fast and is suitable for many applications, its results rely on which parameter values you choose. The same happens for major algorithms.
I suggest you to Start doing grid search over the following randomForest parameters to check if it changes your results: number of trees, number of features, maximum depth of your trees. Analyze the results according to parameter variation. You can combine this experiment with cross validation or such.
You can perform the same for other classifiers.
Is your data normalized? Do you apply standardization or something else worth mentioning?


text:
Q: Unable to parse rectangle bracket I am having issues while implementing xpath logic. I am trying to parse if I get my result as below example:
//html:h1/span[1]

I want to put :html before this string whenever rectangle bracket happens, like below as expected output:
//html:h1/html:span[1]

If my example is:
//html:h1/span/div

Here There is no rectangle bracket, so I want to make my string as it is.
Here is another example:
//html:div/span[5]/div/span

I want expected output like below example:
//html:div/html:span[5]/div/span

I already tried googling and parsing via regex but unable to find the exact match solution.
EDITED:
Just to clear, It is not just span tag. It could be anything like a, p, or others html tag
Some scenario:
//html:div[@id='ins_storybody']/p[2]
Expected output should be:
//html:div[@id='ins_storybody']/html:p[2]
Here is another scenario:
//html:div[@id='ins_storybody']/p[2]/div/span/li[@id='ins_storybody']
Expected output:
//html:div[@id='ins_storybody']/html:p[2]/div/span/li[@id='ins_storybody']
I figured out a way that using regex: match(/\[.@?\]/g) could be possible but unable to get the attached string with rectangle bracket so that I could replace it. Any suggestions?

A: I'm not sure exactly what you want to achieve, but the following code checks if there is any [ anywhere in the input string, and if that is the case, it inserts html: right before span. Please note that this will not work if there is no span in the input string.

str = '//html:h1/span[1]';

q = str.includes('[');

if (q) {
 i = str.indexOf('span');
 newstr = str.slice(0,i) + 'html:' + str.slice(i);
} else {
 newstr = str;
}

console.log(newstr)


text:
Q: Template hierarchy for post format in a custom post type? I'm trying to override the post format taxonomy/archive page for videos and images for posts of type "gallery" (for example), but I'm not sure if I'm doing the right thing.
I've gotten the page to show up correctly with a URL like this
/gallery?post_format=video , but I can't override the template for it, I've only been able to get taxonomy-post-format_post-format-video to work, but I don't want to override the templates for that, I just want to do it for those under the custom post type gallery.
I'm really not sure if I should be using categories/post types for this, if it will be easier. My goal is just to have a gallery page with just videos, and another gallery page of just images, I wanted to make use of WP's inbuilt post formats, but I'm not sure how to move on from here.

A: Well, I figured it isn't entirely possible or correct to force WP to do something it wasn't prepared to do, so I set up a taxonomy for my custom post type and rewrote the slugs so I could get /gallery/videos and gallery/images as archive pages that I can modify.


text:
Q: Would you mind to explain the code in the forum? import Control.Applicative
import Control.Arrow

filter ((&&) <$> (>2) <*> (<7)) [1..10]
filter ((>2) &&& (<7) >>> uncurry (&&)) [1..10]

Both get the same result! However, it is VERY difficult for me to understand. Could someone here explain it in detail?

A: Let's start with the second, which is simpler. We have two mysterious operators here, with the following types:
(&&&) :: Arrow a => a b c -> a b c' -> a b (c, c')
(>>>) :: Category cat => cat a b -> cat b c -> cat a c

The Arrow and Category type classes are mostly about things that behave like functions, which of course includes functions themselves, and both instances here are just plain (->). So, rewriting the types to use that:
(&&&) :: (b -> c) -> (b -> c') -> (b -> (c, c'))
(>>>) :: (a -> b) -> (b -> c) -> (a -> c)

The second has a very similar type to (.), the familiar function composition operator; in fact, they're the same, just with arguments swapped. The first is more unfamiliar, but the types again tell you all you need to know--it takes two functions, both taking an argument of a common type, and produces a single function that gives the results from both combined into a tuple.
So, the expression (>2) &&& (<7) takes a single number and produces a pair of Bool values based on the comparisons. The result of this is then fed into uncurry (&&), which just takes a pair of Bools and ANDs them together. The resulting predicate is used to filter the list in the usual manner.

The first one is more cryptic. We have two mysterious operators, again, with the following types:
(<$>) :: Functor f => (a -> b) -> f a -> f b
(<*>) :: Applicative f => f (a -> b) -> f a -> f b

Observe that the second argument of (<$>) in this case is (>2), which has type (Ord a, Num a) => a -> Bool, while the type of (<$>)'s argument has type f a. How are these compatible?
The answer is that, just as we could substitute (->) for a and cat in the earlier type signatures, we can think of a -> Bool as (->) a Bool, and substitute ((->) a) for the f. So, rewriting the types, using ((->) t) instead to avoid clashing with the other type variable a:
(<$>) :: (a -> b) -> ((->) t) a -> ((->) t) b
(<*>) :: ((->) t) (a -> b) -> ((->) t) a -> ((->) t) b

Now, putting things back in normal infix form:
(<$>) :: (a -> b) -> (t -> a) -> (t -> b)
(<*>) :: (t -> (a -> b)) -> (t -> a) -> (t -> b)

The first turns out to be function composition, as you can observe from the types. The second is more complicated, but once more the types tell you what you need--it takes two functions with an argument of a common type, one producing a function, the other producing an argument to pass to the function. In other words, something like \f g x -> f x (g x). (This function also happens to be known as the S combinator in combinatory logic, a subject explored extensively by the logician Haskell Curry, whose name no doubt seems strangely familiar!)
The combination of (<$>) and (<*>) sort of "extends" what (<$>) alone does, which in this case means taking a function with two arguments, two functions with a common argument type, applying a single value to the latter two, then applying the first function to the two results. So ((&&) <$> (>2) <*> (<7)) x simplifies to (&&) ((>2) x) ((<7) x), or using normal infix style, x > 2 && x < 7. As before, the compound expression is used to filter the list in the usual manner.

Also, note that while both functions are obfuscated to some degree, once you get used to the operators used, they're actually quite readable. The first abstracts over a compound expression doing multiple things to a single argument, while the second is a generalized form of the standard "pipeline" style of stringing things together with function composition.
Personally I actually find the first one perfectly readable. But I don't expect most people to agree!


text:
Q: How do I add an playable audio file to a TableListBox playlist (JUCE C++) I want to click a button to open the file browser, open an audio file(mp3) which gets added to a table. I want it to be so that you can have multiple audio files available on the playlist table. I have some of it figured out, but I'm trying to create an event listener where I click a button, 'Add a track'. How can I populate my table or 'playlist' with the audio file? I have a file chooser already implemented that loads the file to be played and a play button that play a loaded file, I'm just not sure how to add it to the table? Any help is appreciated.
My code so far goes something along the lines of:
Array<File> trackTitles;

...
void PlaylistComponent::buttonClicked(Button* button)
{

    if (button == &loadButton)
    {
        DBG(" MainComponent::buttonClicked: loadButton");
        FileChooser chooser{ "Select a file" };
        if (chooser.browseForFileToOpen())
        {
            trackTitles.add(File{ chooser.getResult() });
            player->loadURL(File{ chooser.getResult() });
        }

    }
}

A: do you need to add a button to the table? here's an example
.h
    class PlaylistComponent : public juce::Component,
                              public TableListBoxModel,
                              public Button::Listener
    {
    .....
    Component *refreshComponentForCell(int rowNumber, int columnId, bool , Component *existingComponentToUpdate) override;
    void paintCell(Graphics &, int rowNumber, int columnId, int width, int height, bool ) override;
    void buttonClicked(Button *button) override;
    void setTracks(Array<File> tracksFile);

    TableListBox tableComponent;

    .....
    }

.cpp
PlaylistComponent::PlaylistComponent()
{
    // In your constructor, you should add any child components, and
    // initialise any special settings that your component needs.

    tableComponent.getHeader().addColumn("", 1, 20);
    tableComponent.getHeader().addColumn("Track Title", 3, 500);
    tableComponent.setModel(this);
    addAndMakeVisible(tableComponent);
}

Component * PlaylistComponent::refreshComponentForCell(int rowNumber, int columnId, bool , Component *existingComponentToUpdate)
{

    if (columnId == ) // The ID and Length columns do not have a custom component
    {
        jassert(existingComponentToUpdate == nullptr);
        return nullptr;
    }

    if(columnId == 1)
    {
        // Creating component if does not existst yet

        TextButton * btn = static_cast<TextButton *> (existingComponentToUpdate);

        if (btn == 0)
        {
            btn = new TextButton { "Play" };
        }

        String id{ std::to_string(rowNumber) };
        btn->setComponentID(id);
        btn->addListener(this);
        existingComponentToUpdate = btn;

    }
    return existingComponentToUpdate;

}
void PlaylistComponent::paintCell(Graphics &g, int rowNumber, int columnId, int width, int height, bool )
{
    if (columnId == 2) {
        g.drawText(trackTitles[rowNumber], 2, 0, width - 4, height, Justification::centredLeft, true);
    }

}

void PlaylistComponent::setTracks(Array<File> tracksFile)
{

    for (int i = 0; i < tracksFile.size(); i++)
    {
        trackTitles.push_back(tracksFile[i].getFileName());

    }
    tableComponent.updateContent();

}

void PlaylistComponent::buttonClicked(Button *button)
{

   //Array<File> file;
   player->loadURL(file[std::stoi(button->getComponentID().toStdString())]); // your player
   player->start();

}

then near the table there should be a button for loading a lot of audio file, you can store it in a vector
Array<File> file;
..........
void loadAudioFiles()
{
    juce::String filters = "*.mp3";
    FileChooser chooser("Select an mp3 files..", File::getSpecialLocation(File::userHomeDirectory), filters);

    if (chooser.browseForMultipleFilesToOpen())
    {
        file = chooser.getResults();
        playlistComponent.setTracks(file );

    }
}


text:
Q: Word or phrase describing situation where adequately addressing "X is not harmful" involves a self-destructive proof There's a nice cartoon on the web that epitomises what I'm trying to describe:

Another dimension of this behaviour, is that it is often used as part of a manipulation attempt, to get someone to do something they wouldn't normally do because of its potential harm:

*

*A asks B to do potentially harmful act X (whether intentionally or out of ignorance).

*B refuses, citing the potential risks from doing X

*A claims X is patently not harmful and B's denial has more to do with ulterior motive Y

*Since B cannot conclusively prove X is harmful until B has engaged in X and caused themselves harm, they are left with two equally bad choices:

*

*either engage in X against your will, risking harm, to prove accusation Y is false, or

*avoid X and give A the ability to claim accusation Y is true, opening B up to further manipulation.

Examples:

A: Here, have some heroin with me.
  B: No man, heroin is addictive, I don't want to.
  A: Heroin's not addictive, you're just saying that to judge me.
B proceeds to get addicted to heroin to prove friendship

A: Come to my party! C is coming too!
  B: Sorry A, I can't! I have exams!
  A: Dude, nobody's ever had to study for that exam! You just don't like C, don't you! That's the real reason you're not coming!
B skips party to study, A tells everyone at school B hates C

A: It's a Tuesday, so let's not use a condom. You can't get pregnant on a Tuesday.
  B: What? Yes you can!
  A: ... omg, you don't trust me! You think I'm cheating and I have an STD don't you! That's why you refuse!
B proceeds to prove their trust, as well as the fact that you can in fact get pregnant on a Tuesday

etc etc.
Is there a good word or phrase that describes either A's behaviour, or the situation B finds themselves in?

A: I might describe B as being:

*

*guilted or manipulated into a lose-lose situation.

*argued or painted into a corner.

*coerced into a no-win situation.

*goaded into a poor decision, just to prove a point.

*a pawn in A's game. (Chess analogy implies sacrifice and manipulation.)

However, I find the cartoon scenario slightly different than the other examples. In the cartoon, it doesn't seem that A or B has ill motives. If you focus on the fact that there's a burning question to be answered, it seems appropriate to say that curiosity killed the cat. Or the wildebeest. If you focus on the fact that there is a debate (still no ill motives), maybe for the sake of argument, B fell on his sword to prove his point.

A: You can call it guilt tripping :

Guilt trip
VERB: to make (someone) feel guilty, especially in order to induce them to do something. (ODO)
NOUN: a strong feeling of being guilty that makes you behave in a particular way. (MMD)

He guilt tripped me into going to the party and doing heroin.

A: Strictly speaking, a self-destructive proof is an ordeal. Merriam-Webster says:

1:  a primitive means used to determine guilt or innocence by submitting the accused to dangerous or painful tests believed to be under supernatural control <ordeal by fire> <ordeal by water>

An ordeal by water was a test of witchcraft. The suspected which was thrown into a river or lake. If she floated and survived, she was obviously a witch and could then be burned at the stake. Drowning proved her innocence.

A: That situation is a dilemma.
ODO:

dilemma
NOUN
1 A situation in which a difficult choice has to be made between two or more alternatives, especially equally undesirable ones.
'His dilemma rests in the choice between telling a lie and losing his
  chance to marry the woman he loves.'
  'He was given two tough choices, a dilemma that he didn't wish to have.'

Also, catch-22 may work.
ODO:

catch-22
NOUN
A dilemma or difficult circumstance from which there is no escape
  because of mutually conflicting or dependent conditions.
'There's always been a bit of a catch 22 about golf - you need to have
  a handicap to join a club, yet it's very difficult to get that
  handicap in a civilised way without spending hours on a rain sodden
  driving range in some murky British suburb.'

A: This sounds like a trial by fire:

A test in which a person is exposed to flames in order to assess his/her truthfulness, commitment, courage, etc.

[Wikitionary]
The idiomatic phrase originates from the medieval practice of determining a person's guilt by having them go through an ordeal, such as walking through a fire.

A: I would describe the situation as being between a rock and a hard place.
As per Wiktionary:

*(idiomatic) To be in a difficult and inescapable position.

*(idiomatic) Having the choice between two unpleasant or distasteful options; in a predicament or quandary.

Similar but less common idioms include begin caught between the devil and the deep blue sea and being between the hammer and the anvil.

A: You could call the situation a Zero-Sum situation:

Zero-Sum

*

*of, relating to, or being a situation (such as a game or relationship) in which a gain for one side entails a corresponding loss for the other side

(Used mainly to reference games/situations where there is no mutual loss or mutual win.)
Examples: Coin flip, dividing up a budget, gambling, etc.

(MWD)
This does imply that B's loss would even out A's gain, so it may not fit every situation. It does work really well for the Wildebeest situation, though.

A: I think the closest to what you're looking for is "cutting off [your] nose to spite your face." Generally, that refers to someone engaging in very self-destructive acts as a petty revenge, but you could also use it here.
You could also use the more generic "sacrifice _____ on the altar of _____." That generalizes well, but always sounds sarcastic.

A: The cartoon is an example of situational irony, defined by dictionary.com as

irony involving a situation in which actions have an effect that is opposite from what was intended, so that the outcome is contrary to what was expected.

That is of course less specific than what you are asking for, but as other answers have pointed out, there doesn't really seem to be a standard idiom for this very specific type of scenario.


text:
Q: GC.KeepAlive. Different MSDN articles for different versions. Did they change anything? The article for .NET Framework v.2 contains two examples.
http://msdn.microsoft.com/en-us/library/system.gc.keepalive(v=vs.80).aspx
The first one is of particular interest as it helps with understanding of Garbage Collector behavior.
But other versinos do not contain similar example. What changed in .NET Framework GC for missing example became not actual?

A: I see nothing in that example became invalid with later versions.
I would guess they were motivated by one of two reasons:

*

*The example code isn't very useful (though it does demonstrate what it's there to demonstrate), and has no practical effect but to waste memory, it could then become another thing encouraging people to do bizarre things with GC that makes things less performant.

*Example code are another piece of code that has to be tested, maintained and bug-fixed. Remove an example, and reduce your testing and bug-fixing overhead.