text:
Q: Python Crawl - count elements and get texts I am trying to crawl website. The url is here https://www.edmunds.com/kia/telluride/2021/consumer-reviews/?pagesize=50
First question is there are stars for rating. So my problem is how can I get the stars they rated? I need the result in integer.

Second question is How do I split and get the date data and the user name?
I tried
source.find(class_ = 'small text-gray mb-2') #type: bs4.element.Tag

There is output.

Vic, 10/17/2020

EX 4dr SUV (3.8L 6cyl 8A)

Vic is user name, and 10/17/2020 is date data.
Here is my code.
chrome_driver = '/Users/chromedriver'
driver = webdriver.Chrome(chrome_driver)

url = 'https://www.edmunds.com/kia/telluride/2021/consumer-reviews/?pagesize=50'

driver.get(url)

src = driver.page_source
source = BeautifulSoup(src, 'html.parser', from_encoding='utf-8')

review_list = source.find_all('div', class_ = "review-item text-gray-darker")

sid = SentimentIntensityAnalyzer()

sum_review = ''

driver.close()

for review in review_list:

list1 = []

score = review.find('span').get_text()
title = review.find('a').get_text().replace('\n', '')
writer = review.find('div', {'class': 'small text-gray mb-2'}).get_text()
date = review.find('span', {'class': 'review-date'}).get_text()
content = review.find('div', {'class': 'truncated-text size-16'}).get_text()

list1.append(score)
list1.append(title)
list1.append(writer)
list1.append(date)
list1.append(content)
sum_review = sum_review + content

lines_list = tokenize.sent_tokenize(content)

I'd appreciate your answer!

A: import requests
import re
import json
import pandas as pd

def main(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0'
    }
    r = requests.get(url, headers=headers)
    match = json.loads(
        re.search(r'__PRELOADED_STATE__ = ({.+})', r.text).group(1))
    allin = []
    for item in match['consumerReviews']['consumerReviews']['reviews']:
        goal = [
            item['author']['authorName'],
            item['created'],
            item['vehicleRating']['overall'],
            item['title'],
            item['text']
        ]
        allin.append(goal)
    df = pd.DataFrame(
        allin, columns=['Author', 'Date', 'Rate', 'Title', 'Content'])
    df.to_csv('Data.csv', index=False)
    print(df)

main('https://www.edmunds.com/kia/telluride/2021/consumer-reviews/?pagesize=50')


text:
Q: Stripe - Get average payments pr customer Im working with a module get alot of statistics but i got stuck with a problem. I want to make a statistic about how many stripe payments a customer do in average (subscriptions). Like i want to know how along a user is subscripted in average.
What i tried to do so far is to get ALL payments (heavy data) and count each customer id, but this is really heavy and the website was working on the process like 20 minutes (167000 payments). Any of you ever wanted this functionality and found a solution for the issue? Or anyone got an idea how i can solve this problem?
Hope you can help me get started in the right direction so i can find a solution for this. :)

*

*Thanks for the time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: this code works on dummy mbox, but not on gmail takeout mbox I have this code, that will translate mbox to JSON. The goals is to transfer the produces JSON to Mongodb database. However, the code was tested on a dummy mbox "example.mbox" and it worked fine. Nevertheless, when the time to test it on the actual mbox, I had an unintended output that did produce the JSON file but, "Skipping MIME content in JSONification (multipart)".. I do not want to skip anything!
import sys
import mailbox
import email
import quopri
import json
import time
from BeautifulSoup import BeautifulSoup
from dateutil.parser import parse

MBOX = 'antonita.mbox'
OUT_FILE = MBOX + '.json'

def cleanContent(msg):

    # Decode message from "quoted printable" format, but first
    # re-encode, since decodestring will try to do a decode of its own
    msg = quopri.decodestring(msg.encode('utf-8'))

    # Strip out HTML tags, if any are present.
    # Bail on unknown encodings if errors happen in BeautifulSoup.
    try:
        soup = BeautifulSoup(msg)
    except:
        return ''
    return ''.join(soup.findAll(text=True))

# There's a lot of data to process, and the Pythonic way to do it is with a
# generator. See http://wiki.python.org/moin/Generators.
# Using a generator requires a trivial encoder to be passed to json for object
# serialization.

class Encoder(json.JSONEncoder):
    def default(self, o): return  list(o)

# The generator itself...
def gen_json_msgs(mb):
    while 1:
        msg = mb.next()
        if msg is None:
            break

        yield jsonifyMessage(msg)

def jsonifyMessage(msg):
    json_msg = {'parts': []}
    for (k, v) in msg.items():
        json_msg[k] = v.decode('utf-8', 'ignore')

    # The To, Cc, and Bcc fields, if present, could have multiple items.
    # Note that not all of these fields are necessarily defined.

    for k in ['To', 'Cc', 'Bcc']:
        if not json_msg.get(k):
            continue
        json_msg[k] = json_msg[k].replace('\n', '').replace('\t', '').replace('\r', '')\
                                 .replace(' ', '').decode('utf-8', 'ignore').split(',')

    for part in msg.walk():
        json_part = {}

        if part.get_content_maintype() != 'text':
            print >> sys.stderr, "Skipping MIME content in JSONification ({0})".format(part.get_content_maintype())
            continue

        json_part['contentType'] = part.get_content_type()
        content = part.get_payload(decode=False).decode('utf-8', 'ignore')
        json_part['content'] = cleanContent(content)
        json_msg['parts'].append(json_part)

    # Finally, convert date from asctime to milliseconds since epoch using the
    # $date descriptor so it imports "natively" as an ISODate object in MongoDB
    then = parse(json_msg['Date'])
    millis = int(time.mktime(then.timetuple())*1000 + then.microsecond/1000)
    json_msg['Date'] = {'$date' : millis}

    return json_msg

mbox = mailbox.UnixMailbox(open(MBOX, 'rb'), email.message_from_file)

# Write each message out as a JSON object on a separate line
# for easy import into MongoDB via mongoimport

f = open(OUT_FILE, 'w')
for msg in gen_json_msgs(mbox):
    if msg != None:
        f.write(json.dumps(msg, cls=Encoder) + '\n')
f.close()

print "All done"

OUT results:
Skipping MIME content in JSONification (image)
Skipping MIME content in JSONification (image)
Skipping MIME content in JSONification (multipart)
Skipping MIME content in JSONification (multipart)
Skipping MIME content in JSONification (image)
Skipping MIME content in JSONification (image)
Skipping MIME content in JSONification (image)
Skipping MIME content in JSONification (multipart)
Skipping MIME content in JSONification (multipart)
Skipping MIME content in JSONification (multipart)
Skipping MIME content in JSONification (multipart)
All done

NOTE: As some has pointed out, the phrase " I do not want to skip anything" refer to the fact that I can jSONify most of the mbox but not multipart nor images. Hence, the part in the code {for part in msg.walk(): ...} was tagged skipping to demonstrate that this code did indeed skipped multipart and images, as without it, i was getting JSON file without binaries for images etc.. It will not be present in the final code though, when i figure how to get images and multipart into JSON.

A: Third Edition of Mining Social Web
I tried making a workable script that not just converts MBOX to JSON, but even extracts the Attachments to usable formats.
Link to the repo -
https://github.com/PS1607/mbox-to-json
Read the README file for usage instructions.
If you want to convert it into CSV instead, change line 55 in src/main.py from df.to_json to df.to_csv


text:
Q: ice:paneConfirmation - is it really so bad? I have discovered a nice component for confirming actions - ice:panelConfirmation. But I think, it has one big mistake. I can't change the name of heading, there is always "Confirm". It is really so bad? Or is there some possibility to change it? I need to translate it to another language, for example.
Here is my code:
 <ice:panelConfirmation id="deleteConfirm" message="#{msg['really']}"
                                       acceptLabel="#{msg['yes']}" styleClass="dialog"
                                       cancelLabel="#{msg['no']}" displayAtMouse="true"/>

...
  <ice:commandButton image="/resources/images/delete.png" action="#{postManager.delete(item)}"
                                         title="#{msg['news.delete']}" styleClass="smallSpaces"
                                         panelConfirmation="deleteConfirm"/>

A: The ice:panelConfirmation component has a "title" attribute that you can use to set the text of the popup header. Have a look here


text:
Q: Javascript link not clickable in IE 8 and below I'm creating a link on my button (visible here) when the page is viewed in older versions of IE (8 and below).
if (ie < 9) {
    document.getElementById('buttonOverride').innerHTML =
    '' + document.getElementById('buttonOverride').innerHTML + '';
}

Where ie is a previously defined variable that identifies the IE version from the user agent.
This works, and the IE developer tools inspector tells me that the link has been inserted, but the link isn't clickable for some reason. Any ideas?

A: You could set the onclick attribute of your override, or even the button itself.
if (ie < 9) {
    var openCam = function () {
        window.location.href = '/cam.html';
    };

    document.getElementById('buttonOverride').setAttribute('onclick', 'openCam()');
}


text:
Q: List comprehention with 2 variable Is there any way to use list comprehension in this case ?
l=[]
for i in range(-1,2):
    for j in range(-1,2):
        l.append([i,j])

Output:
[[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 0], [0, 1], [1, -1], [1, 0], [1, 1]]

A: You can use:
l = [[i, j] for i in range(-1, 2) for j in range(-1, 2)]

Result:
# print(l)
[[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 0], [0, 1], [1, -1], [1, 0], [1, 1]]


text:
Q: Is there C# look-alike for Linux? Is there C# look-alike for Linux? What about a compiler?

A: If you don't want to use Mono, I think Java may be your closest alternative.

A: Look-alike? I am assuming you mean a similar language? You could always just use C# with Mono, a multi-platform port of the .Net framework

A: You could actually use C# with Mono.

A: Mono is the way to go in this case.

A: I found that going from Java to C# was very easy.  Maybe you could try working with Java?  Of course you'd have to learn a whole new set of libraries, so there's a learning curve, but the languages felt pretty similar as I recall (it's been a while)

A: There is another language called Vala. It's not well known, but as you can see from the page, an interesting amount of projects have been produced already.

A: You could always use Boo DSL on Mono to construct a C# clone. But then again it would probably be easier to use C# directly on Mono itself I guess ;)


text:
Q: Product of manifolds with or without boundary Let $M_1, M_2, ... M_k$ be smooth manifolds with or without boundary such that at most one of these has nonempty boundary, say $M_a$ has nonempty boundary where $a$ is in $\{1,2, ..., k\}$.
Then it is said that $M_1 \times M_2 \times ... \times M_k$ is a smooth manifold with boundary. I am curious what its boundary is.
Also, does the same contents hold for just topological manifolds? I am somewhat confused...

A: In both cases the boundary is $X= M_1\times\dots\times\partial M_a \times\dots\times M_k$.
My post was downvoted, so perhaps I missed the intention of the question? The reason the boundary is as above is because any point not in $X$ is contained in a coordinate neighborhood given by $(U,\phi)=(U_1\times\dots\times U_k,\phi_1\times\dots\times\phi_k)$, where  $(U_i,\phi_i)$ is an interior coordinate chart for each $i$. This neighborhood is thus an interior coordinate chart for $M$, which follows because the product of open subsets $\mathbb{R}^{n_i}$ is an open subset of $\mathbb{R}^{n_1+\dots +n_k}$.
For a point $p=(p_1,\dots,p_k)$ in $X$, the corresponding  $(U,\phi)$ is a product of an open subset of $\mathbb{H}^{n_a}$ and open subsets of $\mathbb{R}^{n_i}$, $i\ne a$. This is an open subset of $\mathbb{H}^{n_1+\dots+n_k}$, with $p$ in the boundary.
So we have precisely $\partial M=X$. A similar argument works for topological manifolds.


text:
Q: How to read each character from a BitInputStream when the number of bits varies per character I apologize, it wouldn't let me tag homework.
Hello there, I'm working on a school project using Huffman coding to compress data from a file. In this assignment, you are supposed to read from a file using a BitInputStream object, which I'm not sure is in the JCL because the documentation the professor provided has spelling errors and isn't very explicit with certain things. Anyway, it seems to work about the same as other classes that extend InputStream. The lines of code I keep getting from the class forum are the following:
        try {
            BitInputStream b = new BitInputStream(in);
            int data;

            while((data  = b.readBits(BITS_PER_WORD)) != -1) {
                data = b.readBits(BITS_PER_WORD);
                q.freq[data]++; //instance variable (size 256) in PriorityQueue q to
                //count number of occurrences of each piece of data.
                System.out.println(data);
            }
        }catch(FileNotFoundException e) {
            System.out.println("File not found.");
        }
        catch(IOException e) {
            System.out.println("Error while reading file.");
        }

...where @param in is the generic input stream object and BITS_PER_WORD = 8, inherited from an interface of constants. The problem is that whenever I run this, it appears to skip every other character in the file, starting with the first. So, for example, the small .txt file containing "Eerie eyes seen near lake." would print:
101 105 32 121 115 115 101 32 101 114 108 107 46 10 ('e', 'i', ' ', 'y', etc..). I imagine this has something to do with trying to read 8 bits at a time, as the ascii value of 'a' for example, in bits, is 1100001 (7 bits) and space is 100000 (6 bits). I was wondering if I have to somehow vary the number of bits it's trying to read (and how on earth I would do that) or if I'm coming at this the wrong way (I've only recently gotten used to the idea of working with bits/bytes and there may be something important I don't know).
I apologize for the lengthy question, but let me know if I left out any important info. Thanks!

A: You seem to be calling readBits() an extra time in the while initialisation. This might be why it is skipping letters. You should have something like:
while(data != -1) {
  data = b.readBits(BITS_PER_WORD);


text:
Q: How to install Visual Studio 2015 to use an existing installation of NodeJs, Cordova and android SDK I'm currenlty using nodejs, cordova, android sdk.
I'm trying to install visual studio 2015 but it seems to want to download and install these packages again, creating its own copy.
I want to use the existing tools.
Is it possible?

A: You could point Visual Studio to use your settings by following steps below:

*

*On the Visual Studio menu bar, choose Tools, Options.

*In the Options dialog box, choose Tools for Apache Cordova, and then choose Environment Variable Overrides.

More details in the Configure the Visual Studio Tools for Apache Cordova  on MSDN.
When specify values other then defaults take following notes in consideration:

*

*Visual Studio sometimes, has problems with node 0.12, it requires 0.10

*It may have problems with cordova 5.0.0, better use 4.3.0


text:
Q: Basic Regex Practice A simple question I was unable to find any similar examples which did not recommend using outside libraries, I have an exercise in which we have mock data similar to HTML/XML and we are restricted to using only Java regex library to parse and manipulate it.
We want to translate the data into a map. The format is:
<key> data words here </key>...

...where each data word will be added to the map with the key separately, so the resulting map should look like this:
{key, data
key, words
key, here}

I have come up with some solutions which first find and store the key using a regex, then match the inside of the key tag, store that data in a string, tokenize it using a space and bracket delimiters, and loop through the resulting list to write to the map. Is there a more straightforward or elegant method of doing this where I could capture the key and an array/list of the data words using just regex and eliminating the use of the tokenizer?
Some sample data below (notice there are no nested tags which makes this much simpler than parsing HTML):
<author> A. Cau, R. Kuiper, and W.-P. de Roever. </author>
<title> Formalising Dijkstra's development strategy within Stark's formalism. </title>
<editor> In C. B. Jones, R. C. Shaw, and T. Denvir, editors, </editor>
<booktitle> Proc. 5th. BCS-FACS Refinement Workshop, </booktitle>
<date> 1992. </date>

(all on one line - line breaks added for readability)

A: If I understand correctly, the following regex captures the tag name and its value in group \1 or \2:
<([^>/]+)>(.*?)</\1>

EXPLAINED
< - match < literally
([^>/]+) - match and capture everything that is not a > or / which avoids closing tags
> - match > literally
(.*?) - match and capture anything non-greedily
</\1> - match closing tag


text:
Q: Apply the moving average with a specific condition and a rolling window in R df <- structure(
  list(
    inv = c("INV_1", "INV_1", "INV_1", "INV_1", "INV_1", "INV_2", "INV_2", "INV_2", "INV_2", "INV_2", "INV_2"),
    ass = c("x", "x", "x", "y", "y", "x", "x", "x", "t", "t", "t"),
    datetime = c("2010-01-01", "2010-01-02", "2010-01-03", "2010-01-08", "2010-01-19", "2010-02-20", "2010-02-22", "2010-02-23", "2010-03-01", "2010-03-02", "2010-03-04"),
    price = c(10, 10, 19, 9, 3 , 5, 1, 4, 4, 5, 1),
    operation = c(10, 0, 2, 2, 0, 5, 5, 5, 3, 0, 2)
  ),
  class = "data.frame", row.names = c(NA, -11L)
)

I have this data frame for which I want to compute the moving average of the "price" column.
In particular I need to apply a minor change before doing that. I want to change the "price" column value if the "operation" value on that row is equal to 0.
Hence I need R to:
df <- df %>% mutate( price = if_else(operation == 0, NA, price)

And then when price == NA to fill the value with the moving average of the price column.
Since I could have consecutive NAs in the price column I think that the moving average should be applied with a rolling window.
I'm a new R user so I don't have a real idea of how to do that.
Any idea?
If possible I would prefer a dplyr solution

A: Assuming that the intention is that the average of the modified price from the beginning to the current row of is to be calculated with 0 rows NA'd out so that they are eliminated from the average try this. For example, the third row should use the average of 10 and 19 which is 14.5.
The code specifies an average of n() (= number of rows) elements but partial=TRUE instructs it just to use however many there are if there are fewer.  na.rm=TRUE results in NA's not being included in the average.  We have excluded filter and lag from dplyr since they clobber the functions of the same names in R and so tend to lead to hard to detect errors.  If you need to use them use dplyr::lag and dplyr::filter.
library(dplyr, exclude = c("filter", "lag"))
library(zoo)

df %>%
 mutate(price = ifelse(operation == 0, NA, price),
        avg = rollapplyr(price, n(), mean, na.rm = TRUE, partial = TRUE))

This variation also works. 1:n() specifies that the i elements should be used for the ith row.  Again, na.rm=TRUE will eliminate NA's from the calculation.
df %>%
  mutate(price = ifelse(operation == 0, NA, price),
         avg = rollapplyr(price, 1:n(), mean, na.rm = TRUE))

A: if the intention is to mutate the price with the average prices from previous rows where the operation > 0; then here is my dplyr code.
df <- tibble(df)

  df %>%
    mutate( price = ifelse( operation==0, 0 ,price)) %>%
    mutate(runinngsumPrice = cumsum(price))  %>%
    mutate(runinngsumNNA = cumsum(ifelse(operation==0,0,1)))  %>%
    mutate( price = ifelse( operation==0, runinngsumPrice/runinngsumNNA ,price))  %>%
    select(1:5)

#
#   # A tibble: 11 x 5
#   inv   ass   datetime   price operation
#   <chr> <chr> <chr>      <dbl>     <dbl>
#     1 INV_1 x     2010-01-01 10           10
#   2 INV_1 x     2010-01-02 10            0
#   3 INV_1 x     2010-01-03 19            2
#   4 INV_1 y     2010-01-08  9            2
#   5 INV_1 y     2010-01-19 12.7          0
#   6 INV_2 x     2010-02-20  5            5
#   7 INV_2 x     2010-02-22  1            5
#   8 INV_2 x     2010-02-23  4            5
#   9 INV_2 t     2010-03-01  4            3
#   10 INV_2 t     2010-03-02  7.43         0
#   11 INV_2 t     2010-03-04  1            2


text:
Q: Add a library to VS2017 SPA template I'm trying out the VS2017 Angular SPA template with .Net Core & EF Core.  All works fine in the app so far.  But I tried to add moment to the my Web UI project and don't know to get it working.
I tried:
npm install --save angular2-moment

which was fine, but then referencing moment in angular things go wrong.  There must be some change to webpack required, but the only file I have is webpack.config.js (which doesn't seem to fit examples). I'm new to webpack and could use some guidance as to what to change & how.


text:
Q: Ajuda com distinct Tenho a seguinte consulta sql:
select nome, data, situacao from cadastro
O resultado é assim:
MARIA   01/01/2018  0
MARIA   15/01/2018  1
GISELE  15/01/2018  0
CICERA  08/01/2018  1
ANTONIA 20/01/2018  0
ANTONIA 15/01/2018  1

Preciso fazer um distinct pelo nome:
select distinct(nome), data, situacao from cadastro group by data, situacao
O problema é que ele não faz o distinct porque as datas são diferentes, porém, eu preciso que, quando a paciente tenha duas fichas (situação 0 e 1), seja listada apenas a ficha com situação = 1.
Nesse caso, deveria gerar o resultado assim:
MARIA   15/01/2018  1
GISELE  15/01/2018  0
CICERA  08/01/2018  1
ANTONIA 15/01/2018  1

Alguma sugestão?

A: Sim seu distinct não irá funcionar pelo fato de você está adicionando a data no resultado.
Sugiro você enumerar suas linhas com a função ROW_NUMBER segmentando pelo nome e ordenando a situação de modo decrescente(do maior para o menor).
SELECT l.*
FROM
  (SELECT Cadastro.*,
           ROW_NUMBER() OVER (PARTITION BY nome
                              ORDER BY situacao desc) AS linha
   FROM Cadastro) l
WHERE LINHA = 1;

SqlFiddle
ROW_NUMBER

Definem a saída de um resultado de números. Mais especificamente,
  retorna o número sequencial(1,2,3,4...) de uma linha dentro de uma partição de um
  conjunto de resultados, começando em 1 para a primeira linha em cada
  partição.

Respondendo ao seu comentário:
WHERE LINHA = 1 será a primeira linha sequencial. Caso necessite trocar para pegar as linhas com situacao = 0, basta trocar para WHERE LINHA = 2.
PARTITION BY value_expression
Divide o conjunto de resultados produzido pelo FROM cláusula em partições às quais a função ROW_NUMBER é aplicada. value_expression Especifica a coluna pela qual o conjunto de resultados é particionado. Se PARTITION BY não for especificado, a função tratará todas as linhas do conjunto como um único grupo de resultados de consulta.
Algumas respostas parecidas:

*

*Selecionar primeiro registro dentro de uma segmentação no SQL
Server

*Consultas de linhas ímpares SQL SERVER
Veja mais na documentação:
PostgreSQL ROW_NUMBER function

A: Eu fiz de uma forma não simplificada, mas resolve teu problema,
Tive que adicionar um ID para pegar os registors corretos no where se você tiver outro idenficador a logica é a mesma
select c.nome, c.data, c.situacao
    from cadastro c
    where c.id in (select max(cs.id)
                    from cadastro cs where cs.situacao = 1
                    group by cs.nome)
        or (c.situacao = 0 and
                c.nome not in (select css.nome
                            from cadastro css where css.situacao = 1
                            group by css.nome))

este código esta disponivel no SQL snippet

A: Fiz um exemplo agrupando apenas pelo nome, e usando max(situacao), depois utilizo essa tabela com join no select para buscar os outros dados. Veja:
select
    y.nome,
    x.data,
    y.situacao
from tabela x
inner join (
            select
              t.nome,
              max(t.situacao) as situacao
            from tabela t
            group by t.nome) y on y.nome = x.nome and y.situacao = x.situacao

Coloquei no SQLFiddle: http://sqlfiddle.com/#!17/84343/7
Resultado:

A: Utilizando a mesma lógica de MAX() e Group By fiz uma outra alternativa de solução com subselect:
SELECT
  DISTINCT(C1.nome)
  , (
    SELECT c2.data
    FROM Cadastro AS c2
    WHERE c2.situacao = MAX(C1.situacao)
    AND c2.Nome = C1.Nome
  )
  , MAX(C1.situacao)
FROM
  Cadastro AS C1
GROUP BY C1.Nome

Exemplo online:
SQLFiddle


text:
Q: Strange behavior of phpexcel When trying to get an Excel spreadsheet from php with phpexcel, strange characters are generated in the output if a constant definition (DEFINE (' var',' value') is added.
My code
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="theFile.xls"');
header('Cache-Control: max-age=0');

require_once '../config.php';
include 'PHPExcel.php';
$excel = new PHPExcel();

$writer = PHPExcel_IOFactory::createWriter($excel, 'Excel5');

$excel->setActiveSheetIndex(0);
$excel->getActiveSheet()->SetCellValue('A1', 'Hello');
$excel->getActiveSheet()->SetCellValue('B2', 'world!');
$writer->save('php://output');

I don't understand the reason, since config. php is all it contains.
If I delete the config. php line, the excel file is generated correctly
Does anyone know what this behavior is due to?
this code runs smoothly
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="theFile.xls"');
header('Cache-Control: max-age=0');

include 'PHPExcel.php';
$excel = new PHPExcel();

$writer = PHPExcel_IOFactory::createWriter($excel, 'Excel5');

$excel->setActiveSheetIndex(0);
$excel->getActiveSheet()->SetCellValue('A1', 'Hello');
$excel->getActiveSheet()->SetCellValue('B2', 'world!');
$writer->save('php://output');

config.php content
define('DB_HOST', 'myHost');
define('DB_USER', 'myUser');
define('DB_PASSWORD', 'myPass');
define('DB_DATABASE', 'myDB');

A: I finally found it.
the output to the excel file does not allow ECHO or any other type of text output, in my case the config file had a blank line at the beginning
--->here
<?php
define('DB_HOST', 'myHost');
define('DB_USER', 'myUser');

etc.


text:
Q: History.push replacing last part of path in url I'm using react router v5, for one of my history.push calls it's replacing the last path section.
So instead of "/home/menu/allergens/newValue"
It navigates to "/home/menu/newValue"
It doesn't matter how many paths there are it always just replaces the last one?
All I'm using is history.push('modal/selectroute');
Why would this be?
Example code:
import { useHistory } from "react-router-dom";
export const Thing = () => {
  const history = useHistory();
  return (

      <button onClick={() => history.push("modal/selectroute")}>
        navigate
      </button>

  );
};

A:
it should be navigating to "/thing/modal/selectroute" as the path
supplied to history.push is relative right?

No. react-router-dom@5 routes and links don't use relative paths automatically like this like they do in RRDv6. In v5 you need to build the relative paths manually.
Example:
import { useHistory, useRouteMatch } from "react-router-dom";

export const Thing = () => {
  const history = useHistory();
  const { url } = useRouteMatch(); // <-- get the current url
  return (

      <button
        // prepend it to new target path
        onClick={() => history.push(`${url}/modal/selectroute`)}
      >
        navigate
      </button>

  );
};

See the RRDv5 Nesting demo for more details.

A: In my case I missed (/) in front of the route. You should try doing it once.
For example: history.push("/modal/selectroute"). It worked in my case might work in this as well.


text:
Q: How to Speed up Python code by multiprocessing I would like to speed up my Python code by using a multiprocessing.
I read that ProcessPoolExecutor will be fir best on my purpose but how can I achieve that.
I have a program like this:
    for resource_file in tmp_resource_folder.iterdir():
        with resource_file.open() as f:
            ns_resources = yaml.safe_load(f)
        resources = ns_resources.get('items')

        for resource in resources:
            -----------------
            Slow opperations
            -----------------

How it is possible to run each iteration of the first loop into a child process and achieve the speeding up of the code.
Also after the iterations I would like to wait for all child operation to finish before moving on.
Thanks in advance!

A: The simplest approach would be the following using multiprocessing.Pool with method imap:
import multiprocessing

def worker(resource_file):
    with resource_file.open() as f:
        ns_resources = yaml.safe_load(f)
    resources = ns_resources.get('items')

    for resource in resources:
        -----------------
        Slow opperations
        -----------------

def main():
    pool = multiprocessing.Pool()
    pool.imap(worker, tmp_resource_folder.iterdir())
    # wait for tasks to finish:
    pool.close()
    pool.join()

# required for Windows:
if __name__ == '__main__':
    main()

Instead of using imap, you can also just use method map as follows:
def main():
    pool = multiprocessing.Pool()
    pool.map(worker, tmp_resource_folder.iterdir())

The following is a rather technical description of the difference between imap and map, which you can ignore. But I suggest you read up on the various Pool methods in the multiprocessing module.
The potential disadvantage is that the map method will effectively treat the call as if you had coded the following:
    pool.map(worker, list(tmp_resource_folder.iterdir()))

That is, it will convert the iterable argument to a list so that it can take is length. This could result in using a lot of memory if the number of files was extremely large. But it does that so it can compute an efficient chunksize value, which is used to set the number of tasks it queues up at a time to each process in the pool in order to reduce the number of memory transfers it has to do queue up the tasks. This can result in improved performance. imap by default uses a chunksize value of 1, which is not particularly efficient for very large iterables, but you can specify a third argument to imap, which is a chunksize value to use. But to specify an intelligent value you would really need to know how many files in total you would ultimately be submitting.
The chunksize that map would compute is essentially the iterable size divided by 4 * the pool size:
def compute_chunksize(pool_size, iterable_size):
    chunk_size, remainder = divmod(iterable_size, 4 * pool_size)
    if remainder:
        chunk_size += 1
    return chunk_size

So, for example, if iterdir() would ultimately return 30 files and your pool size was 8 (because you had 8 cores), compute_chunksize would return 1. If you had from 33 to 64 files, then compute_chunksize would return 2.


text:
Q: Confused about the lambda expression I am reading an example code which is to add a 10 pixel wide gray frame replacing the pixels on the border of an image by calling it with the lambda expression:
public static Image transform(Image in, ColorTransformer t) {
    int width = (int) in.getWidth();
    int height = (int) in.getHeight();
    WritableImage out = new WritableImage(width, height);
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            out.getPixelWriter().setColor(x, y,
                    t.apply(x, y, in.getPixelReader().getColor(x, y)));
        }
    }
    return out;
}

@Override
public void start(Stage stage) throws Exception {
    Image image = new Image("test_a.png");
    Image newImage = transform(
                       image,
                       (x, y, c) -> (x <= 10 || x >= image.getWidth() - 10 ||
                                     y <= 10 || y >= image.getHeight() - 10)
                                     ? Color.WHITE : c
                     );
        stage.setScene(new Scene(new VBox(
     new ImageView(image),
     new ImageView(newImage))));
  stage.show();
    stage.show();
 }
}

@FunctionalInterface
interface ColorTransformer {
    Color apply(int x, int y, Color colorAtXY);
}

I am confused about the lambda expression:
Image newImage = transform(
                   image,
                   (x, y, c) -> (x <= 10 || x >= image.getWidth() - 10 ||
                                 y <= 10 || y >= image.getHeight() - 10)
                                 ? Color.WHITE : c
                 );

*

*To add a frame to a figure, I think "&&" should be more reasonable than "||". But, "&&" does not work here! Could anyone please explain this?

*I do not really understand "? Color.WHITE : c". Firstly, why are they outside the previous bracket? Secondly, what does the question mark(?) mean?
Thank you for your help in advance.

A: First off, your question has nothing to do with lambda, but expressions in general.
Starting with the second part: A ? B : C means "if A is considered true, my value is B otherwise it is C.  A kind of if statement inside of an expression.
As to the first part: if any of the individual tests is true (each of which is of the form the point is too far left/right/up/down), then the point is (presumably) outside, and is colored white; otherwise, use the color c.  You can't have them all be true at once: a point can't both be too far left and too far right, for example.

A: Your program is equivalent to this: (if you don't use lambda)
public static Image transform(Image in) {
    int width = (int) in.getWidth();
    int height = (int) in.getHeight();
    WritableImage out = new WritableImage(width, height);
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            Color c = in.getPixelReader().getColor(x, y);
            if (x <= 10 || x >= image.getWidth() - 10 ||
                y <= 10 || y >= image.getHeight() - 10)
                c = Color.WHITE;
          /* else
                c = c; */
             out.getPixelWriter().setColor(x, y, c);
         }
    }
    return out;
}


text:
Q: Flask,Jinja : define Variable for Dict Key consisting "dot" I am working on Jinja template and accessing the keys of a dictionary dump coming from Python code as.
return render_template('dashboard.html', data=data)
Few of the keys within dictionary as "." for example {'this_is.key_with.dots':'value of key'}
Within template I tried using couple of formats i.e.,
{{ data['this_is.key_with.dots] }} as well as `{{ data['this_is.key_with.dots']|e }}.
Tried going though link https://jinja.palletsprojects.com/en/2.11.x/templates/ but couldn't find much in escaping characters in variable.
If someone got idea on this would be helpful to know.
Thanks for the time.


text:
Q: how to find the time in effective way when value get cross the threshold limit There is a graph visualization of list of (time, count) value where time in x axis and count in y axis
e.g.
 list_1 = [(1, 50000), (2,40000), (3,20000), (4,10000), (5, 5000), (6, 3000), (7,500), (8, 10), (9,100), (10,2000), (11,5000),(11,8000),(12,10000), (13,20000)]

My aim is to find the time at which count got increased beyond or equal the limit = 20000 which is (13,20000) along the increase slope side not decrease slope side
please find the graph for more info
I have written a pseudo code which does the same thing but not in effective way

But one constraint is the list_1 is not fixed value but is keep on
  incrementing with new value with f(time, count)

def find_limit():
    list_1 = [(1, 50000), (2, 40000), (3, 20000), (4, 10000), (5, 5000), (6, 3000), (7, 500), (8, 10), (9, 100),
              (10, 2000), (11, 5000), (11, 8000), (12, 10000), (13, 20000)]
    found = False
    limit = 20000
    for time, count in list_1:
        if count < limit:
            found = True
        if found:
            if count >= limit:
                return time

print(find_limit())

Is there any other way I can get the time when count got increase beyond threshold while the list is keep on updating with new value?

A: IIUC
list_1 = [(1, 50000), (2,40000), (3,20000), (4,10000), (5, 5000), (6, 3000), (7,500),
          (8, 10), (9,100), (10,2000), (11,5000),(11,8000),(12,10000), (13,20000)]

df = pd.DataFrame(list_1, columns=['time', 'count'])

# Set the limit
limit = 20_000
times_over_limit = df[df['count'] < limit]['time'].tolist()

# List of times for which count is less than limit value
times_over_limit
[4, 5, 6, 7, 8, 9, 10, 11, 11, 12]

A: Using numpy:
import numpy as np

limit = 20000
list_1 = np.array([(1, 50000), (2, 40000), (3, 20000), (4, 10000), (5, 5000), (6, 3000), (7, 500), (8, 10), (9, 100),
              (10, 2000), (11, 5000), (11, 8000), (12, 10000), (13, 20000)])

res=list_1[((list_1[:-1,1]<limit)&(list_1[1:,1]>=limit)).argmax()+1,:]
#list_1[((list_1[:-1,1]<limit)&(list_1[1:,1]>=limit)).argmax()+1,0] in order to get just 13

In short:
((list_1[:-1,1]<limit)&(list_1[1:,1]>=limit))

Will return Boolean vector with result of comparison of two consecutive numbers for whether limit was crossed between them. Left part takes elements from index 0 to one before last, whereas right part takes elements from index 1 till the last, with respective conditions.
Next thing - argmax() will return first index where both conditions are met, and we need to add 1, since we want to get index where the line has been crossed, not one before.
Output:
[   13 20000]


text:
Q: Including time of day in a linear regression model The title may be entirely inappropriate for this question: that depends on whether I am on the right track. I am developing a statistical model to evaluate flower temperature based on air temperature. I'm not very good at anything statistics related, but I'm decent in programming in Python so I was thinking of building a linear regression in there.
However, I have difficulties figuring out how to build my regression and whether even a linear regression is a good choice at all.
The following plot shows how temperature and flower data varies with the time (Month-day Hour).
The black line = Air temperature.
The coloured lines = various flowers whose temperatures were measured.
Perhaps important, but I can't figure out how to make use of them: the arrows at the top show the wind and direction, while the blue line shows the incident solar radiation.
The y-axis shows the temperature (in Celsius) while the x-axis shows the time.

If I were to compute a linear regression, it would have to be valid for any hour of the day, hence I can't just evaluate how the flower temp varies with the air temp, because a 20 degree air temperature at 1 pm won't give out the same flower temperature as a 20 degree air temperature at 1 am. I tried separating night and day (day varies in between 6 am-7 pm), but even then the results were too chaotic.
After reading this post: Is time of the day (predictor in regression) a categorical or a continuous variable?, I thought maybe that using a categorical approach would work, but I am getting from this is that I would have 24 different equations for each hour of the day, which seems a bit much. I suppose that I am prepared to attempt such an approach, but I was hoping to get some advice before pressing on?
Perhaps I should simply use solar radiation instead of the time? But even then, the shape is periodic and I have no idea how to integrate a periodic component within a linear regression!

A: I think a partially linear modeling framework may be suitable for your problem. If you focus on one flower at the time, note that both the flower data and the air temperature data exhibit strong temporal cycles which peak roughly at the same time. So the simplest partially linear model you could consider for one flower would look like this:
FT_h = beta0 + beta1*AT_h + m(h) + epsilon_h,

where FT_h is the flower temperature for the chosen flower at hour h, AT_h is the air temperature at hour h, m() is a smooth, unknown function meant to capture the temporal cycles you see in the temperature data and epsilon_h is an unknown error term. Here, h = 1, 2, 3, ..., H is an index which counts how many hours you have represented in total in your flower data. In other words, this index counts your hours from the first to the last. If you have 9,000 hours represented in your data, for example, then H = 9,000. In this model, beta1 represents the hourly effect of air temperature on flower temperature, after controlling for temporal effects.
The model can be expanded by adding a linear effect for incident solar radiation (ISR):
FT_h = beta0 + beta1*AT_h + m(h) + beta2*ISR_h + epsilon_h.

If you wanted to throw in wind direction as well, you could code this variable as taking the values North, South, East, West (or add variations like North-East, North-West, etc.) and include it in your model using dummy variables. For example, if you only code this variable as taking the values North, South, East or West, the flower-specific model could be expressed as:
FT_h = beta0 + beta1*AT_h + m(h) + beta2*ISR_h +
       beta3*NorthDummy_h + beta3*EastDummy_h + beta4*WestDummy_h +
       epsilon_h,

where South is treated as the reference direction against which all others will be compared and NorthDummy_h is set to 1 if wind direction was North at hour h and 0 otherwise, EastDummy_h is set to 1 if wind direction was East at hour h and 0 otherwise and WestDummy_h is set to 1 if wind direction was West at hour h and 0 otherwise.
The challenging aspects of these models are:

*

*The need to estimate the (unknown) degree of smoothness of the (unknown) temporal effect m() carefully, given that this is just a nuisance effect and the real interest is in estimating beta1;

*The possibility that the error terms epsilon_h might be temporally correlated, which in turns can affect how item 1. above is addressed.
Many years ago, I conducted research on this very topic - see, for example - http://www.ghement.ca/217.pdf. However, I have not stayed current on the topic so it's possible there have been several advances on ways to handle item 1.
Intuitively, the temporal signal seen in the data is really strong while the air temperature signal is likely tiny by comparison. So you need to find the right balance when determining the degree of smoothness of the temporal effect, so as not to throw the baby with the bath water.
If you are interested in comparing effects of air temperature across flowers, you can expand the model even further. But I would start small to make sure I get a handle first on the simpler, flower-specific models.


text:
Q: Twig trans_default_domain set by dynamic value (i.e. concatenated strings/variables) The following example is working as expected following the manual (http://symfony.com/doc/current/book/translation.html#twig-templates):
{% trans_default_domain "app" %}

However, I would like to add a dynamic value and/or an variable into "app". I tried the following examples but neither one of them are working:
{% set param = 1 %}
{% trans_default_domain "app_"~param %}

Or this:
{% set param = 1 %}
{% trans_default_domain "app_{param}" %}

Or even this does not work:
{% set custom_domain = "app" %}
{% trans_default_domain custom_domain %}

Or this:
{% trans_default_domain "custom_"~"domain" %}

I tried to search the net for this problem, but can't find any similar problems.
It looks like the trans_default_domain is not working with any dynamically generated values. Is this even possible?
Thanks in advance!


text:
Q: Strange result with Mathematica I am trying to integrate the following using Mathematica:
Integrate[Exp[a*Cos[theta]], {theta, 0, 2*Pi}]

I get 2 $\pi$ BesselI[0, a] (which is correct).
Next, I try
Integrate[Exp[a*Cos[2*theta]], {theta, 0, 2*Pi}]

which also gives me 2 $\pi$ BesselI[0, a].
But should the integral not be twice the previous amount?

A: The results seems correct. As the frequency of oscillation increases, there are more waves, but the area under each one decreases also, keeping the overall area the same. Just plot it and you will see. Here is example using $a=2$ (pick any other value you want)
Table[Integrate[Exp[a*Cos[n*theta]], {theta, 0, 2*Pi}], {n, 1, 6}]

Compare to
Table[Plot[Exp[2*Cos[n*theta]], {theta, 0, 2*Pi}], {n, 1, 6}]

Visually, you can see the total area being the same seems reasonable. There are more segments, yes, but each is smaller.
Ok, this is not a mathematical proof, but at least you can see the result seems correct.  The problem is that Mathematica can not find the indefinite integration. Only definite one.
The result also confirmed by numerical integration
 Table[NIntegrate[Exp[2*Cos[n*theta]], {theta, 0, 2*Pi}], {n, 1, 6}]


text:
Q: Virtual hosts for MAMP 4.1.1 on MAC 10.12.6 not working I know this has been asked hundreds of times and I made sure I read all of them, but still I cannot get this working. So as the title suggests, I cannot get a vhost running from MAMP/OSX. Here's a list of things I tried so far:
Created configuration in /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf
<VirtualHost *:80>
    DocumentRoot /Applications/MAMP/htdocs
    ServerName localhost
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/Applications/MAMP/htdocs/abcd/public"
    ServerName abcd.dev
    ServerAlias www.abcd.dev
</VirtualHost>

Removed comment from the line
Include /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf

in the file /Applications/MAMP/conf/apache/httpd.conf
Finally this is how my /etc/hosts file looks
127.0.0.1       localhost
255.255.255.255 broadcasthost
::1             localhost
fe80::1%lo0     localhost

127.0.0.1       abcd.dev

Restarted MAMP and here are the test results:
http://localhost/ - Shows Index of and then /abcd
http://127.0.0.1/ - Shows Index of and then /abcd
abcd.dev - Unable to connect, Firefox was unable to connect to the server abcd.dev
Surprisingly
ping abcd.dev - Returns response 64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.053 ms
ping 127.0.0.1 and ping localhost also returns same response.
I had docker running on my computer, I thought that was messing it up, so I stopped in completely, but the problem continues.
Any help is appreciated.

A: you have specified "www." prefix in your vhosts file, but tried to access is through abcd.dev (without the www.)

A: abcd.dev is now officially a public domain. So basically my browser is trying to locate the site "out there".
Instead let's use something like abcd.local or abcd.loc
Hope this helps someone stuck in .dev labyrinth.


text:
Q: At what percip probability should i display rain? (Dark sky API) When coding a weather app with the darksky api, at what percipprobability should i really show "rain" in my app. I compared the data with a radar from switzerland and got different results. Dark Sky shows a probability of 30% and the radar in another app displays rain at this time.
Should i go with the icons instead?
https://darksky.net/dev/docs


text:
Q: How to decrypt NodeJS crypto on the client side with a known encryption key? I am trying to have AES encryption on the server side, and decryption on the client side. I have followed an example where CryptoJS is used on the client side for encryption and SubtleCrypto on the client side as well for decryption, but in my case I have the encryption and decryption separated.
Suppose I have the following encryption function within React Native:
const encrypt = (str: string) => {
  const iv = crypto.randomBytes(12);
  const myHexToken = "0x...."
  const cipher = crypto.createCipheriv('aes-256-gcm', myHexToken.slice(0,32), iv)
  let encrypted = cipher.update(str, 'utf8', 'hex')
  encrypted += cipher.final('hex');
  const tag = cipher.getAuthTag();

  return {
    message: encrypted,
    tag: tag.toString('hex'),
    iv: iv.toString('hex'),
  };
};

This json is then posted to the client through a webview postMessage.
The client side has the following javascript injected:
var myHexToken = "0x....";

window.addEventListener("message", async function (event) {
  var responseData = JSON.parse(event.data);
  try {
  var decryptedData = await decrypt(responseData.iv, responseData.message, responseData.tag);
  } catch (e) {
    alert(e);
  }
  // ...

How can I decrypt responseData.message within the WebView through SubtleCrypto of the Web Crypto API?
I have tried various things with the following methods, but I keep getting "OperationalError":
function fromHex(hexString) {
  return new Uint8Array(hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
}

function str2ab(str) {
  const buf = new ArrayBuffer(str.length);
  const bufView = new Uint8Array(buf);
  for (let i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

function fromBase64(base64String) {
 return Uint8Array.from(window.atob(base64String), c => c.charCodeAt(0));
}

async function importKey(rawKey) {
  var key = await crypto.subtle.importKey(
    "raw",
    rawKey,
    "AES-GCM",
    true,
    ["encrypt", "decrypt"]
  );
  return key;
}

async function decrypt(iv, data, tag) {
  var rawKey = fromHex(myHexToken.slice(0,32));
  var iv = fromHex(iv);
  var ciphertext = str2ab(data + tag);

  var cryptoKey = await importKey(rawKey)

  var decryptedData = await window.crypto.subtle.decrypt(
    {
      name: "AES-GCM",
      iv: iv
    },
    cryptoKey,
    ciphertext
  )

   var decoder = new TextDecoder();
   var plaintext = decoder.decode(decryptedData);

  return plaintext;
}

UPDATE 1: Added the getAuthTag implementation server side. Changed IV to have length of 12 bytes. Attempt to concatenate ciphertext and tag client side.
I have verified that "myHexToken" is the same both client and server side. Also, the return values of the server side "encrypt()" method are correctly sent to the client.

A: In the WebCrypto code the key must not be hex decoded with fromHex(), but must be converted to an ArrayBuffer with str2ab().
Also, the concatenation of ciphertext and tag must not be converted to an ArrayBuffer with str2ab(), but must be hex decoded with fromHex().
With these fixes decryption works:
Test:
For the test, the following hex encoded key and plaintext are used on the NodeJS side:
const myHexToken = '000102030405060708090a0b0c0d0e0ff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff';
const plaintext = "The quick brown fox jumps over the lazy dog";
const encryptedData = encrypt(plaintext);
console.log(encryptedData);

This results e.g. in the following output:
{
    message: 'cc4beae785cda5c9413f49cf9449a6ae17fdc0f7435b9a8fd954602bdb4f4b825793f6b561c0d9a709007c',
    tag: '046c8e56bbd13db2faed82d1b19c665e',
    iv: '11f87b0eaf006373ae8bc94d'
}

The ciphertext created this way can be successfully decrypted with the fixed JavaScript code:

(async () => {

function fromHex(hexString) {
    return new Uint8Array(hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
}

function str2ab(str) {
    const buf = new ArrayBuffer(str.length);
    const bufView = new Uint8Array(buf);
    for (let i = 0, strLen = str.length; i < strLen; i++) {
        bufView[i] = str.charCodeAt(i);
    }
    return buf;
}

async function importKey(rawKey) {
    var key = await crypto.subtle.importKey(
        "raw",
        rawKey,
        "AES-GCM",
        true,
        ["encrypt", "decrypt"]
    );
    return key;
}

async function decrypt(iv, data, tag) {
    //var rawKey = fromHex(myHexToken.slice(0,32)); // Fix 1
    var rawKey = str2ab(myHexToken.slice(0,32));

    var iv = fromHex(iv);

    //var ciphertext = str2ab(data + tag); // Fix 2
    var ciphertext = fromHex(data + tag);

    var cryptoKey = await importKey(rawKey)

    var decryptedData = await window.crypto.subtle.decrypt(
        {
            name: "AES-GCM",
            iv: iv
        },
        cryptoKey,
        ciphertext
    );

     var decoder = new TextDecoder();
     var plaintext = decoder.decode(decryptedData);

    return plaintext;
}

var myHexToken = '000102030405060708090a0b0c0d0e0ff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff'
var data = {
    message: 'cc4beae785cda5c9413f49cf9449a6ae17fdc0f7435b9a8fd954602bdb4f4b825793f6b561c0d9a709007c',
    tag: '046c8e56bbd13db2faed82d1b19c665e',
    iv: '11f87b0eaf006373ae8bc94d'
}

var plaintext = await decrypt(data.iv, data.message, data.tag);
console.log(plaintext);

})();

A remark about the key: In the posted NodeJS code, const myHexToken = "0x...." is set. It's not clear to me if the 0x prefix is just supposed to symbolize a hex encoded string, or is really contained in the string. If the latter, it should actually be removed before the implicit UTF-8 encoding (by createCiperiv()). In case of a hex decoding it must be removed anyway.
In the posted example a valid hex encoded 32 bytes key is used (i.e. without 0x prefix).

With regard to the key encoding, also note the following:

*

*The conversion of the key from a hex encoded string by a UTF-8 (or ASCII) encoding results in only half of the key being considered, in the example: 000102030405060708090a0b0c0d0e0f. This reduces security, because the value range per byte is reduced from 256 to 16 values.
In order for the entire key to be considered, the correct conversion on the NodeJS side would be: Buffer.from(myHexToken, 'hex') and on the WebCrypto side: var rawKey = fromHex(myHexToken).

*Because of its implicit UTF8 encoding crypto.createCipheriv(..., myHexToken.slice(0,32), ...) creates a 32 bytes key and is functionally identical to str2ab(myHexToken.slice(0,32)) only as long as the characters in the substring myHexToken.slice(0,32) correspond to ASCII characters (which is true for a hex encoded string).


text:
Q: C# Can I emulate a button pressing in form of a process from another process? For example I got a WinForm with a buttons on it. Is it possible to press this button from another process? I want to make something like Webrat virtual browser for Cucumber  testing framework but for desktop applications.

A: You wanna have a look at the pretty new framework by Microsoft: UI Automationand here.
This can do WPF very well but works with WinForm as well.

A: Due to all WinForms controls are wrapper around Win32 controls, you can use Spy++ tool for fetching unmanaged handle of underlied controls (buttons, textboxes etc) via text properties and other signs, and next, use native win32 calls to send custom events to this controls like MouseClick, MouseMove, etc. Consider http://pinvoke.net to more precise info about P/Invoke technique in C#.


text:
Q: What is the steepest roll-off achievable for an analogue low-pass constructed with a single op-amp? I was wondering about this question. What if the only design requirement is having the highest steepness of the roll-off but using only one op-amp? I know it's possible to construct approximations of second order low-pass filters with one but what about higher orders?

A: You can make a high-order low-pass filter with no op-amps at all. In principle you could obtain any roll-off rate you like, given enough pi or T sections. You could then add an op-amp output buffer to make your filter a "one op-amp" filter if for some reason you'd like to do that.
But high-order filters tend to be very sensitive to small changes in component values, so they often require hand-tuning each circuit to achieve good performance, and the performance could drift as temperature changes.
The benefit of using active filters is that the op-amp allows low output impedance and high input impedance, reducing the loading effect of one stage on the next. This means you can cascade several first or second order filters without much interaction from stage to stage, and reduce the need for tuning. If you try to make a high-order active filter in one stage, you're giving up a key advantage of using active filters.

A: You can make a 10th order filter using an 8 pin SOIC chip like the LTC1569-6

This doesn't use any conventional op-amps but, keeping in with the spirit of the question and @thephoton's answer you might regard this chip as counting as at least one op-amp (equivalent).


text:
Q: CentOS 5.5 - passing parameters from grub to the user space I need to add an additional title to my grub.conf file and after OS boot I need start different services depends on it
What the better way to do that?

A: Use runlevel 4 (normally unused) and pass 4 on the kernel command line to boot into it.


text:
Q: airodump error: ioctl(SIOCSIFFLAGS) failed: Name not unique on network # airodump-ng mon0
ioctl(SIOCSIFFLAGS) failed: Name not unique on network

Tried most of the things like Backports but always gave me few error

A: Follow this advice:

1) First stop NetworkManager
$ service network-manager stop
And retry creating mon0 with airmon-ng.

This should solve the problem, you should longer have the
ioctl(SIOCSIFFLAGS) failed: Name not unique on network message.

A: If you are using VM Network interfaces is a normal issue, thoses interfaces take the localhost name and replicate the Interface name, try to change the localhost in /etc/hosts, if that is not working to you, let me know


text:
Q: Inverse Ackermann - primitive recursive or not? I wanted to put this originally on math.stackexchange, since I considered it to be a straightforward question and probably a fairly known fact. After I failed to solve the problem, I browsed through literature and what a surprise - two books claim it is primitive recursive, one resource claims it isn't, and neither one gives proof or reference. One paper also claims that inverse Ackermann function is slower than any primitive recursive function. If it were primitive recursive, I don't see why would that hold.

Now, my questions would be: which one
  is right - $Ack^{-1}$ is/isn't
  primitive recursive, and is/isn't
  slower than any primitive recursive
  function.

If it's a bad MO question, I'll migrate it to M.SE, no problem.

A: Maybe the following is of interest.
There is a pointer in the literature provided by Soare's book on r.e. degrees.
In an exercise one should show that the bijective primitive recursive functions
do not form a group. In rough terms the hint suggests that the inverse of the Ackermann function has no prim rec inverse.

A: The inverse Ackermann function is primitive recursive.
One way to see this is to use the fact that a function $f$ is primitive recursive when and only when

*

*the graph of $f$ is primitive recursive, and

*$f$ is bounded above by some primitive recursive function.

The graph of the Ackermann function is primitive recursive, i.e. the characteristic function of the set $\lbrace \langle x, y, z \rangle : z = A(x,y)\rbrace$ is primitive recursive. This is because checking that $A(x,y) = z$ is easy once $x, y, z$ are given. One can always construct a table of all previous values of $A$ used to justify that $A(x,y) = z$. If $z$ is indeed the correct answer, then the code for this table is not much bigger than $\langle x, y, z\rangle$ (smaller than $17^{17^{x+y+z}}$, for example). So, given a proposed triple $\langle x, y, z \rangle$, we can search for the relevant table and determine whether or not $A(x,y) = z$ is true in a primitive recursive fashion. Of course, the Ackermann function is not bounded above by a primitive recursive function, but that is the only thing that goes wrong.
Since the graph of the Ackermann function is primitive recursive, then so is the graph of the inverse Ackermann function $Ack^{-1}(z) = \max\lbrace x : A(x,x) \leq z\rbrace$. Moreover, the growth rate of $Ack^{-1}$ is bounded by some primitive recursive function (e.g. the identity function). It follows that $Ack^{-1}$ is indeed primitive recursive.

A: A more intuitive answer is, primitive recursiveness is a kind of time complexity, you can compute a primitive recursive funtion in Ack(k,n) steps for some constant k, and can not compute so fast for a non-pr function.
And for inverse Ackermann function, even brute force enumeration will cost just exponential time.


text:
Q: Numpy slicing with list I'm trying to slice an Ndarray a with a list b. But the behaviour is not as I would expect it. What do I have to change to get the wanted result?
a = np.arange(27).reshape(3,3,3)

b = [2,2]

Actual behaviour:
a[:,b]

array([[[ 6,  7,  8],
        [ 6,  7,  8]],

       [[15, 16, 17],
        [15, 16, 17]],

       [[24, 25, 26],
        [24, 25, 26]]])

Wanted behaviour:
a[:,2,2]

array([ 8, 17, 26])

A: Try replacing : with slice(None) and unpacking b:
a[(slice(None), *b)]
# [ 8 17 26]

import numpy as np

a = np.arange(27).reshape((3, 3, 3))
b = [2, 2]
result = a[(slice(None), *b)]

print(result)
# [ 8 17 26]
print((result == a[:, 2, 2]).all())
# True


text:
Q: Git Config command failing through java. $HOME not set I am trying to run git commands through JAVA. My Linux version is REDHAT 7.3 and git version is 1.8. All the commands are working fine but when I run git config --global user.name "myName" it throws an error
 fatal : $HOME not set.
I tried exporting the Home PATH through JAVA by following code :
  export HOME=$HOME:/path/home
But i got the following error:
Cannot run export - execvpe failed (ENOENT - no such file or directory).
Just After running the command I checked the HOME path through System.getEnv("HOME") and it was returning me the correct PATH. I tried updating the Git version to 2.22 as well on RHEL but still no use.
In windows,all the commands are working fine but on Linux it throws the error.

A: Shouldn't the command be
git config user.name "myName"

instead of
git config --user.name "myName"


text:
Q: How to put all the three portions in same line when reducing the screen size? I am new to coding as well as stack overflow and below mentioned is the code, and I am trying to bring both the icons in the same line as the brand logo and menu when reducing the size of screen.
Below mentioned is the code.

                <button type="button" class="navbar-toggle collapsed " data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    Toggle navigation

                </button>

Link (current)

Link

                        Dropdown

Action

Another action

Something else here

Separated link

One more separated link

Link

                        Dropdown

Action

Another action

Something else here

Separated link

CSS:
.badgeq {
    display: flex;
    min-width: 10px;
    padding: 3px 7px;
    font-size: 12px;
    font-weight: 700;
    line-height: 1;
    color: #35BBE6;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    background-color: transparent;
    border-radius: 10px;
}
.badge:after {
    content: "100";
    position: relative;
    background: rgba(0,0,255,1);
    height: 2rem;
    top: 0rem;
    right: 0.5rem;
    width: 2rem;
    text-align: -webkit-center;
    line-height: 2rem;
    font-size: 1rem;
    border-radius: 50%;
    color: white;
    border: 1px solid blue;
}
@media (min-width: 768px) {
  .navbar-nav.navbar-center {
    position: absolute;
    left: 45%;
    transform: translatex(-50%);
    margin-top: 10px;
  }
}

A: Flexbox defines how flex items are laid out inside a flex container. Flex items are positioned inside a flex container along a flex line. By default there is only one flex line per flex container. So, you can try the bellow structure:
<!DOCTYPE html>

flex item 1

flex item 2

flex item 3


text:
Q: Admob giving low fill rate i have an admob account and it has been giving me very low fill rates (3-4%) overall. There is a voilation in the account that says the quality of traffic is not good. Is there anything I can do at my end to fix it?
At the same time audience network is working just fine.
I am asking if i can do any implementation level change that can help me get good fill rate.

A: There is nothing you can do about. Google does many things to checks your traffic quality.
And in most of the cases admob account gets terminated without giving any proper reason to user.
I had started exploring Facebook Audience Network in combination with Admob to maximize my revenue.
Here are some useful links
http://hackerseve.com/android-integrating-facebook-audience-network-fan/
http://hackerseve.com/android-using-together-admob-and-facebook-audience-network/


text:
Q: How to select rows based on unique column I have table with values as

    ColumnA   ColumnB

    ASD       A
    CSD       B
    DSD       C
    ESD       D
    FSD       D
    GSD       D

Column A is primary key, I need result as

    ColumnA   ColumnB

    ASD       A
    CSD       B
    DSD       C
    ESD       D

I want all unique values from column B & their associated first values columnA.
I tried few queries & looked on Google but couldn't find ant solution .
Thanks,
Rohit.

A: First is First in key order (i.e. alphabetically).
SELECT MIN(ColumnA) AS ColumnA, ColumnB
FROM tbl
GROUP BY ColumnB

You've tagged both MySQL and Oracle for some reason. The above will work in both.
Oracle also has analytical functions that can help with this general type of query.

A: select min(columna) columna, columnb
from mytable
group by columnb;

A: With analytics (Oracle):
SQL> WITH tab AS (
  2     SELECT 'ASD' columnA, 'A' columnB FROM DUAL
  3     UNION ALL SELECT 'CSD', 'B' FROM DUAL
  4     UNION ALL SELECT 'DSD', 'C' FROM DUAL
  5     UNION ALL SELECT 'ESD', 'D' FROM DUAL
  6     UNION ALL SELECT 'FSD', 'D' FROM DUAL
  7     UNION ALL SELECT 'GSD', 'D' FROM DUAL
  8  )
  9  SELECT columnA, columnB
 10    FROM (SELECT columnA, columnB,
 11                 rank() over(PARTITION BY columnB ORDER BY columnA) rnk
 12            FROM tab)
 13   WHERE rnk = 1;

COLUMNA COLUMNB
------- -------
ASD     A
CSD     B
DSD     C
ESD     D

A: select min(ColumnA) as ColumnA,ColumnB from table
group by ColumnB

A: CREATE TABLE #t_Val
(
    ColumnA VARCHAR(3) PRIMARY KEY
,   ColumnB CHAR(1) NOT NULL
)

INSERT #t_Val
SELECT 'ASD' ,  'A'
UNION
SELECT 'CSD' ,  'B'
UNION
SELECT 'DSD' ,  'C'
UNION
SELECT 'ESD' ,  'D'
UNION
SELECT 'FSD' ,  'D'
UNION
SELECT 'GSD' ,  'D'

SELECT  MIN(ColumnA),ColumnB
FROM #t_Val
GROUP BY ColumnB

A: Just another way of doing the same thing:
SELECT DISTINCT
    FIRST_VALUE(ColumnA)
    OVER (PARTITION BY ColumnB
          ORDER BY ColumnA) AS ColumnA,
    ColumnB
FROM tbl

This has the advantage of being usable with more than one column (i.e. where the GROUP BY method doesn't work).

A: Here is solution
CREATE TABLE tbl_test (
  col1 varchar(5) collate latin1_general_ci NOT NULL,
  col2 varchar(5) collate latin1_general_ci NOT NULL,
  PRIMARY KEY  (col1)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
INSERT INTO tbl_test VALUES ('ASD', 'A');
INSERT INTO tbl_test VALUES ('CSD', 'B');
INSERT INTO tbl_test VALUES ('DSD', 'C');
INSERT INTO tbl_test VALUES ('ESD', 'D');
INSERT INTO tbl_test VALUES ('FSD', 'D');
INSERT INTO tbl_test VALUES ('GSD', 'D');

SELECT DISTINCT (
col2
), col1
FROM tbl_test
GROUP BY col2
LIMIT 0 , 30;


text:
Q: WebRequest.Create - The operation has timed out I'm trying to crawl a couple of pages on my own site, but I'm getting a time-out webException("The operation has timed out") on my live environment but not on my test environment. The time-out does not occur on the same page twice, but randomly and often after some requests. After the first time-out, the frequency of the time-outs rises.
The requestUristring on test enviroment:
http://localhost/Opgaver/Flytning/Haarde-hvidevarer/Bortkoersel-amerikaner-koeleskab-paa.aspx
The requestUristring on live enviroment:
http://www.servicebyen.dk/Opgaver/Flytning/Haarde-hvidevarer/Bortkoersel-amerikaner-koeleskab-paa.aspx
var webRequest = (HttpWebRequest)WebRequest.Create(requestUriString);
webRequest.KeepAlive = false;
webRequest.Timeout = 3 * 30 * 1000;
webRequest.PreAuthenticate = false;

using (WebResponse webResponse = webRequest.GetResponse()) //ERROR OCCURS HERE
{

    using (Stream responseStream = webResponse.GetResponseStream())
    {
         if (responseStream != null)
         {
              using (var reader = new StreamReader(responseStream))
              {
                   string readToEnd = reader.ReadToEnd();
                   .....
              }

         }
     }
 }

A: I would try setting webRequest.ServicePoint.ConnectionLimit = 100.

A: Try this (but only for your test environment).
Keep-alive: true if the request to the Internet resource should contain a Connection HTTP header with the value

webRequest.KeepAlive = true;
  webRequest.Timeout = 95 * 95 * 100000;


text:
Q: Save date to DB use thread or service or others Android? I am new to Android. I am not sure which I should use when the OS tell me the ANR when I want to save date to DB.
I think there is no UI, so Service is Ok.
Could some one tell what Are Pros and Cons?
And do you think it is stupid if I use a progress dialog and to do the saving?
Thank you all for your time.

A: sorry for my English skill :P
So if u want to save something in sqlite u can do it in UI or in some Async task, or in a service.
Exemple for usage:
    if u have some big data what u want to save, better if u do that in a service, check the service lifcycle here!
    if u have some image u can do it in asynctask and u don't need to block the ui thread.
    for any small thing u can use the ui thread.
Never forget if ur ui thread can't react to any user indication the Android engine will kill ur ap, thats why u need to do this in back if u have a lot of data.
A good AsyncTask tutorial!


text:
Q: How to insert feature that allows user to select seconds at the beginning? I'm about to create a little click game. It works quite well (thanks to the help of several people). To complete it I would like to add another function.
I'd like users to choose whether they want to play 5, 10 or 15 seconds when they click Start. Other seconds should be left out, otherwise it will be too complicated with the high-score.
The high-score function should then work in such a way that the high-score of 5, 10 or 15 seconds is displayed at the end, depending on what the player selects.
Enclosed you will find the code of HTML, JavaScript and stylesheet, with a high-score function for 5 seconds.
HTML

<link href="style.css" rel="stylesheet">

Willkommen zu unserem Reaktionsspiel! Wenn du bereit bist, klicke auf "Start"

<button id="start" type=button >Start</button>
<button id="clicker" type=button>KLICK</button>

CSS
body
{
width: 100%;
height:100%;
margin: 0 auto;
padding: 0;
background-color:black;
display:flex;
flex-direction:column;
}

#welcome {

    font-size:20px;
    margin:auto;
    width:400px;
    height:50px;
    color:white;
    border-style:solid;
    border-color:white;
    text-align:center;
    margin-top:5%;
}

#start {
    color:white;
    background-color:black;
    margin:auto;
    margin-top:0%;
    border-style:solid;
    border-color:white;
    text-align:center;
    font-size:40px;
    width:100px;
    height:80px;
    transition: transform 0.7s;

}

#start:hover {

    background-color:white;
    color:black;
    cursor:pointer;
    transform: scale(1, -1);

}

#time{
    margin-top:5%;
    margin-left:5%;
    color:white;
    font-size:50px;
    display:none;
}

#clicker{
    color:white;
    background-color:black;
    margin:auto;
    margin-top:10%;
    border-style:solid;
    border-color:white;
    text-align:center;
    font-size:40px;
    width:200px;
    height:100px;
    display:none;
    position:absolute;
    margin-left:35%;

}

#clicker:hover {

    cursor:pointer;

}

JAVASCRIPT
let klick = 0;
display = document.querySelector('#time');

$("#start").click(function() { //clickfunktion beim starten.
  $("#start").fadeOut(); //Der Startbutton geht weg
  $("#welcome").fadeOut(); // Das Willkommensschild geht weg

  $("#time").fadeIn(900); //Timer kommt
  $("#clicker").animate({
    height: 'toggle'
  }); //clicker wird gestartet

  var dauer = 5;

  startTimer(dauer); //übergibt die variable dauer, und dass die Funktion gestartet wird.
})

function startTimer(dauer) {
  let timer = 5;
  runTimer();
  zeit = setInterval(runTimer, 1000); //zahl gibt an, wie oft die Function pro zeit wiederholt wird. Hier eine Sekunde (1000Millisekunden)
  function runTimer(){
    display.textContent = parseInt(timer); // zeigt sekunden-variable

    --timer; //setzt den timer immer einen herab

    if (timer < 0.00) {

      timer = 5;
      console.log(timer);
      $("#start").fadeIn();
      $("#welcome").fadeIn();
      $("#time").fadeOut();
      $("#clicker").fadeOut();
      $("#clicker").css("margin-top", "10%");
      $("#clicker").css("margin-left", "50%");

      alert("Sauber du hast " + klick + " klicks in 5 Sekunden geschafft!");
      alert('High Score is ' + highScore(klick));

      klick = 0
      console.log(timer);

      clearInterval(zeit);

    } //wenn timer auf 0 ist, wird alles wieder angezeigt und die Interval-Function beendet

}

};

$("#clicker").click(function() {
  let zufall = Math.floor(Math.random() * 40) - 20 //setzt eine zufällige höhe für den clicker
  let zufal = Math.floor(Math.random() * 45) //Zufällige Variable für den Linkswert

  klick = klick + 1 //setzt den zähler beim klicken eins hoch
  if (klick % 2 == 0) {
    $("#clicker").animate({
      opacity: '0.3',
      left: zufall + "%",
      top: zufal + "%"
    }, "fast"); //bewegt den Klick-Block auf eine zufällige Stelle
  } else {
    $("#clicker").animate({
      opacity: '1.0',
      left: zufall + "%",
      top: zufal + "%"
    }, "fast")

  }

});

function highScore(score) {
  var saved = 0;
  saved = parseFloat(localStorage.getItem('highScore')) || 0;
  score = parseFloat(score) || 0;

  if (score > saved) {
    saved = score;
    localStorage.setItem('highScore', score);
  }
  return saved;
}

A: The solution actualy try with my system and working well .Bellow is html and js that I changed

<link href="style.css" rel="stylesheet">

Willkommen zu unserem Reaktionsspiel! Wenn du bereit bist, klicke auf "Start"

<select id="gt" style="position:fixed;right:300px;top:65px;height:40px;width:100px;">
    <option value="5">five second</option>
    <option value="10">Ten second</option>
    <option value="15">Finteen second</option>
</select>
<button id="start" type=button >Start</button>
<button id="clicker" type=button>KLICK</button>

let klick = 0;
display = document.querySelector('#time');

$("#start").click(function() { //clickfunktion beim starten.
  $("#start").fadeOut(); //Der Startbutton geht weg
  $("#welcome").fadeOut(); // Das Willkommensschild geht weg

  $("#time").fadeIn(900); //Timer kommt
  $("#clicker").animate({
    height: 'toggle'
  }); //clicker wird gestartet
    var d = $("#gt option:selected").val();

  var dauer = parseInt(d);

  startTimer(dauer); //übergibt die variable dauer, und dass die Funktion gestartet wird.
})

function startTimer(dauer) {
    let timer = parseInt(dauer);
  runTimer();
  zeit = setInterval(runTimer, 1000); //zahl gibt an, wie oft die Function pro zeit wiederholt wird. Hier eine Sekunde (1000Millisekunden)
  function runTimer(){
    display.textContent = parseInt(timer); // zeigt sekunden-variable

    --timer; //setzt den timer immer einen herab

    if (timer < 0.00) {

      timer = 5;
      console.log(timer);
      $("#start").fadeIn();
      $("#welcome").fadeIn();
      $("#time").fadeOut();
      $("#clicker").fadeOut();
      $("#clicker").css("margin-top", "10%");
      $("#clicker").css("margin-left", "50%");

      alert("Sauber du hast " + klick + " klicks in 5 Sekunden geschafft!");
      alert('High Score is ' + highScore(klick));

      klick = 0
      console.log(timer);

      clearInterval(zeit);

    } //wenn timer auf 0 ist, wird alles wieder angezeigt und die Interval-Function beendet

}

};

$("#clicker").click(function() {
  let zufall = Math.floor(Math.random() * 40) - 20 //setzt eine zufällige höhe für den clicker
  let zufal = Math.floor(Math.random() * 45) //Zufällige Variable für den Linkswert

  klick = klick + 1 //setzt den zähler beim klicken eins hoch
  if (klick % 2 == 0) {
    $("#clicker").animate({
      opacity: '0.3',
      left: zufall + "%",
      top: zufal + "%"
    }, "fast"); //bewegt den Klick-Block auf eine zufällige Stelle
  } else {
    $("#clicker").animate({
      opacity: '1.0',
      left: zufall + "%",
      top: zufal + "%"
    }, "fast")

  }

});

function highScore(score) {
  var saved = 0;
  saved = parseFloat(localStorage.getItem('highScore')) || 0;
  score = parseFloat(score) || 0;

  if (score > saved) {
    saved = score;
    localStorage.setItem('highScore', score);
  }
  return saved;
}


text:
Q: Devise wrong number of arguments (2 for 1) upon session_controller#create I'm trying to login with the default activeadmin email - admin@example.com and password - password but when i click login i get the error
 `wrong number of arguments (2 for 1)`

  # POST /resource/sign_in
  def create
    self.resource = warden.authenticate!(auth_options)
    set_flash_message(:notice, :signed_in) if is_flashing_format?
    sign_in(resource_name, resource) #ERROR SHOWING AT THIS LINE
    yield resource if block_given?
    respond_with resource, location: after_sign_in_path_for(resource)
  end

May i know what's going wrong ? This is the error i got in my terminal
Started POST "/admin/login" for 127.0.0.1 at 2014-07-24 16:49:53 +0800
Processing by ActiveAdmin::Devise::SessionsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"[FILTERED]", "admin_user"=>{"email"=>"admin@example.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Login"}
  AdminUser Load (0.6ms)  SELECT  "admin_users".* FROM "admin_users"  WHERE "admin_users"."email" = 'admin@example.com'  ORDER BY "admin_users"."id" ASC LIMIT 1
   (0.1ms)  BEGIN
  SQL (0.3ms)  UPDATE "admin_users" SET "current_sign_in_at" = $1, "last_sign_in_at" = $2, "sign_in_count" = $3, "updated_at" = $4 WHERE "admin_users"."id" = 1  [["current_sign_in_at", "2014-07-24 08:49:53.235190"], ["last_sign_in_at", "2014-07-24 08:49:18.879844"], ["sign_in_count", 16], ["updated_at", "2014-07-24 08:49:53.236414"]]
   (0.4ms)  COMMIT
Completed 500 Internal Server Error in 85ms

ArgumentError - wrong number of arguments (2 for 1):
  devise (3.2.4) app/controllers/devise/sessions_controller.rb:17:in `create'
  actionpack (4.1.0) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
  actionpack (4.1.0) lib/abstract_controller/base.rb:189:in `process_action'
  actionpack (4.1.0) lib/action_controller/metal/rendering.rb:10:in `process_action'
  actionpack (4.1.0) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
  activesupport (4.1.0) lib/active_support/callbacks.rb:113:in `call'
  activesupport (4.1.0) lib/active_support/callbacks.rb:229:in `block in halting'
  activesupport (4.1.0) lib/active_support/callbacks.rb:229:in `block in halting'
  activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
  activesupport (4.1.0) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
  activesupport (4.1.0) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
  activesupport (4.1.0) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
  activesupport (4.1.0) lib/active_support/callbacks.rb:86:in `run_callbacks'
  actionpack (4.1.0) lib/abstract_controller/callbacks.rb:19:in `process_action'
  actionpack (4.1.0) lib/action_controller/metal/rescue.rb:29:in `process_action'
  actionpack (4.1.0) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
  activesupport (4.1.0) lib/active_support/notifications.rb:159:in `block in instrument'
  activesupport (4.1.0) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activesupport (4.1.0) lib/active_support/notifications.rb:159:in `instrument'
  actionpack (4.1.0) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
  actionpack (4.1.0) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
  activerecord (4.1.0) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
  actionpack (4.1.0) lib/abstract_controller/base.rb:136:in `process'
  actionview (4.1.0) lib/action_view/rendering.rb:30:in `process'
  actionpack (4.1.0) lib/action_controller/metal.rb:195:in `dispatch'
  actionpack (4.1.0) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
  actionpack (4.1.0) lib/action_controller/metal.rb:231:in `block in action'
  actionpack (4.1.0) lib/action_dispatch/routing/route_set.rb:80:in `dispatch'
  actionpack (4.1.0) lib/action_dispatch/routing/route_set.rb:48:in `call'
  actionpack (4.1.0) lib/action_dispatch/routing/mapper.rb:45:in `call'
  actionpack (4.1.0) lib/action_dispatch/journey/router.rb:71:in `block in call'
  actionpack (4.1.0) lib/action_dispatch/journey/router.rb:59:in `call'
  actionpack (4.1.0) lib/action_dispatch/routing/route_set.rb:676:in `call'
  newrelic_rpm (3.7.2.195) lib/new_relic/rack/error_collector.rb:55:in `call'
  newrelic_rpm (3.7.2.195) lib/new_relic/rack/agent_hooks.rb:32:in `call'
  newrelic_rpm (3.7.2.195) lib/new_relic/rack/browser_monitoring.rb:27:in `call'
  newrelic_rpm (3.7.2.195) lib/new_relic/rack/developer_mode.rb:45:in `call'
  warden (1.2.3) lib/warden/manager.rb:35:in `block in call'
  warden (1.2.3) lib/warden/manager.rb:34:in `call'
  rack (1.5.2) lib/rack/etag.rb:23:in `call'
  rack (1.5.2) lib/rack/conditionalget.rb:35:in `call'
  rack (1.5.2) lib/rack/head.rb:11:in `call'
  clearance (1.3.0) lib/clearance/rack_session.rb:10:in `call'
  actionpack (4.1.0) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
  actionpack (4.1.0) lib/action_dispatch/middleware/flash.rb:254:in `call'
  rack (1.5.2) lib/rack/session/abstract/id.rb:225:in `context'
  rack (1.5.2) lib/rack/session/abstract/id.rb:220:in `call'
  actionpack (4.1.0) lib/action_dispatch/middleware/cookies.rb:560:in `call'
  activerecord (4.1.0) lib/active_record/query_cache.rb:36:in `call'
  activerecord (4.1.0) lib/active_record/connection_adapters/abstract/connection_pool.rb:621:in `call'
  activerecord (4.1.0) lib/active_record/migration.rb:380:in `call'
  actionpack (4.1.0) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.1.0) lib/active_support/callbacks.rb:82:in `run_callbacks'
  actionpack (4.1.0) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.1.0) lib/action_dispatch/middleware/reloader.rb:73:in `call'
  actionpack (4.1.0) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
  better_errors (1.1.0) lib/better_errors/middleware.rb:84:in `protected_app_call'
  better_errors (1.1.0) lib/better_errors/middleware.rb:79:in `better_errors_call'
  better_errors (1.1.0) lib/better_errors/middleware.rb:56:in `call'
  actionpack (4.1.0) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  actionpack (4.1.0) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.1.0) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.1.0) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.1.0) lib/active_support/tagged_logging.rb:68:in `block in tagged'
  activesupport (4.1.0) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (4.1.0) lib/active_support/tagged_logging.rb:68:in `tagged'
  railties (4.1.0) lib/rails/rack/logger.rb:20:in `call'
  actionpack (4.1.0) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
  rack (1.5.2) lib/rack/runtime.rb:17:in `call'
  activesupport (4.1.0) lib/active_support/cache/strategy/local_cache_middleware.rb:26:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  actionpack (4.1.0) lib/action_dispatch/middleware/static.rb:64:in `call'
  rack (1.5.2) lib/rack/sendfile.rb:112:in `call'
  railties (4.1.0) lib/rails/engine.rb:514:in `call'
  railties (4.1.0) lib/rails/application.rb:144:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  rack (1.5.2) lib/rack/content_length.rb:14:in `call'
  rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service'

A: You've said you are using both devise and clearance in your app. Both gems handle authentication, and conflict with each other.
In particular, clearance defines a sign_in method that takes only one parameter:
https://github.com/thoughtbot/clearance/blob/8d3958eb5fdc9b762df4788fd81793801940b754/lib/clearance/authentication.rb#L33
While devise defines one that takes two:
https://github.com/plataformatec/devise/blob/b786c384d54a6365bdc6c0cf6068dc5325a301a9/lib/devise/controllers/sign_in_out.rb#L30
You should either remove clearance or devise from your app, as they perform the same task.

A: Replace
sign_in(resource_name, resource)

with
sign_in(resource)


text:
Q: Fill HTML content to Docx template I'm working on a project which aims to gather survey from users and fill them into our Word template.
The user input is in HTML format with inline style and inline images ( tag with base64 or image link source), and I want to fill them into our existing survey template which is in Docx format.
I have tried multiples library including:

*

*ruby/sablon

*java/docx4j

*nodejs/docxtemplater (raw xml feature)

But none of them seems to match with what I need (maybe I missed it?).
Is there any way to achieve what I want to do? I'm open to any kind of tools or programming languages.

A: docx4j's content control data binding can bind escaped XHTML; it uses docx4j-ImportXHTML to convert the escaped XHTML to real docx content.  You can Google 'OpenDope' for more.


text:
Q: Paying to Access Custom Fields Per Post I need a way to protect access to custom fields within my posts. I've been looking at several plugs ins, but none seem quite right.
I do not need to protect the body of my post, just a set of custom fields. I need a "pay to access" button to appear if a user has not purchased the post.
Also, I need access to the field purchased only on a per post basis. I.E. Post Title #1 purchase does NOT also give access to fields in Post Title #2
My access to these fields within the posts needs to be set to $x.xx for 30 days or one month.
Can anyone please help? I'm about at the end of my rope.

A: This sounds like custom development work, I doubt there is a pre-built solution. At its most basic, I'd say you need to a membership solution.  There are a several out there, some free, some premium.
Then in your front-end you can wrap the display of all the custom fields with current_user_can() using a capability that only that level has. For custom user roles you can probably just get away with:
if( current_user_can('gold_member') ) {
 echo 'whoa check this out';
} else {
  echo 'sorry, no need to be a gold member to see this';
}

EDIT
or to make it post specific:
if( current_user_can('read_post_14') ) {
 echo 'whoa check this out';
} else {
  echo 'sorry, no need to be a gold member to see this';
}

You'd have to create a new role for each post though.... possibly on the save_post hook. But I'm not sure how you'd assign the role to user when he/she pays for a specific post.


text:
Q: clang can't optimize away global variables used only in main()? If I plug this c++ program into clang (version 3.7)
///*
#include "stdio.h"
#include "stdint.h"
//extern int printf(const unsigned char*, ...);

extern "C" void __cxa_pure_virtual() { }

struct A
{
    virtual void foo() = 0;
};

struct B : A
{
    uint32_t x;
    B(int x) : x(x) { }
    virtual void foo()
    {
        printf("This is a test %d\n", x);
    }
};
//*/
uint64_t thing = 0;
float other = 10.0f;
B b(12345);
int main()
{

    thing++;
    A* a = &b;
    other *= 3.14159f;
    a->foo();
}

And compile with clang -emit-llvm main.cpp -fno-rtti -O3 -S, then I get the following byte code:
; ModuleID = 'main.cpp'
target datalayout = "e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128"
target triple = "i686-pc-linux-gnu"

%struct.B = type { %struct.A, i32 }
%struct.A = type { i32 (...)** }

$_ZN1B3fooEv = comdat any

$_ZTV1B = comdat any

@thing = global i64 0, align 8
@other = global float 1.000000e+01, align 4
@b = global %struct.B { %struct.A { i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*], [3 x i8*]* @_ZTV1B, i64 0, i64 2) to i32 (...)**) }, i32 12345 }, align 4
@_ZTV1B = linkonce_odr unnamed_addr constant [3 x i8*] [i8* null, i8* null, i8* bitcast (void (%struct.B*)* @_ZN1B3fooEv to i8*)], comdat, align 4
@.str = private unnamed_addr constant [19 x i8] c"This is a test %d\0A\00", align 1
@llvm.global_ctors = appending global [0 x { i32, void ()*, i8* }] zeroinitializer

; Function Attrs: nounwind readnone
define void @__cxa_pure_virtual() #0 {
entry:
  ret void
}

define i32 @main() #1 {
entry:
  %0 = load i64, i64* @thing, align 8, !tbaa !1
  %inc = add i64 %0, 1
  store i64 %inc, i64* @thing, align 8, !tbaa !1
  %1 = load float, float* @other, align 4, !tbaa !5
  %mul = fmul float %1, 0x400921FA00000000
  store float %mul, float* @other, align 4, !tbaa !5
  %vtable = load void (%struct.A*)**, void (%struct.A*)*** bitcast (%struct.B* @b to void (%struct.A*)***), align 4, !tbaa !7
  %2 = load void (%struct.A*)*, void (%struct.A*)** %vtable, align 4
  tail call void %2(%struct.A* getelementptr inbounds (%struct.B, %struct.B* @b, i32 0, i32 0))
  ret i32 0
}

; Function Attrs: nounwind
define linkonce_odr void @_ZN1B3fooEv(%struct.B* nocapture readonly %this) unnamed_addr #2 comdat align 2 {
entry:
  %x = getelementptr inbounds %struct.B, %struct.B* %this, i32 0, i32 1
  %0 = load i32, i32* %x, align 4, !tbaa !9
  %call = tail call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([19 x i8], [19 x i8]* @.str, i32 0, i32 0), i32 %0)
  ret void
}

; Function Attrs: nounwind
declare i32 @printf(i8* nocapture readonly, ...) #2

attributes #0 = { nounwind readnone "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="pentium4" "target-features"="+sse,+sse2" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #1 = { "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="pentium4" "target-features"="+sse,+sse2" "unsafe-fp-math"="false" "use-soft-float"="false" }
attributes #2 = { nounwind "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="pentium4" "target-features"="+sse,+sse2" "unsafe-fp-math"="false" "use-soft-float"="false" }

!llvm.ident = !{!0}

!0 = !{!"clang version 3.7.1 "}
!1 = !{!2, !2, i64 0}
!2 = !{!"long long", !3, i64 0}
!3 = !{!"omnipotent char", !4, i64 0}
!4 = !{!"Simple C/C++ TBAA"}
!5 = !{!6, !6, i64 0}
!6 = !{!"float", !3, i64 0}
!7 = !{!8, !8, i64 0}
!8 = !{!"vtable pointer", !4, i64 0}
!9 = !{!10, !11, i64 4}
!10 = !{!"_ZTS1B", !11, i64 4}
!11 = !{!"int", !3, i64 0}

If you look at the main function, I have two variables that are useless.  Sure I increment one and I do some multiplication on another, but I never use the values in them ever.
But if you look at the output of the byte code, it looks like it is still doing the useless math.
Is it just me or is this a bug?

A: Those variables are variables in global scope. The compiler simply couldn't figure out whether or not those variables could be declared and referenced in other translation units.
I'd be surprised if any modern C++ compiler is sophisticated enough to figure out that execution flow could not escape this translation unit, in a defined manner, and thus it would be safe to optimize away unused global variables in this translation unit.

A: No, I don't believe that this is a bug, as your variables are globals.
Clang cannot remove this math as it can't know that any externally called function (like the printf function, in a different translation unit) doesn't declare extern float other; and somehow uses it.
Try writing:
int main()
{
    uint64_t thing = 0;
    float other = 10.0f;
    B b(12345);

    thing++;
    A* a = &b;
    other *= 3.14159f;
    a->foo();
}


text:
Q: how to access connection object in another class in java? i am using xampp mysql, this code is for JDBC program. actually there are two class one is dbconnect.java and another is login.java. I want to access the connection object (i.e. conn) in another class(i.e. login.java). But i don't have proper idea, i have included the code here please suggest me what is the problem and what are the solutions?
This is the code of dbconnect.java
package stundentrecord;

import java.sql.Connection;
import java.sql.DriverManager;

public class dbconnect {
    public void conect(){
        Connection con = null;
        String url = "jdbc:mysql://localhost:3306/";
        String db = "studentRecord";
        String driver = "com.mysql.jdbc.Driver";
        String user = "root";
        String pass = "";
        try{
            Class.forName(driver);
            con = DriverManager.getConnection(url + db, user, pass);
            if(con==null){
                System.out.println("Connection cannot be established");
            }
            // con.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

and here is the code from another class named login.java
if(source==login){
    if(username!=null && password!=null) {
        Connection conn= null;
        Statement stmt = null;
        dbconnect db = new dbconnect();
        db.conect();
        String query = "SELECT * from userlogin";
        try{
            stmt=(Statement) conn.createStatement(); // here is the problem
            ResultSet rs = stmt.executeQuery(query);  // here is the problem
            while (rs.next()) {
                String user = rs.getString("username");
                String pass=rs.getString("password");
                System.out.println("Welcome "+user);
            }
        } catch(SQLException ex){
            ex.getMessage();
        }
        StundentRecord SR = new StundentRecord();
    } else {
        JOptionPane.showMessageDialog(null,"Username or password field is empty","error    !!",JOptionPane.ERROR_MESSAGE);
    }
}

What is the real problem and how to solve it?

A: The easiest way would be to make the connect method non void and return the connection:
public Connection conect() {
    Connection con = null;
    String url = "jdbc:mysql://localhost:3306/";
    String db = "studentRecord";
    String driver = "com.mysql.jdbc.Driver";
    String user = "root";
    String pass = "";
    try {
        Class.forName(driver);
        con = DriverManager.getConnection(url + db, user, pass);
        if (con == null) {
            System.out.println("Connection cannot be established");
        }
        return con;
    } catch (Exception e) {
        System.out.println(e);
    }
    return null;
}

A: You should return your CONNECTION object from you connection class and assign it to your login class... Now your connection object is null...


text:
Q: what does 0L stands for in c++ accumulate function? I came across this line of code shown below, what does 0L stand for?
nums is just a 1d vector. I knew this line of code trying to get the total sum of the nums array.
long r = accumulate(begin(nums), end(nums), 0L) + 1;


text:
Q: pandas.DataFrame.merge with None (NaN) I need to join the fields containing None/Nan. But pandas betrays that, is that normal? (simulate intersect, it's need to keep the indexes of first dframe)
a = pandas.DataFrame([[None, 1], [1, 2]], index=[10, 11], columns=['a', 'b'])
b = pandas.DataFrame([[None, 2], [1, 2]], columns=['c', 'd'])

a.merge(
    right=b.drop_duplicates().set_index(b.columns.to_list()),
    how='inner',
    left_on=a.columns.to_list(),
    right_index=True)

#       a  b
# 11  1.0  2
# 11  1.0  2 # Where does this row come from ???
#
# While i was expecting just:
#       a  b
# 11  1.0  2

But
a = pandas.DataFrame([[None, 1], [1, 2]], index=[10, 11], columns=['a', 'b'])
b = pandas.DataFrame([[None, 1], [1, 2]], columns=['c', 'd'])

a.merge(
    right=b.drop_duplicates().set_index(b.columns.to_list()),
    how='inner',
    left_on=a.columns.to_list(),
    right_index=True)

#       a  b
# 11  1.0  2
# Where is the row [None, 1] ???
#
# While i was expecting:
#       a  b
# 10  NaN  1
# 11  1.0  2

How to join with None ?


text:
Q: How to put the camera preview into a UIImageView? I want to put the camera live view (back camera) inside the ViewController in iOS in Swift but I don't know how to do it.

A: Please, search for answers first and if you do not found then come and ask.
Here I am giving some which I found it here only. you can get more.
How to Add Live Camera Preview to UIView
 Take photos with live video preview using AVFoundation


text:
Q: How to make where condition include nil value I find ActiveRecord, funnel value is not "input" value
and I make  where condition
here is my code
@calls = Call.searchable.where.not(funnel: "input")

these command work good, but result is also except nil value
I wanna only  funnel is not 'input'
how to add OR condition in where statement
SQL Statement is
select * from call where is_visible = 1 and (funnel != 'input or funnel is null)

A: The blow code should help you.
@calls = Call.searchable.where("funnel != 'input' or funnel is null")

A: This will also work if values are dynamic
Call.searchable.where("funnel != ? OR funnel is ?",@value1, nil)


text: Q: Firebase auth Redirect to Facebook app instead of website for login on mobile Is it possible configure my firebase project so that if a user is on mobile and they need to log in, they are redirected to the facebook mobile app instead of the facebook website in their browser?. I thought iOS would automatically intercept the link but it just takes you to the facebook site. Users with the app installed might not already be logged in through their browser since they are used to using the app and i'd like to avoid the extra login step for them