text:
Q: How to add option to select list in jQuery whit "selectpicker" class? I have 2 select list and I want add option to both  select lists in jQuery. I add option  with bellow code in jQuery but this work just on list1 and not work on  list2 with id=mySelect2 because list2 have class.
$("#mySelect1").append(new Option("option text", "value"));
$("#mySelect2").append(new Option("option text", "value"));

MY  Jsfiddle is here.
List1:
<select id='mySelect1'     >
<option value="4444">4444</option>
<option value="Elite1">Elite1</option>
<option value="Elite">Elite</option>
</select>

List2:
<select id='mySelect2'   data-live-search="true" data-live-search-style="startsWith" class="selectpicker"  >

<option value="4444">4444</option>
<option value="Elite1">Elite1</option>
<option value="Elite">Elite</option>

</select>

How can I add option  to list2?
I use this link but not work too.

A: Just call the render method on the selectpicker element after adding the new option
$("#mySelect1").append(new Option("option text", "value"));
$("#mySelect2").append(new Option("option text", "value"));
$("#mySelect2").selectpicker('render')

https://developer.snapappointments.com/bootstrap-select/methods/#selectpickerrender

A: You can use the refresh method to add (or, even remove) options. You may do something like this:

$(function () {
    $('#mySelect2').selectpicker();
});

$('#addButton').click(function(){
    let valuetoadd = prompt('What to add?');
  $('#mySelect2,#mySelect1').append(`<option value="${valuetoadd}">${valuetoadd}</option>`);
  $('#mySelect2').selectpicker('refresh');
})
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/css/bootstrap-select.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/js/bootstrap-select.js"></script>

<select id='mySelect1'     >
<option value="4444">4444</option>
<option value="Fedex">Fedex</option>
<option value="Elite">Elite</option>
</select>

<hr>

<select id='mySelect2'   data-live-search="true" data-live-search-style="startsWith"  >

<option value="4444">4444</option>
<option value="Fedex">Fedex</option>
<option value="Elite">Elite</option>

</select>

<button id="addButton">
Add New Value
</button>


text:
Q: Calculating $\int_{0}^\infty \frac{\cos(2x)}{(x^2 + 1)(x^2 + 4)} dx$ using residue calculus I want to calculate
$$\int_{0}^\infty \frac{\cos(2x)}{(x^2 + 1)(x^2 + 4)} dx$$
using residue calculus
My solution
First observation is that:
$$\int_\mathbb R \frac{e^{2ix}}{(x^2 + 1)(x^2 + 4)}  dx = \int_\mathbb R \frac{\cos(2x)}{(x^2 + 1)(x^2 + 4)} dx + i \int_\mathbb R \frac{\sin(2x)}{(x^2 + 1)(x^2 + 4)}dx$$
whereas $\int_\mathbb R \frac{\sin(2x)}{(x^2 + 1)(x^2 + 4)}dx = 0$ since this function is odd, as multiplication of odd function with even function.
If we define now $$f(z) = \frac{e^{2iz}}{(z^2 + 1)(z^2 + 4)} = \frac{e^{2iz}}{(z^2 - i^2)(z^2 - 4i^2)} = \frac{e^{2iz}}{(z-i)(z+i)(z-2i)(z+2i)}$$
We will see that we have four poles in points $i, -i, 2i, -2i$ with rank $1$.
Now let's define our contour for $r > 2$:
$$\gamma_1: [-r ,r] \ni t \rightarrow t \in \mathbb C$$
$$\gamma_2: [0, \pi] \ni t \rightarrow Re^{it}$$
Our final contour is $\gamma = \gamma_1 + \gamma_2$
Firstly let's consider our integral on $\gamma_2$:
$$|\int_ {\gamma_2} f(z) dz| = |\int_0 ^ \pi \frac{e^{2ire^{it}}}{((re^{it})^2 + 1)((re^{it})^2 + 4)}ire^{it} dt| \le \int_0^\pi|\frac{|e^{-2\sin(t)}|}{((re^{it})^2 + 1)((re^{it})^2 + 4)}r dt$$
Now we know that:
$$\frac{1}{|(re^{it})^2 + 1|} \le \frac{1}{r^2 - 1}$$
$$\frac{1}{|(re^{it})^2 + 4|} \le \frac{1}{r^2 - 4}$$
$$\int_0^\pi e^{-A \sin t}dt < \frac{\pi}{A}$$
so
$$\int_0^\pi|\frac{|e^{-2\sin(t)}|}{((re^{it})^2 + 1)((re^{it})^2 + 4)}r dt <  \frac{r\pi}{2} \cdot \frac{1}{(r^2 - 1)(r^2 + 4)} \rightarrow 0 $$
So when going with $r$ to infinity we'll have our integral only on $\gamma_1$. To calculate so, we'll just calculate residuals in $i$ and $2i$:
$$\textrm{res}_if(z) = \lim_{z \rightarrow i} = \lim_{z \rightarrow i}\frac{e^{2iz}}{(z + i)(z - 2i)(z + 2i)} = \frac{e^{-2}}{6}$$
$$\textrm{res}_{2i}f(z) = \lim_{z \rightarrow 2i} = \lim_{z \rightarrow 2i}\frac{e^{2iz}}{(z - i)(z - i)(z + 2i)} = \frac{e^{-4}}{12}$$
So finally we have that our integral equals to:
$$\pi(\frac{e^{-2}}{6} + \frac{e^{-4}}{12})$$
which unfortunately is different from what wolfamalpha suggests. Could you please tell me where did I make the mistake?

A: Those residues are wrong. You have\begin{align}\operatorname{res}_{z=i}\frac{e^{2iz}}{(z^2+1)(z^2+4)}&=\lim_{z\to i}\frac{e^{2iz}}{(z+i)(z^2+4)}\\&=\frac{e^{-2}}{6i}\end{align}and, by the same argument,$$\operatorname{res}_{z=2i}\frac{e^{2iz}}{(z^2+1)(z^2+4)}=-\frac{e^{-4}}{12i}.$$Therefore\begin{align}\int_{-\infty}^\infty\frac{\cos(2x)}{(x^2+1)(x^2+4)}\,\mathrm dx&=\int_{-\infty}^\infty\frac{e^{2ix}}{(x^2+1)(x^2+4)}\,\mathrm dx\\&=2\pi i\left(\frac{e^{-2}}{6i}-\frac{e^{-4}}{12i}\right)\\&=2\pi\left(\frac{e^{-2}}6-\frac{e^{-4}}{12}\right).\end{align}So,$$\int_0^\infty\frac{\cos(2x)}{(x^2+1)(x^2+4)}\,\mathrm dx=\pi\left(\frac{e^{-2}}6-\frac{e^{-4}}{12}\right).$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Obtain the client id from Ustream I am developing a android streaming app, I will like to use the Ustream api to streaming a video from the app, i know how to do it, my problem is that I need a client id and a client secret id to validate the user's credentials using OAuth 2.0, but I have no idea where to get it since that in the api documentation is not explained and I can not find it anywhere else
Any help is highly appreciated
Regards


text:
Q: Plotting with python matplotlib in ipython/pandas When I try to plot using ipython, for some reason no matter what i try the y axis does not get the right format.
I see that the range is between 3528 and 3536. But somehow it shows the same weirdly.
ANd it shows something at the top as +3.528e3. HOw do i change this to just display similar to the x-axis format?

here is the code I have
            plt.figure()
            plt.plot(all_strks, all_fwds, 'o')
            plt.plot(all_strks, fwdline)

            #ax = plt.gca()
            #ax.set_ylim(all_fwds.min(),all_fwds.max())

            #x1,x2,y1,y2 = plt.axis()
            #print x1,x2,all_fwds.min(),all_fwds.max()
            #plt.axis([x1,x2,all_fwds.min(),all_fwds.max()])

A: Set the offset vale false. Here is all the info you need.
Here is the tutorial link.
ax = plt.gca()
ax.ticklabel_format(useOffset=False,useMathText=None)

Or as shown in the example,
from matplotlib.ticker import OldScalarFormatter
gca().xaxis.set_major_formatter(ScalarFormatter(useOffset=False))
gca().yaxis.set_major_formatter(ScalarFormatter(useOffset=False))


text:
Q: Time stamp but the stamp needs to be in another sheet I'm trying to make a KPI that is dependent on completion of task. And I need to time stamp in order to pull this off.
I can make regular time stamps. But what I need is that the time stamp needs to record in different sheet in the same spreadsheet.
I have a master sheet where my employees record and register all calls that come through. It's called "MASTER SHEET".
And a KPI SHEET where I need to record the time /time stamp here/
function onEdit() {
  var s = SpreadsheetApp.getActiveSheet();
  if( s.getName() == "MASTER SHEET" )
    var r = s.getActiveCell();
    if( r.getColumn() == 2 )
      var nextCell = r.offset(0, 1); <<<<<<<<<<<<<<<<<this is where I'm stuck.
      if( nextCell.getValue() === '' ) //is empty?
        nextCell.setValue(new Date());
    }
  }
}

This function only stamps in the same sheet so it doesn't work for me.

A: Try something like this:
function onEdit(e) {
if (e.source.getActiveSheet()
    .getName() !== 'MASTER SHEET' || e.range.columnStart !== 2) return;
e.source.getSheetByName('KPI SHEET')
    .getRange(e.range.rowStart, 4)
    .setValue(e.value ? new Date() : '');
}


text:
Q: Why scrapy selenium is not getting any data? I am trying to scrape the "product details (a table)" and "Please choose a size (a JavaScript button type)" section from this JS based webpage https://www.breuninger.com/de/damen/luxus/bekleidung-jacken-maentel/. I am using scrapy-selenium to scrape this webpage. This code is able to scrape everything but these 02 sections. I have checked it using only selenium and got the result. But not with the scrapy-selenium. I also used scrapy-splash but it can't even render the full page. I have checked out the previous questions but can't get the solution. What actually I am doing wrong here?
import scrapy
from scrapy_selenium import SeleniumRequest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time

class ProductsSpider(scrapy.Spider):
    name = 'products'
    allowed_domains = ['www.breuninger.com']

def start_requests(self):
    options = webdriver.ChromeOptions()
    options.headless = True

    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
    driver.set_window_size(1920, 1080)

    driver.get("https://www.breuninger.com/de/damen/luxus/bekleidung-jacken-maentel/")
    time.sleep(5)

    banner_btn = driver.find_element(By.XPATH, "//div[@class='banner-actions-container']/button")
    banner_btn.click()
    time.sleep(3)

    links = driver.find_elements(By.XPATH, "//suchen-produktliste[@id='produktliste']/section/div/suchen-produkt/div/a")

    for link in links:
        href= link.get_attribute('href')
        yield SeleniumRequest(
                url = href,
                callback= self.parse,
                wait_time=1
        )

    driver.quit()
    return super().start_requests()

 def parse(self, response):

    yield {
    'Bold-title' : response.xpath("(//span[@itemprop='name'])[1]/text()").get(),
    'Price' : response.xpath("//div[@itemprop='offers']/span/text()").get(),
    'Beschreibung': response.xpath("//div[@class='bewerten-textformat--produktdetails-detail']/div/ul/li/text()").getall()
    }

A: You don't really need the heavy guns of selenium here to get the products' details like price, description, and brand.
You can try this:
import pandas as pd
import requests
from bs4 import BeautifulSoup
from tabulate import tabulate

url = "https://www.breuninger.com/de/damen/luxus/bekleidung-jacken-maentel/"

headers = {
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36",
}

soup = (
    BeautifulSoup(
        requests.get(url, headers=headers).text,
        "lxml",
    ).select(".suchen-produkt a")
)

products = [
    [
        i.select_one(".suchen-produkt__marke").getText(),
        i.select_one(".suchen-produkt__name").getText(),
        i.select_one(".suchen-produkt__preis").getText(),
    ] for i in soup
]

df = pd.DataFrame(products, columns=["Brand", "Description", "Price"])
df.to_csv("products.csv", index=False)
print(tabulate(df, headers="keys", tablefmt="grid"))

That should give you a table like this (along a .csv file).
+----+-------------------------+--------------------------------------------------------------+------------------+
|    | Brand                   | Description                                                  | Price            |
+====+=========================+==============================================================+==================+
|  0 | BURBERRY                | Jacke BINHAM                                                 | 1.549,99 €       |
+----+-------------------------+--------------------------------------------------------------+------------------+
|  1 | BURBERRY                | Trenchcoat KENSINGTON                                        | 1.849,99 €       |
+----+-------------------------+--------------------------------------------------------------+------------------+
|  2 | RALPH LAUREN Collection | Blouson mit Schmucksteinen                                   | 2.050 €          |
+----+-------------------------+--------------------------------------------------------------+------------------+
|  3 | BURBERRY                | Trenchcoat KENSINGTON                                        | 1.849,99 €       |
+----+-------------------------+--------------------------------------------------------------+------------------+
|  4 | BURBERRY                | Trenchcoat WATERLOO                                          | 1.889,99 €       |
+----+-------------------------+--------------------------------------------------------------+------------------+
|  5 | BURBERRY                | Trenchcoat ISLINGTON                                         | 1.849,99 €       |
+----+-------------------------+--------------------------------------------------------------+------------------+
|  6 | BURBERRY                | Trenchcoat WATERLOO                                          | 1.889,99 €       |
+----+-------------------------+--------------------------------------------------------------+------------------+
|  7 | MONCLER                 | Daunenweste LIANE                                            | 495 €            |
+----+-------------------------+--------------------------------------------------------------+------------------+
|  8 | BURBERRY                | Trenchcoat                                                   | 1.849,99 €       |
+----+-------------------------+--------------------------------------------------------------+------------------+
|  9 | MONCLER                 | Jacke im Materialmix                                         | 650 €            |
+----+-------------------------+--------------------------------------------------------------+------------------+
| 10 | MONCLER                 | Jacke AGDE                                                   | 695 €            |
+----+-------------------------+--------------------------------------------------------------+------------------+
| 11 | MONCLER                 | Jacke CECILE                                                 | 520 €            |
+----+-------------------------+--------------------------------------------------------------+------------------+
| 12 | MONCLER                 | Jacke TIYA                                                   | 695 €            |
+----+-------------------------+--------------------------------------------------------------+------------------+
| 13 | MONCLER                 | Daunenweste LIANE                                            | 495 €            |
+----+-------------------------+--------------------------------------------------------------+------------------+
| 14 | MONCLER                 | Daunenparka HERMANVILLE                                      | 1.250 €          |
+----+-------------------------+--------------------------------------------------------------+------------------+
| 15 | BURBERRY                | Trenchcoat KENSINGTON                                        | 999,99 €         |
+----+-------------------------+--------------------------------------------------------------+------------------+
| 16 | MONCLER                 | Jacke AGDE                                                   | 695 €            |
+----+-------------------------+--------------------------------------------------------------+------------------+
| 17 | MONCLER                 | Daunenweste ALPISTE                                          | 750 €            |
+----+-------------------------+--------------------------------------------------------------+------------------+
| 18 | MONCLER                 | Regenmantel HIENGU                                           | 735 €            |
+----+-------------------------+--------------------------------------------------------------+------------------+
| 19 | MONCLER                 | Jacke TIYA                                                   | 695 €            |
+----+-------------------------+--------------------------------------------------------------+------------------+
| 20 | MONCLER                 | Jacke HOULGATE                                               | 780 €            |
+----+-------------------------+--------------------------------------------------------------+------------------+

and more ...

PS. That last XPath of yours doesn't work on that page, hence the empty list you get.


text:
Q: What does it mean for partial derivative to exist but not continuous?
What does it mean for partial derivative to exist but not continuous?

Continuous partial derivatives imply differentiability and differentiability imply continuity of a function and the existence of partial derivatives. I also understand that any other implication of this statement is false.

A: It is possible to have a function of several variables that has partial derivatives everywhere, but which is not fully differentiable everywhere. In such a case the partial derivatives will be discontinuous.
A typical example of the kind of functions we're talking about would be
$$ \begin{align}
f(r\cos\theta,r\sin\theta) &= r\sin(2\theta) & \quad \text{for }r>0 \\
f(0,0) &= 0 \end{align} $$
This has both partial derivatives everywhere, but they are not continuous. We have $\frac{\partial f}{\partial y}=0$ at $(0,0)$ but $\frac{\partial f}{\partial y}=2$ at $(x,0)$ for every $x>0$. And the function is not differentiable at $(0,0)$, because the linear mapping induced by the partial derivatives doesn't approximate it well enough in directions other than the one the partial derivatives were taken in.

Even in one dimension, it is possible to be differentiable everywhere, but not continuously differentiable; the classical example is
$$ f(x) = \begin{cases} 0 & \text{when }x=0 \\
x^2\sin(1/x) & \text{otherwise} \end{cases} $$


text:
Q: Connection Refused - Why does zookeeper tries to connect to localhost instead of a server ip My Reduce Tasks fail because all the namenode fails trying to connect to localhost instead of 10.10.187.170 ..
My application even tries to connect manually in the code..
Configuration conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum", "10.10.187.170");
conf.set("hbase.zookeeper.property.clientPort","2181");
conf.set("hbase.master","10.10.187.170");

My hbase-site.xml:
<?xml version="1.0" encoding="UTF-8"?>

<!--Autogenerated by Cloudera CM on 2013-08-14T06:27:30.291Z-->
<configuration>
<property>
<name>hbase.rootdir</name>
<value>hdfs://ip-10-10-187-170.eu-west-1.compute.internal:8020/hbase</value>
</property>
<property>
<name>hbase.client.write.buffer</name>
<value>2097152</value>
</property>
<property>
<name>hbase.client.pause</name>
<value>1000</value>
</property>
<property>
<name>hbase.client.retries.number</name>
<value>10</value>
</property>
<property>
<name>hbase.client.scanner.caching</name>
<value>1</value>
</property>
<property>
<name>hbase.client.keyvalue.maxsize</name>
<value>10485760</value>
</property>
<property>
<name>hbase.rpc.timeout</name>
<value>60000</value>
</property>
<property>
<name>hbase.security.authentication</name>
<value>simple</value>
</property>
<property>
<name>zookeeper.session.timeout</name>
<value>60000</value>
</property>
<property>
<name>zookeeper.znode.parent</name>
<value>/hbase</value>
</property>
<property>
<name>zookeeper.znode.rootserver</name>
<value>root-region-server</value>
</property>
<property>
<name>hbase.zookeeper.quorum</name>
<value>ip-10-10-187-170.eu-west-1.compute.internal</value>
</property>
<property>
<name>hbase.zookeeper.property.clientPort</name>
<value>2181</value>

Error:
2013-08-24 20:05:36,213 INFO org.apache.zookeeper.ClientCnxn: Opening socket connection to server localhost/127.0.0.1:2181. Will not attempt to authenticate using SASL (Unable to locate a login configuration)
2013-08-24 20:05:36,213 WARN org.apache.zookeeper.ClientCnxn: Session 0x0 for server null, unexpected error, closing socket connection and attempting reconnect
java.net.ConnectException: Connection refused
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:567)
at org.apache.zookeeper.ClientCnxnSocketNIO.doTransport(ClientCnxnSocketNIO.java:350)
at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1068)

A: I finally found out why it was connecting to the localhost.
I was having more than one configuration object to interact with 2 or more tables in HBase. Only for one of the conf object, i was setting the zookeeper quorum address. Didn't set it for the other objects.
By setting the zookeeper quorum address for all the objects did the trick.
Edit : Using only one conf object is more desirable(mapper or reducer). And by using it like
public void setup(Configuration conf) {
    conf.set("hbase.zookeeper.quorum", "xxxxx");
}

The above code is easier to follow than having multiple objects which reduces HBase access time.


text:
Q: Is there any Linux alternative of windows desktop search tool "everything"? Is there any alternative of popular windows desktop search "Search Everything (by Voidtools)" for linux. "Everything" is the only reason I have to stay with windows and not able to switch to linux as primary OS. I am looking for the alternative for quite sometime. I guess, someone who has already used "Everything" on windows, can only understand what I am looking for. Any help is appreciated.

A: Take a look at Recoll.

Recoll finds keywords inside documents as well as file names. It can search most document formats. It can reach any storage place: files, archive members, email attachments, transparently handling decompression. One click will open the document inside a native editor or display an even quicker text preview. The software is free, open source, and licensed under the GPL.

A: I don't really know what is your use case.
To have a index of all file names and search for them use
updatedb & locate

to find manually things in files use ( only as example ):
grep <search-string> -R *

find . -type f -exec grep <search-string> {} \;

Indexing source code:
ctags & etags

More information about text indexing:
Command-line fulltext indexing?
Hope this helps


text:
Q: Saving images with opencv and pyautogui interactively with the user I have the code below which I try to do the following:
Starts capturing the camera image but wanted to also display a dialog box containing a text field and an "ok" button, where the user must enter a value and pressing the "ok" button then scritp saves the image (jpg) naming it with the value that the user passed.
import cv2
import time
import pyautogui

camera_port = 0

camera = cv2.VideoCapture(camera_port)
camera.set(3, 1280)# set the resolution
camera.set(4, 1024)

emLoop = True

while (emLoop):

    retval, img = camera.read()
    #gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    cv2.imshow('Foto', img)

    k = cv2.waitKey(100)

    if k == 27:
        emLoop = False

    elif k == ord('s'):
        nome = input(pyautogui.prompt(text='Scanei o código.', title='Aviso:', default=''))
        cv2.imwrite(nome, img)

camera.release()
cv2.destroyAllWindows()

Capture would always be active and as long as the user was entering the values and clicking "ok" would save the images, when the user clicked the "cancel" dialog box, would end the capture and terminate the script.
I'm trying to do this but unsuccessfully so far ... :(

A: The function pyautogui.prompt opens a dialog box with a text field where the user can type something that will be returned. This is similar to how the function input works. Both have a string as an argument to be displayed as a prompt message to the user. The difference is that the former uses the terminal as the input interface instead of a dialog box.
It looks weird mixing them the way you are trying: nome = input(pyautogui.prompt(...)). It means like: Open a dialog box so the user can type a prompt message that will be displayed for himself in the console. After that, he types again something that will be returned to the nome variable.
Try either this:
nome = pyautogui.prompt(text='Scanei o código.', title='Aviso:', default='')

Or this:
nome = input('Aviso: Scanei o código.')


text:
Q: Trouble with callable interface in android I have created blank project and try do next code. Unfortunately I got problem:
Main activity does't load while don't finish my thread. If don't use return value from thread all work normal.
unfortunately
final ExecutorService service;
        final Future task;
    service = Executors.newFixedThreadPool(1);
    task    = service.submit(new Foo());

    try
    {
        final String str;

        // waits the 10 seconds for the Callable.call to finish.
        str = task.get();
        Log.d("VSK",str);
    }
    catch(final InterruptedException ex)
    {
        ex.printStackTrace();
    }
    catch(final ExecutionException ex)
    {
        ex.printStackTrace();
    }

    service.shutdownNow();

}
class Foo
        implements Callable<String>
{
    public String call()
    {
        try
        {
            // sleep for 10 seconds
            Thread.sleep(10 * 1000);
        }
        catch(final InterruptedException ex)
        {
            ex.printStackTrace();
        }

        return ("Hello, World!");
    }
}

A: This line str = task.get(); blocks main thead while your callable being executed in other thread. Return result from your task via Handler or use AsyncTask.


text:
Q: Over the probability of answering in a random way to given questions. Let's suppose there is a test of $N$ questions, each one with multiple choices answer, let's say $p$. To say if better, for every question there are $p$ possible answers, but one and only one is the correct one.
What is the probability to get a good score by answering them in a random way? (good score = at least $70-80$ %).
I also would like to generalise it, by introducing $N_i$ questions, in which each of them has a different number of multiple choice answer $p_i$, in which

*

*Case 1: one and only one is the correct one;

*Case 2: there could be one or 2 correct answers (not always $2$).
To be clear: $p_i$ represents the number of given answers, not the number of possible correct answers.
How could I proceed?
I thought that for the first question, in which we have $N$ questions with $p$ possible answers each one, we can safely state that there is one and only one way in which we can get $100$ %. So I have $\frac{1}{p}$ probability to answer correctly to the first question, $\frac{1}{p}$ for the second and so on.
The moral is: I have $$\frac{1}{p^N}$$
probability of answering good to all the question. That seems legit. But what if I ask for a total score of $80$ % ?
About the second case, I guess the same reasoning holds, namely: $\frac{1}{p_1}$, $\frac{1}{p_2}$ and so on.. hence:
$$P = \prod_{k = 1}^N\frac{1}{p_i}$$
And if I have the possibility of having two correct answers, I shall introduce a sort of bias $b_i$ such that
$$b_i = \begin{cases} 1 \\ 2 \end{cases}$$
Depending on the question. Example: if the second question has $4$ possible answers but only $2$ of them are correct, then I'll have $1/2$ probability in guessing them correctly.
This suggests me the probability for each question is
$$P_i = \frac{b_i}{p_i}$$
So the total probability should be:
$$P = \prod_{i = 1}^N \left(\frac{b_i}{p_i}\right)$$
Does that hold? Or it's a load of malarkey?
And how could I manage to get the desired result of $80$ %?


text:
Q: Send blob via websocket cause page reload I'm trying to send recordRTC blob via websocket to my Java server, my goal is to build a video stream service.
However, when the server received the blob, and write file, the web page would refresh, cause recordRTC stopped and socket disconnct.
Used package
<dependency>
    <groupId>org.java-websocket</groupId>
    <artifactId>Java-WebSocket</artifactId>
    <version>1.4.0</version>
</dependency>

The following is my code.
Server side
public void onMessage( WebSocket conn, ByteBuffer message ) {
    byte[] bytes = new byte[message.remaining()];
    message.get(bytes, 0, bytes.length);
    if(bytes.length > 0) {
        OutputStream os = null;
        UUID uuid  =  UUID.randomUUID();
        String id=uuid.toString();
        String filename =id.replace("-", "");
        try {
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(
                            new File("./uploads/"+filename +".webm")));
            bos.write(bytes);
            bos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Client side
function startCapture() {
    logElem.innerHTML = "";
    try {
        videoElem.srcObject = navigator.mediaDevices.getDisplayMedia(displayMediaOptions).then(
            (stream)=>{
                console.log(stream);
                recordRTC = RecordRTC(stream);
                recordRTC.startRecording();
                // blob segment and send every 3 second
                recording = setInterval(()=>{
                    recordRTC.stopRecording(()=>{
                            console.log("BLOB : ", recordRTC.getBlob());
                            recordRTC.getBlob().arrayBuffer().then((val)=>{
                                console.log("BLOB : ", recordRTC.getBlob());
                                socket.send(val);
                            });
                    })
                    recordRTC.startRecording();
                }, 3000);
                videoElem.srcObject = new MediaStream(stream);
        });
    } catch (err) {
        console.error("Error: " + err);
    }
}

reload event picture
I found the reload EVENT occur after the fisrt blob sent and write to file, but I don't know why the event happend.
If server don't write blob to file, just receive it, the websocket and web would work perfectly without reloading.
How could I solve the reload EVENT problem?
Thanks


text:
Q: Year over Year by Month Comparison and Month to Date in BigQuery Edit: @shawnt00 has the correct answer. Thank you very much!
I am having trouble accurately doing a year over year comparison by month but at any point during the month. For example for August 2022 vs 2021, I want to compare August 1 - August 25, rather than full month of August 2021.
I am also using a daily date field.
I want the final result to basically be:
Product_ID, Year, Month, PY_Sales, CY_Sales
Edit: I have daily totals. Some products do have not sales on certain days though:

product_id
sale_date
units

1
2021-01-01
5

2
2021-01-02
4

...
...
...

1
2021-06-05
2

2
2022-01-06
1

2
2022-08-15
9

This is the code I have, but it doesn't do MTD. So 2021 August is the entire month of August and I want it the same dates for 2022. I used this code because some products do not have sales on certain months.
    WITH cte AS
(
SELECT
     PRODUCT_ID,
     EXTRACT(YEAR FROM SALE_DATE) AS Year,
     EXTRACT(MONTH FROM SALE_DATE) AS Month,
     CONCAT(EXTRACT(YEAR FROM SALE_DATE), '-',EXTRACT(MONTH FROM SALE_DATE)) AS Year_Month,
     SUM(Units) AS Units
FROM data
WHERE Product_ID = 1
AND DATE(SALE_DATE) >= '2019-01-01'
GROUP BY 1, 2, 3
),

    diff AS
(
SELECT
     COALESCE(c.PRODUCT_ID, p.PRODUCT_ID) AS Product_ID,
     COALESCE(c.Year, p.Year + 1) AS Year,
     COALESCE(c.Month, p.Month) AS Month,
     IFNULL(c.Units, 0) AS Current_Units,
     IFNULL(p.Units, 0) AS Previous_Units,
     NULLIF(((IFNULL(c.Units, 0) - IFNULL(p.Units,0)) / p.Units),0) * 100 AS Percent_Change
FROM CTE c
FULL OUTER JOIN CTE p ON c.PRODUCT_ID = p.PRODUCT_ID AND c.Year = p.Year + 1 AND c.Month = p.Month
WHERE c.Year <= EXTRACT(YEAR FROM CURRENT_DATE())
ORDER BY 2, c.Year, c.Month
)
SELECT *
FROM diff
--This is to avoid dividing by 0
WHERE diff.Previous_Units > 0
--AND Percent_Change <= -.5

A: You could just roll up two different monthly totals and then switch for the current month comparison:
with agg as (
    select
        PRODUCT_ID,
        extract(year from SALE_DATE) as yr,
        extract(month from SALE_DATE) as mth,
        sum(Units) as Units,
        sum(case when extract(day from SALE_DATE) <= extract(day from current_date())
                 then Units end) as UnitsMTD
    from data
    where date(SALE_DATE) >= '2019-01-01' -- one year before report output
    group by 1, 2, 3
)
select c.Yr, c.Mth, c.PRODUCT_ID,
    case when Yr  = extract(year  from current_date())
          and Mth = extract(month from current_date())
         then (c.UnitsMTD - p.UnitsMTD) / p.UnitsMTD
         else (c.Units    - p.Units   ) / p.Units
    end as Percent_Change
from agg c left outer join agg p
    on p.Product_ID = c.Product_ID and p.Yr = c.Yr - 1 and p.Mth = c.Mth
order by c.Yr, c.Mth, c.PRODUCT_ID;

Note my earlier comment about leap years. This will treat February 28 of the year following a leap year as an "MTD" month. You might need to handle that differently inside the case expression.


text:
Q: Recently proposed problem by George Andrews on partitions in Mathstudent Journal (India) Show that the number of parts having odd multiplicities in all partitions of $n$ is equal to difference between the number of odd parts in all partitions of $n$ and the number of even parts in all partitions of $n.$
Example: $n=5.$ The number of partitions   $5',\quad4'1',\quad3'2',\quad3'11,\quad221',\quad2'1'11,\quad1'1111$ have $10$ parts with odd multiplicities (marked with $'$). On the other hand, the number of odd parts is $15$, $$5,1,3,3,1,1,1,1,1,1,1,1,1,1,1$$ and the number of even parts is $5$, $$4,2,2,2,2.$$ I gave up solving the problem because in this problem parts are taken in all partitions not any single partition. I tried thinking some bijective proof or analytic proof using generating function but gave up as it seems to me a very different problem . Does anyone have any idea? The problem is very nice and it is recently been proposed by George Andrews in Mathstudent Journal (India).

A: This answer is based upon generating functions. We start by considering the generating function of all partitions of $n$
\begin{align*}
\prod_{m=1}^\infty\frac{1}{1-z^m}=\prod_{m=1}^\infty\frac{1}{(1-z^{2m})(1-z^{2m-1})}\tag{1}
\end{align*}

From the RHS of (1) we derive $A(z,t)$, a generating function of all partitions with marked odd parts and $B(z,t)$, a generating function with marked even parts.
  \begin{align*}
A(z,t)&=\prod_{m=1}^\infty\frac{1}{(1-z^{2m})(1-tz^{2m-1})}\\
&=1+tz+(t^2+1)z^2+(t^3+2t)z^3+(t^4+2t^2+2)z^4\\
&\qquad+(t^5+2t^3+4t)z^5+\cdots\\
B(z,t)&=\prod_{m=1}^\infty\frac{1}{(1-tz^{2m})(1-z^{2m-1})}\\
&=1+z+(t+1)z^2+(t+2)z^3+(t^2+2t+2)z^4\\
&\qquad+(t^2+3t+3)z^5+\cdots
\end{align*}
Similarly we obtain a generating function $C(z,t)$ with marked odd multiplicities by separating terms with odd and even index
  \begin{align*}
C(z,t)&=\prod_{m=1}^{\infty}\left(\frac{1}{1-z^{2m}}+\frac{tz^m}{1-z^{2m}}\right)\\
&=\prod_{m=1}^{\infty}\frac{1+tz^m}{1-z^{2m}}\\
&=1+tz+(t+1)z^2+(t^2+2t)z^3+(t^2+2t+2)z^4\\
&\qquad+(3t^2+4t)z^5+\cdots
\end{align*}
In terms of generating functions the equality of the difference between the number of odd and even partitions of a number $n$ and the number of odd multiplicities of the partitions of $n$ translates to the following
Claim:
  \begin{align*}
\left.\frac{\partial}{\partial t}A(z,t)\right|_{t=1}-\left.\frac{\partial}{\partial t}B(z,t)\right|_{t=1}
=\left.\frac{\partial}{\partial t}C(z,t)\right|_{t=1}
\end{align*}

Before we show the claim we do a plausibility check and look at partitions of small $n=1,\ldots,5$.
\begin{array}{c|ccc|l}
n
&[z^n]\left.\frac{\partial}{\partial t}A(z,t)\right|_{t=1}
&[z^n]\left.\frac{\partial}{\partial t}B(z,t)\right|_{t=1}
&[z^n]\left.\frac{\partial}{\partial t}C(z,t)\right|_{t=1}
&partitions\\
1&1&0&1&1\\
2&2&1&1&2,1^2\\
3&5&1&4&3,21,1^3\\
4&8&4&4&4,31,2^2,21^2,1^4\\
5&15&5&10&5,41,32,31^2,2^21,21^3,1^5\\
\hline
\end{array}
Here we see  the coefficients of the power series for $n=1,\ldots,5$ and observe the difference of odd and even parts coincides with the number of odd multiplicities. :-)
The right-most column lists the partitions of $n$ with the compact notation e.g. $21^3$ is a short-hand for $2+1+1+1$.

We obtain using logarithmic differentiation
  \begin{align*}
\left.\frac{\partial}{\partial t}A(z,t)\right|_{t=1}
&=\left.\frac{\partial}{\partial t}\prod_{m=1}^\infty\frac{1}{(1-z^{2m})(1-tz^{2m-1})}\right|_{t=1}\\
&=\left.\prod_{m=1}^\infty\frac{1}{(1-z^{2m})(1-tz^{2m-1})}\sum_{k=1}^\infty\frac{z^{2k-1}}{1-z^{2k-1}}\right|_{t=1}\\
&=\prod_{m=1}^\infty\frac{1}{(1-z^{2m})(1-z^{2m-1})}\sum_{k=1}^\infty\frac{z^{2k-1}}{1-z^{2k-1}}\\
&=\prod_{m=1}^\infty\frac{1}{1-z^{m}}\color{blue}{\sum_{k=1}^\infty\frac{z^{2k-1}}{1-z^{2k-1}}}\\
\end{align*}
  and similarly
  \begin{align*}
\left.\frac{\partial}{\partial t}B(z,t)\right|_{t=1}
&=\left.\frac{\partial}{\partial t}\prod_{m=1}^\infty\frac{1}{(1-tz^{2m})(1-z^{2m-1})}\right|_{t=1}\\
&=\prod_{m=1}^\infty\frac{1}{1-z^{m}}\color{blue}{\sum_{k=1}^\infty\frac{z^{2k}}{1-z^{2k}}}\\
\end{align*}
  Next we get
  \begin{align*}
\left.\frac{\partial}{\partial t}C(z,t)\right|_{t=1}
&=\left.\frac{\partial}{\partial t}\prod_{m=1}^\infty\frac{1+tz^m}{1-z^{2m}}\right|_{t=1}\\
&=\left.\prod_{m=1}^\infty\frac{1+tz^m}{1-z^{2m}}\sum_{k=1}^\infty\frac{z^k}{1+tz^k}\right|_{t=1}\\
&=\prod_{m=1}^\infty\frac{1+z^m}{1-z^{2m}}\sum_{k=1}^\infty\frac{z^k}{1+z^k}\\
&=\prod_{m=1}^\infty\frac{1}{1-z^{m}}\color{blue}{\sum_{k=1}^\infty\frac{z^k}{1+z^k}}
\end{align*}

We observe the claim is valid if the following holds:
\begin{align*}
\color{blue}{\sum_{k=1}^\infty\frac{z^{2k-1}}{1-z^{2k-1}}
-\sum_{k=1}^\infty\frac{z^{2k}}{1-z^{2k}}
=\sum_{k=1}^\infty\frac{z^k}{1+z^k}}\tag{2}
\end{align*}

We start with the left-hand side of (2) and get
  \begin{align*}
\color{blue}{\sum_{k=1}^\infty}&\color{blue}{\frac{z^{2k-1}}{1-z^{2k-1}}
-\sum_{k=1}^\infty\frac{z^{2k}}{1-z^{2k}}}\\
&=\sum_{k=1}^\infty\left(\frac{z^{k}}{1-z^{k}}-\frac{z^{2k}}{1-z^{2k}}\right)
-\sum_{k=1}^\infty\frac{z^{2k}}{1-z^{2k}}\\
&=\sum_{k=1}^\infty\left(\frac{z^{k}}{1-z^{k}}-\frac{2z^{2k}}{1-z^{2k}}\right)\\
&=\sum_{k=1}^\infty\frac{z^k}{1-z^k}\left(1-\frac{2z^k}{1+z^k}\right)\\
&=\sum_{k=1}^\infty\frac{z^k}{1-z^k}\cdot\frac{1-z^k}{1+z^k}\\
&\color{blue}{=\sum_{k=1}^\infty\frac{z^k}{1+z^k}}
\end{align*}
  and the claim follows.


text:
Q: Vector parallel to Parametric Line Find a constant vector parallel to the line given parametrically by:
$$x = 1 - a$$
$$y = 2 + 3a$$
$$z = 1 + a$$
I made $a$ the subject and worked out the equation of a line represented by this as $r = (-i + 2j + k) + a(i + 3j + k)$. This means a constant vector parallel to the line would be $i + 3j + k$.
Is this correct ?


text:
Q: Celery task hangs when .apply_async() or .delay() is used within request processed by Django, but works fine when invoked in shell Invokement of a following task:
task__determine_order_details_processing_or_created_status.apply_async(
    args=[order_record.Order_ID],
    eta=datetime.now(GMT_timezone)+timedelta(minutes=1)
)

Ends up in the workers' timeout. It looks like the method is never releasing the worker to continue its job
web_1               | [2019-11-21 05:43:43 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:1559)
web_1               | [2019-11-21 05:43:43 +0000] [1559] [INFO] Worker exiting (pid: 1559)
web_1               | [2019-11-21 05:43:43 +0000] [1636] [INFO] Booting worker with pid: 1636

Whereas, the same command invoked with the usage of Django shell creates a completely working celerty task:
celery_1            | [2019-11-21 05:47:06,500: INFO/MainProcess] Received task: task__determine_order_details_processing_or_created_status[f94708be-a0ab-4853-8785-a11c8c7ca9f1]  ETA:[2019-11-21 05:48:06.304924+00:00]

docker-compose.yml:
  web:
    build: ./server
    command: gunicorn server.wsgi:application --reload --limit-request-line 16376 --bind 0.0.0.0:8001
    volumes:
      - ./server:/usr/src
    expose:
      - 8001
    env_file: .env.dev
    links:
      - memcached
    depends_on:
      - db_development_2
      - redis

  db_development_2:
    restart: always
    image: postgres:latest
    volumes:
        - postgres_development3:/var/lib/postgresql/volume/
    env_file: .env.dev
    logging:
      driver: none

  redis:
    image: "redis:alpine"
    restart: always
    logging:
      driver: none

celery:
    build: ./server
    command: celery -A server.celery worker -l info
    env_file: .env.dev
    volumes:
      - ./server:/usr/src
    depends_on:
      - db_development_2
      - redis
    restart: always

  celery-beat:
    build: ./server
    command: celery -A server.celery beat -l info
    env_file: .env.dev
    volumes:
      - ./server:/usr/src
    depends_on:
      - db_development_2
      - redis
    restart: always
    logging:
      driver: none

A: Can you please share more details?
Error is from gunicorn right?
Are you running this in docker environment? Celery on different container?
What does WSGI<-->YOUR_APP command look like?
example:
gunicorn app.wsgi:tour_application -w 6 -b :8000 --timeout 120

Can you try with more time-out like 120 in above eg.?


text:
Q: Read numbers in a string with any number of digits in python I am having trouble in parsing my string. Here are my codes:
name='report 11 hits'
print(name[7:9])
print(name[11:])

output:
11
hits

But, if I need to type the string as
name='report 112 hits'
print(name[7:9])
print(name[10:])

output:
11
 hits

That means, whenever I am typing a number more than three digits, the program is not reading it well. I was wondering if someone could write me how to modify my code in such a way that no matter what digit I write, the program will read it correctly. Thanks.

A: You can use split() and then print the second element of the generated list:
name='report 112 hits'
namelist = name.split()
print(namelist[0])
# report
print(namelist[1])
# 112
print(namelist[2])
# hits

A: name='report 112 hits'
import re
print re.search(r'\d+', name).group()
# 112

But if you know for sure that the number will be the second element in the string, separated by a space, then you can do
print name.split(None, 2)[1]
# 112

This split will be efficient as we limit the maximum splitting by 2.

A: Assuming there will always be spaces:
_, count, hits = name.split(" ")
print(count)
print(hits)

A: If you are guaranteed that the string is always 'report ### hits' where ### is some number of digits, you could do:
name = 'report 11155342 hits'
print name.split()[1]
print name.split()[2]

A: import re

name='report 11155342 hits'

print(re.findall(r'\d+', name)[0])

prints:
11155342


text:
Q: Why leave a trailing comma after a key value pair in an object literal? I was looking at gruntjs and I looked at some JSON examples used to configure Grunt tasks.
Here is an example of the JSON:
grunt.initConfig({
  concat: {
    foo: {
      // concat task "foo" target options and files go here.
    },
    bar: {
      // concat task "bar" target options and files go here.
    },
  },
  uglify: {
    bar: {
      // uglify task "bar" target options and files go here.
    },
  },
});

As you can see, there is an 'extra' comma after each of the bar properties. I tried this notation in Chrome and it is valid. Although it is valid, I wouldn't use this notation but why would people use it?

A:
I tried this notation in Chrome and it is valid.

Simply because it works in Chrome doesn't mean it's valid. It is valid because the spec says so :-)

I wouldn't use this notation but why would people use it?

To make copy&pasting easier. You can just append new properties without caring additional work. It's a bad practice in program code because older browsers (notably IE) and the ES3 spec disallow them, but in a config file (i.e. in a known environment) it makes life easier.


text:
Q: How to add buttons to NowPlayingView of Apple Watch using SwiftUI The NowPlayingView is a structure. We can use it like:
NowPlayingView()

According to Apple's documentation

Don't add any other elements to the view.

We, developer can not add anything to the view.
But the Apple Music and Podcast's NowPlayingView are different.
Apple Music NowPlayingView:

Podcast NowPlayingView:

So I want to know if there any chance we can customize the NowPlayingView.

A: According to Apple's Engineer, developers can not change anything on NowPlayingView.
Additionally, the bottom-right menu button is neither not available to developers.
Reference:
Can not modify NowPlayingView. Can not use menu button


text:
Q: call asynchronous operation by task I have Duplex and Sessionfull service and an operation as:
public FindStudies_DTO_OUT FindStudies(FindStudies_DTO_IN findStudies_DTO_IN)
    {
        var token = Token;
        List<Study_C> ret = new List<Study_C>();
        _dispatcherCallBack = OperationContext.Current.GetCallbackChannel<IDispatcherCallBack>();
        AnnuncedFindStudies += DispatcherService_AnnuncedFindStudies;
        AnnuncedSPError += DispatcherService_AnnuncedSPError;
        Parallel.ForEach(Cluster, sp =>
        {
            //Blah blah
            OnAnnuncedSPError(new SPError_DTO()
            {
                ServicePointName = sp.Name,
                ErrorMessage = "Ping failed for " + sp.Name
            });
            var result = new List<Study_C>();//Filled
            lock (ret)
            {
                OnAnnounceFindStudies(new FindStudies_DTO()
                {
                    ServicePointName = sp.Name,
                    Studies = result
                });
                ret.AddRange(result);
            }
            //blah blah
        });
        return new FindStudies_DTO_OUT(ret.Sort(findStudies_DTO_IN.SortColumnName, findStudies_DTO_IN.SortOrderBy));
    }

and In consumer side (Web application in generic handler):
var findTask = Task.Factory.StartNew(() =>
                    {
                        DispatcherClient dispatcherClient = new DispatcherClient(new DispatcherCallBack(), "dispatcherEndPoint", Token, Global.Cluster);
                        dispatcherClient.AnnuncedSPError += DispatcherClient_AnnuncedSPError;
                        dispatcherClient.AnnuncedFindStudies += DispatcherClient_AnnuncedFindStudies;
                        var res = dispatcherClient.FindStudies(new FindStudies_DTO_IN(startIndex, numberOfRows, col.FromText(sortColumnName), sort.FromText(sortOrder), criteria, searchMatching));
                        studies = Studies;
                    });
                    findTask .Wait();

in client-side when I set break-point on var findTask everything works perfectly but when I remove break-point it works just in the first go but after that I have get the below exception:

InvalidOperationException: An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>. This exception may also indicate an attempt to call an "async void" method, which is generally unsupported within ASP.NET request processing. Instead, the asynchronous method should return a Task, and the caller should await it.

does anybody know how the client-side should be implemented?
Thanks in advance.

A: I don't know why I can't use infinite wait in client side, but from what I have read here it is recommended don't do that asyc over sync and vice versa.
Anyway I have resolved this problem by below solution:
In server side a task be run and some event are handled in that:
public FindStudies_DTO_OUT FindStudies(FindStudies_DTO_IN findStudies_DTO_IN)
    {
        var token = Token;
        List<Study_C> ret = new List<Study_C>();
        _dispatcherCallBack = OperationContext.Current.GetCallbackChannel<IDispatcherCallBack>();
        AnnuncedFindStudies += (s, e) =>
        {
            _dispatcherCallBack.OnAnnounceFindStudies(e);
        };
        AnnuncedSPError += (s, e) =>
        {
            _dispatcherCallBack.OnAnnunceSPError(e);
        };
        AnnuncedComplete += (s, e) =>
        {
            _dispatcherCallBack.OnAnnunceComplete();
        };
        Task.Run(() =>
        {
            //Blah blah
            if (proxyGetError)
                OnAnnuncedSPError(new SPError_DTO()
                {
                    ServicePointName = sp.Name,
                    ErrorMessage = "Ping failed for " + sp.Name
                });
            var result = new List<Study_C>();//Filled
            lock (ret)
            {
                OnAnnounceFindStudies(new FindStudies_DTO()
                {
                    ServicePointName = sp.Name,
                    Studies = result
                });
            }
            //blah blah
            OnAnnounceComplete();
        });
        return new FindStudies_DTO_OUT();
    }

and in consumer side a task be run also with a timeout and it be completed when AnnuncedComplete get raised:
 DispatcherClient dispatcherClient = new DispatcherClient(new DispatcherCallBack(), "dispatcherEndPoint", Token, Global.Cluster);
                    Task.Run(() =>
                    {
                        studies = new List<Study_C>();
                        try
                        {
                            ManualResetEvent ev = new ManualResetEvent(false);
                            dispatcherClient.AnnuncedSPError += (s, e) =>
                            {
                                spErrorMessage += e.ServicePointName + "<br/>";
                            };
                            dispatcherClient.AnnuncedFindStudies += (s, e) =>
                            {
                                lock (studies)
                                {
                                    studies.AddRange(e.Studies);
                                }
                            };
                            dispatcherClient.AnnuncedComplete += (s, e) =>
                            {
                                ev.Set();
                            };
                            var rrr = dispatcherClient.FindStudies(new FindStudies_DTO_IN(startIndex, numberOfRows, col.FromText(sortColumnName), sort.FromText(sortOrder), criteria, searchMatching)).Studies;
                            ev.WaitOne();
                        }
                        catch (Exception exp)
                        {
                            Logging.Log(LoggingMode.Error, "Failed to Find Studies by Dispatcher, EXP:{0}", exp);
                        }
                    }).Wait(dispatcherClient.Endpoint.Binding.ReceiveTimeout);

The main problem was findTask.Wait() with no milliseconds timeout
but by setting milliseconds timeout for task everything works nice.
I think in ASP.Net pipeline an infinite task is not acceptable for this reason engine should know a task will be ended finally by timeout....


text:
Q: How can I call a controller from other folder with ActionLink I have 2 controllers in different folders. /Areas/Admin/Controllers/ and the other one is in /Controllers.
Here's the code I'm using
@Html.ActionLink("Back", "Directory", "DirectoryWebService", new { ReturnUrl = Model.ReturnUrl }, new { @class = "common-button" })
Using the code from Views/Directories/filename.cshtml works fine and generates the correct link "/DirectoryWebService/Directory?returnUrl=/Default/Traceability"
DirectoryWebService is in /Controllers folder
However, using this code from /Areas/Admin/Views/Organizations/Index.cshtml generates the following link "/Admin/DirectoryWebService/Directory
ReturnUrl=%2FDirectoryWebService%2FDirectory%3FreturnUrl%3D%2FDefault%2FTraceability"
Controller for Index.cshtml is in /Areas/Admin/Controllers/ folder
The question is how can I avoid /admin in the path for the second case? I haven't mentioned in my code.
PS I know about the a tag solution. It works fine but I need actionLink here.

A: You may remove the area variable from route.
@Html.ActionLink("Back", "Directory", "DirectoryWebService", new {
  area = "",
  returnUrl = Model.ReturnUrl
}, new {
  @class = "common-button"
});


text:
Q: Compare two dates in R I have a tab-separated text file that I imported to R. I used the following command for the import:
data = read.table(soubor, header = TRUE, sep = "\t", dec = ".", colClasses =c("numeric","numeric","character","Date","numeric","numeric"))

When I run str(data) to check the data-types of my columns I get:
'data.frame':   211931 obs. of  6 variables:
$ DataValue   : num  0 0 0 0 0 0 0 0 0 NA ...
$ SiteID      : num  1 1 1 1 1 1 1 1 1 1 ...
$ VariableCode: chr  "Sucho" "Sucho" "Sucho" "Sucho" ...
$ DateTimeUTC : Date, format: "2012-07-01" "2012-07-02" "2012-07-03" "2012-07-04" ...
$ Latitude    : num  50.8 50.8 50.8 50.8 50.8 ...
$ Longitude   : num  15.6 15.6 15.6 15.6 15.6 ...

A reproducible sample of the first 20 rows of my data is here:

my_sample = dput(data[1:20,])

structure(list(DataValue = c(0, 0, 0, 0, 0, 0, 0, 0, 0, NA, NA,
NA, NA, NA, NA, NA, NA, 0, 0, 0), SiteID = c(1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), VariableCode = c("Sucho",
"Sucho", "Sucho", "Sucho", "Sucho", "Sucho", "Sucho", "Sucho",
"Sucho", "Sucho", "Sucho", "Sucho", "Sucho", "Sucho", "Sucho",
"Sucho", "Sucho", "Sucho", "Sucho", "Sucho"), DateTimeUTC = structure(c(15522,
15523, 15524, 15525, 15526, 15527, 15528, 15529, 15530, 15531,
15532, 15533, 15534, 15535, 15536, 15537, 15538, 15539, 15540,
15541), class = "Date"), Latitude = c(50.77, 50.77, 50.77, 50.77,
50.77, 50.77, 50.77, 50.77, 50.77, 50.77, 50.77, 50.77, 50.77,
50.77, 50.77, 50.77, 50.77, 50.77, 50.77, 50.77), Longitude = c(15.55,
15.55, 15.55, 15.55, 15.55, 15.55, 15.55, 15.55, 15.55, 15.55,
15.55, 15.55, 15.55, 15.55, 15.55, 15.55, 15.55, 15.55, 15.55,
15.55)), .Names = c("DataValue", "SiteID", "VariableCode", "DateTimeUTC",
"Latitude", "Longitude"), row.names = c(NA, 20L), class = "data.frame")

Now I want to filter my table by the date. Note that I'm running my code inside a for loop. First, I subset my data by 1st July 2012 and do some processing. Then, I subset my data by 2nd July and do some processing, and so on.. For example, I want to get all rows with date equal to 6th July 2012. I tried the code:
startDate = as.Date("2012-07-01");
endDate = as.Date("2012-07-20");
all_dates = seq(startDate, endDate, 1);

#the following code I'm trying to run inside a loop...
for (j in 1:length(all_dates)) {
    filterdate = all_dates[j];
    my_subset = my_sample[my_sample$DateTimeUTC == filterdate,]
    #now I want do do some processing on my_subset...
}

But the above code returns an empty dataset starting from step 7 of the loop.
So, for example:
subset_one = my_sample[my_sample$DateTimeUTC == all_dates[6],]

returns: 3 obs of 6 variables.
But, for some unknown reason, the example:
subset_two = my_sample[my_sample$DateTimeUTC == all_dates[7],]

returns: 0 obs of 6 variables.
(note: I edited the above code to make my problem 100% reproducible)
Any ideas what I'm doing wrong?

A: The following solution solved my problem:
Instead of using the Date data type, I tried to use the POSIXct data type.
Here is the example code for reading the tab-separated textfile after which the subsetting worked in all steps of my for loop:
data = read.table("data.txt", header = TRUE, sep = "\t", dec = ".",
    colClasses =c("numeric","numeric","character","POSIXct","numeric","numeric"));
startDate = as.POSIXct("2012-07-01");
endDate = as.POSIXct("2012-07-20");
all_dates = seq(startDate, endDate, 86400); #86400 is num of seconds in a day

#the following code I'm trying to run inside a loop...
for (j in 1:length(all_dates)) {
    filterdate = all_dates[j];
    my_subset = data[data$DateTimeUTC == filterdate,]
    #now I want do do some processing on my_subset...
}


text:
Q: jquery.mobile 1.4.3 Uncaught TypeError: Cannot read property 'concat' of undefined Whenever I trying to use a greater version of jquery 1.12.4 then this issue comes.
and whenever I use lower version then "post" function error
so please give me a solutions.


text:
Q: How to Auto-update a powerpoint presentation on another PC I have 10 computers running a powerpoint presentation at 10 different sites.  These computers display the presentation on a flat screen television as our electronic menu board.
What i'd like to do is setup a script to auto upload the power point files each night so if a change has taken place we do not have to physically connect to each location.
I was thinking of making a basic batch file to send the powerpoint file via FTP commands. However, I have the following questions:
How can I close the presentation on the remote computer before I overwrite the current presentation, and how can I relaunch the presentation after the upload finishes?

A: There are several ways of doing this. The way your hinting at could be done as follows. Assuming you have high enough privileges.

*

*Open the document form a network drive this makes it easier for you as you don't need to distribute copies. If they are in the same domain this should be easy to accomplish. As an alternative you could use ftp, but personally i would use something like robocopy or a rsync client like unison.

*Kill the powerpoint task. You can do this with taskkill, using something like sc, psexec, telnet, ssh, rsh... or you could just use wmic as follows:
wmic /node:computer process where name="powerpoint.exe" delete

you can also directly control computers with the task scheduler so you could do all of the needed things with one batch from Task Scheduler as an alternative.

*Restart the powerpoint with the new document if you save the presentation as a "Powerpoint Show" it will automatically fo to show mode; again you can use whatever but with wmic it would look as follows:
 wmic /node:computer process call create "pth\2\powerpoint.exe pth\2\f.pps"

rinse and repeat. Note that I don't have any powerpoint to test this on so hard to be super definitive. However i would do this with powershell and call the powerpoint COM API to load stuff as it can be more elegant.


text:
Q: How to properly take screen shots in Xamarin iOS simulator I am currently taking screen shots for my application using iOS simulator. The issue I am coming across is that they are being being taking with borders and causing it to be rejected.

I have another approved application with screen shots and it doesn't have rounded borders.

I am using this button to take screen shots

A: Try to run the iOS simulator in the Mac and then take the screenshot. I did a test and the screenshot in the mac does not has the rounded borders.
Another way is you can use some tools to edit those screenshots to achieve what you want:).


text:
Q: Keep throwing exception until correct value is found I have the following code
//Querying for move
        int playerMove = currentPlayer.PlayCard(myBoard);

        //Making move
        try {
            playMove(playerMove, currentPlayer);
        }
        catch (IndexOutOfBoundsException e) {

            System.out.println("Sorry, I don't think you can do that...");

        }

The move the player makes needs to be associated to an index in an ArrayList. Right now, my code cathces the exception of a player making an invalid move correctly, but I would like to know how I can modify it so the player keeps being asked to make a move until they make a valid one.
Thank you! :)

A: Use a while loop
while(!IsMoveValid)
{
    int playerMove = currentPlayer.PlayCard(myboard);
    IsMoveValid = CheckMoveValidity(playerMove, myBoard);
}
playMove(playerMove, currentPlayer);

and
public bool CheckMoveValidity(int move, Board board)
{
    if (move > 0) && (move < board.Length)
    {
        return true;
    } else {
        return false;
    }
    // you could make this helper method shorter by doing
    // return (move > 0) && (move < board.Length);
}

Note this doesn't use exceptions in the logic :)

A: As easy as a cake
while(true){
    //Querying for move
    int playerMove = currentPlayer.PlayCard(myBoard);

    //Making move
    try {
        playMove(playerMove, currentPlayer);
        break; // break the while loop
    } catch (IndexOutOfBoundsException e) {
         System.out.println("Sorry, I don't think you can do that...");
    }
}


text:
Q: Веб парсинг с помощью python подскажите как с помощью регулярки получить значение DOI: 10.13108/2021-13-1-3 из всего html (пример)

Попытался сделать так , но все равно не получается
 doi = soup.find('a', title=re.compile(r"DOI: 10.13108\/\d{4}-\d{2}-\d{1,}-\d{1,}"))

A: как пример
import re
from bs4 import BeautifulSoup

html_doc = """

"""
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.find_all(title=re.compile("DOI: 10.13108/")))

вывод
[,
 ]


text:
Q: Error Activating Accounts in Authentication System I am stuck in part 18 of this Authentication tutorial.
I did a var_dump on $user in the activate route, and it returned null. I don't know how to fix this. My code is included below:
<?php

$app->get('/activate', $guest(), function() use ($app) {

    $request = $app->request;

    $email = $request->get('email');
    $email = $request->get('identifier');

    $hashedIdentifier = $app->hash->hash($identifier);

    $user = $app->user->where('email', $email)
        ->where('active', false)
        ->first();
        var_dump($user);
        var_dump($user->active_hash);

    if (!$user || !$app->hash->hashCheck($user->active_hash, $hashedIdentifier)) {
        echo $hashedIdentifier;
        echo $user->active_hash;
    } else {
        $user->activateAccount();
        $app->render('auth/activate.php');
    }
})->name('activate');


text:
Q: How to left align bootstrap 3 dropdown menu?
In the above image MenuItems are align to right side of the MyMenu, I needed to left align the MenuItems of MyMenu (I mean it must aligned to left edge of MyMenu), I try to use pull-left and pull-right class like
 with my code, but it doesn't work. anyone has an idea how to do this ?
Here is my code

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

          </button>

Home

                   My Menu

Menu Item 01

Menu Item 01

Menu Item 02

Menu Item 03

Menu Item 04

A: Change navbar-right to navbar-left and add a pull-right class to the UL.

Check out the JSfiddle for an example.
http://jsfiddle.net/eqcpLj6k/1/

A: for Twitter Bootstrap 3

hope it helps :)

A: For Bootstrap 3.1.0 or above use .dropdown-menu-left or .dropdown-menu-right to display the drop down menus right or left side of the parent menu. In your case try following.

     My Menu

Bootstrap is BEST

A: Adding this style element to the dropdown
 will align the dropdown to the left side of the menu item:
left:0;

See this Bootply which targets the .dropdown-menu.pull-left and adds a left:0;.
This should solve your problem.

Update
I see that Bootstrap has deprecated pull-right and pull-left as of Bootstrap 3.1.0. Use dropdown-menu-left class to use built-in Bootstrap css to align the dropdown on the left edge so you don't need extra CSS. See this updated Bootply

A: For Bootstrap 4:
There are CSS classes named: .dropup, .dropright and .dropleft.

  <button type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropleft
  </button>

Source: Bootstrap

A: As the answers given above are too old, would like to provide working solution for Bootstrap 3.3.7.

Use the given css on your .dropdown-menu div :
.dropdown-left-manual {
  right: 0;
  left: auto;
  padding-left: 1px;
  padding-right: 1px;
}

Explaination :

*

*"right:0;" to make then ending of menu inline with end of dropdown
button.

*"left:auto;" to override the left:0 given in dropdown-menu
class by bootstrap.

*paddings are used to correct hovers on menu item, can be ignored.

A: For a dropdown item that has been floated to the right of the screen, with its dropdown content flowing over the screen, just add the below code to prevent the content of the dropdown from flowing over the screen.
right: 0;


text:
Q: "invalid memory address or nil pointer deference" doing tutorial This is the exact code copied from the tutorial. Im new in Go and web developing in general so im having a hard time debugging such error.
 package main

import (
    "fmt"
    "html/template"
    "log"
    "net/http"
    "strings"
)

func sayhelloName(w http.ResponseWriter, r *http.Request) {
    r.ParseForm() //Parse url parameters passed, then parse the response packet for the POST body (request body)
    // attention: If you do not call ParseForm method, the following data can not be obtained form
    fmt.Println(r.Form) // print information on server side.
    fmt.Println("path", r.URL.Path)
    fmt.Println("scheme", r.URL.Scheme)
    fmt.Println(r.Form["url_long"])
    for k, v := range r.Form {
        fmt.Println("key:", k)
        fmt.Println("val:", strings.Join(v, ""))
    }
    fmt.Fprintf(w, "Hello astaxie!") // write data to response
}

func login(w http.ResponseWriter, r *http.Request) {
    fmt.Println("method:", r.Method) //get request method
    if r.Method == "GET" {
        t, _ := template.ParseFiles("login.gtpl")
        t.Execute(w, nil)
    } else {
        r.ParseForm()
        // logic part of log in
        fmt.Println("username:", r.Form["username"])
        fmt.Println("password:", r.Form["password"])
    }
}

func main() {
    http.HandleFunc("/", sayhelloName) // setting router rule
    http.HandleFunc("/login", login)
    err := http.ListenAndServe(":9090", nil) // setting listening port
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

There is also another file called login.gtpl with basic html codes
<html>
    <head>
    <title></title>
    </head>
    <body>
        <form action="/login" method="post">
            Username:<input type="text" name="username">
            Password:<input type="password" name="password">
            <input type="submit" value="Login">
        </form>
    </body>
</html>

here is the error message
2017/07/23 18:41:29 http: panic serving 127.0.0.1:61254: runtime error: invalid
memory address or nil pointer dereference
goroutine 18 [running]:
net/http.(*conn).serve.func1(0xc04203adc0)
        C:/Go/src/net/http/server.go:1721 +0xd7
panic(0x717940, 0x901950)
        C:/Go/src/runtime/panic.go:489 +0x2dd
html/template.(*Template).escape(0x0, 0x0, 0x0)
        C:/Go/src/html/template/template.go:94 +0x3f
html/template.(*Template).Execute(0x0, 0x8da500, 0xc0420fa0e0, 0x0, 0x0, 0xc0420
08390, 0x90e480)
        C:/Go/src/html/template/template.go:117 +0x36
main.login(0x8de180, 0xc0420fa0e0, 0xc042030400)
        D:/sample/src/github.com/sunilrajramchandani/astaxie/web.go:29 +0x47e
net/http.HandlerFunc.ServeHTTP(0x786e68, 0x8de180, 0xc0420fa0e0, 0xc042030400)
        C:/Go/src/net/http/server.go:1942 +0x4b
net/http.(*ServeMux).ServeHTTP(0x90e480, 0x8de180, 0xc0420fa0e0, 0xc042030400)
        C:/Go/src/net/http/server.go:2238 +0x137
net/http.serverHandler.ServeHTTP(0xc04207ab00, 0x8de180, 0xc0420fa0e0, 0xc042030
400)
        C:/Go/src/net/http/server.go:2568 +0x99
net/http.(*conn).serve(0xc04203adc0, 0x8de740, 0xc04203e3c0)
        C:/Go/src/net/http/server.go:1825 +0x619
created by net/http.(*Server).Serve
        C:/Go/src/net/http/server.go:2668 +0x2d5
method: GET
2017/07/23 18:41:29 http: panic serving 127.0.0.1:61255: runtime error: invalid
memory address or nil pointer dereference
goroutine 4 [running]:
net/http.(*conn).serve.func1(0xc0420f0000)
        C:/Go/src/net/http/server.go:1721 +0xd7
panic(0x717940, 0x901950)
        C:/Go/src/runtime/panic.go:489 +0x2dd
html/template.(*Template).escape(0x0, 0x0, 0x0)
        C:/Go/src/html/template/template.go:94 +0x3f
html/template.(*Template).Execute(0x0, 0x8da500, 0xc04213e000, 0x0, 0x0, 0xc0421
36090, 0x90e480)
        C:/Go/src/html/template/template.go:117 +0x36
main.login(0x8de180, 0xc04213e000, 0xc042030500)
        D:/sample/src/github.com/sunilrajramchandani/astaxie/web.go:29 +0x47e
net/http.HandlerFunc.ServeHTTP(0x786e68, 0x8de180, 0xc04213e000, 0xc042030500)
        C:/Go/src/net/http/server.go:1942 +0x4b
net/http.(*ServeMux).ServeHTTP(0x90e480, 0x8de180, 0xc04213e000, 0xc042030500)
        C:/Go/src/net/http/server.go:2238 +0x137
net/http.serverHandler.ServeHTTP(0xc04207ab00, 0x8de180, 0xc04213e000, 0xc042030
500)
        C:/Go/src/net/http/server.go:2568 +0x99
net/http.(*conn).serve(0xc0420f0000, 0x8de740, 0xc04203e500)
        C:/Go/src/net/http/server.go:1825 +0x619
created by net/http.(*Server).Serve
        C:/Go/src/net/http/server.go:2668 +0x2d5
method: GET
2017/07/23 18:41:29 http: panic serving 127.0.0.1:61257: runtime error: invalid
memory address or nil pointer dereference
goroutine 6 [running]:
net/http.(*conn).serve.func1(0xc0420f00a0)
        C:/Go/src/net/http/server.go:1721 +0xd7
panic(0x717940, 0x901950)
        C:/Go/src/runtime/panic.go:489 +0x2dd
html/template.(*Template).escape(0x0, 0x0, 0x0)
        C:/Go/src/html/template/template.go:94 +0x3f
html/template.(*Template).Execute(0x0, 0x8da500, 0xc0420fa2a0, 0x0, 0x0, 0xc0420
084b0, 0x90e480)
        C:/Go/src/html/template/template.go:117 +0x36
main.login(0x8de180, 0xc0420fa2a0, 0xc042162000)
        D:/sample/src/github.com/sunilrajramchandani/astaxie/web.go:29 +0x47e
net/http.HandlerFunc.ServeHTTP(0x786e68, 0x8de180, 0xc0420fa2a0, 0xc042162000)
        C:/Go/src/net/http/server.go:1942 +0x4b
net/http.(*ServeMux).ServeHTTP(0x90e480, 0x8de180, 0xc0420fa2a0, 0xc042162000)
        C:/Go/src/net/http/server.go:2238 +0x137
net/http.serverHandler.ServeHTTP(0xc04207ab00, 0x8de180, 0xc0420fa2a0, 0xc042162
000)
        C:/Go/src/net/http/server.go:2568 +0x99
net/http.(*conn).serve(0xc0420f00a0, 0x8de740, 0xc04210c140)
        C:/Go/src/net/http/server.go:1825 +0x619
created by net/http.(*Server).Serve
        C:/Go/src/net/http/server.go:2668 +0x2d5
method: GET
2017/07/23 18:41:29 http: panic serving 127.0.0.1:61259: runtime error: invalid
memory address or nil pointer dereference
goroutine 8 [running]:
net/http.(*conn).serve.func1(0xc0420f0140)
        C:/Go/src/net/http/server.go:1721 +0xd7
panic(0x717940, 0x901950)
        C:/Go/src/runtime/panic.go:489 +0x2dd
html/template.(*Template).escape(0x0, 0x0, 0x0)
        C:/Go/src/html/template/template.go:94 +0x3f
html/template.(*Template).Execute(0x0, 0x8da500, 0xc0420ec1c0, 0x0, 0x0, 0xc0420
62f30, 0x90e480)
        C:/Go/src/html/template/template.go:117 +0x36
main.login(0x8de180, 0xc0420ec1c0, 0xc042000400)
        D:/sample/src/github.com/sunilrajramchandani/astaxie/web.go:29 +0x47e
net/http.HandlerFunc.ServeHTTP(0x786e68, 0x8de180, 0xc0420ec1c0, 0xc042000400)
        C:/Go/src/net/http/server.go:1942 +0x4b
net/http.(*ServeMux).ServeHTTP(0x90e480, 0x8de180, 0xc0420ec1c0, 0xc042000400)
        C:/Go/src/net/http/server.go:2238 +0x137
net/http.serverHandler.ServeHTTP(0xc04207ab00, 0x8de180, 0xc0420ec1c0, 0xc042000
400)
        C:/Go/src/net/http/server.go:2568 +0x99
net/http.(*conn).serve(0xc0420f0140, 0x8de740, 0xc04200a5c0)
        C:/Go/src/net/http/server.go:1825 +0x619
created by net/http.(*Server).Serve
        C:/Go/src/net/http/server.go:2668 +0x2d5
method: GET
2017/07/23 18:41:34 http: panic serving 127.0.0.1:61264: runtime error: invalid
memory address or nil pointer dereference
goroutine 34 [running]:
net/http.(*conn).serve.func1(0xc042198000)
        C:/Go/src/net/http/server.go:1721 +0xd7
panic(0x717940, 0x901950)
        C:/Go/src/runtime/panic.go:489 +0x2dd
html/template.(*Template).escape(0x0, 0x0, 0x0)
        C:/Go/src/html/template/template.go:94 +0x3f
html/template.(*Template).Execute(0x0, 0x8da500, 0xc04213e1c0, 0x0, 0x0, 0xc0421
361b0, 0x90e480)
        C:/Go/src/html/template/template.go:117 +0x36
main.login(0x8de180, 0xc04213e1c0, 0xc042030600)
        D:/sample/src/github.com/sunilrajramchandani/astaxie/web.go:29 +0x47e
net/http.HandlerFunc.ServeHTTP(0x786e68, 0x8de180, 0xc04213e1c0, 0xc042030600)
        C:/Go/src/net/http/server.go:1942 +0x4b
net/http.(*ServeMux).ServeHTTP(0x90e480, 0x8de180, 0xc04213e1c0, 0xc042030600)
        C:/Go/src/net/http/server.go:2238 +0x137
net/http.serverHandler.ServeHTTP(0xc04207ab00, 0x8de180, 0xc04213e1c0, 0xc042030
600)
        C:/Go/src/net/http/server.go:2568 +0x99
net/http.(*conn).serve(0xc042198000, 0x8de740, 0xc04203e780)
        C:/Go/src/net/http/server.go:1825 +0x619
created by net/http.(*Server).Serve
        C:/Go/src/net/http/server.go:2668 +0x2d5
method: GET
2017/07/23 18:42:04 http: panic serving 127.0.0.1:61279: runtime error: invalid
memory address or nil pointer dereference
goroutine 36 [running]:
net/http.(*conn).serve.func1(0xc0421980a0)
        C:/Go/src/net/http/server.go:1721 +0xd7
panic(0x717940, 0x901950)
        C:/Go/src/runtime/panic.go:489 +0x2dd
html/template.(*Template).escape(0x0, 0x0, 0x0)
        C:/Go/src/html/template/template.go:94 +0x3f
html/template.(*Template).Execute(0x0, 0x8da500, 0xc0420fa460, 0x0, 0x0, 0xc0420
085d0, 0x90e480)
        C:/Go/src/html/template/template.go:117 +0x36
main.login(0x8de180, 0xc0420fa460, 0xc042162100)
        D:/sample/src/github.com/sunilrajramchandani/astaxie/web.go:29 +0x47e
net/http.HandlerFunc.ServeHTTP(0x786e68, 0x8de180, 0xc0420fa460, 0xc042162100)
        C:/Go/src/net/http/server.go:1942 +0x4b
net/http.(*ServeMux).ServeHTTP(0x90e480, 0x8de180, 0xc0420fa460, 0xc042162100)
        C:/Go/src/net/http/server.go:2238 +0x137
net/http.serverHandler.ServeHTTP(0xc04207ab00, 0x8de180, 0xc0420fa460, 0xc042162
100)
        C:/Go/src/net/http/server.go:2568 +0x99
net/http.(*conn).serve(0xc0421980a0, 0x8de740, 0xc04210c3c0)
        C:/Go/src/net/http/server.go:1825 +0x619
created by net/http.(*Server).Serve
        C:/Go/src/net/http/server.go:2668 +0x2d5
method: GET
2017/07/23 18:43:04 http: panic serving 127.0.0.1:61329: runtime error: invalid
memory address or nil pointer dereference
goroutine 10 [running]:
net/http.(*conn).serve.func1(0xc0420f01e0)
        C:/Go/src/net/http/server.go:1721 +0xd7
panic(0x717940, 0x901950)
        C:/Go/src/runtime/panic.go:489 +0x2dd
html/template.(*Template).escape(0x0, 0x0, 0x0)
        C:/Go/src/html/template/template.go:94 +0x3f
html/template.(*Template).Execute(0x0, 0x8da500, 0xc04213e380, 0x0, 0x0, 0xc0421
362d0, 0x90e480)
        C:/Go/src/html/template/template.go:117 +0x36
main.login(0x8de180, 0xc04213e380, 0xc042030700)
        D:/sample/src/github.com/sunilrajramchandani/astaxie/web.go:29 +0x47e
net/http.HandlerFunc.ServeHTTP(0x786e68, 0x8de180, 0xc04213e380, 0xc042030700)
        C:/Go/src/net/http/server.go:1942 +0x4b
net/http.(*ServeMux).ServeHTTP(0x90e480, 0x8de180, 0xc04213e380, 0xc042030700)
        C:/Go/src/net/http/server.go:2238 +0x137
net/http.serverHandler.ServeHTTP(0xc04207ab00, 0x8de180, 0xc04213e380, 0xc042030
700)
        C:/Go/src/net/http/server.go:2568 +0x99
net/http.(*conn).serve(0xc0420f01e0, 0x8de740, 0xc04203e880)
        C:/Go/src/net/http/server.go:1825 +0x619
created by net/http.(*Server).Serve
        C:/Go/src/net/http/server.go:2668 +0x2d5

A: You appear to be executing an invalid or nil template. The error you're ignoring is probably the missing clue:
t, _ := template.ParseFiles("login.gtpl")

Never ignore errors.
Instead, check the error with
t, err := template.ParseFiles("login.gtpl")
if err != nil {
    /* Report or handle the error here */
}


text:
Q: How to recover event in an message driven architecture I was just wondering what are the standard approaches for recovering,replaying messages in message driven architecture.
Take for instance
A consumer unexpectedly dies before completing the event and updating the status to complete or what if the event is taking
longer than usual to complete.
Each event will have a row on a table so that we can track the event. Lets say the replay is triggered when an event row has not
been updated for some period of time say 15 minutes and the status is not complete.
In either case where a consumer dies
unexpectedly or an event is taking more than 15 minutes. A replay would be triggered. This will result in duplicate events for
the same message.
One approach to solve the hung process is to have a timeout and kill the process after that. Is there other ways?

A: It is expected that on failure the event will be redelivered. So the event processing must be idempotent.
How exactly the idempotency is achieved depends on a specific use case.


text:
Q: Deploy SvelteKit with AWS Amplify Hi I've been trying to deploy my Svelte kit 1.0 to AWS Amplify. I push the commits and then Amplify builds and verify the app pass , but then if I visit the app URL it's just a blank page. Please see build below.

version: 1
frontend:
  phases:
    preBuild:
      commands:
        - npm ci
    build:
      commands:
        - npm run build
  artifacts:
    # IMPORTANT - Please verify your build output directory
    baseDirectory: /.svelte-kit/build
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*

A: If you want to publish a SvelteKit app to AWS Amplify, you have to make sure to use the correct adapter which is @sveltejs/adapter-static. You also need to set the pretender default to true.
Reference Deploy static Svelte-Kit app with AWS Amplify


text:
Q: How to best share and store enum-like data between microservices? Situation:
A microservices architecture with:

*

*Microservices are written in Java with Spring Boot and Hibernate

*An options-service which provides information about Options via a REST interface

*Option data which could be modelled as follows e.g. via an enum (representative)

*

*Has some attributes like enabled status associated with it. It is unlikely that more attributes belonging to Option will be added in future which have to be directly tied to it.

*New Options and OptionTypes have to be seldom added. They will never be deleted (just disabled if need be).

*An Option should have a unique identifier which can be referenced

*There should be no UNKOWN option if possible

enum OptionType {
   TYPE_A,
   TYPE_B,
   TYPE_C;
}

enum Option {
    TYPE_A_X1(TYPE_A),
    TYPE_A_X2(TYPE_A),

    TYPE_B_Z1(TYPE_B, false),
    TYPE_B_Z2(TYPE_B);

    TYPE_C_U1(TYPE_C);
    TYPE_C_U2(TYPE_C);
    TYPE_C_U3(TYPE_C);

    private final OptionType type;
    private final boolean enabled;

    Option(OptionType type){
        this.type = type;
        this.enabled = true;
    }

    Option(OptionType type, boolean enabled){
        this.type = type;
        this.enabled = enabled;
    }
}

*

*Other microservices (currently 3) need to be able to access Option data. They need to know which Options exist and somehow reference an Option e.g. via its name or identifier

*

*One of those services (example-service) needs to provide the Option data type as filter settings in its own REST interface to the outside world. The filter object in JSON would look something like this:

{
  "typeA": "TYPE_A_X1",
  "typeB": "TYPE_B_Z2",
  "typeC": [ "TYPE_C_U1", "TYPE_C_U2"]
  // more filter settings
}

Different approaches of storing and sharing this Option data between microservices as I see it:

*

*options-service stores Option data in its own database. If I read my data from database into my Hibernate entities Option is only a String everywhere from there on.

*

*Pro:

*

*Easy to rename, add and remove Options

*Con:

*

*No type safety when working with Option in code e.g. when deserialising a response containing Option

*example-service cannot easily offer Option data in its OpenAPI doc (just Strings)

*Microservices need to query and cache Option data from options-service

*Option data only lives in source code in an enum as e.g. modelled above and is shared between different services via a lib.

*

*Pro:

*

*Type safety everywhere where Options are needed. Really useful when deserializing reponses containing Options data but also for generating OpenAPI doc

*Microservices can still reference an Option in its database via its name since it is unique

*Con:

*

*Editing the name of an Option is difficult

*Removing an Option not possible

*If a new Option/OptionType is added the order in which the services relying on that lib update their lib version matters. Since we cannot deserialize responses into an UNKNOWN Option type.

*There is also the possibility of a mixed database and enum solution which comes with the big drawback that one has to maintain both sources of truth.
What is the best way to store and share the Option data between microservices? What is best practice?

A: While enums are very helpful in most programming languages, they can become a nightmare in inter-service communication.
If you use an enum in your microservice endpoints, it becomes part of the API specification. Changing them on one side will result in problems of serialization/deserialization on the other side.
So you should only use enums in your API if

*

*you are definitely sure they will never change (e.g. weekdays) or

*you are the owner of the code of all participating services and are able to orchestrate a big bang redeployment.

In these cases, you may create a shared lib between your services.
If this does not apply, make your life easier and consider most enum-like data (e.g. currency codes, country codes) as simple string values that are subject to change. If you want to have a central management for these values, why don't create a microservice for it that acts as a master? That's what microservice architectures are made for. Offer some endpoints that other services can query from time to time. You don't even need a persistence layer for that.

A: Another option : Use the first option, but with a specialised class.

*

*This allow for type safety,

*but does not require your enums to be known at compile time.

*Still, if you need to check the validity of your Option instance, you need a service that has cached the list of allowed Options.

Example code:
import com.fasterxml.jackson.annotation.JsonValue;

public class Option {
    @JsonValue
    private String value;

    Option(String value) {
        this.value = value;
    }
}

A: First Option :
Define or Create new Module / MicroServices / Project that only Contains your CommonMessage , String Message, Enum, Exception or everything that Common and reusable for your multiple microservices that using spring-boot.
But those Enum is not parameterizing so you can not Create Update Or Delete.
And you create your Option ENUM class for multiple purpose and you can inject those class from POM.xml as a dependency.
Second Option :
Store it in Database as an Entity Object , so you can manage those data.
if you want to use those data on other microservices, dont forget to use this artifact as dependency in POM.xml so other microservices can call your service or repository.


text:
Q: Rails - Rack how to TEST "invalid byte sequence in UTF-8" by sending in json I have been working on a middleware that encodes the body for UTF-8 and returns a 422 to the client if the string cannot be encoded. I have passing specs.
There are 99,234,3978,224 articles(I googled) on how to handle this but not how to test, and by test, I want to send invalid JSON to my local server via curl or postman.
I have tried a few things all POST's
 { "name": "bad string \255" }
 { "name": "bad string \xAD" }
 { "name": "bad string <invaild japanese chars that some other post said was invaild>" }

Either ad chars where escaped the \ by adding another one or just treated it like text, which makes sense but not what I want.


text:
Q: How to remove element from vector by value but only single instance of that value? Here is the problem,
I have a vector and I need to remove 2 elements from the vector, one after another. I know the value of those two elements and index of those elements.
First I tried to remove those two elements using index i.e.
v.erase(v.begin()+index1);
v.erase(v.begin()+index2);

But problem is after erasing first element index of second element in the array changes.
So, I tried to remove them by value i.e.
v.erase(remove(v.begin(),v.end(),value),v.end());

But this remove all the instances of that value (e.g. if there are 2 "1" it will remove both of them), while I want only one element to be removed.
How to solve it ?

A: When you remove an element from a std::vector<>, any iterator at or after the point of erase is invalidated.
This is why you must first remove the element that is at a position with the greater index.
Example :
using namespace std;

int main()
{
  vector<int> v { 1, 2, 3, 4, 5, 6, 7};

  size_t index1 = 3; // We want to remove 4
  size_t index2 = 5; // We want to remove 6

  v.erase(begin(v) + index2); // We remove the element with the greater index first
  v.erase(begin(v) + index1); // fine, v.begin() + index1 is BEFORE the previous point of erasure

  for(auto val : v)
    cout << val << " ";

  return 0;
}

Edit :

*

*Here is a generic algorithm, remove_at_indexes, for removing elements from a container by specifying indexes in form of a range (of std::size_t)

*It will work on any STL compliant container (vector, string, deque ...)

Code:
template<class Iterator, class IteratorId>
Iterator remove_at_indexes(Iterator first, Iterator last, IteratorId indexes_begin, IteratorId indexes_end)
{
    std::sort(indexes_begin, indexes_end, std::less<size_t>());

    std::size_t count { 0 };

    if (first != last)
        for(auto i = first; i != last; i++)
            if(indexes_begin == indexes_end)
               first++;
            else
            {
                if (count != *indexes_begin)
                    *first++ = std::move(*i);
                else
                    indexes_begin++;
                count++;
            }

    return first;
}

Usage example :
  vector<int> v { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  vector<size_t> indexes { 4, 1, 9 };

  v.erase(remove_at_indexes(v.begin(), v.end(), indexes.begin(), indexes.end()), v.end());

Output :

1 3 4 6 7 8 9

Demo here.

A: You may use:
v.erase(v.begin() + std::max(index1, index2));
v.erase(v.begin() + std::min(index1, index2));

or even
auto indexes = std::minmax(index1, index2);
v.erase(v.begin() + indexes.second);
v.erase(v.begin() + indexes.first);


text:
Q: Calculating Percentage of COUNT with GROUP BY Here are the two tables and the only columns that matter for this question.
Mailing M
m_id: Id for each of three mailing type
Mailing Received MR
u_id: Id for person who received mailing
m_id: FK
I have successfully created this query
SELECT
    m.m_id AS 'Mailing Type',
    COUNT(mr.u_id) AS 'Mailings Received'
FROM mailing m
Left join
mailing_received mr
ON mr.m_id = m.m_id
GROUP BY m.m_id

which returns a table that looks like this
Mailing Type     Mailings Received
1                500
2                350
3                600

Which is fantastic. Really. But I am trying to return a third column that tells the percentage of the mailings received by mailing type and that is not going as smoothly. Here is what I have tried in a sub query thus far:
SELECT
m.m_id,
u_id * 100/ (SELECT COUNT(*) FROM mailing_received) AS "PERC REC"
FROM mailing m
LEFT JOIN
mailing_received mr
ON
m.m_id = mr.m_id
GROUP BY m.m_id;

No dice.
EDIT: u_id is sorted into three rows through the COUNT and GROUP BY functions. I have no idea how to create a column of percentages when return rows are divided as such.

A: This should work:
SELECT
    m.m_id AS "Mailing Type",
    COUNT(mr.u_id) AS "Mailings Received",
    COUNT(mr.u_id) / (SELECT COUNT(*) FROM mailing_received) AS "PERC REC"
FROM mailing m
Left join mailing_received mr
       ON mr.m_id = m.m_id
GROUP BY m.m_id


text:
Q: Upload Images to Amazon S3 using Django I'm currently resizing images on the fly when a user uploads a picture. The original picture is stored on Amazon S3 in a bucket called djangobucket. Inside this bucket, contains thousands of folders.
Each folder is named after the user. I don't have to worry about bucket creation or folder creation since all of that is handled from the client side.
Here is a diagram:
djangobucket  ------------> bob ---------> picture1.jpg
                                           picture2.jpg
                                           picture3.jpg
                                           picture4.jpg

As you can see, Bob has many pictures. Once a user uploads a picture to S3, I download it through Django via a URL, in this case it would be: http://s3.amazonaws.com/djangobucket/bob/picture1.jpg
I download the image and perform image processing and save the processed image on my django app server.
I would like to send this processed image back into bob's folder so that it can be publicly reached at http://s3.amazonaws.com/djangobucket/bob/picture1_processed.jpg
The client already has access to the amazon key and secret key so that he or she can upload pictures to this bucket. All users on the service use the same keys. I too will be using the same keys.
I've heard of something called Boto, but it involves Bucket creation and I'm unsure of how to do just the uploading part. I'm only concerned about uploading the picture to the appropriate user folder.
I've been researching this for hours so I've turned to the experts here.
Here is my code, just so that you can get a better understanding of what I'm doing.
user = 'bob'

url = 'http://s3.amazonaws.com/djangobucket/bob/picture1.jpg'
filename = url.split('/')[-1].split('.')[0]

download_photo = urllib.urlretrieve(url, "/home/ubuntu/Desktop/Resized_Images/%s.jpg" % (filename))
downloaded_photo = Image.open("/home/ubuntu/Desktop/Resized_Images/%s.jpg" % (filename))

resized_photo = downloaded_photo.resize((300, 300), Image.ANTIALIAS)
new_filename = filename + "_processed"

resized_photo.save("/home/ubuntu/Desktop/Resized_Images/%s.jpg" % (new_filename))

I would like to send the resized photo saved in /home/ubuntu/Desktop/Resized_Images/
to Bob's folder in the djangobucket on Amazon S3 and make it publicly visible.
Thanks for your help.
EDIT
I found this link: http://www.laurentluce.com/posts/upload-and-download-files-tofrom-amazon-s3-using-pythondjango/
Not quite how to use it for my case, but I think I'm on the right track.

A: boto is the best way to do this.
You can get an existing bucket using:
get_bucket(bucket_name, validate=True, headers=None)

After installing boto, this code should do what you need to do
from boto.s3.connection import S3Connection
from boto.s3.key import Key

conn = S3Connection('<aws access key>', '<aws secret key>')
bucket = conn.get_bucket('<bucket name>')
k = Key(bucket)
k.key = 'file_path_on_s3' # for example, 'images/bob/resized_image1.png'
k.set_contents_from_file(resized_photo)

Here are some links to the Boto API and Boto S3 Doc


text:
Q: Override the existing Spring Security authentication How can I override the existing Spring Security authentication by invoking a Web Service and when it's failed, need to redirect some third party login page.
For calling this authentication web service, I need to get some ServletRequest parameter and for redirection, I need to access the ServletResponse.
Therefore I need to find out some Authentication method with ServletRequest and ServletResponse parameters.
But still, I failed to find out such a ProcessingFilter or AuthenticationProvider.
According to Spring Security basic it seems I have to override the AuthenticationProvider related authenticate method.
According to use case, I have to implement the Spring Security Pre-authentication,
but the issue is PreAuthenticatedAuthenticationProvider related 'authenticate' method only having the Authentication parameter.
PreAuthenticatedAuthenticationProvider
public class PreAuthenticatedAuthenticationProvider implements
        AuthenticationProvider, InitializingBean, Ordered {

    public Authentication authenticate(Authentication authentication) {}

}

As solution, is there any possibility to use custom implementation of AuthenticationFailureHandler ?
Thanks.

A: I have got resolved the issue as following manner,

*

*Implementing a custom AbstractPreAuthenticatedProcessingFilter

Override the doFilter method
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    try {

        // Get current Authentication object from SecurityContext
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        // Call for third party WS when the Authenticator object is null
        if (auth == null) {

            logger.debug("doFilter : Proceed the authentication");

            String appId = "My_APP_ID";
            String redirectURL = request.getRequestURL().toString();

            // Call for third party WS for get authenticate
            if (WS_Authenticator.isAuthenticated(appId, redirectURL)) {

                // Successfully authenticated
                logger.debug("doFilter : WS authentication success");

                // Get authenticated username
                String userName = WS_Authenticator.getUserName();

                // Put that username to request
                request.setAttribute("userName", userName);

            } else {

                String redirectURL = WS_Authenticator.getAuthorizedURL();
                logger.debug("doFilter : WS authentication failed");
                logger.debug("doFilter : WS redirect URL : " + redirectURL);

                ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
                ((HttpServletResponse) response).sendRedirect(redirectURL);

                // Return for bypass the filter chain
                return;
            }

        } else {
            logger.debug("doFilter : Already authenticated");
        }

    } catch (Exception e) {
        logger.error("doFilter: " + e.getMessage());
    }

    super.doFilter(request, response, chain);
    return;
}

Override the getPreAuthenticatedCredentials method
@Override
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {

    // Get authenticated username
    String[] credentials = new String[1];
    credentials[0] = (String) request.getAttribute("userName");

    return credentials;
}

*

*Implementing a CustomAuthenticationUserDetailsServiceImpl

Override the loadUserDetails method
public class CustomAuthenticationUserDetailsServiceImpl implements AuthenticationUserDetailsService<Authentication> {

    protected static final Logger logger = Logger.getLogger(CustomAuthenticationUserDetailsServiceImpl.class);

    @Autowired
    private UserDataService userDataService;

    public UserDetails loadUserDetails(Authentication token) throws UsernameNotFoundException {

        // Get authenticated username
        String[] credentials = (String[]) token.getCredentials();
        String userName = credentials[0];

        try {

            // Get user by username
            User user = userDataService.getDetailsByUserName(userName);

            // Get authorities username
            List<String> roles = userDataService.getRolesByUserName(userName);
            user.setCustomerAuthorities(roles);
            return user;

        } catch (Exception e) {
            logger.debug("loadUserDetails: User not found! " + e.getMessage());
            return null;
        }
    }
}


text:
Q: Form model binding Laravel / Angular Is there anny possibility when editing an entry (an update actually) with an Angular form, to populate the fields with the data already stored in the database?
In other words, can I do form model binding with Angular/Laravel?

A: If you're going to use ngResource and when you'll get data from Laravel, then you can bind the returned JSON object as a model to your form.
    $scope.formDatamodel = {};

    //Suppose you will get data from Laravel here
    var Apidata = $resource('/api/account/updateStatus').get();

    Apidata.$promise(data){

        $scope.formDatamodel = data;

    }

Now you will have to make ngModel binding in your form controller.
<input type="password" name="password" ng-model="formDatamodel.password">

A: I'm not sure if this is the right approch, but this is how I did it.
I get the data with the show method:
Factory:
            show : function(
            id
        )
        {
            return $http.get('/api/rides/' + id);
        }

Controller:
        $scope.rideEdit = {};
    var id = $stateParams.id;
    // Alles nemen van 1 record
    Ride.show(id)
        .success(function(data) {
            console.log(data);
            $scope.rideEdit.Dataname = data.name;
            $scope.rideEdit.Description = data.description;
            $scope.rideEdit.datetime = data.ridedatetime;
            $scope.rideEdit.persons = data.ridepersons;
            $scope.rideEdit.vertrekpunt = data.ridevertrekpunt;
            $scope.rideEdit.eindpunt = data.rideeindpunt;
        });

So then it displays the data.