text:
Q: Extraer información de diferentes nodos XML con el mismo PATH con PYTHON Estoy intentando extraer la información que contienen distintos nodos dentro de un mismo path:
La parte de XML que me esta dándo problemas es la siguente:

El codigo que he utilizado para extraer el texto de dentro de estos nodos es el siguente:
for nodo in tree.find(/Body/.../RateEntryCollection/RateEntry)
print(nodo.text)

El problema es que con esta funcion solo puedo entraer información en el primer nodo "RateEntry".
Como puedo entrar dentro de los otros nodos que tienen el mismo Path?
Muchas gracias

A: En este caso puedes jugar un poco con XPATH para conseguir lo que deseas.
Teniendo en cuenta el siguiente XML:
<firstNode>
    <RateEntryCollection>
        <RateEntry Action ="MERGE">
            <anotherNode>
                Example1
            </anotherNode>
        </RateEntry>
        <RateEntry Action ="MERGE">
            <anotherNode>
                Example2
            </anotherNode>
        </RateEntry>
    </RateEntryCollection>
</firstNode>

Supongamos que queremos todas los elementos (para ello usamos .//* para obtener todo desde la raíz:
#!/usr/bin/env python3

import xml.etree.ElementTree as ET

tree = ET.parse("example.xml")

root = tree.getroot()

for element in root.findall(".//*"):
    print(element)

Resultado:
<Element 'RateEntryCollection' at 0x7f67e2e26430>
<Element 'RateEntry' at 0x7f67e2e26480>
<Element 'anotherNode' at 0x7f67e2e264d0>
<Element 'RateEntry' at 0x7f67e2e26570>
<Element 'anotherNode' at 0x7f67e2e265c0>

En caso de necesitar los elementos RateEntry, sabiendo la estructura:
for rate_entry in root.findall(".//RateEntryCollection/*"):
    print(rate_entry)

Nos devuelve:
<Element 'RateEntry' at 0x7ff83708e520>
<Element 'RateEntry' at 0x7ff83708e610>

Si deseas solo el primero puedes jugar como un array:
for rate_entry in root.findall(".//RateEntryCollection/RateEntry[1]"):
    print(rate_entry)

Resultado:
<Element 'RateEntry' at 0x7f1b3b5e6570>

Si deseas el contenido del tag Action:
for rate_entry in root.findall(".//RateEntryCollection/RateEntry[1]"):
    print(rate_entry.get('Action'))

Resultado:
MERGE

P.D: Sino es lo que buscas, trata, por favor, de colocar un ejemplo válido para poder ayudarte mejor :)


text:
Q: Finding and comparing stock prices at a specific day of every month So, the code I'm trying to make is solving for which days of the month would historically be the best days to  buy and sell a stock at. The stock I'm looking at in particular is UVXY. I'm trying to figure out which days would be the historical monthly lows and which ones would be the historical monthly highs, and average those out. The code I have so far isn't working because on some days of the month, the 20th or 10th isn't a trading day. The actual string would be much longer and have more dates, but I'm open to using yfinance to get the historical prices, I'm just not sure how it would work. Thanks!

from bs4 import BeautifulSoup

content = """

Fri 09-24-2021      22.22     22.27     20.38      20.49    47101392
Thu 09-23-2021      22.52      22.63      21.32      21.48    48145436
Wed 09-22-2021      24.88      25.37      22.88      23.68    59917888
Tue 09-21-2021      26.03      28.18      25.20      25.86    73069928
Mon 09-20-2021      26.26      30.81      25.36      27.31   104578920
Fri 09-17-2021      21.56      23.58      21.33      23.48    61526336
Thu 09-16-2021      21.91      22.66      21.04      21.38    42485960
....
Wed 12-07-2016    9150.00    9390.00    8780.00    9270.00       37485
Tue 12-06-2016    9530.00    9660.00    9130.00    9210.00       27220

"""

soup = BeautifulSoup(content, "html.parser")
stuff = soup.find('pre').text
lines = stuff.split("\n")

listOfStuff=[]
openPriceOfTrades=[]
closePriceOfTrades=[]
difference=[]

for line in lines:
  if(line[7:9]=="20"):
    closePriceOfTrades.append(line[20:-46])
  if line[7:9]=="10":
    openPriceOftrades.append(line[20:-46])
    difference = []   # initialization of result list

for i in range(len(openPriceOfTrades)-1):
  print(len(openPriceOfTrades))
  difference.append(float(closePriceOfTrades[i])-float(openPriceOfTrades[i]))
print(difference)

A: You should learn pandas.DataFrame.
First I would remove lines with
 to have only data.
content = """

Fri 09-24-2021      22.22     22.27     20.38      20.49    47101392
Thu 09-23-2021      22.52      22.63      21.32      21.48    48145436
Wed 09-22-2021      24.88      25.37      22.88      23.68    59917888
Tue 09-21-2021      26.03      28.18      25.20      25.86    73069928
Mon 09-20-2021      26.26      30.81      25.36      27.31   104578920
Fri 09-17-2021      21.56      23.58      21.33      23.48    61526336
Thu 09-16-2021      21.91      22.66      21.04      21.38    42485960
Wed 12-07-2016    9150.00    9390.00    8780.00    9270.00       37485
Tue 12-06-2016    9530.00    9660.00    9130.00    9210.00       27220

"""

# remove lines with `<>`
content = '\n'.join(line for line in content.split('\n') if not line.startswith('<')).strip()

print(content)

and then it looks like file CSV with spaces as separator and you can use io to simulate file in memory and read it
import pandas as pd
import io

df = pd.read_csv(io.StringIO(content), sep='\s+', names=['day', 'date', 'A', 'B', 'C', 'D', 'volumen'])

and then you can create column with date-day
df['date-day'] = df['date'].str[3:5]

And then you can select all rows with 20 in column date-day and calculate average (mean)
day_20 = df[ df['date-day'] == '20' ]

print(day_20.mean())

Or you can use groupby to work with all days at the same time.
for value, group in df.groupby('date-day'):
    print('--- date-day:', value, '---')
    #print(group.mean())
    print('mean "A":', group['A'].mean())
    print('mean "B":', group['B'].mean())
    print('mean "C":', group['C'].mean())
    print('mean "D":', group['D'].mean())

Full working code:
content = """

Fri 09-24-2021      22.22     22.27     20.38      20.49    47101392
Thu 09-23-2021      22.52      22.63      21.32      21.48    48145436
Wed 09-22-2021      24.88      25.37      22.88      23.68    59917888
Tue 09-21-2021      26.03      28.18      25.20      25.86    73069928
Mon 09-20-2021      26.26      30.81      25.36      27.31   104578920
Fri 09-17-2021      21.56      23.58      21.33      23.48    61526336
Thu 09-16-2021      21.91      22.66      21.04      21.38    42485960
Wed 12-07-2016    9150.00    9390.00    8780.00    9270.00       37485
Tue 12-06-2016    9530.00    9660.00    9130.00    9210.00       27220

"""

# remove lines with `<>`
content = '\n'.join(line for line in content.split('\n') if not line.startswith('<')).strip()

import pandas as pd
import io

df = pd.read_csv(io.StringIO(content), sep='\s+', names=['day', 'date', 'A', 'B', 'C', 'D', 'volumen'])

df['date-day'] = df['date'].str[3:5]

print(df)

day_20 = df[ df['date-day'] == '20' ]
print(day_20)

for value, group in df.groupby('date-day'):
    print('--- date-day:', value, '---')
    #print(group.mean())
    print('mean "A":', group['A'].mean())
    print('mean "B":', group['B'].mean())
    print('mean "C":', group['C'].mean())
    print('mean "D":', group['D'].mean())

Result:
   day        date        A        B        C        D    volumen date-day
0  Fri  09-24-2021    22.22    22.27    20.38    20.49   47101392       24
1  Thu  09-23-2021    22.52    22.63    21.32    21.48   48145436       23
2  Wed  09-22-2021    24.88    25.37    22.88    23.68   59917888       22
3  Tue  09-21-2021    26.03    28.18    25.20    25.86   73069928       21
4  Mon  09-20-2021    26.26    30.81    25.36    27.31  104578920       20
5  Fri  09-17-2021    21.56    23.58    21.33    23.48   61526336       17
6  Thu  09-16-2021    21.91    22.66    21.04    21.38   42485960       16
7  Wed  12-07-2016  9150.00  9390.00  8780.00  9270.00      37485       07
8  Tue  12-06-2016  9530.00  9660.00  9130.00  9210.00      27220       06

   day        date      A      B      C      D    volumen date-day
4  Mon  09-20-2021  26.26  30.81  25.36  27.31  104578920       20

--- date-day: 06 ---
mean "A": 9530.0
mean "B": 9660.0
mean "C": 9130.0
mean "D": 9210.0
--- date-day: 07 ---
mean "A": 9150.0
mean "B": 9390.0
mean "C": 8780.0
mean "D": 9270.0
--- date-day: 16 ---
mean "A": 21.91
mean "B": 22.66
mean "C": 21.04
mean "D": 21.38
--- date-day: 17 ---
mean "A": 21.56
mean "B": 23.58
mean "C": 21.33
mean "D": 23.48
--- date-day: 20 ---
mean "A": 26.26
mean "B": 30.81
mean "C": 25.36
mean "D": 27.31
--- date-day: 21 ---
mean "A": 26.03
mean "B": 28.18
mean "C": 25.2
mean "D": 25.86
--- date-day: 22 ---
mean "A": 24.88
mean "B": 25.37
mean "C": 22.88
mean "D": 23.68
--- date-day: 23 ---
mean "A": 22.52
mean "B": 22.63
mean "C": 21.32
mean "D": 21.48
--- date-day: 24 ---
mean "A": 22.22
mean "B": 22.27
mean "C": 20.38
mean "D": 20.49

If you would use yfinance then you would get data directly as pandas.DataFrame

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I change the color of selected menu item in Ant Design? In Ant Design, the default color of a selected menu item is blue, but I want to change the color. Here's some of my code:

import React from 'react';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  NavLink,
} from 'react-router-dom';
import { Layout, Menu } from 'antd';
import Create from './Create';
import Dashboard from './Dashboard';
import './layout.css';
const { Header, Footer, Sider, Content } = Layout;
const { Item } = Menu;

function LayoutPage() {
  return (
    <Router>
      <Layout style={{ minHeight: '100vh' }}>
        <Sider>
          <Menu
            theme='dark'
            defaultSelectedKeys={['item1']}
            mode='inline'
          >
            <Item key='item1' className='customclass'>
              <NavLink to='/'>
                Dashboard
              </NavLink>
            </Item>
            <Item key='item2' className='customclass'>
              <NavLink to='/create'>
                Create
              </NavLink>
            </Item>
          </Menu>
        </Sider>
        <Layout>

          <Content
            style={{
              padding: 24,
              background: '#EBF1FC',
              minHeight: 280,
            }}
          >

              <Switch>
                <Route exact path='/'>
                  <Dashboard />
                </Route>
                <Route path='/create'>
                  <Create />
                </Route>
                </Route>
              </Switch>

          </Content>
        </Layout>
      </Layout>
    </Router>
  );
}
export default LayoutPage;
.ant-menu.ant-menu-dark .ant-menu-item-selected.customclass {
  background-color: '#B039CC';
}

In the css file you can see me attempting this solution but weirdly it only works if the menu mode is 'horizontal'.
I also tried this method, in which I created my custom Menu component and overrode the ant-menu-item-selected property but that did not work either (i think it's because I also need to use the Item component, which I have to access using my custom Menu component).

A:  .ant-menu-item-selected {
    background-color: #B039CC !important;
  }

add important

A: You  say  this  method ,  it only works if the menu mode is 'horizontal', beacause .ant-menu-horizontal this statement only matches the horizontalmode...
you can remove the word horizontal,and tyr again.,like this:
.ant-menu > .ant-menu-item:hover,
.ant-menu > .ant-menu-submenu:hover,
.ant-menu > .ant-menu-item-active,
.ant-menu> .ant-menu-submenu-active,
.ant-menu > .ant-menu-item-open,
.ant-menu> .ant-menu-submenu-open,
.ant-menu > .ant-menu-item-selected,
.ant-menu > .ant-menu-submenu-selected {
  color: red;
  border-bottom: 2px solid red;
}


text:
Q: nextcloud - client denied by server configuration: /usr/share/nextcloud I am used to install owncloud server on Fedora, but this time I installed nextcloud on CentOS 7. I followed the procedure
# yum install nextcloud
# yum install crypto-utils mod_ssl openssl
# genkey hostname

edit

/etc/httpd/conf.d/ssl.conf

adding

SSLCertificateFile /etc/pki/tls/certs/hostname.crt
SSLCertificateKeyFile /etc/pki/tls/private/hostname.key

let's prepare the database

# yum install mariadb-server
# systemctl enable --now mariadb
$ mysql_secure_installation

$ mysql -u root -p
CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';
CREATE DATABASE IF NOT EXISTS nextcloud;
GRANT ALL PRIVILEGES ON nextcloud.* TO 'username'@'localhost' IDENTIFIED BY 'password';
FLUSH PRIVILEGES;
quit

then

# sudo -u apache php occ maintenance:install --data-dir /var/lib/nextcloud/data/ --database "mysql" --database-name "nextcloud"  --database-user "nextcloud" --database-pass "password" --admin-user "admin" --admin-pass "password"

then edit

/etc/owncloud/config.php

and add machine ip address under 'trusted_domains'

# firewall-cmd --permanent --zone=public --add-service=http
# firewall-cmd --permanent --zone=public --add-service=https
# firewall-cmd --reload

Unfortunately this time nextcloud does not work, indeed by trying to open
https://machine_ip/nextcloud

I get
Forbidden. You don't have permission to access /nextcloud on this server. Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

a few lines of # cat /var/log/httpd/ssl_error_log
[Tue Mar 07 00:51:39.331935 2017] [authz_core:error] [pid 2456] [client removed_by_me:51184] AH01630: client denied by server configuration: /usr/share/nextcloud
[Tue Mar 07 00:51:39.331988 2017] [authz_core:error] [pid 2456] [client removed_by_me:51184] AH01630: client denied by server configuration: /usr/share/nextcloud/core/templates/403.php
[Tue Mar 07 00:59:19.968622 2017] [ssl:warn] [pid 2498] AH01909: RSA certificate configured for fe80::removed_by_me:443 does NOT include an ID which matches the server name
[Tue Mar 07 00:59:20.006434 2017] [ssl:warn] [pid 2498] AH01909: RSA certificate configured for fe80::removed_by_me:443 does NOT include an ID which matches the server name
[Tue Mar 07 00:59:30.267154 2017] [authz_core:error] [pid 2503] [client removed_by_me:51450] AH01630: client denied by server configuration: /usr/share/nextcloud
[Tue Mar 07 00:59:30.267226 2017] [authz_core:error] [pid 2503] [client removed_by_me:51450] AH01630: client denied by server configuration: /usr/share/nextcloud/core/templates/403.php
[Tue Mar 07 01:00:20.574679 2017] [authz_core:error] [pid 2505] [client removed_by_me:51488] AH01630: client denied by server configuration: /usr/share/nextcloud
[Tue Mar 07 01:00:20.574931 2017] [authz_core:error] [pid 2505] [client removed_by_me:51488] AH01630: client denied by server configuration: /usr/share/nextcloud/core/templates/403.php
[Tue Mar 07 01:00:49.528960 2017] [ssl:emerg] [pid 2537] AH02204: Init: Pass phrase incorrect for key of fe80::removed_by_me:443
[Tue Mar 07 01:00:49.529005 2017] [ssl:emerg] [pid 2537] SSL Library Error: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Tue Mar 07 01:00:49.529021 2017] [ssl:emerg] [pid 2537] SSL Library Error: error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error
[Tue Mar 07 01:00:49.529032 2017] [ssl:emerg] [pid 2537] SSL Library Error: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Tue Mar 07 01:00:49.529044 2017] [ssl:emerg] [pid 2537] SSL Library Error: error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error (Type=RSA)
[Tue Mar 07 01:00:49.529066 2017] [ssl:emerg] [pid 2537] SSL Library Error: error:04093004:rsa routines:OLD_RSA_PRIV_DECODE:RSA lib
[Tue Mar 07 01:00:49.529077 2017] [ssl:emerg] [pid 2537] SSL Library Error: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
[Tue Mar 07 01:00:49.529087 2017] [ssl:emerg] [pid 2537] SSL Library Error: error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error (Type=PKCS8_PRIV_KEY_INFO)
[Tue Mar 07 01:01:12.593572 2017] [ssl:warn] [pid 2568] AH01909: RSA certificate configured for fe80::removed_by_me:443 does NOT include an ID which matches the server name
[Tue Mar 07 01:01:12.669001 2017] [ssl:warn] [pid 2568] AH01909: RSA certificate configured for fe80::removed_by_me:443 does NOT include an ID which matches the server name
[Tue Mar 07 01:19:01.904878 2017] [authz_core:error] [pid 2573] [client removed_by_me:55170] AH01630: client denied by server configuration: /usr/share/nextcloud
[Tue Mar 07 01:19:01.905130 2017] [authz_core:error] [pid 2573] [client removed_by_me:55170] AH01630: client denied by server configuration: /usr/share/nextcloud/core/templates/403.php
You don't have permission to access /nextcloud on this server.

Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

# cat /etc/httpd/conf.d/nextcloud.conf
# cat /etc/httpd/conf/httpd.conf
# cat /etc/httpd/conf.d/ssl.conf
# ls -latr /etc/httpd/conf.d/
total 64
-rw-r--r--. 1 root root  691  6 nov 01.32 php.conf
-rw-r--r--. 1 root root 1252 14 nov 17.53 userdir.conf
-rw-r--r--. 1 root root 2926 14 nov 19.04 autoindex.conf
-rw-r--r--. 1 root root  366 14 nov 19.05 README
-rw-r--r--. 1 root root 2407  1 mar 02.39 nextcloud-defaults.inc
-rw-r--r--. 1 root root 1893  1 mar 02.39 nextcloud.conf
-rw-r--r--. 1 root root  263  1 mar 02.39 nextcloud-auth-none.inc
-rw-r--r--. 1 root root  313  1 mar 02.39 nextcloud-auth-local.inc
-rw-r--r--. 1 root root  278  1 mar 02.39 nextcloud-auth-any.inc
-rw-r--r--. 1 root root  994  1 mar 02.39 nextcloud-access.conf.avail
drwxr-xr-x. 5 root root 4096  6 mar 13.59 ..
drwxr-xr-x. 2 root root 4096  6 mar 17.30 .
-rw-r--r--. 1 root root 9432  6 mar 17.33 ssl.conf
-rw-r--r--. 1 root root  837  7 mar 00.25 welcome.conf

# ls -latr /etc/httpd/conf.modules.d/
total 44
-rw-r--r--. 1 root root  216  6 nov 01.32 10-php.conf
-rw-r--r--. 1 root root  451 14 nov 17.53 01-cgi.conf
-rw-r--r--. 1 root root   88 14 nov 17.53 00-systemd.conf
-rw-r--r--. 1 root root   41 14 nov 17.53 00-ssl.conf
-rw-r--r--. 1 root root  957 14 nov 17.53 00-proxy.conf
-rw-r--r--. 1 root root  742 14 nov 17.53 00-mpm.conf
-rw-r--r--. 1 root root   41 14 nov 17.53 00-lua.conf
-rw-r--r--. 1 root root  139 14 nov 17.53 00-dav.conf
-rw-r--r--. 1 root root 3739 14 nov 17.53 00-base.conf
drwxr-xr-x. 5 root root 4096  6 mar 13.59 ..
drwxr-xr-x. 2 root root 4096  6 mar 17.30 .

If you need any other log, please tell me

A: Solved with
# ln -s /etc/httpd/conf.d/nextcloud-access.conf.avail /etc/httpd/conf.d/z-nextcloud-access.conf

Source: lines [7,12] of /etc/httpd/conf.d/nextcloud.conf


text:
Q: Compare documents (images) I need to compare a pdf with about 27000 pages (scanned pages) to another pdf with about 28000 pages (also scanned pages) so that I can find the 1000 pages which differ.
Does anyone now a good program to do this job?

A: Compare It! is a nice tool, it can compare files of pretty much any type and find differences between the two. It should work for PDFs; I'm not sure if it would show up as the actual PDF or as code.


text:
Q: Intel HAXM installation failed when installing it using SDK Manager in windows 8.1 (intel pentium®) When I install it using SDK manager on Android Studio, I get the error message:
Preparing "Install Intel x86 Emulator Accelerator (HAXM installer) (revision: 7.6.5)".
        Warning: Package "com.android.repository.impl.generated.v2.RemotePackage@44b0bc2c" (extras;intel;Hardware_Accelerated_Execution_Manager) should be installed in
        "C:\Users\muham_000\AppData\Local\Android\Sdk\extras\intel\Hardware_Accelerated_Execution_Manager" but
        it already exists.
        Installing in "C:\Users\muham_000\AppData\Local\Android\Sdk\extras\intel\Hardware_Accelerated_Execution_Manager-2" instead.
        Downloading https://dl.google.com/android/repository/extras/intel/haxm-windows_v7_6_5.zip
        "Install Intel x86 Emulator Accelerator (HAXM installer) (revision: 7.6.5)" ready.
        Installing Intel x86 Emulator Accelerator (HAXM installer) in C:\Users\muham_000\AppData\Local\Android\Sdk\extras\intel\Hardware_Accelerated_Execution_Manager-2
        "Install Intel x86 Emulator Accelerator (HAXM installer) (revision: 7.6.5)" complete.
        "Install Intel x86 Emulator Accelerator (HAXM installer) (revision: 7.6.5)" finished.
        Parsing C:\Users\muham_000\AppData\Local\Android\Sdk\build-tools\30.0.3\package.xml
        Parsing C:\Users\muham_000\AppData\Local\Android\Sdk\build-tools\33.0.0\package.xml
        Parsing C:\Users\muham_000\AppData\Local\Android\Sdk\emulator\package.xml
        Parsing C:\Users\muham_000\AppData\Local\Android\Sdk\extras\intel\Hardware_Accelerated_Execution_Manager\package.xml
        Parsing C:\Users\muham_000\AppData\Local\Android\Sdk\extras\intel\Hardware_Accelerated_Execution_Manager-2\package.xml
        Warning: Observed package id 'extras;intel;Hardware_Accelerated_Execution_Manager' in inconsistent location 'C:\Users\muham_000\AppData\Local\Android\Sdk\extras\intel\Hardware_Accelerated_Execution_Manager-2' (Expected 'C:\Users\muham_000\AppData\Local\Android\Sdk\extras\intel\Hardware_Accelerated_Execution_Manager')
        Warning: Already observed package id 'extras;intel;Hardware_Accelerated_Execution_Manager' in 'C:\Users\muham_000\AppData\Local\Android\Sdk\extras\intel\Hardware_Accelerated_Execution_Manager'. Skipping duplicate at 'C:\Users\muham_000\AppData\Local\Android\Sdk\extras\intel\Hardware_Accelerated_Execution_Manager-2'
        Parsing C:\Users\muham_000\AppData\Local\Android\Sdk\patcher\v4\package.xml
        Parsing C:\Users\muham_000\AppData\Local\Android\Sdk\platform-tools\package.xml
        Parsing C:\Users\muham_000\AppData\Local\Android\Sdk\platforms\android-32\package.xml
        Parsing C:\Users\muham_000\AppData\Local\Android\Sdk\platforms\android-33\package.xml
        Parsing C:\Users\muham_000\AppData\Local\Android\Sdk\sources\android-33\package.xml
        Parsing C:\Users\muham_000\AppData\Local\Android\Sdk\system-images\android-33\google_apis\x86_64\package.xml
        Parsing C:\Users\muham_000\AppData\Local\Android\Sdk\tools\package.xml
        Android SDK is up to date.
        Running Intel® HAXM installer
        Intel HAXM installation failed!
        For more details, please check the installation log: C:\Users\MUHAM_~1\AppData\Local\Temp\haxm_install-20221013_1255.log
        Intel® HAXM installation failed. To install Intel® HAXM follow the instructions found at: https://github.com/intel/haxm/wiki/Installation-Instructions-on-Windows
        Done

I checked the logs while installing the XHAM and this is the content of the log:
  Version: 7.6.5
    Output folder: C:\Program Files\Intel\HAXM
    Extract: checktool.exe... 100%
    Execute: C:\Program Files\Intel\HAXM\checktool.exe --verbose
    CPU vendor          *  GenuineIntel
    Intel64 supported   *  Yes
    VMX supported       *  Yes
    VMX enabled         *  Yes
    EPT supported       -  NoSS
    NX supported        *  Yes
    NX enabled          *  Yes
    Hyper-V disabled    *  Yes
    OS version          *  Windows 6.3.9600
    OS architecture     *  x86_64
    Guest unoccupied    *  Yes. 0 guest(s)
    The system requirements are not satisfied.


text:
Q: WPF Focus on "run" element I would like to change the background of the Run that has the focus in a FlowDocument in a RichTextBox.
I would like to provide to my users a visual cue as to which Run element they are currently editing and I think a light background would be the best way for my application.
I see that the Run has Focusable (which I set to true), IsFocused, FocusVisualStyle, GotFocus, etc. but none of those properties or events seam to work.
Thank you for any help you can give.

A: You can use a data trigger to get the effect you want. Here's an example:
<Style TargetType="{x:Type RichTextBox}">
    <Style.Triggers>
        <Trigger Property="IsFocused" Value="true">
            <Setter Property="BorderBrush" Value="LightGrey" />
        </Trigger>
    </Style.Triggers>
</Style>


text:
Q: How to add listings using event tracking in Google Analytics? I'm trying to add listings like this screenshot which is photoshopped:

The real result that I didn't want this, one list is totally stacked.

My script when someone uses input as number and click button to send data:
ga('send', 'event', 'User Behavior', 'Input & Button', 'Individual count', variable_input_number);

A: Event value is a metric, so the second example is actually the expected result - metrics are always added up. The only way to get the breakdown would be if you have at least one dimension (label presumably in your case, or adding a custom dimension and setting it as secondary dimension in your report) that is different per event. If you want to record each individual number as it is submitted you should probably use the number as event label and group by event category, but you cannot break down events by individual values.


text:
Q: jquery 1.8.2 zip has version 1.4.2 js file I downloaded jquery-ui-1.8.2.zip first via a link provided in the official jQuery page and then from google sources.
When unzipped, they both contained 'jquery-1.4.2.js'.
I am trying to use the "automcomplete" feature which should be in the 1.8 package, but when using the file from the mentioned zip, I only get "TypeError: $("#inputId").autocomplete is not a function".
Seems like the jquery file is indeed the the same as the name says.
I also tried loading an earlier version of jQuery (1.8.16). The zip had "jquery-1.6.2.js".
Now please explain if there is a reason for this. For me it seems erroneous.
Our project is currently using jQuery 1.7.2.
Also the version 1.8.14 zip has jquery-1.5.1.js.

A: You're confusing jQuery with jQuery-UI.  The latest version of jQuery is 1.7.2, the latest version of jQuery-UI is 1.8.22.  jQuery-UI requires a minimum of jQuery 1.3.2 to function, so be sure you're including both files in your page, with jQuery loaded first.

A: it works for me, Jquery1.8 it must be your browser cache, in any case you all you have to do is download it and replace jquery with the lastest version of the jquery...


text:
Q: Converting columns in SQLite database to cell values Let's say I have the following database structure:

fruits
vegetables
grains

banana
carrot
wheat

apple
broccoli
barley

watermelon
cabbage
malt

strawberry
tomato
semolina

And I want it to be a bit easier to work with, transforming it into the following structure instead:

name
type

banana
fruit

apple
fruit

broccoli
vegetable

barley
grain

tomato
vegatable

wheat
grain

How would I go about writing a python program that could do this for me?
I found this solution to be workable - but maybe it's not as pythonic/readable as it should be:
import sqlite3

def transform():
    con = sqlite3.connect('database.db')
    cur = con.cursor()
    cur2 = con.cursor()
    cur3 = con.cursor()
    data = cur.execute('''SELECT * FROM table_1''')
    columns = []
    for column in data.description:
        columns.append(column[0])
    for columnx in columns:
        cur2.execute(f'''SELECT {columnx} FROM table_1''')
        content = cur2.fetchall()
        for word in content:
            word = str(word)
            word = word.strip("(),' ")
            if word != "None":
               cur3.execute(f'''INSERT INTO table_1_V2 (column1, column2) VALUES (?,?);''',(str(word),str(columnx)))
    con.commit()

A: The following program does the job - although it could probably be a bit more pythonic/readable:
import sqlite3

def transform():
    con = sqlite3.connect('database.db')
    cur = con.cursor()
    cur2 = con.cursor()
    cur3 = con.cursor()
    data = cur.execute('''SELECT * FROM table_1''')
    columns = []
    for column in data.description:
        columns.append(column[0])
    for columnx in columns:
        cur2.execute(f'''SELECT {columnx} FROM table_1''')
        content = cur2.fetchall()
        for word in content:
            word = str(word)
            word = word.strip("(),' ")
            if word != "None":
               cur3.execute(f'''INSERT INTO table_1_V2 (column1, column2) VALUES (?,?);''',(str(word),str(columnx)))
    con.commit()

In the INSERT statement here, column1, column2 can be extended with however many columns you want to fill in your new table, and the values that are to be inserted in the new column are found at the end of the statement (word and columnx here). Note that you have to actually create the new table with the desired contents for this code to work.


text:
Q: How to plot very custom line styles with matplot in R ?par explains that lty can be specified as a vector of alternating drawn/skipped line segment lengths.
For example c(1,3,1,1) would look something like this:
─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─

But if I try to pass lty=c(1,3,1,1) to matplot (or if I preset it using par), then matplot assumes I want to cycle through style 1 (solid), style 3 (dotted), style 1 (solid), style 1 (solid), resulting in this
────────────────────────────────────────────────────────────────────────────
─   ─   ─   ─   ─   ─   ─   ─   ─   ─   ─   ─   ─   ─   ─   ─   ─   ─   ─
────────────────────────────────────────────────────────────────────────────
────────────────────────────────────────────────────────────────────────────
────────────────────────────────────────────────────────────────────────────
─   ─   ─   ─   ─   ─   ─   ─   ─   ─   ─   ─   ─   ─   ─   ─   ─   ─   ─
────────────────────────────────────────────────────────────────────────────
────────────────────────────────────────────────────────────────────────────

instead of this
─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─
─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─
─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─
─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─
─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─
─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─
─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─
─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─ ─   ─

How can I make matplot understand that it should interpret the whole vector as one style?

A: So ?par actually says that the custom line types should be specified as a character, with an even number of elements, e.g. "33".
Regardless, matplot won't handle mixing this in with the normal integer specification because it has "co-opted" the lty argument to be a vector, one value for each line.
You could pass matplot a character vector and specify each lty manually, e.g. something like lty = c("44","22","33","3322"). Or you could create your own version of matplot by altering the final few lines to be this:
if (!add) {
        ii <- ii[-1L]
        plot(x[, 1L], y[, 1L], type = type[1L], xlab = xlab,
            ylab = ylab, xlim = xlim, ylim = ylim, lty = lty[[1L]],
            lwd = lwd[1L], lend = lend[1L], pch = pch[1L], col = col[1L],
            cex = cex[1L], bg = bg[1L], ...)
    }
    for (i in ii) lines(x[, i], y[, i], type = type[i], lty = lty[[i]],
        lwd = lwd[i], lend = lend[i], pch = pch[i], col = col[i],
        cex = cex[i], bg = bg[i])

so that it uses [[ rather than [ to select the appropriate lty value. Then you can pass a list of values to lty and each will be interpreted properly.


text:
Q: MySQL server has gone execute large script files Please help me to get rid of this errors
While i run some large number of mysql scripts at once i got this kind of errors

ERROR: 2006  MySQL server has gone away Error: 1153  Got a packet
  bigger than 'max_allowed_packet' bytes

How to get rid of this error, im using Navicat mysql and WAMP server??
In running scripts i choose continue on error so scripts still running with error msgs and values in Message log. Will this work and can i run the error values later??

A: try using these commands from mysql terminal
set global max_allowed_packet=1000000000;
set global net_buffer_length=1000000;

A: The answer from ayush solves it, but if you un-check the option "Run multiple queries in each execution" in the dialog box when executing SQL file it might do the trick as well (but the execution will take longer to run).


text:
Q: what are some exotic spaces over which people have defined random variables? We usually formulate random variables as functions from some probability space to the space of real numbers $\mathbb R^n$, i.e. vector-valued random variables. A more exotic application is a random variable as a function to a function space, such as with Brownian motion, i.e. function valued random variables.
What are some more exotic spaces over which we can define random variables, that have actually been studied and possibly applied in non-trivial ways?


text:
Q: SQL Query without nested queries Let's say we have these tables;
table user:
- id
- username
- email
table user2group:
- userid
- groupid
table group:
- id
- groupname
How do I make one query that returns all users, and the groups they belong to (as an array in the resultset or something..)

A: select u.id, u.username, u.email, g.groupid, g.groupname
from user u
join user2group ug on u.userid=ug.userid
join group g on g.groupid=ug.groupid
order by u.userid

As you are looping through the result set, each time you see a new userid make a new user object (or whatever) and add the groups to it.

A: Eric's answer is great, but I would use a LEFT JOIN instead of an INNER to get users that do not belong to any group as well.
SELECT
  u.id,
  u.username,
  u.email,
  g.groupid,
  g.groupname
FROM
  user u
  LEFT JOIN user2group ug ON u.userid = ug.userid
  LEFT JOIN group g ON g.groupid = ug.groupid
ORDER BY
  u.userid

A: Both of the above are more or less correct (deepends if each user has a group or not). But they will also both give a result set with several entries for each user.
There are ways of concatenating every group member into one comma separated string, I'd suggest you read about it here:
http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/
Another method I personally like is to use bit values instead of the relational table user2group
table user then gets a int (or bigint) field group, and each group ID is assigned one bit value (ie: 1,2,4,8,16 and so on) The value of the user table's group field is then the sum of the groupID it's assigned to. To query if its got a group you do:
where (group AND groupID = groupID)


text:
Q: Is R's names function equal to Pandas df.columns? I'm given a task of converting an R script to Python. I'm trying to understand the functionality.
It is mentioned as below in the script.
#get id for single_triad
id <- names(forecast_object_list[single_triad_index])

forecast_object_list is something that is returned from R's by() function. I'm not sure if it's going to be a list or dataframe in R.
single_triad_index is an integer counter in a for loop.
What does this names() function actually do?
I don't have access to databases that are used in the R script to execute and look at the format of data.
After some research, I understood that it is returning headers in a dataframe. http://www.endmemo.com/program/R/names.php
Does that mean I can use pandas's df.columns to get the column names from a dataframe like:
list(my_dataframe.columns.values)
Are these two equal? or am I assuming it wrong?

A: names() returns the names of an object's elements. For example, if we call names on each of the following elements R will return [1] "a" "b":
ve <- c(a = 1, b = 2) # atomic vector
li <- list(a = 1, b = 2) # list
df <- data.frame(a = 1, b = 2) # data frame

For your purposes it would worth knowing that data frames are just a special kind of list - is.list(li) and is.list(df) will both return TRUE. That means that, depending on what you are doing, you frequently don't need to differentiate between these two data objects. That said, sometimes there are differences, e.g. while names() works for both data frames and lists, colnames() will only work for data frames (and matrices, etc.). It ultimately depends on the available attributes.
If we compare the above to Python then the result seems to be the same. I think the main difference is that names() is a generic accessor that can be used with multiple data object types, while .columns is a specific attribute of the Pandas DataFrame object.
df = DataFrame({'a':[1], 'b':[2]})
df.columns.to_list()
# ['a', 'b']


text:
Q: You have an error in your SQL syntax;
You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near ''14
') UNION (SELECT * FROM staff WHERE city_id = '368' AND gender = '' at
  line 1

Code:
(SELECT * FROM staff
     WHERE city_id = '2' AND gender = 'MALE' AND staff_status != '3'
     ORDER By s_level ASC LIMIT '$new_sixty')
UNION
(SELECT * FROM staff
     WHERE city_id = '2' AND gender = 'FEMALE' AND staff_status != '3'
     ORDER By s_level ASC LIMIT '$new_forty');

A: Remove the ' ' from the limit
(SELECT * FROM staff WHERE city_id = '2' AND gender = 'MALE' AND staff_status != '3' ORDER By s_level ASC LIMIT $new_sixty) UNION
    (SELECT * FROM staff WHERE city_id = '2' AND gender = 'FEMALE' AND staff_status != '3' ORDER By s_level ASC LIMIT $new_forty);


text:
Q: Identify if an iOS In-App Purchase is a consumable or non-consumable? I need a small help to know if what I propose in my iOS app is a consumable currency or not.
From the Apple Developer In-App Purchase webpage:

Consumable
Users can purchase different types of consumables, such as lives or gems in a game, to further their progress through an app. Consumable in-app purchases are used once, are depleted, and can be purchased again.

Users can buy a currency that has a name, such as "bucks", for example: 100 bucks can be bought for $1.
User can receive or send this currency to another user. When desired, he can convert this virtual currency to money = for example: $1 for 95 bucks.
This currency is like a cryptocurrency and my app is not a game.
So is this currency a consumable or non-consumable? I need help with understanding to prevent my app from getting rejected.

A: If an item can be used once and then is not available again, it is a consumable.
If an item can be reused over and over, it's a non-consumable.
This is explained in the developer Apple's IAP overview you referenced:

Consumable
Users can purchase different types of consumables, such as lives or gems in a game, to further their progress through an app. Consumable in-app purchases are used once, are depleted, and can be purchased again.
Non-Consumable
Users can purchase non-consumable, premium features within an app. Non-consumables are purchased once and do not expire, such as additional filters in a photo app. Apple can host content associated with your non-consumable in-app purchases.

Based on your comments, I would say you have a Consumable IAP.  You app could be reject for other reasons, though, so this is no guarantee that it will pass App Review.

A: If your app is a currency (the value is consumed outside the app or generated / mined / calculated outside the app) then you need to worry more about section 3.1.5 Goods & Services

*

*https://developer.apple.com/app-store/review/guidelines/#goods-and-services
These sections restrict outside consumables to prohibit in app purchase, and you would use ApplePay section 3.1.5(a) since this is direct trade and commerce. If your currency has any sort of investment or risk, then it's a trading app section 3.1.5(b).
Only if your currency is consumed and purchased multiple times, would you have to understand if it's consumed within the app exclusively.
Since you are primary currency and trading, IAP isn't going to govern your approval or rejection at all.


text:
Q: Run ESLint from NPM script on Windows In my project I'm trying to implement ESLint as part of a build process that is launched from an npm script.
I've got eslint and all of the plugins I need all installed as npm packages and I've got my .eslintrc file all setup.  When I then run the command ...
eslint src

... on a mac, everything works perfectly.  I can therefore take that command and stick it into an npm script and it works just fine.
However, on windows I'm experiencing a problem.  When I install the eslint npm package I am unable to use eslint from the command line.  I see that it has installed in the node_modules directory and that it put the executable in the node_modules/.bin directory, but when I run the command ...
eslint src

... I get an error saying that the eslint command is not found.
I can get it to work if I install eslint and all of my plugins globally, but this isn't ideal because anyone else who clones my code will need to do that also.  It's as if on windows, the command line does not have a path mapped to node_modules/.bin.
I tried to solve this problem with this little trick :
PATH=$(npm bin):$PATH eslint src

When I run this command directly from the command line it seems to be able to find the eslint command and everything works perfectly.  However, when I place that same command into an npm script, the script runs with no output and no error.
Any direction on how to get this working would be awesome.  Thanks.

A: If you configure your package.json this way
{
  "name": "test",
  "version": "0.1.1",
  "description": "Validate files with ESLint",
  "scripts": {
    "test": "eslint src"
  },
  "devDependencies": {
    "eslint": "^2.0.0",
    "eslint-config-ideal": "^0.1.0"
  }
}

Now just run
npm install

and after that run
npm test

This is should work across OS.
Note: If you run eslint directly then you need to install the eslint globally with npm install eslint -g command.


text:
Q: Filter pandas dataframe based on a column: keep all rows if a value is that column So I have a dataframe like the following:
Name    Age    City
A       21     NY
A       20     DC
A       35     OR
B       18     DC
B       19     PA

I need to keep all the rows for every Name and Age pair where a specific value is among those associated with column City. For example if my target city is NY, then my desired output would be:
Name    Age    City
A       21     NY
A       20     DC
A       35     OR

Edit1: I am not necessarily looking for a single value. There might be cases where there are multiple cities that I am looking for. For example: NY and DC at the same time.
Edit2: I have tried the followings which does not return correct output (daah):
df = df[df['City'] == 'NY']

and
df = df[df['City'].isin('NY')]

A: You can create function - first test City for equal and get all unique names for again filtering by isin:
def get_df_by_val(df, val):
    return df[df['Name'].isin(df.loc[df['City'].eq(val), 'Name'].unique())]

print (get_df_by_val(df, 'NY'))
  Name  Age City
0    A   21   NY
1    A   20   DC
2    A   35   OR

print (get_df_by_val(df, 'PA'))
  Name  Age City
3    B   18   DC
4    B   19   PA

print (get_df_by_val(df, 'OR'))
  Name  Age City
0    A   21   NY
1    A   20   DC
2    A   35   OR

EDIT:
If need check multiple values per groups use GroupBy.transform with compare sets with issubset:
vals = ['NY', 'DC']

df1 = df[df.groupby('Name')['City'].transform(lambda x: set(vals).issubset(x))]
print (df1)
  Name  Age City
0    A   21   NY
1    A   20   DC
2    A   35   OR


text:
Q: Ignore errors in sql files in VS 2012 I have ".sql" files in my VB.NET projects in Visual Studio 2012.
They are configured as:
Build Action = None
Copy to output Directory = Copy Always

When the file is open in the text editor in Visual Studio, I get compile errors.
When the file is closed, I don't get compile errors.
I don't want it to find errors in these files, because I don't want to prevent the project from successfully building.  These are basically just text files for me.
Any ideas on how to disable this?
(An example of an error would be SQL80001: Incorrect syntax near '<', which makes sense because it IS invalid SQL, but is how I want it.)

A: The phantom errors, while annoying, will not prevent the project from successfully building. They will just cloud up the error list and make finding the real issues more difficult.  I know this does not address your core problem but it should at least get your project building!


text:
Q: Windows 2012 R2 - L1 cache N/A I have a number of Windows 2012 R2 servers running as VMs on a XenServer 7.0 host. When I open Task Manager in any VM, it reports the L1 cache to be "N/A". The server is a decent spec, only a year old, a Dell R730. Should I be concerned or is this normal, and if so, why?

A: It's because XenServer doesn't pass this information to the VM's. Nothing to worry about.


text:
Q: How to avoid page break after \part entry in ToC with memoir I am using the memoir class for a document with many chapters and parts.
In the ToC sometimes there is a page break between the name of \part and the name of the next chapter.
Table of Contents

Part I
1. Chapter ........... 5
2. Chapter ........... 10
3. Chapter ........... 15

Part II
1. Chapter ........... 20
2. Chapter ........... 25
3. Chapter ........... 30

Part III
‹page breaks here›

I tried to find out in the memoir documentation, but as a beginner I did not understand how to avoid the page breaking after a new part.
As Steven explained to me here (look there for an example), I certainly have to use needspace, but I don't now how.

A: One of the (IMO) best ways to fix something like this is to make the space above \part and \chapter entries flexible, that usually solves the problem. Otherwise use the
\addtocontents{toc}{\protect\newpage}
\part{title}

Not sure what you mean by "but I would prefer a solution, that avoid such a page break in the header"
\setlength{\cftbeforepartskip}{2.25em plus 0.5em minus 0.5em}
% default is 1em plus 0pt
\setlength{\cftbeforechapterskip}{1.0em plus 0.5em minus 0.25em}
% default is 1em plus 0pt


text:
Q: When should you use  as opposed to
*? What determines whether one should prefer to use <ul> over <article>, or vice versa in a HTML document?
As an example I have a portfolio page with a list of items, which would be more appropriate?

A: Element names form part of the semantic web/HTML, so you should use the one you deem most appropriate for your content, MDN is often a good resource to get an overview on what appropriate content may be, some suggestions from which are below.
Lists tend to include shorter, more concise often text only or very image-light content. It sounds like you likely want to look at the section or article tags.
Section

The HTML Section Element (<section>) represents a generic section of a
  document, i.e., a thematic grouping of content, typically with a
  heading.

Article

The HTML <article> Element represents a self-contained composition in
  a document, page, application, or site, which is intended to be
  independently distributable or reusable, e.g., in syndication. This
  could be a forum post, a magazine or newspaper article, a blog entry,
  a user-submitted comment, an interactive widget or gadget, or any
  other independent item of content.

List (ul)

The HTML unordered list element (<ul>) represents an unordered list of
  items, namely a collection of items that do not have a numerical
  ordering, and their order in the list is meaningless. Typically,
  unordered-list items are displayed with a bullet, which can be of
  several forms, like a dot, a circle or a squared.


text:
Q: Play-Services-Maps and Android Studio 3.3 issue with AndroidX involving Annotation library I've recently updated my project to build from Android Studio 3.3, which involved making the following changes (prompted on Android Studio startup):
build.gradle dependency:
classpath 'com.android.tools.build:gradle:3.3.0'
gradle-wrapper:
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip
This produced a number of errors in a feature module when trying to sync which uses Google Maps. I'm using version 16.0.0 of play-services-maps:
implementation "com.google.android.gms:play-services-maps:16.0.0"
The errors that appeared when trying to sync gradle were:
ERROR: Unable to resolve dependency for ':featureModule@flavorDebugFeature/compileClasspath': Could not resolve androidx.annotation:annotation:1.0.0.

ERROR: Unable to resolve dependency for ':featureModule@flavorDebugFeature/compileClasspath': Could not resolve androidx.annotation:annotation:1.0.1.

ERROR: Unable to resolve dependency for ':featureModule@flavorDebugFeature/compileClasspath': Could not resolve androidx.core:core:1.0.0.

ERROR: Unable to resolve dependency for ':featureModule@flavorDebugFeature/compileClasspath': Could not resolve androidx.core:core:1.0.1.

This is repeated for every possible flavour variant combination in this module.
It's worth pointing out that this project was migrated to androidX some months ago and has been working fine.
The fix for the errors are to add the following to the gradle dependencies for that failing module:
implementation "androidx.annotation:annotation:1.0.1"
implementation "androidx.core:core:1.0.1"

The app then compiles fine and runs on device. Perfect. Until we try and run lint in a CI build before release on the project, and we hit a spot of bother, with the error message:
Execution failed for task ':featureModule:lintFlavorDebug'.
> Lint infrastructure error
  Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
... [several lines omitted for brevity]
 Caused by: java.lang.IllegalStateException: Expected task 'processFlavorDebugAndroidTestJavaRes' output files to contain exactly one file, however, it contains no files.
    at org.gradle.api.internal.file.AbstractFileCollection.getSingleFile(AbstractFileCollection.java:65)
    at com.android.build.gradle.internal.variant.BaseVariantData.getJavaResourcesForUnitTesting(BaseVariantData.java:700)
    at com.android.build.gradle.internal.ide.ModelBuilder.createAndroidArtifact(ModelBuilder.java:992)
    at com.android.build.gradle.internal.ide.ModelBuilder.createVariant(ModelBuilder.java:617)
    at com.android.build.gradle.internal.ide.ModelBuilder.buildAndroidProject(ModelBuilder.java:399)
    at com.android.build.gradle.internal.ide.ModelBuilder.buildAll(ModelBuilder.java:212)
    at com.android.tools.lint.gradle.LintGradleExecution.createAndroidProject(LintGradleExecution.java:352)
    at com.android.tools.lint.gradle.LintGradleExecution.analyze(LintGradleExecution.java:85)
    ... 59 more

This issue goes away if we remove the 2 new dependencies (plus Google Maps, which seems to be the cause of the requirement for the core and annotations libraries).
I've done some searching both here and via Google, and the Expected task 'processFlavorDebugAndroidTestJavaRes' output files to contain exactly one file, however, it contains no files. exception has been seen by others, and their solution is to make sure the base build.gradle file has the baseFeature true flag in defaultConfig, which is already present in my project.
I'm now stuck for where to go next in trying to solve this issue.


text:
Q: batch script to overwrite a file set path=folderX
( for /F "delims=" %%a in (!path!/file.txt) do (
   set "line=%%a"
   if !line!==Status=ON (
   set line=Status=OFF
   echo !line!
   )

)) > "!path!/file.txt"

what this script is suppose to do is open file.txt in folderX, replace the line Status=ON with Status=OFF. But when I run the code it says System cannot find the file folderX/file.txt, if I look at the file it turns into a blank file. If I assign a different name (file2.txt) then it works and file2.txt is correctly edited and placed in the right folder. Why is this? I thought it would overwrite the original by using >

A: You are reading from the same file you are writing to.  Use a different filename and add a rename or move command as the last line.


text:
Q: Elasticsearch Painless script search document based on availability I'm using ES version 7.0. I have a index of stores with availability (opening and closing time) in UTC time. I stored time in Integer so that it can be easy to match with the current time in painless script.
One sample doc is below:
{
          "availability" : {
            "thu" : [
              {
                "start" : 0,
                "end" : 400
              },
              {
                "start" : 1300,
                "end" : 2400
              }
            ],
            "tue" : [
              {
                "start" : 1300,
                "end" : 2400
              },
              {
                "start" : 0,
                "end" : 400
              }
            ],
            "wed" : [
              {
                "start" : 0,
                "end" : 400
              },
              {
                "start" : 1300,
                "end" : 2400
              }
            ],
            "sat" : [
              {
                "start" : 1400,
                "end" : 2400
              },
              {
                "start" : 0,
                "end" : 500
              }
            ],
            "fri" : [
              {
                "start" : 0,
                "end" : 400
              },
              {
                "start" : 1300,
                "end" : 2400
              }
            ],
            "mon" : [
              {
                "start" : 0,
                "end" : 200
              },
              {
                "start" : 1300,
                "end" : 2400
              }
            ],
            "sun" : [
              {
                "start" : 1400,
                "end" : 2400
              },
              {
                "start" : 0,
                "end" : 200
              }
            ]
          },

.
.
.
.
    }

below is the query with painless script:
GET stores/_search
{
  "query": {
    "bool": {
      "filter" : {
        "script" : {
          "script" : {
            "source": "String d = params.day, start_key = 'availability.'+d+'.start', end_key = 'availability.'+d+'.end'; long t = params.time; if(doc[start_key].size() != 0 && doc[end_key].size() != 0){ long s =  doc[start_key].value; long e = doc[end_key].value; return (s <= t && e > t); }",
            "lang": "painless",
            "params" : {
                "day" : "wed",
                "time" : 300
              }
          }
        }
      }
    }
  }
}

The above query is working for time 300 for Wednesday and giving the above doc in result but not working for time 1400 on Wednesday. Looks like script is matching always the first value from the availability array.
I also tried to loop through the day of availability but that is giving me no field found error.
GET stores/_search
{
  "query": {
    "bool": {
      "filter" : {
        "script" : {
          "script" : {
            "source": "String d = params.day, start_key = 'availability.'+d+'.start', end_key = 'availability.'+d+'.end'; long t = params.time; if(doc[start_key].size() != 0 && doc[start_key].size() != 0){ for(item in doc['availability.'+d]){ long s =  item['start'].value; long e = item['end'].value; if (t >= s && t < e){ return true; } }}",
            "lang": "painless",
            "params" : {
                "day" : "wed",
                "time" : 300
              }
          }
        }
      }
    }
  }
}

The above query returns the below error
{ ....
"reason": {
          "type": "script_exception",
          "reason": "runtime error",
          "script_stack": [
            "org.elasticsearch.search.lookup.LeafDocLookup.get(LeafDocLookup.java:94)",
            "org.elasticsearch.search.lookup.LeafDocLookup.get(LeafDocLookup.java:41)",
            "for(item in doc['availability.'+d]){ long ",
            "                ^---- HERE"
          ],
          "script": "String d = params.day, start_key = 'availability.'+d+'.start', end_key = 'availability.'+d+'.end'; long t = params.time; if(doc[start_key].size() != 0 && doc[start_key].size() != 0){ for(item in doc['availability.'+d]){ long s =  item['start'].value; long e = item['end'].value; if (t >= s && t < e){ return true; } }}",
          "lang": "painless",
          "caused_by": {
            "type": "illegal_argument_exception",
            "reason": "No field found for [availability.wed] in mapping with types []"
          }
        }
..... }

Also getting error while using doc['availability']['wed']
Anything that I'm missing here?

A: If availability.wed is of type object use below
{
  "query": {
    "script": {
      "script": {
        "source": "String d = params.day; for(int i=0; i<doc['availability.'+params.day+'.start'].length;i++){ long start =doc['availability.'+params.day+'.start'][i]; long end = doc['availability.'+params.day+'.end'][i]; if(start <= params.time && end > params.time){ return true;}} ",
        "lang": "painless",
        "params": {
          "day": "wed",
          "time": 2300
        }
      }
    }
  }
}

If availability.wed is of type nested use below
Mapping:
PUT testindex10/_mappings
{
  "properties": {
    "name":{
      "type": "text"
    },
    "availability": {
      "type": "object",
      "properties": {
        "mon": {
          "type": "nested",
          "properties": {
            "start": {
              "type": "integer"
            }
          }
        },
        "tue": {
          "type": "nested",
          "properties": {
            "start": {
              "type": "integer"
            }
          }
        },
        "wed": {
          "type": "nested",
          "properties": {
            "start": {
              "type": "integer"
            }
          }
        },
        "thu": {
          "type": "nested",
          "properties": {
            "start": {
              "type": "integer"
            }
          }
        },
        "fri": {
          "type": "nested",
          "properties": {
            "start": {
              "type": "integer"
            }
          }
        },
        "sat": {
          "type": "nested",
          "properties": {
            "start": {
              "type": "integer"
            }
          }
        }
      }
    }
  }
}

Data:
[
      {
        "_index" : "testindex10",
        "_type" : "_doc",
        "_id" : "snyiPm0ButCCF6l_WyTl",
        "_score" : 1.0,
        "_source" : {
          "name" : "store1",
          "availability" : {
            "mon" : [
              {
                "start" : 0,
                "end" : 400
              },
              {
                "start" : 1300,
                "end" : 2400
              }
            ],
            "tue" : [
              {
                "start" : 1300,
                "end" : 2400
              },
              {
                "start" : 0,
                "end" : 400
              }
            ],
            "wed" : [
              {
                "start" : 0,
                "end" : 200
              },
              {
                "start" : 1300,
                "end" : 2400
              }
            ],
            "thu" : [
              {
                "start" : 1400,
                "end" : 2400
              },
              {
                "start" : 0,
                "end" : 500
              }
            ],
            "fri" : [
              {
                "start" : 0,
                "end" : 400
              },
              {
                "start" : 1300,
                "end" : 2400
              }
            ]
          }
        }
      },
      {
        "_index" : "testindex10",
        "_type" : "_doc",
        "_id" : "s3yiPm0ButCCF6l_liQq",
        "_score" : 1.0,
        "_source" : {
          "name" : "store2",
          "availability" : {
            "mon" : [
              {
                "start" : 0,
                "end" : 400
              },
              {
                "start" : 1300,
                "end" : 2400
              }
            ],
            "tue" : [
              {
                "start" : 1300,
                "end" : 2400
              },
              {
                "start" : 0,
                "end" : 400
              }
            ],
            "wed" : [
              {
                "start" : 0,
                "end" : 500
              },
              {
                "start" : 1300,
                "end" : 2400
              }
            ],
            "thu" : [
              {
                "start" : 1400,
                "end" : 2400
              },
              {
                "start" : 0,
                "end" : 500
              }
            ],
            "fri" : [
              {
                "start" : 0,
                "end" : 400
              },
              {
                "start" : 1300,
                "end" : 2400
              }
            ]
          }
        }
      }
    ]

Query
GET testindex10/_search
{
  "query": {
    "bool": {
      "filter": {
        "nested": {
          "path": "availability.wed",
          "query": {
            "script": {
              "script": {
                "source": "String d = params.day; long start =doc['availability.'+params.day+'.start'].value; long end = doc['availability.'+params.day+'.end'].value; if(start <= params.time && end > params.time){ return true;}  ",
                "lang": "painless",
                "params": {
                  "day": "wed",
                  "time": 400
                }
              }
            }
          }
        }
      }
    }
  }
}

Result:
 [
      {
        "_index" : "testindex10",
        "_type" : "_doc",
        "_id" : "s3yiPm0ButCCF6l_liQq",
        "_score" : 0.0,
        "_source" : {
          "name" : "store2",
          "availability" : {
            "mon" : [
              {
                "start" : 0,
                "end" : 400
              },
              {
                "start" : 1300,
                "end" : 2400
              }
            ],
            "tue" : [
              {
                "start" : 1300,
                "end" : 2400
              },
              {
                "start" : 0,
                "end" : 400
              }
            ],
            "wed" : [
              {
                "start" : 0,
                "end" : 500
              },
              {
                "start" : 1300,
                "end" : 2400
              }
            ],
            "thu" : [
              {
                "start" : 1400,
                "end" : 2400
              },
              {
                "start" : 0,
                "end" : 500
              }
            ],
            "fri" : [
              {
                "start" : 0,
                "end" : 400
              },
              {
                "start" : 1300,
                "end" : 2400
              }
            ]
          }
        }
      }
    ]

Another way to solve same without script(better performance) would be
{
  "query": {
    "bool": {
      "filter": {
        "nested": {
          "path": "availability.wed",
          "query": {
            "bool": {
              "must": [
                {
                  "range": {
                    "availability.wed.start": {
                      "lte": 400
                    }
                  }
                },
                {
                  "range": {
                    "availability.wed.end": {
                      "gte": 400
                    }
                  }
                }
              ]
            }
          }
        }
      }
    }
  }
}


text:
Q: PHP function to use password_hash, hash or MD5 depending on availability I'm creating a script and would ideally like to convert user password into a hash using password_hash function, however I want to make the hashing dynamic to make sure password_hash function actually exists, so i've written the following function to return a hash depending on what function is available.
function generateHash($hashpwd){
    if (function_exists('password_hash')) {
        return password_hash($hashpwd, PASSWORD_DEFAULT);
    } elseif (function_exists('hash')) {
        return hash('sha512', $hashpwd);
    } else {
        return md5($hashpwd);
    }
}

Is there anything wrong with this method or will it work? also I am creating the hash using password_hash in the following way:
password_hash($hashpwd, PASSWORD_DEFAULT);

But most places i've seen example syntax in the following format:
password_hash($hashpwd, PASSWORD_DEFAULT)."\n";

Difference being the \n is the \n needed and what is it for?

A: Every version of PHP that lacks password_hash (below 5.5) is now end-of-lifed and insecure as a result. It is a) not worth accounting for these now dangerously-insecure versions of PHP, and b) not worth the security hit to your users caused by downgrading to MD5 as the hashing algorithm.

But most places i've seen example syntax in the following format:
password_hash($hashpwd, PASSWORD_DEFAULT)."\n";

I've never, ever seen this done. \n is a new line. Saving that into your database alongside the hash will cause problems - it'd only be worth doing if you were outputting the hash somewhere for debugging/viewing.

A: *

*A single unsalted SHA512 is a bad fallback for password_hash. At the very least you need to use a different algorithm here including a salt. Preferably use crypt with a decent hash algorithm, which is what password_hash wraps anyway.

*There's a password_hash backport available for PHP 5.3.7+, depending on your OS even some older versions. You shouldn't realistically need to support anything older than that. You need to draw the line in the sand somewhere. Most new projects require at least 5.6+. If you need to support anything older, use a trusted library like PHPass, which is backwards compatible until PHP 3.

*password_hash($hashpwd, PASSWORD_DEFAULT)."\n"; is just for debugging output, the trailing newline is not part of the password hash.

A: You wrote:

Is there anything wrong with this method or will it work? also I am creating the hash using password_hash in the following way:

password_hash($hashpwd, PASSWORD_DEFAULT);

But most places i've seen example syntax in the following format:

password_hash($hashpwd, PASSWORD_DEFAULT)."\n";

Difference being the \n is the \n needed and what is it for?

There is a difference between both, a big one.
The second one will embed a hidden line break character that will make  your password verification fail silently.
As per this user contributed note about the use of password_hash() supplied by Jay Blanchard, a member here on Stack Overflow.

Be care when using the example from the documentation which concatenates a newline character \n to the end of the hash, i.e.:
echo password_hash("rasmuslerdorf", PASSWORD_DEFAULT)."\n";
People are storing the hash with the concatenated newline and consequently password_verify() will fail.

Edit:
September 29th, 2017.
Special note:
I revisited the manual on password_hash() today and noticed that they removed the user contributed note http://php.net/manual/en/function.password-hash.php#121017 (supplied by Jay Blanchard) where the documentation was modified to remove the \n reference, where it now reads as:
echo password_hash("rasmuslerdorf", PASSWORD_DEFAULT);

which removed the ."\n" from it.
This now has a bearing on the question asked and answers given.
I believe this had something to do with a bug report filed yesterday, as per this comment in another answer inside this same question.
I also have to note that this modification (of the manual's syntax) could have adverse effects on previously posted answers stating that the url is no longer valid.
Personally, I feel they should have kept that note in there and/or stated something about its previous usage.


text:
Q: Python class methods In Python, which is the best way (style wise) to allow public access to an object's variables?
There are lots of options I've seen from different languages, I was wondering which of these (if any) is the preferred Python method? These are the options I'm currently torn between:

*

*Allow direct access to object variables (e.g. print(object.variable)), ignore data hiding

*Allow access to object variables by a wrapper function:

class X:
    variable_a = 0
    variable_b = 0
...
    def get_variable_a(self):
        return self.variable_a

If this is the recommended way, how do you name the methods? (get_variablename(), or just variablename etc?)
What does everyone recommend for this?
thanks!
Lucy

A: Don't bother using accessors until they're necessary; converting a simple attribute to a property is quick and easy, and doesn't need modification of client code.
When I write a property, I use _get_FOO() and _set_FOO() for the accessors, and _FOO for the attribute itself.

A: There are no "private" variables in Python. Check section 9.6 of this document http://docs.python.org/tutorial/classes.html
There is a convention though, that the users of the class should treat variables with names, starting with underscore to be not touched directly. Still, there is no mechanism which may prevent this.
Same with the mangled names (starting with 2 underscores).

A: Just allow direct access to any variables that you wish to expose as the public API. If you need to change the behavior you can always turn it into a property later on.
Notice that this is orthogonal to information hiding. obj.get_some_implementation_detail() is no better than obj.some_implementation_detail.

A: You can use
Getters and setters (Java like)
class SomeClass(object):
  ...

  def get_x(self):
    return self._x
  def set_x(self, x):
    self._x = x

c = SomeClass()
print c.get_x()
c.set_x(10)

Properties (C# like)
class SomeClass(object):
  ...

  def get_x(self):
    return self._x
  def set_x(self, x):
    self._x = x
  x = property(get_x, set_x)

c = SomeClass()
print c.x
c.x = 10

I think it is merely a matter of style. Choose the one you like better. Same applies to the naming convention, choose one convention and stick to it.
In any case, data hiding can be done with pseudo-private variables (beginning with two underscores). They cannot be accessed directly, as opposed to the example variables (_x not starting with two underscores).


text:
Q: Pandas aggregate to a list of dicts I have pandas dataframe like this (single column):
request_headers
0   {'name': 'name1', value: 'value1'}
0   {'name': 'name2', value: 'value2'}
.....

Would like to aggregate many such records to a single record with a column which is a list of the above directories, like this:
request_headers
0   [{'name': 'name1', value: 'value1'}, {'name': 'name2', value: 'value2'}]

How to do that ? (tried with agg({col:  lambda x: ",".join(x)}) and few similar but failing)
Thanks,
Update: Answer somebody provided is not correct, it's easy to do it for non-dict values, but for dict values we got error that it's unhashable. So the question is still valid. The problem here is that column value is a dict.
Update2: OK, sorry, one more example:
details = {
    'request_headers' : [{"name": "name1", "value": "value1"}, {"name": "name2", "value": "value2"}],
}

df = pd.DataFrame(details)
df.groupby(df.index).agg(list)

is giving me:
0   [{'name': 'name1', 'value': 'value1'}]
1   [{'name': 'name2', 'value': 'value2'}]

While i would like to get:
0 [{'name': 'name1', 'value': 'value1'},{'name': 'name2', 'value': 'value2'}]

So technically it's not even groupby, but some concatenation ?
(i have actually exploded my df before and need to "implode" it now)


text:
Q: localScroll next prev button iam creating an fullscreen scroller, with localScroll/scrollTo.
now i need help with next- prev buttons . and maybe keyboard buttons.
any one can help me.
code at  http://www.hell-yeah.se/localscroll
the anchor codes is p1,p2,p3,p4,p5,p6 and so on so maybe its posible to make something with that.
/ Erik


text:
Q: express route matching a regex I am using expressjs and I want to create a route except for all the paths that start with /api/2.
This is what I tried

app.get(/^((?!\/api\/2).)*$/, home.index)

Am I doing something wrong here? Couldn't find much information on how to declare regex routes.
Help appreciated. Thanks


text:
Q: File length and Byte[] size doesn't match in JAVA I am trying to convert a image to byte[] which will be sent to a service, will determine the file size if it is allowable or not. But I am getting different size in of actual image file and byte[].
My test code:
File file=new File("path/photo.jpg"); //around 4.5 MB
img = ImageIO.read(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", bos );
byte [] data = bos.toByteArray();
System.out.println("fileSize:"+file.length());
System.out.println("byteSize:"+ data.length);

output
 fileSize:4544732 //equals to actual image size
 byteSize:1468863

My target is: I need to measure the actual filesize from the byte[] of that image.

A: ImageIO is not needed for your use-case.
Try this instead.
final byte[] content = Files.readAllBytes(file.toPath());


text:
Q: Why is the variable x not locally scope in the StringExpression?  Clear[x]
 StringCases["abcadcacb","a"~~x_~~"c"->x]

{b,d}

 x=99;
 StringCases["abcadcacb","a"~~x_~~"c"->x]

{99,99}

This fails even if x is local in a Module
Module[{x}, StringCases["abcadcacb", "a" ~~ x_ ~~ "c" -> x]]

A: Why x_->x causes problems is explained in:
Unexpected behavior of rule matching a pattern
Shortly, use :>.
Why Module fails to help? While Rule is not a scoping construct it is considered one by Module. Which means x inside will not be scoped by Module if x_ appears in a left hand side of rule.:
Module[{x},
  Hold @ Column @ {
    Rule[x_, x]
  , RuleDelayed[x_, x]
  , Module[{x}, x]
  , DirectedEdge[x_, x]
  , foo[x_, x]
  , Rule[y_, y x]}
 ]

Relevant part of docs:

Symbols that occur as pattern names in lhs are treated as local to the rule. This is true when the symbols appear on the right-hand side of /; conditions in lhs, and when the symbols appear anywhere in rhs, even inside other scoping constructs.
ref/Rule/Details

About issues with nested scoping constructs you can take a look at:
Enforcing correct variable bindings and avoiding renamings for conflicting variables in nested scoping constructs
which also explains the last example with y_->y x.
Also related:
Unexpected behavior of rule matching a pattern


text:
Q: SPF soft fail when sending E-Mails to a google group I am experiencing weird behaviour when trying to send emails to a google group (managed by Google Apps).
I am convinced that my SPF configuration, including both IPv4 and IPv6 addresses of my sender domain nl.nix-wie-weg.de is correct, because if I am sending E-Mails through the smarthost of our mail provider to my personal Gmail address, all SPF tests pass according to the mail headers:
Received-SPF: pass (google.com: domain of newsletter@nl.nix-wie-weg.de designates 2a01:488:42:1000:57e6:3c52:: as permitted sender) client-ip=2a01:488:42:1000:57e6:3c52::;
Authentication-Results: mx.google.com;
       spf=pass (google.com: domain of newsletter@nl.nix-wie-weg.de designates 2a01:488:42:1000:57e6:3c52:: as permitted sender) smtp.mail=newsletter@nl.nix-wie-weg.de

Also notice the Return-Path: being identical to the From: header:
Return-Path: <newsletter@nl.nix-wie-weg.de>

However, if I am sending the same email from the same sender with the exact same SMTP host to an email address that is a Google Group (created by our Google Apps account to send email to every single employee) I can observe SPF tests failing:
Return-Path: <alle+bncBAABBDOPVCNQKGQEYW5JKQQ@nix-wie-weg.de>
Received: from mail-lb0-f198.google.com (mail-lb0-f198.google.com [209.85.217.198])
        by mx.google.com with ESMTPS id zo5si4843525lbb.224.2014.05.07.05.31.10
        for <florian.unglaub@nix-wie-weg.de>
        (version=TLSv1 cipher=ECDHE-RSA-RC4-SHA bits=128/128);
        Wed, 07 May 2014 05:31:10 -0700 (PDT)
Received-SPF: softfail (google.com: domain of transitioning alle+bncBAABBDOPVCNQKGQEYW5JKQQ@nix-wie-weg.de does not designate 87.139.167.110 as permitted sender) client-ip=87.139.167.110;

Notice the Return-Path: suddenly differing from the previous mail. The IP address mentioned in the headers 87.139.167.110 is our local dial-up IP address. How does this make sense? Furthermore, I don't see any reason why the SPF checks should suddenly affect the Return-Path: email address?
The remaining SPF checks in the header seam to work fine:
Received: from vwp0075.webpack.hosteurope.de (vwp0075.webpack.hosteurope.de. [2a01:488:42:1000:57e6:3c52::])
        by mx.google.com with ESMTPS id z42si16241162eel.62.2014.05.07.05.31.09
        for <alle@nix-wie-weg.de>
        (version=TLSv1 cipher=RC4-SHA bits=128/128);
        Wed, 07 May 2014 05:31:09 -0700 (PDT)
Received-SPF: pass (google.com: domain of newsletter@nl.nix-wie-weg.de designates 2a01:488:42:1000:57e6:3c52:: as permitted sender) client-ip=2a01:488:42:1000:57e6:3c52::;

Any hints or help is really appreciated. Thanks.

A: Add your IP address to your DNS entry for SPF.
Change: v=spf1 mx include:aspmx.googlemail.com include:_spf.google.com ~all
To this: v=spf1 mx include:aspmx.googlemail.com include:_spf.google.com ip4:87.139.167.110 ~all


text:
Q: Interchanging Summation and Integral Lets Think of this: I posted a question and got a wonderful answer by a smart user, but I couldn't understand part of the method.
$$\begin{align}
\sum_{n=1}^{\infty}\frac{1}{9n^2 + 3n - 2}
&=\frac{1}{3}\sum_{n=1}^{\infty}\left(\frac{1}{3n - 1}-\frac{1}{3n + 2}\right)\\\\
&=\frac{1}{3}\sum_{n=1}^{\infty}\int_0^1\left(x^{3n-2}-x^{3n+1}\right){\rm d}x\\\\
&=\frac{1}{3}\int_0^1\sum_{n=1}^{\infty}\left(x^{3n-2}-x^{3n+1}\right){\rm d}x\\\\\end{align}$$
How is it possible to interchange the summation and integral?
Thanks!
And in general, for what does this apply? Thank you very much!

A: You're allowed to do this anytime the series is uniformly convergent.
In uniform convergence, you tell me the $\epsilon$ that you want the entire partial sum to be within for the entire graph, and I give you an $M$ that guarantees you can get within $\epsilon$ if you choose $n > M$, but the $M$ must work anywhere on the graph, and not be dependent on which point you choose. In regular (called pointwise) convergence, the $\epsilon-M$ guarantee can use a different $M$ at different points on the graph.
Pointwise vs. Uniform Convergence
https://proofwiki.org/wiki/Definition:Uniform_Convergence


text:
Q: How can AppStore apps stop supporting ios4? I have a app on App Store supporting IOS4+ device. However, I really wanted to use some new API feature in ios5 and decided to bump my base SDK to IOS5.
My questions is, what is the setting needed on iTunesConnect? Does Apple allow me to do this? What will happen to those clients running my app on IOS4? Will they just stop receiving update notification from app store?
If Apple forbidden the change, what is the best option for me? I don't want to make another app which has the same interface/functionality but with only iOS5+ device support..

A: All you need to do is update your project by setting the Deployment Target to your new minimum version. In this case, set the Deployment Target to iOS 5.0 or 5.1. Build and test. When your app is approved, it will only be usable on devices with the version of iOS you selected, or later.
Existing users still on iOS 4 will still be able to use their existing app. But they can't install any further updates.


text:
Q: read matrix from file using Numpy I am new in python. I want to read a multiple array from text file to a python array
[
    [
        [1 1] [1 1]
    ]
    [
        [2 2] [2 2]
    ]
    [
        [3 3] [3 3]
    ]
    ...
    ...
    ...
]

I have tried this but seems I am not really good with python
dt = np.dtype(None, 2, 2)
data = np.fromfile(fileName, dtype=dt)
print(data)

by the np.dtype I want to tell python that the type is an array of unknown size containing arrays that each contains two arrays of two integer


text:
Q: Why do I have to click twice to execute method in Label MouseDown event I'm working on an assignment for College and the requirements are that I have to use multi-threading, now everytime I login, I have to click twice to change the UI for the MainWindow. Any idea what I might be doing wrong?
If I use the code from the user_login method it works fine, UI updates quickly, but when I use multi-threading I have to click the label twice in order to change my UI.
I've done the same using a button control but also has the same result for both tests given above.
        private void tbLogin_MouseDown(object sender, MouseButtonEventArgs e)
        {
            //Assign Class Property Values
            login.Student_Email = txtstd_Email.Text;
            login.Student_Password = txtstd_Password.Password;

            Thread user_login_thread = new Thread(() => User_Login(login.Student_Email,
                                                                   login.Student_Password));
            user_login_thread.Start();

            if (login.UserLoggedIn)
            {
                foreach (Window window in Application.Current.Windows)
                {
                    if (window.GetType() == typeof(MainWindow))
                    {
                        //Change page on login
                        (window as MainWindow).frmView.Source = new Uri("Views/Dashboard.xaml", UriKind.Relative);
                    }
                }
            }

            user_login_thread.Join();

            if (chkRemember.IsChecked == true)
            {
                Properties.Settings.Default.Student_Email = login.Student_Email;
                Properties.Settings.Default.Student_Password = login.Student_Password;
                Properties.Settings.Default.Save();
            }

        }

private void User_Login(string email, string password)
{
    //Security object
    Secure security = new Secure();

    conn.Open();

    string sql = "SELECT Student_Number, Student_FullName, Student_Email, Student_Password FROM
                 Student_Data WHERE Student_Email=@Email";

    using (SqlCommand cmd = new SqlCommand(sql, conn))
    {
        cmd.Parameters.Add("@Email", System.Data.SqlDbType.VarChar, 55).Value = email;
        cmd.Parameters.Add("@Pass", System.Data.SqlDbType.VarChar, 55).Value = password;

        SqlDataReader reader = cmd.ExecuteReader();

        if (reader.Read() &&
           login.Student_Password.Equals(security.Decrypt(reader["Student_Password"].ToString())))
        {

            login.UserLoggedIn = true;
        }
        else
        {
           _ = MessageBox.Show("Login Unsuccessful", "Student Login Unsuccessfull",
                               MessageBoxButton.OKCancel, MessageBoxImage.Error);
        }
    }

    conn.Close();
}

A: The primary issue is that you are not waiting for the query to finsih before checking if (login.UserLoggedIn).
I'd advise you to use async and await for this instead of threading.
You have some other issues also:

*

*connection and reader objects need using blocks.

*Do not cache the connection, create a new one when you need it.

*Reversible encryption on a password is a bad idea, use hashing instead. Pass the hash to the server for it to verify, don't bring it back to the client app.

*Don't block the thread with message boxes while the connection is open.

*Don't read more columns than you need.

*If you only have one column and row use ExecuteScalar

private async void tbLogin_MouseDown(object sender, MouseButtonEventArgs e)
{
    //Assign Class Property Values
    login.Student_Email = txtstd_Email.Text;
    login.Student_Password = txtstd_Password.Password;

    await User_Login(login.Student_Email, login.Student_Password));

    .....

private async Task User_Login(string email, string password)
{
    //Security object
    Secure security = new Secure();

    const string sql = @"
SELECT 1
FROM Student_Data
WHERE Student_Email = @Email
  AND Student_Password = @Pass;
";

    using (var conn = new SqlConnection(yourConnString))
    using (var cmd = new SqlCommand(sql, conn))
    {
        cmd.Parameters.Add("@Email", SqlDbType.VarChar, 55).Value = email;
        cmd.Parameters.Add("@Pass", SqlDbType.VarChar, 55).Value = security.Encrypt(password);
        await conn.OpenAsync();
        login.UserLoggedIn = await comm.ExecuteScalarAsync() != null;
    }
    if (!login.UserLoggedIn)
    {
       _ = MessageBox.Show("Login Unsuccessful", "Student Login Unsuccessfull",
                           MessageBoxButton.OKCancel, MessageBoxImage.Error);
    }
}


text:
Q: Is this rewrite correct? If x mod 9 = 1, can I rewrite the equation as x = 1 mod 9. If not, what is the correct way?
I know this sounds silly. But please help me.

A: There are two possible meanings of "mod" here:
One is a binary operation: $a \operatorname{mod} n$ is a number; it is the unique integer $r$ with $0 \le r < n$ such that $a - r$ is a multiple of $n$. If interpreted this way, the two equations aren't equivalent (for example, $x = 10$ is a solution of the former but not he latter).
The other is an equivalence relation: $a \equiv b \pmod{n}$ is a statement; it means that $b - a$ is a multiple of $n$. Only the second equation you wrote makes sense in this notation.
Maybe you could mix notations (e.g. it is always true that $a \equiv a \operatorname{mod} n \pmod{n}$), but that rapidly gets confusing.


text:
Q: Concatenate with text and punctuation dynamic range I'm trying to add punctuation and text by using concatenate to a range of dynamic cells in excel and I'm trying to figure out the VBA code for it.
So, I'm doing the following:

Final result:

With macro recorder I get this
Range("B3").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=""<>""&RC[-1]"
Range("B3").Select
Selection.AutoFill Destination:=Range("B3:B5")
Range("B3:B5").Select

Is there a way that I can do the autofill to be dynamic, it's currently focused on cells B3 to B5 (as I will have many more cells and never a fixed amount of cells)?
Is there an alternative concatenate formula that I can use?
Many Thanks

A: Fill Down a Simple Formula Using VBA
Option Explicit

Sub Test1()

    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!

    With ws.Range("A3:A" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row)
        .EntireRow.Columns("B").Formula = "=""<>""&" & .Cells(1).Address(0, 0)
        ' or
        '.Offset(, 1).Formula = "=""<>""&" & .Cells(1).Address(0, 0)
    End With

End Sub

Sub Test2()

    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!

    With ws.Range("B3:B" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row)
        .Formula = "=""<>""&" & .Cells(1).EntireRow.Columns("A").Address(0, 0)
        ' Or
        '.Formula = "=""<>""&" & .Cells(1).Offset(, -1).Address(0, 0)
    End With

End Sub


text:
Q: Como eu faço para acessar os elementos DOM no Electron? Sou novo no Electron, e estou tentando fazer uma função a partir de um click em um menu. Segue abaixo meu exemplo.
index.html

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Electron</title>

    <input type="text" name="campo" id="campo" value="">
    <button type="button" name="funcao" onclick="funcao()">Função</button>

    <input type="text" name="url" id="url">

Neste exemplo, ao digitar alguma coisa no input "url" e clicar no button, aparecerá o que foi digitado no input "campo".
O que queria é fazer o mesmo mas clicando no menu "Função".
main.js (somente na parte desejada, que seria a parte do menu com a função logo embaixo)
  {
    label: 'Função',
    click () { funcao(); }
  },

function funcao() {
  document.getElementById("campo").value = document.getElementById("url").value;
}

O erro é:

"ReferenceError: document is not defined"

A: dá uma olhada no código abaixo:

    <meta charset="utf-8">
    <title>Electron</title>

    <input type="text" name="campo" id="campo" value="">
    <button type="button" id="demo" onclick="funcao()">Função</button>

    <input type="text" name="url" id="url">

execute aqui: https://jsfiddle.net/eltonpering/3prg6pj0/


text:
Q: Field memberRepo in (...) required a bean of type that could not be found I'm working on a Spring Boot project. Implementing Back-End code with the data, I've got an error.
  Before working on the security, that is, when I've just done with the MemberRepository, MemberService, and MemberController, it worked well. After I worked on the security, that kind of error occurs.
I'm using IntelliJ as the IDE, and the methods were MySQL, Java, Spring Boot, Spring Security, and Maven. The OS is Mac.
This is a part of MemberRepository.java code:
package com.springboot.reserving.member;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.context.annotation.Bean;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository
public interface MemberRepository extends CrudRepository<Member, Long> { ... }

This is a part of MemberService.java code:
package com.springboot.reserving.member;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class MemberService {

    @Autowired
    MemberRepository memberRepository;

    ...
}

This is CustomUserDetailService.java code:
package com.springboot.reserving.member;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    MemberRepository memberRepo;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return Optional.ofNullable(memberRepo.read(username))
                .filter(m -> m != null)
                .map(m -> new SecurityMember(m)).get();
    }
}

The error message was:
Description:

Field memberRepo in com.springboot.reserving.member.CustomUserDetailsService required a bean of type 'com.springboot.reserving.member.MemberRepository' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'com.springboot.reserving.member.MemberRepository' in your configuration.

What should I do to fix this error?

A: One possible reason is that spring doesn't create Spring Data Repository out of the interface.
In a nutshell, spring data project generates a "proxy" in runtime - an implementation of the interface that will contain all the required methods for working with the database.
In order to make is possible you should enable this proxy generation for you DAOs:
This can be done with:
@EnableJpaRepositories(basePackages = "com.springboot.reserving.member")

So make sure you have this annotation on spring boot application class.


text:
Q: Do browsers have to "render" (for lack of a better term) divs that have the display:none property? If I have, for instance:

    (The content of this div is a huge QuickTime movie.)

    (The content of this div is just lines of text.)

Will the browser try to start downloading the QT movie in the first div?
I tried searching this site and Google before asking, so if it's been answered before and my Google-Fu is just off today, I sincerely apologize. It seems like a question that would have been asked, but I couldn't find it.

A: Anything with a
 that is set to display:none is still technically and semantically there. Any content contained within the hidden
 will be loaded as if it were visible.


text:
Q: How to make dynamic profit target and stop loss in ninjascript
*

*set Profit Target PT1 = 10, Stop Loss SL = 1%

*When reach exit PT 1 then close half of the position "long1", set stop loss to breakeven, and PT 2 = first break in opposite direction to the trade entry direction.
so, when I meet the first red candle after exiting half of the position, I'd like to sell the another half of the position "long2". If not, exit at stop loss = breakeven.

How to make dynamic pt and sl?
if (Position.MarketPosition == MarketPosition.Long)
{
     SetProfitTarget("Long_1", CalculationMode.Price, vwap[0] + Close[0] * ProfitTargetPercent);
     SetStopLoss("Long_1", CalculationMode.Percent, StopLossPercent, false);
}
...
EnterLong("Long_1");
EnterLong("Long_2");


text:
Q: Multiple applications in Node.js I have many node.js applications (created by different people) running on different ports in a single server. I want to run all those seperate application in a single node.js server.
I am new to Node.js. I have worked on web development tools like web2py before. In web2py we can create multiple applications in a single server.
Is there any framework in node.js which will help to create multiple applications in a single node.js server.
I have tried to create multiple applications like this
app.use('/app1', express.Router());
app.use('/app2', express.Router());
var app1 = require("./applications/app1/server_code.js");
var app1_inst = new app1(express.Router());

It is working, but the problem is, I have to change all the internal application url to "/app1/url".
Is there any other easy way to do that.


text:
Q: SSL Client Cert Verification optimisation We currently have a group of web-services exposing interfaces to a variety of different client types and roles.
Background:

*

*Authentication is handled through SSL Client Certificate Verification. This is currently being done in web-service code (not by the HTTP server). We don't want to use any scheme less secure than this. This post is not talking about Authorisation, only Authentication.

*The web-services talk both SOAP and REST(JSON) and I'm definitely not interested in starting a discussion about the merits of either approach.

*All operations exposed via the web-services are stateless.

My problem is that verifying the client certificate on each requests is very heavyweight, and easily dominates CPU time on the application server. I've already tried seperating the Authentication & Application portions onto different physical servers to reduce load, but that doesn't improve dispatch speed overall - the request still takes a constant time to authenticate, no matter where that is done.
I'd like to try limiting the number of authentications by generating an HTTP cookie (with an associated server-side session) after successful client certificate verification, which when supplied by the client will cause client certificate verification to be skipped (though still talking over SSL). I'd also like to time-limit the sessions, and make the processes as transparent as possible from a client perspective.
My questions:

*

*Is this still as secure? (and how can we optimise for security and pragmatism?)

*Are there free implementations of this scheme? (I'm aware of the SiteMinder product by CA)

*Given the above, should we continue to do Authentication in-application, or move to in-server ?

A:
generating an HTTP cookie (with an
associated server-side session) after
successful client certificate
verification, which when supplied by
the client will cause client
certificate verification to be skipped
Is this still as secure? (and how can
we optimise for security and
pragmatism?)

It's not quite as secure in theory, because the server can no longer prove to himself that there's not a man-in-the-middle.
When the client was presents a client-side certificate, the server can trust it cryptographically. The client and server should be encrypting and data (well, the session key) based on the client's key. Without a client-side cert, the server can only hope that the client has done a good job of validating the server's certificate (as perceived by the client) and by doing so eliminated the possibility of Mr. MitM.
An out-of-the-box Windows client trusts over 200 root CA certificates. In the absence of a client-side cert, the server ends up trusting by extension.
Here's a nice writeup of what to look for in a packet capture to verify that a client cert is providing defense against MitM:
http://www.carbonwind.net/ISA/ACaseofMITM/ACaseofMITMpart3.htm
Explanation of this type of MitM.
http://www.networkworld.com/community/node/31124
This technique is actually used by some firewall appliances boxes to perform deep inspection into the SSL.
MitM used to seem like a big Mission Impossible-style production that took a lot to pull off. Really though it doesn't take any more than a compromised DNS resolver or router anywhere along the way. There are a lot of little Linksys and Netgear boxes out there in the world and probably two or three of them don't have the latest security updates.
In practice, this seems to be good enough for major financial institutions' sites, although recent evidence suggests that their risk assessment strategies are somewhat less than ideal.

Are there free implementations of this scheme? (I'm aware of the SiteMinder product by CA)

Just a client-side cookie, right? That seems to be a pretty standard part of every web app framework.

Given the above, should we continue to do Authentication in-application, or move to in-server ?

Hardware crypto accelerators (either a SSL proxy front end or an accelerator card) can speed this stuff up dramatically.
Moving the cert validation into the HTTP server might help. You may be doing some duplication in the crypto math anyway.
See if you would benefit from a cheaper algorithm or smaller key size on the client certs.
Once you validate a client cert, you could try caching a hash digest of it (or even the whole thing) for short time. That might save you from having to repeat the signature validations all the way up the chain of trust on every hit.
How often to your clients transact? If the ones making up the bulk of your transactions are hitting you frequently, you may be able to convince them to combine multiple transactions in a single SSL negotiation/authentication. Look into setting the HTTP Keep-Alive header. They may be doing that already to some extent. Perhaps your app is doing client cert validation on every HTTP request/response, or just once at the beginning of each session?
Anyway, those are some ideas, best of luck!


text:
Q: Android 4.0.3 emulator will not display on-screen keyboard I have tried everything, and I cant get my emulator on android 4.0.3 to show me the on-screen keyboard when I type into an EditText. Any ideas? I've tried creating an emulator of a different resolution (as suggested in another post) to no avail.

A: I had the exact same problem and fixed it by the solution provided here:
Android 4.0 keyboard issue in emulator.?