text:
Q: How to make RegEx more performant? In my code I'm doing a regex match case in Scala like this:
line match {
    case regexp(unix_time, elapsed, remotehost, code_status, bytes, method, url, rfc931, peerstatus_peerhost, file_type) =>
        LogLine(getHumanDate(unix_time), elapsed, remotehost, code_status, bytes, method, url, rfc931, peerstatus_peerhost, file_type)
    case _ => throw new IllegalArgumentException("Could not parse row: " + line)
}

I'm using this regex pattern.
val regexp = """(\d{9,10}\.\d{3})\s*(\d+) (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) (\w+\/\d+) (\d+) (\w+) (\S+) (\-) (\w+\/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\w+\/\-) (\S+)""".r

I'm interested in making it more performant. I got it working with this but it's not very fast and I guess it can be done better.
Here are some sample log lines that needs to match:
1393930710.739 278 192.168.1.20 TCP_MISS/200 5848 GET http://www.coderanch.com/templates/default/images/quote.gif - HIER_DIRECT/145.20.133.81 text/plain

1393930719.989 73 192.168.178.27 TCP_MEM_HIT/200 268805 GET http://sunny:8080/viewapp/classpath/jquery.js - HIER_NONE/- application/x-javascript

1393997284.209  59287 192.168.1.2 TCP_MISS/503 0 CONNECT 172.104.89.123:5228 - HIER_NONE/- -

A: Since your goal is to match lines, the first improvement you can do is to use the start of line anchor ^ (that will make the pattern fail faster)
^(\d{9,10}\.\d{3})\s*(\d+) (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) (\w+/\d+) (\d+) (\w+) (\S+) (-) (\w+/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\w+/-) (\S+)

(I have removed all uneeded escape). An other thing you can do is to remove uneeded capturing groups (I'm not sure that (-) is very useful) and try to put the end of line anchor $

A: not sure you can really gain performance keeping a unique regexp. if you don't really need to check every parts format, it might be faster if you parse using .split(" ") and then check result length and only potentially malformated parts...

A: You are unlikely to get much faster using regex matching since even just splitting on spaces:
def split_apart(line: String) = line.split("""\s+""") match {
  case Array(unix_time, elapsed, remotehost, code_status, bytes, method, url, rfc931, peerstatus_peerhost, file_type) =>
    (unix_time, elapsed, remotehost, code_status, bytes, method, url, rfc931, peerstatus_peerhost, file_type)
  case _ => throw new Exception(":(")
}

takes 60% of the time of the full regex match.
If you are absolutely sure you have to care about this, then you will need to do it by hand.  Something like this is about 6x faster (on Java6 where substring doesn't actually copy the string data; I haven't checked 7):
def parse(line: String) = {
  def fail(s: String) = throw new Exception("Could not parse '"+s+"' in "+line)
  def checkA(s: String) = {
    if (s.length < 13 || s.length > 14 || s(s.length-4) != '.') fail(s)
    var i = 0
    while (i < s.length-4) { if (!s(i).isDigit) fail(s); i += 1 }
    i += 1
    while (i < s.length) { if (!s(i).isDigit) fail(s); i += 1 }
    s
  }
  def checkB(s: String) = {
    if (s.length == 0) fail(s)
    var i = 0
    while (i < s.length) { if (!s(i).isDigit) fail(s); i += 1 }
    s
  }
  def checkC(s: String) = {
    if (s.length < 7) fail(s)
    var i = 0
    while (i < s.length && s(i).isDigit) i += 1
    if (i < 1 || i > 3 || s(i) != '.') fail(s)
    var j = i+1
    i = j
    while (i < s.length && s(i).isDigit) i += 1
    if (i < j+1 || i > j+3 || i >= s.length || s(i) != '.') fail(s)
    j = i+1
    i = j
    while (i < s.length && s(i).isDigit) i += 1
    if (i < j+1 || i > j+3 || i >= s.length || s(i) != '.') fail(s)
    j = i+1
    i = j
    while (i < s.length && s(i).isDigit) i += 1
    if (i != s.length) fail(s)
    s
  }
  def checkD(s: String) = {
    if (s.length < 3) fail(s)
    var i = 0
    while (i < s.length && { var c = s(i); c.isLetterOrDigit || c=='_' }) i += 1
    if (i+1 >= s.length || !(s(i)=='/')) fail(s)
    i += 1
    while (i < s.length && s(i).isDigit) i += 1
    if (i != s.length) fail(s)
    s
  }
  def checkE(s: String) = checkB(s)
  def checkF(s: String) = {
    if (s.length < 0) fail(s)
    var i = 0
    while (i < s.length) { var c = s(i); if (!(c.isLetterOrDigit || c=='_')) fail(s); i += 1 }
    s
  }
  def checkG(s: String) = s
  def checkH(s: String) = { if (s != "-") fail(s); s }
  def checkI(s: String): String = {
    if (s.length < 3) fail(s)
    var i = 0
    while (i < s.length && { var c = s(i); (c.isLetterOrDigit || c=='_') }) i += 1
    if (i+1 >= s.length || !(s(i)=='/')) fail(s)
    i += 1
    if (s(i) == '-' && i+1 == s.length) return s
    var j = i
    while (i < s.length && s(i).isDigit) i += 1
    if (i < j+1 || i > j+3 || s(i) != '.') fail(s)
    j = i+1
    i = j
    while (i < s.length && s(i).isDigit) i += 1
    if (i < j+1 || i > j+3 || i >= s.length || s(i) != '.') fail(s)
    j = i+1
    i = j
    while (i < s.length && s(i).isDigit) i += 1
    if (i < j+1 || i > j+3 || i >= s.length || s(i) != '.') fail(s)
    j = i+1
    i = j
    while (i < s.length && s(i).isDigit) i += 1
    if (i != s.length) fail(s)
    s
  }
  def checkJ(s: String) = s
  val cs = line
  val a0 = 0
  var a1 = 0
  while (a0 < line.length && !cs(a1).isWhitespace) a1 += 1
  var b0 = a1+1
  while (b0 < line.length && cs(b0).isWhitespace) b0 += 1
  var b1 = b0+1
  while (b1 < line.length && !cs(b1).isWhitespace) b1 += 1
  val c0 = b1+1
  var c1 = c0+1
  while (c1 < line.length && !cs(c1).isWhitespace) c1 += 1
  val d0 = c1+1
  var d1 = d0+1
  while (d1 < line.length && !cs(d1).isWhitespace) d1 += 1
  val e0 = d1+1
  var e1 = e0+1
  while (e1 < line.length && !cs(e1).isWhitespace) e1 += 1
  val f0 = e1+1
  var f1 = f0+1
  while (f1 < line.length && !cs(f1).isWhitespace) f1 += 1
  val g0 = f1+1
  var g1 = g0+1
  while (g1 < line.length && !cs(g1).isWhitespace) g1 += 1
  val h0 = g1+1
  var h1 = h0+1
  while (h1 < line.length && !cs(h1).isWhitespace) h1 += 1
  val i0 = h1+1
  var i1 = i0+1
  while (i1 < line.length && !cs(i1).isWhitespace) i1 += 1
  val j0 = i1+1
  var j1 = j0+1
  while (j1 < line.length && !cs(j1).isWhitespace) j1 += 1
  ( checkA(line.substring(a0,a1)),
    checkB(line.substring(b0,b1)),
    checkC(line.substring(c0,c1)),
    checkD(line.substring(d0,d1)),
    checkE(line.substring(e0,e1)),
    checkF(line.substring(f0,f1)),
    checkG(line.substring(g0,g1)),
    checkH(line.substring(h0,h1)),
    checkI(line.substring(i0,i1)),
    checkJ(line.substring(j0,j1))
  )
}

But you'd better really, really care about that 6x speedup in order to do it this way.  This is a maintenance nightmare.


text:
Q: How can I use shell scripting to send an email when Handbrake gets done? I am currently encoding a lot of home videos converted from VHS tapes using Handbrake. I am using Ubuntu 64bit dual core machine and usually queue a lot of these videos. My question is how can I use shell scripting to keep checking on the handbrake process and send me an email when Handbrake finishes encoding a video file.
One idea was to look at the handbrake log but the standard log level does not provide much information, does anyone have any other ideas?

A: Use handbrake's CLI client in a shell script and have it email you at the end.
Something like this:
#/bin/sh
handbrake -i /dev/mydev -o myfile > out.txt
handbrake -i /dev/mydev2 -o myfile2 >> out.txt
handbrake -i /dev/mydev3 -o myfile3 >> out.txt
mail -s "done with handbrake" me@domain.com < out.txt

A: Alternatively, if you want things to remain flexible, you don't even need to write a script. You can simply write the commands mentioned in Stu Thompson's answer directly on the command line. Just remember to separate them with the symbol '&&'.
Say:
handbrake -i /dev/mydev -o myfile > out.txt && handbrake -i /dev/mydev2 -o myfile2 >> out.txt && handbrake -i /dev/mydev3 -o myfile3 >> out.txt && mail -s "done with handbrake" me@domain.com < out.txt

This gives you the flexibility to invoke your app any way you like instead of being stuck with whatever you wrote in the script.
By the way, as you can figure out yourself, issuing any two commands separated by '&&' on the command line means: run the first command and if it completes successfully, run the second command.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Check if $F$ is epimorphism For given polymonial $p \in \mathbb R [x]_2$ we have
$$f_p^*: \mathbb R[x]_2 \rightarrow \mathbb R$$

$$f_p^*(q) = p(-1)q(1) + p(0)q(0) + p(1)q(-1) $$
where $q\in \mathbb R [x]_2$
We have also  $$F: \mathbb R[x]_2 \rightarrow (\mathbb R[x]_2 )*$$ which is given with formula:
$$F(p) = f_p^* $$
where $p \in \mathbb R [x]_2$
Check if $F$ is epimorphism
My try
Ok, it seems to be simple, I have just to show that:
$$F(\alpha t + \beta w) = \alpha F(t) + \beta F(w) $$
so I have
$$\forall q. \alpha f_t^* (q) + \beta f_w^*(q) = f_{\alpha t+ \beta w}^*(q) $$
I want to go from right to left but how to use polymonial $\alpha t+ \beta w$?

A: For linearity, all you have to see is that for all real $x$ and $y$, $(\alpha t + \beta \omega)(x).q(y) = (\alpha t(x) + \beta \omega(x)).q(y) = \alpha t(x)q(y) + \beta \omega(x)q(y)$. Since you sum this behavior three time with $(-1,1)$, $(0,0)$ and $(1,-1)$ for $x$ and $y$, linearity is pretty straight-forward.
For surjectivity all you have to check if that given a linear form $g \in \mathbb{R}[x]_2$ there exists a polynomial $p$ of degree 2 such that $g = F(p)$
The thing to see here is that a polynomial of degree 2 can be determined given three different points and their values (it is Lagrange interpolation).
Consider $g \in \mathbb{R}[x]_2^*$. All you have to do is determined its values on a base, for example $\{1, x, x^2\}$ and it will be uniquely defined since $g$ is a linear form. By evaluation on this base you get three reals $g(1) = \alpha$, $g(x) = \beta$, $g(x^2) = \gamma$.
It gives you the linear system:
$p(-1) + p(0) + p(1) = \alpha$
$p(-1) - p(-1) = \beta$
$p(-1) + p(1) = \gamma$
I let you convince yourself that this linear system is always resoluble (its determinant is -2)
It gives you a the values of p for $0$, $1$, $-1$ which allows you, by Lagrange interpolation, to determine $p$, which is what you wanted to prove surjectivity.


text:
Q: What's the correct way to address someone in a letter when you know their name but not their gender? I'm writing a formal appeal letter as a reply to a letter I got from a government agency. Unfortunately, the person sending it only put their name with an intial, e.g. "J. Smith" and no title. They're in a foreign French speaking country, and I don't want to be too informal.
What would be the correct way to address them in my reply? "Dear Sir or Madam", "Dear J. Smith"... any suggestions?

A: I would suggest "Dear J. Smith", unless you know a title or honorary that you could use in place of the first initial.  While it seems impersonal, it's clear that there is no personal relationship involved since you don't know the sender.
The other option would be to try to research the sender prior to replying to gather a gender, title, or honorary.

A: What is their title? (If they have one)
For example:
Dear Ambassador Smith:
Dear Senator Booker:
Just title and last name will do...

A: If you know their title, then definitely use that.
"Dear Sir" or "Dear Sirs" was long considered the correct salutation on all formal or semi-formal business letters in the US when title was not used, however recently the "Dear Sir or Madam" is what I have seem more.


text:
Q: Laravel: I can not visualize images when uploading the web to my Hosting I have a web developed in Laravel, in local I can visualize all the content of the web without problems, I have uploaded the web to my hosting in the domain folder where I want to have the web (it is a shared hosting with several domains), I configured the base of data and modified the .htaccess file. The web loads, however it does not display the logo or the images stored in public / images.
Any idea what this is? I appreciate any guidance
I advance that my web is not in the public_html folder, because that folder is occupied by another web. All the files are in a domain.com folder
This is the method I'm using to call the images src="{{asset('images/test/home/banner-home.jpg')}}"
I have already checked and there are no syntax errors between uppercase and lowercase.
this is the error that I receive in each image:
Failed to load resource: the server responded with a status of 404 (Not Found)

A: you can do it this way:

*

*in  your domain.com, create another folder and move all the files and folders to the newly created folder.

*from the newly created folder, copy all the files and folders in public back to domain.com

*open your index.php in domain.com and configure this:
i. require DIR.'/newlycreatedfolder/vendor/autoload.php';
ii. $app = require_once DIR.'/newlycreatedfolder/bootstrap/app.php';

*i hope all your header files are called using: {{ asset() }} and your logo using {{ url() }}


text:
Q: Existence of irreducible polynomials of certain degrees True or false: there exists a field $K$ and a positive integer $n$ such that every polynomial over $K$ of degree $n$ is reducible (in $K[z]$) but there exists an irreducible polynomial of degree $n+1$.
Motivation: two extreme cases are well known.  If $K={\mathbb Q}$ the statement is false as there are irreducible polynomials of every degree.  I am not sure but I believe this is also true for finite fields.  If $K={\mathbb R}$ then there are irreducible polynomials of degree $1$ and $2$ only.

A: $\bigcup_{m\ge 1}\Bbb{F}_{p^{2^m}}$ doesn't have any quadratic extension.
The quadratic closure of $\Bbb{Q}$ works too: that is $E=\bigcup_{m\ge 0} E_m$ where $E_0=\Bbb{Q},E_{m+1}=E_m(\{ a^{1/2},a\in E_m\})$. Any element $b\in E$ is contained in a finite tower of quadratic extensions so $[\Bbb{Q}(b):\Bbb{Q}]$ divides a power of $2$, therefore $x^3-2$ is irreducible over $E$.


text:
Q: Bootstrap dropdown menu links not clickable I have a page: http://www.poh.me/nordisk/ where the dropdown menu links on this page works, but the subslinks (e.g. http://www.poh.me/nordisk/contact/) the anchors becomes unclickable.
I've tried every thing from removing data-toggle from the links to z-index css and other tips I read from others having a similar problem.
Any help is much appreaciated :-)
Thanks!!

A: You have errors in your code:

Uncaught TypeError: Cannot read property 'top' of undefined
$(".links a, .nav a").click(function (event) {
    event.preventDefault();
    var dest = 0;

    //                Error here
    //                       vvvv
    if ($(this.hash).offset().top > $(document).height() - $(window).height()) {
        dest = $(document).height() - $(window).height();
    } else {
        dest = $(this.hash).offset().top;
    }
    $('html,body').animate({scrollTop: dest}, 800, 'swing');
});


text: Q: Weird round icon in android studio instead of panel? I have a weird round instead of a panel in Android Studio so nothing works. It works only after rebooting the laptop. Restarting studio not working. How to fix it?


text:
Q: Is there a way to return early from a select statement in postgresql? I take a user-provided search query and split it into tokens, then generate a WHERE clause that checks each token against each text column (I'll leave out the indexes here for brevity, but they are well-indexed for with gin trigrams and performance is generally good).
Given a table like this
CREATE TABLE public.people (
    first_name text NOT NULL,
    last_name text NOT NULL,
  full_address text NOT NULL
)

and a search query such as 'barry wisteria lane', I'll end up with a SELECT statement similar to this:
SELECT * FROM public.people WHERE
  (
    first_name ILIKE '%barry%' OR
    last_name ILIKE '%barry%' OR
    full_address ILIKE '%barry%'
  ) AND (
    first_name ILIKE '%wisteria%' OR
    last_name ILIKE '%wisteria%' OR
    full_address ILIKE '%wisteria%'
  ) AND (
    first_name ILIKE '%lane%' OR
    last_name ILIKE '%lane%' OR
    full_address ILIKE '%lane%'
  )
  LIMIT 10
  -- this order by is psuedocode that hopefully expresses what's happening
  -- an actual example would be very long and difficult to read
  -- the result is rows that are matched due to hits on first_name are first
  ORDER BY similarity_to_tokens(first_name), similarity_to_tokens(last_name), similarity_to_tokens(full_address) DESC

this is fine and very performant. It becomes unperformant if the search query is short and returns a lot of matching rows which then need to be sorted. Sorting all these rows is a waste if there are more rows that matched on first_name than the LIMIT, because the other rows will always be discarded after the sort.
It's probable that I'm thinking about this problem from the wrong angle because I'm new to database work, but what seems like a simple way of gaining performance (in a normal programming language) would be to stop checking for matches on last_name and full_address if the number of matches on first_name has already reached what's specified in LIMIT, seeing as when the rows are sorted, those that matched on first_name are first.
It seems to me that setting and modifying variables is not possible in SQL, so is there another way to approach this?
Currently I do it in the application layer, where I decide if I feel the query is so short it warrants a first attempt where I only check first_name, then do a second call to the database if too few results are returned from the first attempt. But making 2 calls for one query is ugly and makes the performance worse in the case of misses with the initial call.


text:
Q: Slack chatPostMessage fails I'm trying to send a message from a Plugin by calling directly to the bot

self._bot.sc.api_call('chat.postMessage', data={
    'channel': "#general",
    'text': "test msg",
    'unfurl_media': 'true',
    'as_user': 'true',
     })

Always returns with:
   {'ok': False, 'error': 'channel_not_found'}

A: #general is your channel name, not your channel Id, so you should use channel Id, you can find your channel id here

A: Problem solved

    self._bot.sc.api_call(
        'chat.postMessage',
         channel="#general",
         text="My message text here",
         unfurl_media='true',
         as_user='true',
       )


text:
Q: Is python pandas dataframe too slow? I have an interesting problem. I have two files, NYPD_Motor_Collisions.csv has 1.2M lines and weatherfinal.txt has 109K lines. The objective is to merge the temp and prec data from weatherfinal.txt to the Collisions files as two columns based on the latitudes and longitudes. I wrote the following code using dataframe in pandas python.
from math import cos, asin, sqrt
import pandas as pd
import numpy as np
import os
import re
import datetime

def distance(lat1, lon1, lat2, lon2):
    p = 0.017453292519943295
    a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p)*cos(lat2*p) * (1-cos((lon2-lon1)*p)) / 2
    return 12742 * asin(sqrt(a))

def closest(data, v):
    return min(data, key=lambda p: distance(v['lat'],v['lon'],p['lat'],p['lon']))

tempDataList = []

#v = {'lat': 39.7622290, 'lon': -86.1519750}
#print(closest(tempDataList, v))

print os.getcwd()

filed_ = open("weatherfinal.txt", 'r')
fileo_ = open("weatherfinal_updated.txt","w")
lines_ = filed_.readlines()
for line_ in lines_:
    outline = re.sub("  +"," ",line_)
    fileo_.write(outline + "\n")
fileo_.close()

df = pd.read_csv("NYPD_Motor_Vehicle_Collisions.csv")

colhead = np.append(df.columns.values,['TEMP', 'PREP'])

outdf = pd.DataFrame(columns=colhead)

df2 = pd.read_csv("weatherfinal_updated.txt",' ')
df2.set_index(['WBANNO', 'LST_DATE', 'LST_TIME'])

sensorIds = df2['WBANNO'].unique()

for ids_ in sensorIds:
    longitude = df2.loc[df2['WBANNO']==ids_,'LONGITUDE'].iloc[0]
    latitude = df2.loc[df2['WBANNO'] == ids_, 'LATITUDE'].iloc[0]
    tempDataList.append({'lat':latitude,'lon':longitude,'SENSORID': ids_ })

print tempDataList

for index, row in df.iterrows():
    lon_ = row['LONGITUDE']
    lat_ = row['LATITUDE']
    tdate = row['DATE']
    ttime = row['TIME']
    tcal = 5
    pcal = 0
    fwdate = datetime.datetime.strptime(str(tdate), '%m/%d/%Y').strftime('%Y%m%d')
    fwtime = datetime.datetime.strptime(str(ttime), '%H:%M').strftime('%H%M')
    ntime = float(fwtime) + float(100)
    closests_ = closest(tempDataList, {'lat':lat_,'lon':lon_})
    sensorid = closests_['SENSORID']
    usedSensorId = sensorid
    selectedWeatherRow = df2.loc[(df2.WBANNO == sensorid) & (df2.LST_DATE == float(fwdate)) & (df2.LST_TIME >= float(fwtime)) & (df2.LST_TIME < ntime) ,['T_CALC', 'P_CALC']]
    if len(selectedWeatherRow.index) == 0:
        for sensId in sensorIds:
            if sensId == sensorid:
                continue
            selectedWeatherRow = df2.loc[(df2.WBANNO == sensId) & (df2.LST_DATE == float(fwdate)) & (df2.LST_TIME >= float(fwtime)) & (df2.LST_TIME < ntime), ['T_CALC', 'P_CALC']]
            if len(selectedWeatherRow.index) == 0:
                continue
            else:
                tcal = selectedWeatherRow['T_CALC'].values[0]
                pcal = selectedWeatherRow['P_CALC'].values[0]
                usedSensorId = sensId
                break
    else:
        tcal = selectedWeatherRow['T_CALC'].values[0]
        pcal = selectedWeatherRow['P_CALC'].values[0]
    row['TEMP'] = tcal
    row['PREP'] = pcal
    outdf.loc[index] = row
    print index, tcal, pcal, fwdate, fwtime, ntime, usedSensorId

print "Loop completed"
outdf.to_csv("NYPD_TRAFFIC_DATA.csv")
print "file completed"

This program has been running for days. Not sure why dataframe is too slow. I rewrote the program without dataframe using dictionaries and it completed in a few minutes. Not sure if dataframe is slow or I am not using it correctly. Just posting here for learning.


text:
Q: an urn contains six ball of each of the three colors: red, blue, and green. An urn contains six balls of each of the three colors: red, blue, green. Find the expected number of different colors obtained when three balls are drawn:
a. with replacement;
b. without replacement.
The correct answers are:
a: 19/9
b: 2.1912
I just don't know how to get to get to the answers.
Thanks for any help

A: We can also use recurrences, where A,B,C are the number of balls of three colors:
a)
\begin{align*}
  f(a,b,c) = \left\{\begin{matrix}
  3-\left(\lfloor\frac{a}{A}\rfloor + \lfloor\frac{b}{B}\rfloor+\lfloor\frac{c}{C}\rfloor\right)&   \text{if }A+B+C-(a+b+c) = 3\\
  \dfrac{a\cdot f(a-1,b,c)+b\cdot f(a,b-1,c)+c\cdot f(a,b,c-1)}{a+b+c} &  \text{otherwise}
\end{matrix}\right.
\end{align*}
b)
\begin{align*}
  f(a,b,c) = \left\{\begin{matrix}
  3-\left(\lfloor\frac{a}{A}\rfloor + \lfloor\frac{b}{B}\rfloor+\lfloor\frac{c}{C}\rfloor\right)&   \text{if }A+B+C-(a+b+c) = 3\\
  \dfrac{A\cdot f(a-1,b,c)+B\cdot f(a,b-1,c)+C\cdot f(a,b,c-1)}{A+B+C} &  \text{otherwise}
\end{matrix}\right.
\end{align*}

A: The count, $X,Y$, of different colours drawn with and without replacement (respectively) will have the support: $\{1, 2, 3\}$.   Find the probability of each, for the two experiments, then use:
$$\begin{align}\mathsf E(X) & = \sum_{k=1}^3 k\;\mathsf P(X{=}k) \\[1ex] & = \mathsf P(X{=}1)+2\,\mathsf P(X{=}2)+3\,\mathsf P(X{=}3) \\[1ex] & = 2 -\mathsf P(X=1)+\mathsf P(X=3) \\[2ex]\mathsf E(Y) & = 2 -\mathsf P(Y=1)+\mathsf P(Y=3) \end{align}$$
$\mathsf P(X=1), \mathsf P(Y=1)$ are the probabilities that all three balls are the same colour.
$\mathsf P(X=3), \mathsf P(Y=3)$ are the probabilities that all three balls are of distinct colours.

A: Let us take a card deck that contains only three colors : spade, diamond and heart, and suits from 1 to 6.
1) Define a poker hand as a hand of three cards. There are several types of hands, full color, pair and tricolor. Let count the hands without replacement :
tricolor : $ {6 \choose 1} {6 \choose 1} {6 \choose 1} = 216 $
pair : $ {3 \choose 1} {2 \choose 1} {6 \choose 1} {6 \choose 2} = 540 $
full color : $ {3 \choose 1} {6 \choose 3}= 60 $
their sum is $ {18 \choose 3} = 816 $ , the average # of colors is ${ 3×216 + 2×540 + 1×60 \over 816 }\approx 2.1912   $
2) When replacing, the G.F. is  $(x+y+z)^3$
The needed coefficients satisfy 6 + 18 + 3 = 27;
The average # of colors is ${ 3×6 + 2×18 + 1×3 \over 27 } = {19 \over 9}   $


text:
Q: Asyncio doesn't execute the tasks asynchronously I'm playing around with asyncio module of Python and I don't know what's the problem with my simple code. It doesn't execute the tasks asynchronously.
#!/usr/bin/env python3

import asyncio
import string

async def print_num():
    for x in range(0, 10):
        print('Number: {}'.format(x))
        await asyncio.sleep(1)

    print('print_num is finished!')

async def print_alp():
    my_list = string.ascii_uppercase

    for x in my_list:
        print('Letter: {}'.format(x))
        await asyncio.sleep(1)

    print('print_alp is finished!')

async def msg(my_msg):
    print(my_msg)
    await asyncio.sleep(1)

async def main():
    await msg('Hello World!')
    await print_alp()
    await msg('Hello Again!')
    await print_num()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()

Here's the output when the script is called:
Hello World!
Letter: A
Letter: B
Letter: C
Letter: D
Letter: E
Letter: F
Letter: G
Letter: H
Letter: I
Letter: J
Letter: K
Letter: L
Letter: M
Letter: N
Letter: O
Letter: P
Letter: Q
Letter: R
Letter: S
Letter: T
Letter: U
Letter: V
Letter: W
Letter: X
Letter: Y
Letter: Z
print_alp is finished!
Hello Again!
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9
print_num is finished!

A: You are calling the functions sequentially, so the code also executes sequentially. Remember that await this means "do this and wait for it to return" (but in the meantime, if this chooses to suspend execution, other tasks which have already started elsewhere may run).
If you want to run the tasks asynchronously, you need to:
async def main():
    await msg('Hello World!')
    task1 = asyncio.ensure_future(print_alp())
    task2 = asyncio.ensure_future(print_num())
    await asyncio.gather(task1, task2)
    await msg('Hello Again!')

See also the documentation of the asyncio.gather function. Alternatively, you could also use asyncio.wait.

A: You're encountering a common source of confusion with await statements, which is that they behave sequentially for 'child' coroutines but they behave asynchronously for 'neighbouring' coroutines.
For example:
import asyncio

async def child():
    i = 5
    while i > 0:
        print("Hi, I'm the child coroutine, la la la la la")
        await asyncio.sleep(1)
        i -= 1

async def parent():
    print("Hi, I'm the parent coroutine awaiting the child coroutine")
    await child() # this blocks inside the parent coroutine, but not the neighbour
    print("Hi, I'm the parent, the child coroutine is now done and I can stop waiting")

async def neighbour():
    i = 5
    while i > 0:
        await asyncio.sleep(1)
        print("Hi, I'm your neighbour!")
        i -= 1

async def my_app():
    # start the neighbour and parent coroutines and let them coexist in Task wrappers
    await asyncio.wait([neighbour(), parent()])

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(my_app())

Which will output:
Hi, I'm the parent coroutine awaiting the child coroutine
Hi, I'm the child coroutine, la la la la la
Hi, I'm the child coroutine, la la la la la
Hi, I'm your neighbour!
Hi, I'm the child coroutine, la la la la la
Hi, I'm your neighbour!
Hi, I'm the child coroutine, la la la la la
Hi, I'm your neighbour!
Hi, I'm the child coroutine, la la la la la
Hi, I'm your neighbour!
Hi, I'm the parent, the child coroutine is now done and I can stop waiting
Hi, I'm your neighbour!

Process finished with exit code 0


text:
Q: What is inverse proportionality?
Translated from danish:

This musical instrument consists of some pipes that have different lengths, and that each has its own tone. The frequency of the tone is inversely proportional to the pipes length. A pipe with the length of 9,4cm has a tone with frequency 880 Hz.
a) How long does a pipe have to be to have a frequency of 588 Hz?

So far I have thought to do the following:

*

*I do not know where to start, it's a topic I don't understand how to solve.

A: When we describe a relationship between two variables $x$ and $y$ as being "inversely proportional", we mean that they have a relationship like $$y=\frac kx\tag{inversely proportional}$$  where $k$ is just a constant called, unimaginatively, the "constant of proportionality".  Compare this to a "directly proportional" relationship $$y=kx\tag{directly proportional}$$
So in your problem if $L$ is the length of the pipe and $F$ is the frequency it produces then the relationship between them should be $$L=\frac kF$$ for some $k$.  By giving us one length with its associated frequency, the question is giving us a way to figure out what the value of $k$ should be.  We just plug in the $L$ and $F$ it gives us and solve for $k$:  $$9,4 = \frac{k}{800} \implies k = 9,4\times 800 = 7520$$  Knowing this we can solve the problem.  It asks us to find the length of the pipe $L$ when $F=588$.  So now we just plug in the $k$ value we found and the $F$ value it gives us to get $$L= \frac{7520}{588} \approx \require{enclose}\enclose{roundedbox}{12.789\text{ cm}}$$


text:
Q: How to specify language dialect in \lstline option? First, here is some code that works fine:
\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\begin{document}
\lstinline[language=algol,keywordstyle=\color{blue}]{int a}
\end{document}

This uses the algol 68 dialect and it works fine. Now I am going to replace int with integer in the code which requires algol 60 dialect for proper syntax highlighting.
\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\begin{document}
\lstinline[language=[60]algol,keywordstyle=\color{blue}]{integer a}
\end{document}

Obviously this does not work due to [...] within [...]. I get this error:
Runaway argument?
{integer a} \end {document}

How do I specify the language dialect within \lstline option?

A: TeX sees the ] in [60]algol as the closing bracket for the optional argument so, putting it differently, what it understood was that the optional argument was language=[60 and chaos ensued. Hide the [60]algol inside a pair of {...}:
\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\begin{document}
\lstinline[language={[60]algol},keywordstyle=\color{blue}]{integer a}
\end{document}


text:
Q: Deploy mariaDB and nextcloud via Docker with a mariaDB error message I have a question about nextcoud, mariaDB and Docker.
Initial situation:
I have a Synology NAS and would like to install mariaDB and nextcloud via Docker.
I found a tutorial here: https://mariushosting.com/synology-how-to-install-nextcloud-using-docker/
As in the tutorial I also use portainer.
Here is my configuration in compose file format:
version: '2.9'

services:

  mariadb:
    container_name: mariadb
    image: mariadb
    command: --transaction-isolation=READ-COMMITTED --binlog-format=ROW
    restart: always
    volumes:
      - mariadb:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=rootpassword
      - MYSQL_PASSWORD=mysqlpassword
      - MYSQL_DATABASE=nextcloudatabasename
      - MYSQL_USER=nextclouduser

  nextcloud:
    container_name: nextcloud
    ports:
      - 40010:80
    links:
      - mariadb
    environment:
      - PUID=1024
      - PGID=100
      - TZ=Europe/Berlin
    volumes:
      - /volume1/docker/nextcloudStable/html:/var/www/html
      - /volume1/docker/nextcloudStable/custom_apps:/var/www/html/custom_apps
      - /volume1/docker/nextcloudStable/config:/var/www/html/config
      - /volume1/docker/nextcloudStable/data:/var/www/html/data
      - /volume1/docker/nextcloudStable/themes:/var/www/html/themes/
    image: nextcloud
    restart: always

volumes:
  mariadb: # nextcloud

After deployment I also get the installation page of nextcloud under IP of NAS: http://192.168.1.10:40010/
I entered mariadb as host and get the following error message:
Error while trying to create admin user:
Failed to connect to the database: An exception occurred in driver:
SQLSTATE[HY000] [1045] Access denied for user 'nextclouduser'@'172.17.0.7' (using password: YES)

Could someone please explain me why the error occurs and how I can fix it.
Thanks a lot

A: First I set up my container with Portainer. Here I logged in the mariaDB container and set the PW manually.
mysql -u root -p
SET PASSWORD FOR 'nextclouduser'@'%' = PASSWORD('X123');

I also tried the deployment with a docker-compose.yml file and the docker-compose up -d command. No manual PW setting was necessary.

A: below works for me just do it as a stack in portainer
version : '3.8'

volumes:
  nextcloud:
  db:

services:
  db:
    image: mariadb
    restart: always
    command: --transaction-isolation=READ-COMMITTED --binlog-format=ROW --innodb-file-per-table=1 --skip-innodb-read-only-compressed

    volumes:
      - db:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=pass
      - MYSQL_PASSWORD=passt
      - MYSQL_DATABASE=nextcloud
      - MYSQL_USER=nextcloud

  cloud:
      image: nextcloud
      restart: always
      ports:
        - 8888:80
      links:
        - db
      volumes:
        - nextcloud:/var/www/html
      environment:

      - MYSQL_PASSWORD=pass
      - MYSQL_DATABASE=nextcloud
      - MYSQL_USER=nextcloud
      - MYSQL_HOST=db


text:
Q: Django - Manipulating query strings (search filters) I'm looking to manipulate query strings so I can create search filters -- I was wondering what would be the best approach. I'd like to be able to add/update/remove parts. For example:
Color

*

*Blue (www.google.com/?color=blue)

*Red (wwww.google.com/?color=red)

*Green (www.google.com/?color=green)

*None (www.google.com/?)

I found a couple snippets that do this but I was looking through the docs and I saw the QueryDict objects. I'm not sure how that would work out in the template. What is the best and safest approach?


text:
Q: TFS "Copy Outputs to Drop Folder" parameter in build process template I want do some job in my build process template only if parameter "Copy Outputs to Drop Folder" is set to true. Is there any variable that is associated with this parameter?

A: I've managed to do it by checking Not String.IsNullOrEmpty(BuildDetail.DropLocation).


text:
Q: How to copy all messages of a conversation in one folder? For archiving purposes, I would like to copy/move all messages of a conversation in one folder, including sent messages and messages stored in different folders. I tried several things, like "Cmd+A" while one message of a conversation is selected, but nothing seems to work. Is there a way to do that?
The idea is the following: I use an IMAP account an whenever a project is finished, I move the corresponding folder on the server to an archive, e.g., from ./Mail to ./MailArchive. At the moment, all mails are included except the mails I sent. To get a complete archive, the sent mails should be in there as well.

A: The answer above about selecting all the messages in a conversation is good, but it forgets that you specified that the messages are not all in the same folder. What you need to do is create a smart folder first to get all the messages into a "virtual" folder, then select them. The smart folder could use a condition such as a specific word or string in the subjects of the emails, or you could simply grab all your emails (Sender contains @, for example), then use the Command-Shift-K shortcut to select the conversation, if they all come up as a single conversation.

A: This is doable, but needs to include all the folders where emails are part of the conversation thread.
To start you must be able to see your list of email folders, then select the inbox, then hold the command key, and select the rest of the folders that need to be part of the thread. You now have a mess of emails from a bunch of folders visible.
Select one of the messages in the thread. Mail should now highlight the rest of the messages in the thread. You can add another thread by command clicking another email.
Now do cmd-shift-k to select all the messages in the thread(s). It's under the View menu, Select, All messages in this conversation.
You can now move them all, the easiest is to right-click, or Ctrl-click, and select the option to move them, and the destination folder. You can also use the Move to or Copy to options in the Message menu.


text:
Q: Why should we use the "write" methods in filechannel while they already exist in RandomAccessFile This is my code, which uses FileChannel to write to the file:
package logging;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Test {

    public static void main(String args[]){
        try {

            RandomAccessFile rf = new RandomAccessFile("C:\\Users\\kalyan\\Desktop", "rw");
            FileChannel fc = rf.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            byteBuffer.putChar('a');

            while(byteBuffer.hasRemaining()) {
                fc.write(byteBuffer); //usig filechannel to write to the file
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In the above example, I am using FileChannel's write method to write to the file, i.e., fc.write.
Why shouldn't we use rf.write, which already exists in RandomAccessFile?

A: there's no reason not to use the write() methods which exist on RandomAccessFile.  if you happen to be interacting with code which requires a WritableByteChannel, however, you would want to use the FileChannel instead of RandomAccessFile.

A: In your example it makes no difference, but if you used ByteBuffer.allocateDirect you could write faster. ByteBuffer API says
A byte buffer is either direct or non-direct. Given a direct byte buffer, the Java virtual machine will make a best effort to perform native I/O operations directly upon it. That is, it will attempt to avoid copying the buffer's content to (or from) an intermediate buffer before (or after) each invocation of one of the underlying operating system's native I/O operations

A: Given that there is no RandomAccessFile.write overload that takes a byte buffer I'd say the reason for using the file channel is pretty obvious. But lets assume you really meant your question in a more general manner. Being able to manipulate a RAF via its file channel opens up a variety of additional functionality:

*

*File region locking

*Memory mapping

*Byte swaps from other channel objects

*Writing to portions of the file without modifying the current file pointer

It is this added functionality you will be looking at if you use a RAF's file channel, as opposed to the simple ability to write data at the current FP.


text:
Q: get all links from a div with JSoup Basically, I am using Jsoup to parse a site, I want to get all the links from the following html:

     Dis Be the link

Any idea how?

A: Straight from jsoup.org, right there, first thing you see:
Document doc = Jsoup.connect("https://en.wikipedia.org/").get();
log(doc.title());
Elements newsHeadlines = doc.select("#mp-itn b a");
for (Element headline : newsHeadlines) {
  log("%s\n\t%s",
    headline.attr("title"), headline.absUrl("href"));
}

Modifying this to what you need seems trivial:
Document doc = Jsoup.connect("https://en.wikipedia.org/").get();
Elements anchorTags = doc.select("ul.detail-main-list a");
for (Element anchorTag : anchorTags) {
  System.out.println("Links to: " + anchorTag.attr("href"));
  System.out.println("In absolute form: " + anchorTag.absUrl("href"));
  System.out.println("Text content: " + anchorTag.text());
}

The ul.detail-main-list a part is a so-called selector string. A real short tutorial on these:

*

*foo means: Any HTML element with that tag name, i.e. <foo></foo>.

*.bar means: Any HTML element with class bar, i.e. <foo class="bar baz"></foo>

*#bar means: Any HTML element with id bar, i.e. <foo id="bar">

*These can be combined: ul.detail-main-list matches any
 tags that have the string detail-main-list in their list of classes.

*a b means: all things matching the 'b' selection that have something matching 'a' as a parent. So ul a matches all  tags that have a
 tag around them someplace.

The JSoup docs are excellent.

A: You can do a specific a href link in this way from any website.
public static void main(String[] args) {
    String htmlString = "\n" +
            " \n" +
            " \n" +
            "
\n" +
            "
 \n" +
            "     Dis Be the link\n" +
            "
 \n" +
            "
" +
            " \n" +
            ""
            + "";
    Document html = Jsoup.parse(htmlString);
    Elements elements = html.select("a");
    for(Element element: elements){
        System.out.println(element.attr("href"));
    }
}

Output:
/manga/toki_wa/v01/c001/1.html


text:
Q: How to get the css with in inline styles using jquery I am loading the styles dynamically from the database in my asp.net mvc (C#) application.
I am trying to change some of the properties like (background, font color, font size,...) of the loaded inline style. I am using jquery.rule to do this.
I need to update the complete inline style including the changes, back to the database using jquery.
The inline style inside the head looks like:
<style type="text/css">
    <!
    -- body
    {
        background: #fff;
        margin: 0px;
        padding: 0px;
        font: normal 12px Tahoma, Verdana, Arial;
        color: #636363;
    }
    a
    {
        color: #d0d0d0;
        text-decoration: none;
    }
    #header
    {
        padding-left: 35px;
        height: 60px;
        vertical-align: middle;
        padding-top: 25px;
    }
    -- ></style>

I need to get updated inline style. How to do it?

A:
I need to update the complete inline style including the changes, back to the database using jquery.

Are you trying to read the inline style declarations of an element in the page? If so, this is tricky. In theory you should be able to call element.getAttribute('style') or the jQuery equivalent. However DOM attribute access doesn't work in IE; in fact IE doesn't store the attribute as used in the document at all, only the parsed style declarations that result from it.
There's not a jQuery-specific means of reading all styles, but you can get the effective inline style rules as CSS using DOM Level 2 Style.
var style= element.style.cssText;

But in IE this will separate any shortcut properties you have used, for example setting border can result in you getting border-style, border-color and border-width back. IE will also upper-case the property names. This may or may not matter to you.
You'd probably be better off remembering the inline style changes you make in a separate lookup object so you can read it more easily. You can attach that to the element using jQuery's data() method, make all changes to both the 'real' element.style and the lookup $(element).data('stylestore') objects, then retrieve all set styles from the lookup when you're about to post.

A: Use the jQuery ajax method to post form serialized data to your action method:
$.ajax({
   type: "POST",
   url: "/YourController/UpdateCss",
   data: "font=arial&color=#fff&font-size=10px"
   success: function(result){
      // handle your result here
   }
});

You can then access the posted data in your controller action via the "FormCollection":
[AcceptVerbs(HttpVerbs.Post)]
public String UpdateCss(FormCollection form)
{
    // handle your form here
    return "Success";
}

Hope this helps
-Mark


text:
Q: Findbugs validation in SONAR are skipping important violations I'm having a problem with violation in Sonar to find a basic problem in some codes that we have in my company. Below there is a test class that represents the situation that I want to clarify:
import entity.Cidade;

public class TesteSonar {

    public void testarSonar() {

        Cidade cidade = testarSonar2();

        cidade.getEstado();

    }

    public Cidade testarSonar2() {

        return null;
    }

}

In this class, we have the situation where the variable "cidade" receives the return of the method "testarSonar2()" that is null, and after that I use a action from this object. It's obvious that will throw a NullPointerException. My question is: Why findbugs didn't catch this kind of problem?
This situation points to a credibility problem in Sonar in the results that I receive from the tool. Could anyone help to understand why this is happing this way?
Thank's
Alexandre from Brazil

A: I've just made a test and indeed, no error is reported.
However, please note that the problem comes from Findbugs, not from Sonar itself - as Sonar relies on external tools for bug detection. So I'd advise you to ask the question on the Findbugs' mailing list.


text:
Q: How to delete a specific row from a table using angularjs? I'm working on this Angularjs table. When I delete a customer (clicking on remove) the specific customer goes away and that works fine :). But let's say I search for an specific customer like Alex typing Alex in the search box, then I want to delete it, but for some reason my removePerson function targets the first customer from the table. Please tell me what I'm doing wrong inside my removePerson funcion. Thanks a lot!!
and here's my code:
var App = angular.module('sortApp', ['ui.bootstrap'])

App.controller('mainController', function($scope, $modal, $log, $filter) {

$scope.sortType     = 'id'; // set the default sort type
$scope.sortReverse  = false;  // set the default sort order
$scope.searchPerson  = '';     // set the default search/filter term

// Array - List of People
$scope.People = [
{ id: 1, name: 'Mike', Lastname: 'White', age: 26 },
{ id: 2, name: 'Carl', Lastname: 'Barns', age: 41 },
{ id: 3, name: 'Deb', Lastname: 'McDonals',age: 78 },
{ id: 4, name: 'Tommy', Lastname: 'Humbs', age: 32 },
{ id: 5, name: 'Mary', Lastname: 'Browns', age: 18 },
{ id: 6, name: 'Alex', Lastname: 'Sams', age: 50 },
{ id: 7, name: 'Beto', Lastname: 'Burns', age: 27 }
];
/*
This function adds a new customer
*/
$scope.addPerson = function(){
var customer = {
    name: $scope.name,
    Lastname: $scope.Lastname,
    age: $scope.age,
};

$scope.People.push(customer);
};
/*
This function removes a customer
*/
$scope.removePerson = function(index){

if(confirm("Are you sure to remove Customer")){
        $scope.People.splice(index, 1);
    }
 };
 $scope.openPopupScreen = function() {

 var modalInstance = $modal.open({
  template: '

Add Customer

    <form >' +
    ' NAME:<input style = "width:300px;"type="text" class="form-control ng-scope ng-pristine ng-valid" ng-model="person.name">
' +
    ' LASTNAME:<input style = "width:300px;" type="text" class="form-control ng-scope ng-pristine ng-valid" ng-model="person.Lastname">
' +
    ' AGE:<input style = "width:300px;" type="number"class="form-control ng-scope ng-pristine ng-valid" ng-model="person.age">
' +
    ' <button id = "myid" type="button" class="btn btn-success" ng-click="add()">Add New Customer</button>' +
    '  <button type="reset" class="btn ">Clear</button>' +
    '
'+
    '
Please enter a name
'+
  '
'+
  '
'+
    '
Please enter a lastname
'+
  '
'+
  '
'+
    '
Please enter age
'+
  '
'+
    ' </form>' +
    '
' +
    '
' +
    '  close' +
    '
',
  controller: ModalInstanceCtrl
});
modalInstance.result.then(function (newPerson) {
  $scope.People.push(newPerson);
});
};

var ModalInstanceCtrl = function($scope, $modalInstance) {
$scope.person = {name: '', Lastname: '', age: ''};
$scope.error_name_message = true;
$scope.error_lastname_message = true;
$scope.error_age_message = true;

$scope.ok = function() {
$modalInstance.close($scope.selected.item);
};

$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};

$scope.add = function() {
//Pass newPerson to caller from main controller
if($scope.person.name === ""){

$scope.error_name_message= false;
  $("#Error_Message_name").show().delay(1900).fadeOut(900); // don't leave error on screen for long
}
else if($scope.person.Lastname === ""){
  $scope.error_lastname_message = false;
  $("#Error_Message_Lastname").show().delay(1900).fadeOut(900); // don't leave error on screen for long
}
else if($scope.person.age === "" || $scope.person.age < 1){
  $scope.error_age_message = false;
  $("#Error_Message_Age").show().delay(1900).fadeOut(900); // don't leave error on screen for long
}
else{
$modalInstance.close($scope.person);
}
};
};

});

A: This is happening because you are passing the index key of the array of displayed element that is not the same of the original array. You can fix this in different ways. The one proposed here should work. Hope it helps.
Change your removePerson function into this:
$scope.removePerson = function(index){
    if(confirm("Are you sure to remove Customer")){
        angular.forEach($scope.People, function(value, key) {
            if (value.id === index){
                $scope.People.splice(key, 1);
            }
        });
    }
};

And pass the id of the Person to the function from your HTML:
<button type="button" class="btn btn-danger fa fa-trash-o" ng-click="removePerson(people.id)"></button>


text:
Q: Prove $\lim_{n\to \infty} \int_E f^{1/n}(x)dm=m(E)$ Let $f:E \to \mathbb{R}$ be a measurable and non-negative function, with $0<f(x)<1$. I have to prove that $\lim_{n\to \infty} \int_E f^{1/n}(x)dm=m(E)$.

I've got various questions:

*

*f is measurable and non-negative, but we don't know if it is non-decreasing, so we can't use the monotone convergence theorem, right? And is Fatou's lemma useful?

*So what we have to use to enter the limit inside the integral is the dominated convergence theorem? But to use this, first I would have to see if its hypotheses are satisfied, right?

*So now, $\lim_{n\to \infty} \int_E f^{1/n}(x)dm=\int_E \lim_{n\to \infty} f^{1/n}(x)dm=\int_E f^{0}(x)dm=\int_E dm=m(E)$
Could anyone answer those 3 questions, please? Is it ok what I have done?

A: If $m(E) <\infty$ then DCT applies since $0< f^{1/n} \leq 1$. Suppose $m(E)=\infty$. Let $F_N=E\cap [-N,N]$. Then $\int_E f^{1/n}dm \geq \int_F f^{1/n}dm \to m(F)$. Can can finish the proof by letting $N \to \infty$?
MCT is also applicable since $ f^{1/n}$ is positive and increases to $1$.
Details for the first proof: $\lim \inf_{n \to \infty} \int_E f^{1/n}dm \geq \lim \inf_{n \to \infty} \int_{F_N} f^{1/n}dm =m(F_N)$. This is true for each $N$ and $F_N$ increase to $E$ as $N$ increases to $\infty$. Hence, $m(F_n) \to m(E)=\infty$ proving that $\lim_{n \to \infty} \int_E f^{1/n}dm=\infty$.

A: Measurability issues are not complicated since $f$ is measurable. You can use the monotone convergence theorem, for  $0<f<1$, and so the sequence $h_n:=f^{1/n}$ is monotone increasing. Now $\lim_nf^{1/n}=1$; hence, an application of the monotone convergence theorem gives
$$\lim_{n\rightarrow\infty}\int_Ef^{1/n}\,dm=\int_E\lim_{n\rightarrow\infty}f^{1/n}\,dm=\int_E\,dm=m(E)$$


text:
Q: how does node.js clustering work? i am trying to understand the following piece of code that is use to create miltiple servers to make use of a multi core cpu.
 var cluster = require("cluster");
 var http = require("http");
 var numCPUs = require("os").cpus().length;
 var port = parseInt(process.argv[2]);

 if (cluster.isMaster) {
     for (var i = 0; i < numCPUs; i++) {
         cluster.fork();
     }

     cluster.on("exit", function(worker, code, signal) {
         cluster.fork();
     });
 } else {
     http.createServer(function(request, response) {
         console.log("Request for: " + request.url);
         response.writeHead(200);
         response.end("hello world\n");
     }).listen(port);
 }

my question is, given every created server listens on same port, what guarantees that a request won't be served by more than one server?

A: In node v0.10, the OS kernel always chooses which child gets the request. In node v0.11+ and io.js v1.0.0+, manual round-robin scheduling is used (except on Windows for now). This default behavior is configurable by setting an environment variable though.


text:
Q: A submanifold of vector bundle whose intersection with each $E_p$ is linear subspace of same dimension is a subbundle? I am learning the theory of smooth manifolds using the book Introduction to Smooth manifolds by John M. Lee, the definition of smooth subbundle in the book is as follows:
Let $\pi:E\to M$ be a smooth vector bundle, if $S\subset M$ is an embedded submanifold of $E$ whose intersection with $E_p=\pi^{-1}(p)$ is a linear subspace of $E_p$ for $\forall p\in M$ and $\pi|_S:S\to M$ is a smooth vector bundle, then $\pi|_S:S\to M$ is called a subbundle.
My question is: if $S\subset M $ is an embedded submanifold of $M$ and $S\cap E_p$ is a linear subspace of $E_p$ with the same dimension $m$ for $\forall p\in M$, is $\pi|_S:S\to M$ a subbundle? If the answer is no, could you give a counterexample, because I think this is counterintuitive. Thanks in advance!


text:
Q: GCP Workflow : Can we setup a step wait for other steps to complete? I am using GCP Workflow Beta to check if I can build some of my workflows. The documentation mentions how we can conditionally execute steps with switch case and next for jumps. However can we have a flows where

*

*A step waits for two or more previous steps to complete

*Multiple steps triggered the same time.

As you can see, what I am implying is conditional parallel execution of steps. Is there a way to do this ?
Also, I see we have some basic functions like len, string etc in the examples. Can you please guide me where I can find a list of all such functions that are available ? I was looking for something to manipulate JSON.

A: You can't wait a step because you can't run multiple step in parallel for now.
In my company, we also expect, and wait, a lot about parallelization and that's why I had a meeting with the PM yesterday to share these expectation with him. It's one of the top priority in the roadmap but I don't know when it will be released (something like Q1 or Q2 2021 I guess).
The functions sounds like python code but it's not really clear in the documentation. I will share this with the PM.


text:
Q: Prove or disprove that $[L:K] = \deg(p)$ Let $L/K$ be a finite extension and let $\beta \in L$. If $p$ is the minimal polynomial of $\beta$ then is it true that $[L:K] = \deg(p)$? If not, give a counterexample.
Can someone help me figure out if this is true or not?

A: Let $K=\mathbb{Q}(i,\sqrt{2})$ and consider the extension $K/\mathbb{Q}$. Consider the minimal polynomial of $i$ over $\mathbb{Q}$, which is $p(x)=x^{2}+1$, i.e. $\deg(p)=2$. But $$[K:\mathbb{Q}]=4\neq 2=\deg(p).$$


text:
Q: Binding paper-tabs with on the post-card tutorial with little modification I just started my first web application development using polymer. I ran into a tutorial on the polymer website, and I want to add some modifications to be able know more about this new technology. After trying to run into the tutorial, i decided to place a scaffold around the element I just made, so the paper-tabs and the post-card list are inside the scaffold's content. Then I tried to wire up the paper-tabs and post-cards again, using the favorites function introduced by the tutorial, as it turns out, I got no response. I changed also the labels of the paper-tabs but I left the name attribute unchanged.
Can you help me what's going wrong on my code?
index.html
<!doctype html>

  <title>unquote</title>
  <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">

  <link rel="import" href="../components/font-roboto/roboto.html">
  <link rel="import"
    href="../components/core-header-panel/core-header-panel.html">
  <link rel="import"
    href="../components/core-toolbar/core-toolbar.html">
  <link rel="import"
    href="../components/paper-tabs/paper-tabs.html">
  <link rel="import" href="sample-Scaffold.html">

<core-header-panel>
    <sample-scaffold>
    </sample-scaffold>
</core-header-panel>

sampleScaffold.html
<link rel="import" href="/components/core-toolbar/core-toolbar.html">
<link rel="import" href="/components/core-menu/core-menu.html">
<link rel="import" href="/components/core-item/core-item.html">
<link rel="import" href="/components/core-header-panel/core-header-panel.html">
<link rel="import" href="/components/core-drawer-panel/core-drawer-panel.html">
<link rel="import" href="/components/core-scaffold/core-scaffold.html">
<link rel="import" href="/components/core-input/core-input.html">
<link rel="import" href="/components/paper-item/paper-item.html">
<link rel="import" href="/components/core-icon-button/core-icon-button.html">
<link rel="import" href="../components/polymer/polymer.html">

<link rel="import" href="post-list.html">
<polymer-element name="sample-scaffold">
  <template>

   <core-scaffold>

      <core-header-panel navigation flex>
        <core-toolbar id="navheader">
           <core-field id="core_field" icon="search" theme="core-light-theme" center horizontal layout>
            <core-icon icon="search" id="core_icon"></core-icon>
            <core-input placeholder="Device Name..." id="core_input" flex></core-input>
          </core-field>
        </core-toolbar>
        <core-menu>
            <paper-item label="Team Migration" icon="polymer" id="paper_item1" center horizontal layout></paper-item>
            <paper-item label="Team Customization" icon="polymer" id="paper_item2" center horizontal layout></paper-item>
            <paper-item label="Team Spectial Projects" icon="polymer" id="paper_item3" center horizontal layout></paper-item>
            <paper-item label="Team New Solutions" icon="polymer" id="paper_item4" center horizontal layout></paper-item>
            <paper-item label="Team SRT" icon="polymer" id="paper_item5" center horizontal layout></paper-item>
        </core-menu>
      </core-header-panel>

SSCOI ITEM DASHBOARD

        <paper-tabs id="tabs" selected="all" valueattr="name" self-end>
          <paper-tab name="all">All devices</paper-tab>
          <paper-tab name="wires">Extension Wires</paper-tab>
          <paper-tab name="printers">Printers</paper-tab>
          <paper-tab name="pinpads">Pinpads</paper-tab>
          <paper-tab name="scanners">Scanners</paper-tab>
          <paper-tab name="favorites">Borrowed</paper-tab>
          <paper-tab name="other">Other</paper-tab>
        </paper-tabs>

          <post-list show="all"></post-list>

</core-scaffold>
  </template>

</polymer-element>

post-card.html
<link rel="import" href="../components/polymer/polymer.html">
<link rel="import" href="../components/core-icon-button/core-icon-button.html">

<polymer-element name="post-card">
  <template>

      <content select="img"></content>
      <content select="h2"></content>

    <core-icon-button
      id="favicon"
      icon="favorite"
      on-tap="{{favoriteTapped}}"></core-icon-button>
    <content></content>
  </template>

</polymer-element>

post-list.html
<link rel="import" href="../components/polymer/polymer.html">
<link rel="import" href="../components/core-icon-button/core-icon-button.html">

<polymer-element name="post-card">
  <template>

      <content select="img"></content>
      <content select="h2"></content>

    <core-icon-button
      id="favicon"
      icon="favorite"
      on-tap="{{favoriteTapped}}"></core-icon-button>
    <content></content>
  </template>

</polymer-element>

Pardon the code, I am just learning web development, the  tab in the paper-tabs, has the favorite attribute name.
Thank you so much.
Joseph Nicholas R. Alcantara


text:
Q: Can I mix dual and triple channel ram? My motherboard has 6 memory slots, when I first built it I used 3x2gb sticks of DDR3 memory - which was plenty at the time.
However, now that its time to upgrade, it is much cheaper to buy a second pair of 2x4gb memory sticks. Can I have 3x2gb and 2x4gb memory on my motherboard? Will this cause performance issues?


text:
Q: how can I get good binary image using Otsu method for this image? here is my image
a.png
for binarization I try this code.
im=rgb2gray(I);
maxp=uint16(max(max(im)));
minp=uint16(min(min(im)));
bw=im2bw(im,(double(minp+maxp))/(1.42*255));
bw=~bw;
imm=bw;

but I need binarization by otsu.how can I get good binary output  using otsu method?
plz help
thanks

A: MATLAB has its own implementation of Otsu thresholding called multithresh. In your case the code to obtain the segmented image should be something like this:
im=rgb2gray(I); % convert image to grayscale
thresh = multithresh(im); % find one threshold (using Otsu method)

segmented_im = imquantize(im, thresh); % segment image
imagesc(segmented_im); % show segmented image

I haven't tested it so I don't know how well it would perform on your image.
EDIT:
I tested it, and it doesn't work as expected. One of the problems is that Otsu's method works well when there is a clear bimodal distribution of the pixel intensities. This bimodality is lacking in your image. A call to imhist(im) after the grayscale conversion leads to this (comments added by me):

As you can see, the distribution is almost trimodal, and the threshold selected by multithresh is the first one, while you want the second one. The first workaround that comes to my mind (especially if all the images in your dataset are similar to the one you posted, i.e. have a similar intensity distribution) is to make multithresh output two thresholds, and then selecting the last (highest) one:
thresholds = multithresh(im, 2);
thresh = thresholds(end);

Then proceed with the segmentation of the image as stated above. This second method leads to this segmentation:

EDIT 2 (putting it all together):
Indeed the output segmented_im is not a binary image, but a label image. It's easy enough to convert it to a binary image. I will include directly all the code in this next snippet:
im=rgb2gray(I); % convert image to grayscale
thresholds = multithresh(im, 2); % find two thresholds using Otsu
thresh = thresholds(end); % select larger one

segmented_im = imquantize(im, thresh); % segment image

segmented_im(segmented_im == 1) = 0; % make background black (0)
segmented_im(segmented_im == 2) = 255; % make foreground white (255)

binary_im = im2bw(segmented_im); % make binary (logical) image

imshow(binary_im); % show binary image

binary_im il a logical matrix with false (0) for background, and true (1) for foreground. segmented_im is a double matrix with 0 for background and 255 for foreground. I hope this serves your purposes!


text:
Q: Unable to get values from switch statement to push in to an array I've spent hours trying to figure out this exercise and stuck at this point.  I'm unable to get values from my switch statement to push to an array for "displayVal", and "val" variables.
const getDeck = () => {
  const suits = ['Spades','Hearts','Diamonds','Clubs'];
  let cards = [];

  for(let s=0; s < suits.length; s++){

   for(let d = 0; d < 13; d++){
    let displayVal;
    let val;

     switch (d) {
      case (d === 1):
        displayVal = "Ace";
        val = 11;
        break;
      case (d >=2 && d <= 10):
         displayVal = d;
         val = d;
         break;
        case (d === 11):
          displayVal = "Jack"
          val = 10;
          break;
        case (d === 12):
          displayVal = "Queen"
          val = 10;
          break;
        case (d === 13):
          displayVal = "King"
          val = 10;
     }
    cards.push({
    val,
    displayVal,
    suit: suits[s]
  } );

   }

 }
 return cards;
}

const deck = getDeck();
console.log(`Deck length equals 52? ${deck.length === 52}`);

A: Using Branch if-else
Actually, you are using conditions so go ahead with branched if-else
const getDeck = () => {
      const suits = ["Spades", "Hearts", "Diamonds", "Clubs"];
      let cards = [];

      for (let s = 0; s < suits.length; s++) {
        for (let d = 0; d < 13; d++) {
          let displayVal;
          let val;

          if (d === 1) {
            displayVal = "Ace";
            val = 11;
          } else if (d >= 2 && d <= 10) {
            displayVal = d;
            val = d;
          } else if (d === 11) {
            displayVal = "Jack";
            val = 10;
          } else if (d === 12) {
            displayVal = "Queen";
            val = 10;
          } else if (d === 13) {
            displayVal = "King";
            val = 10;
          } else {
            displayVal = "";
            val = 0;
          }
          cards.push({
            val,
            displayVal,
            suit: suits[s],
          });
        }
      }
      return cards;
    };

    const deck = getDeck();
    console.log(deck);
    console.log(`Deck length equals 52? ${deck.length === 52}`);

Using Switch case
const getDeck = () => {
    const suits = ['Spades','Hearts','Diamonds','Clubs'];
    let cards = [];

    for(let s=0; s < suits.length; s++){

     for(let d = 0; d < 13; d++){
      let displayVal;
      let val;

       switch (true) {
        case (d === 1):
          displayVal = "Ace";
          val = 11;
          break;
        case (d >=2 && d <= 10):
           displayVal = d;
           val = d;
           break;
          case (d === 11):
            displayVal = "Jack"
            val = 10;
            break;
          case (d === 12):
            displayVal = "Queen"
            val = 10;
            break;
          case (d === 13):
            displayVal = "King"
            val = 10;
          default:
            displayVal =""
            val =0
       }
      cards.push({
      val,
      displayVal,
      suit: suits[s]
    } );

     }

   }
   return cards;
  }

  const deck = getDeck();
  console.log(deck);
  console.log(`Deck length equals 52? ${deck.length === 52}`);

A: There is an alternative way / approach that may be used here.
Code Snippet

const getDeck = () => {
  const suits = ['Spades','Hearts','Diamonds','Clubs'];
  const getValueOf = x => x === 1 ? 11 : x > 10 ? 10 : x;
  const displayValMap = {1: 'Ace', 11: 'Jack', 12: 'Queen', 13: 'King'};
  return suits.map(
    suit => (
      [
        ...Array(13)
        .keys()
      ]
      .map(x => x + 1)
      .map(d => ({
        val: getValueOf(d),
        displayVal: d in displayValMap
          ? displayValMap[d]
          : d,
        suit
      }))
    )
  ).flat();
}

const deck = getDeck();
console.log(`Deck length equals 52? ${deck.length === 52}`);
console.log(deck);

Explanation

*

*Set-up ways to get val and displayVal (in above snippet, getValueOf - a one-line method; and displayValMap an object, is used)

*Iterate through the suits

*Use ... spread-operator to generate an array of length 13, then get the keys of the array.

*Use .map to make the generated array start from 1, instead of 0

*For each element in the array, create an object with val, displayVal and suit props

*And, finally, use .flat() to return all objects into a single array instead of nested-arrays.

Another way may be:

const getDeck = () => ['Spades','Hearts','Diamonds','Clubs'].map(
    suit => (
      [
        ...Array(13)
        .keys()
      ]
      .map(d => ({
        val: (d === 0 ? 10 : d > 9 ? 9 : d) + 1,
        displayVal: {0: 'Ace', 10: 'Jack', 11: 'Queen', 12: 'King'}[d] || d + 1,
        suit
      }))
    )
).flat();

console.log(getDeck().length);
console.log(getDeck());


text:
Q: Iterate data to new rows with line break in SAS I have multiple lines of data in one field that I need to iterate out to their own rows. The issue is I do not have a traditional delimiter- they are only separated by line breaks. I have tried to use
xp = prxchange('s/[\r+\n]/>/',-1,x) combined with scan, but the prxchange function is not working through the whole block of text. prxchange is only recognizing the first line break and removing the rest of the data. Any idea how to fix or different approaches?

A: Just use SCAN() to parse the string. No need for the slower speed or complexity of regular expressions.
data want;
  set have;
  do row=1 to countw(x,'0D0A'x);
    line=scan(x,row,'0D0A'x);
    output;
  end;
run;


text:
Q: CMS to develop an aggregator of posts I would like to know if there is a CMS where users sign up and create posts (with text, images and videos) and then these posts are displayed on the main page of the website. Posts can be voted. Posts can also be filtered by most voted, most recent and by tag name. Basically, it will be like the Stack Overflow website but instead of questions, users post a topic.
If such a CMS does not exists, what options are available to develop one in terms of existing CMS/templates/themes that I can customize or otherwise?

A: There is some alternatives to go on with. I would go with a PHP one since it's more widespread but they should all do the job. Here's 2 of them:
http://www.osqa.net/
http://www.lampcms.com/
You can find more by doing a Google search with the keywords "Q&A Platform".


text:
Q: Open apps using node.js spawn I'm trying to do a little application with node.js that would run on mac and execute some commands.
I've successfully used spawn to run command lines such as xcodebuild, but xcrun doesn't seems to work when I try to open the iOS Simulator.
I can open on terminal by typing:
xcrun instruments -w 'iPhone 5s (9.2)' -t <template>

But if I use node and try to use spawn like this:
var args = ['instruments', '-w', `iPhone 5s (9.2)`, '-t', 'noTemp'];
var xcrun = spawn('xcrun', args);

So it got me thinking that maybe it had some limitation opening apps? I tried to run:
var args = ['/Applications/Spotify.app'];
var xcrun = spawn('open', args);

And nothing happens. I couldn't find anything related to that. My question is: is there anyway to open apps using node.js spawn? If there is, does someone know what's the problem with my code?
Here's the full code if needed:
var args = ['instruments', '-w', `${fullDevice}`, '-t', 'noTemp'];
var xcrun = spawn('xcrun', args);

xcrun.stdout.on('data', (data)=>{
    console.log(data.toString('utf8'));
})

xcrun.on('close', (code) => {
    socket.emit({
        time: commands.getCurrentTime(),
        type: 'success',
        log: 'Device booted...'
    });
    callback();
    if (code !== 0) {
        console.log(`open process exited with code ${code}`);
    }
});

OBS: if I run this piece of code the application doesn't terminate, the program doesn't continue and nothing happens.
EDIT: Changed:
xcrun.on('data', (data)=>{

To:
xcrun.stdout.on('data', (data)=>{

A: Spawned processes have two separate streams for stdout and stderr, so you will need to listen for data on those objects and not the spawned process object itself:
xcrun.stdout.on('data', function(data) {
  console.log('stdout: ' + data.toString());
});
xcrun.stderr.on('data', function(data) {
  console.log('stderr: ' + data.toString());
});

A: The problem was one line above. Not sure why, but there's a socket.emit call that is wrong and actually hold the program's execution.


text:
Q: Git: Give access to the master without access to the commit history We have our own Git server and want from now to involve external parties in the development of one of our library.
We'd like to have only one repo, keep the commit history private and enable both internal team and external team to work on the same repo.
In Git, how to give access to the current "master" of this library for external parties without access to the commit history (previous versions) which may contain some sensitive data?


text:
Q: Webwork actions, the lifecycle of variables declared in the action class I'm using the webwork framework (JIRA plugin development) and was wondering about the lifecycle of the variables in the action class.
I have a few private variables in the action class that are set when during the doDefault() method.
These are used in the input view to set up jqGrid columns and then when the user has entered some data they click submit which puts the grid data into a hidden input.
The next thing that happens is the doValidation() method is called before the doExecute(), which displays the input view if there are any errors.
The problem is that the variables set up in the doDefault() method are now null.
Can anyone explain to me how the lifecycle of variables works in the webwork actions?
Cheers

A: The action is not stored between invocations.  You'll need to perform those calculations again or store them somewhere (in the page or in the session).
Basic lifecycle:
Browser requests page -> action created -> action returns result -> result page returned to browser

A: For more JIRA-specific information and examples, take a look at the Webwork sample at https://plugins.atlassian.com/plugin/details/17189
"This plugin is a collection of working samples demonstrating how JIRA web pages are generated using JSP, Webwork1 and Velocity template files. Note: this plugin requires you to download the source and build it yourself."
I'm the author of the plugin.
~Matt


text:
Q: Can you pick and choose what gets inherited in a sub-class in Swift? I have a base class (Spaceship) that has some variables and an initializer.
I also have a subclass (UFO) that only needs one of the variables of the superclass.
When I try and create a basic UFO object, I get: "missing argument for parameter 'weapon' in call var c = UFO()"
I realize that error message is asking for a weapon parameter, but how do I (and is it even possible?) to create a basic UFO object that doesn't need a weapon parameter?
Have spent hours tinkering with "override", "init" and "super" commands. I've read a lot of the articles here on SO and other sites, but have not seen any examples similar to my situation. Again, I'm assuming that what I want to do is possible to begin with.
class Spaceship {

    var isUFO = false
    var weapon:String

     init(weapon:String) {
         self.weapon = weapon
     }

    func printSomething() {
     print("Test")
    }
}

class UFO: Spaceship {
}

var a = Spaceship(weapon:"Laser")
a.printSomething() //OUTPUT: Test

var b = UFO(weapon:"")
          //This runs, but I don't want to have to fill in parameters
b.printSomething()    //OUTPUT: Test

var c = UFO()       //Ultimately this is what I want to do
c.printSomething()
       //OUTPUT: missing argument for parameter 'weapon' in call var c =    UFO()

A: What you can do is mark weapon as optional String. Also, in init(weapon:) use default value of weapon as nil, i.e
class Spaceship {
    var isUFO = false
    var weapon: String? //here...

    init(weapon: String? = nil) { //here...
        self.weapon = weapon
    }

    func printSomething() {
        print("Test")
    }
}

Now, you can simply create the object of class UFO both with and without weapon, i.e.
var a = Spaceship(weapon:"Laser")
var b = UFO(weapon:"Another Weapon")
var c = UFO()

A: First, when using inheritence, you'll have to think about an "is a" relationship: An UFO is a spaceship. So when each spaceship has a weapon, and an UFO is a spaceship, then every UFO also has to have a weapon.
What you could do is make your weapon an optional, but I think this is somehow a mis-usage. Also, re-think your isUFO property:

*

*A spaceship should not make assumptions about special subclasses

*You could use the is operator to check the dynamic type of a Spacehip
If you don't want this inheritence behaviour, you might better think about something else, like protocols, where you only specify certain behaviour but no memory layout.


text:
Q: Streaming large video files .net I am trying to stream a large file in webforms from an HttpHandler. It doesn't seem to work because its not streaming the file. Instead its reading the file into memory then sends it back to the client. I look all over for a solution and the solution are telling me that they stream the file when they are doing the same thing. My solution that stream is this:
using (Stream fileStream = File.OpenRead(path))
{
    context.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(360.0));
    context.Response.Cache.SetCacheability(HttpCacheability.Public);
    context.Response.AppendHeader("Content-Type", "video/mp4");
    context.Response.AppendHeader("content-length", file.Length);
    byte[] buffer = new byte[1024];
    while (true)
    {
      if (context.Response.IsClientConnected)
     {
       int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
       if (bytesRead == 0) break;
       context.Response.OutputStream.Write(buffer, 0, bytesRead);
       context.Response.Flush();
     }
     else
     {
       break;
     }

   }
   context.Response.End();
}

What is happening is for small files if I debug the code, it will play the video but not until it reaches the context.Respond.End() line. But for large files this will not work because it is storing the whole file in memory which will bring issues.

A: What really matters here is the 'Range' header. Although the existing answer is correct, it contains no explanation.
When you make a request without specifying a range, the whole entire file is streamed. Video players automatically specify the 'range' header with a starting byte that is in accordance with the players position in the video.
Since this is inherently part of HTTP, it's extremely well documented in RFC 7233.
The 'Accept-Range: bytes' header tells the client that we want to accept the range header as byte counts. The status code '206' tells the client that we sent partial content, aka only a piece of the whole file. The 'Content-Range: start-end/total' header tells the client the range of the information that we're sending back in the current request.
Here is a fully functional snippet:
public static void RespondFile(this HttpListenerContext context, string path, bool download = false) {

    HttpListenerResponse response = context.Response;

    // tell the browser to specify the range in bytes
    response.AddHeader("Accept-Ranges", "bytes");

    response.ContentType = GetMimeType(path);
    response.SendChunked = false;

    // open stream to file we're sending to client
    using(FileStream fs = File.OpenRead(path)) {

        // format: bytes=[start]-[end]
        // documentation: https://www.rfc-editor.org/rfc/rfc7233#section-4
        string range = context.Request.Headers["Range"];
        long bytes_start = 0,
        bytes_end = fs.Length;
        if (range != null) {
            string[] range_info = context.Request.Headers["Range"].Split(new char[] { '=', '-' });
            bytes_start = Convert.ToInt64(range_info[1]);
            if (!string.IsNullOrEmpty(range_info[2]))
                bytes_end = Convert.ToInt64(range_info[2]);
            response.StatusCode = 206;
            response.AddHeader("Content-Range", string.Format("bytes {0}-{1}/{2}", bytes_start, bytes_end - 1, fs.Length));
        }

        // determine how many bytes we'll be sending to the client in total
        response.ContentLength64 = bytes_end - bytes_start;

        // go to the starting point of the response
        fs.Seek(bytes_start, SeekOrigin.Begin);

        // setting this header tells the browser to download the file
        if (download)
            response.AddHeader("content-disposition", "attachment; filename=" + Path.GetFileName(path));

        // stream video to client
        // note: closed connection during transfer throws exception
        byte[] buffer = new byte[HttpServer.BUFFER_SIZE];
        int bytes_read = 0;
        try {

            while (fs.Position < bytes_end) {
                bytes_read = fs.Read(buffer, 0, buffer.Length);
                response.OutputStream.Write(buffer, 0, bytes_read);
            }

            response.OutputStream.Close();

        } catch(Exception) {}

    }

}

Note that we can simply check the file stream's "Position" (in bytes) rather than keeping track of how many bytes we've already sent in total.

A: I had a similar issue, where the video had to be downloaded completely before playing.
I can see you want to stream videos, to be more specific.
You have to be careful about the encoding (make sure it is streamable), don't rely on the extension only, because the person who created the file could have build the video in a wierd way, but 99% of the time you should be good. I use mediainfo.
In your case should be  H.264.
It also depends on browser and what you use to stream (other than backend code). For my case, I used Chrome/Html5 and .webm (VP8/Ogg Vorbis). It is working for files over 1G. Didn't test for bigger than 4G...
The code I use for download of the video:
    public void Video(string folder, string name) {
        string filepath = Server.MapPath(String.Format("{0}{1}", HttpUtility.UrlDecode(folder), name));
        string filename = name;

        System.IO.Stream iStream = null;
        byte[] buffer = new Byte[4096];
        int length;
        long dataToRead;

        try {
            // Open the file.
            iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
                        System.IO.FileAccess.Read, System.IO.FileShare.Read);

            // Total bytes to read:
            dataToRead = iStream.Length;

            Response.AddHeader("Accept-Ranges", "bytes");
            Response.ContentType = MimeType.GetMIMEType(name);

            int startbyte = 0;

            if (!String.IsNullOrEmpty(Request.Headers["Range"])) {
                string[] range = Request.Headers["Range"].Split(new char[] { '=', '-' });
                startbyte = Int32.Parse(range[1]);
                iStream.Seek(startbyte, SeekOrigin.Begin);

                Response.StatusCode = 206;
                Response.AddHeader("Content-Range", String.Format(" bytes {0}-{1}/{2}", startbyte, dataToRead - 1, dataToRead));
            }

            while (dataToRead > 0) {
                // Verify that the client is connected.
                if (Response.IsClientConnected) {
                    // Read the data in buffer.
                    length = iStream.Read(buffer, 0, buffer.Length);

                    // Write the data to the current output stream.
                    Response.OutputStream.Write(buffer, 0, buffer.Length);
                    // Flush the data to the HTML output.
                    Response.Flush();

                    buffer = new Byte[buffer.Length];
                    dataToRead = dataToRead - buffer.Length;
                } else {
                    //prevent infinite loop if user disconnects
                    dataToRead = -1;
                }
            }
        } catch (Exception ex) {
            // Trap the error, if any.
            Response.Write("Error : " + ex.Message);
        } finally {
            if (iStream != null) {
                //Close the file.
                iStream.Close();
            }
            Response.Close();
        }
    }

Make sure your response header contains everything you need.

A: Maxad's answer is the perfect answer .I also made some changes for .Net Core version:
<video id="myvideo" height="400" width="600" controls>
    <source src="../api/StreamApi/GetStream" type="video/mp4"/>
</video>

    [Route("api/StreamApi/GetStream")]
    [HttpGet]
    public async Task GetStream()
    {
        string filepath = @"C:\temp\car.mp4";
        string filename = Path.GetFileName(filepath);

        System.IO.Stream iStream = null;
        byte[] buffer = new Byte[4096];
        int length;
        long dataToRead;

        try
        {
            // Open the file.
            iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
                        System.IO.FileAccess.Read, System.IO.FileShare.Read);

            // Total bytes to read:
            dataToRead = iStream.Length;

            Response.Headers["Accept-Ranges"] = "bytes";
            Response.ContentType = "application/octet-stream";

            int startbyte = 0;

            if (!String.IsNullOrEmpty(Request.Headers["Range"]))
            {
                string[] range = Request.Headers["Range"].ToString().Split(new char[] { '=', '-' });
                startbyte = Int32.Parse(range[1]);
                iStream.Seek(startbyte, SeekOrigin.Begin);

                Response.StatusCode = 206;
                Response.Headers["Content-Range"] = String.Format(" bytes {0}-{1}/{2}", startbyte, dataToRead - 1, dataToRead);
            }
            var outputStream = this.Response.Body;
            while (dataToRead > 0)
            {
                // Verify that the client is connected.
                if (HttpContext.RequestAborted.IsCancellationRequested == false)
                {
                    // Read the data in buffer.
                    length = await iStream.ReadAsync(buffer, 0, buffer.Length);

                    // Write the data to the current output stream.
                    await outputStream.WriteAsync(buffer, 0, buffer.Length);
                    // Flush the data to the HTML output.
                    outputStream.Flush();

                    buffer = new Byte[buffer.Length];
                    dataToRead = dataToRead - buffer.Length;
                }
                else
                {
                    //prevent infinite loop if user disconnects
                    dataToRead = -1;
                }
            }
        }
        catch (Exception ex)
        {
            // Trap the error, if any.

        }
        finally
        {
            if (iStream != null)
            {
                //Close the file.
                iStream.Close();
            }
            Response.Clear();
        }
    }


text:
Q: check when the array has finished shuffling to do some operation I am using array.shuffle() to reorder the content of an array randomly, I want to check when the array has finished shuffling to do some operations because I found that when I just put the code after array.shuffle() the array didn't finish shuffling and the code was fired. thank you for your help!

A: You don't need to wait or something as the method shuffle is synchronous , which means next line will run after it finishes shuffling
var arr = ["1","2","3"]
arr.shuffle()
print(arr) // ["2", "1", "3"]


text:
Q: warning: implicitly reading from a sync is deprecated; apply a '.read??()' method I just upgraded from chapel 1.23 to 1.24. Now the compiler screams at me;

warning: implicitly reading from a sync is deprecated; apply a
'.read??()' method

For example. the code block below lists this warning at the last line.
var allStatesLock$: sync bool;
allStatesLock$.writeXF(true);
allStatesLock$;

.read??() does not seam to be a method in chapel 1.24.

A: @ahysing: Sorry for the confusion caused by this error message.  As @Noah correctly mentions in the comments, the ?? here is meant to be a placeholder for various options like FE, FF, or XX.
In Chapel 1.24.0, implicit accesses to synchronization variables were deprecated for reasons documented in the Chapel 1.23.0 release notes (starting on slide 6 of the Ongoing Efforts deck).  Replacing implicit reads with .readFE() and implicit writes with .writeEF(val) should keep your code working without warnings.


text:
Q: CSS: Set max-height to same value as height becomes when "none" max-height? So I am making a dropdown that uses transition of max-height and opacity, for example if the dropdown was 500 pixels in height, I would use 500px for max-height when open, and 0 when closed. However, my dropdown's height is auto calculated. I need to set max-height to this auto calculated height, so that the transition has correct timin. Otherwise, if I used a larger max-height value, when being closed the dropdown would not move until max-height had transitioned below the true value, and then suddenly move faster for the remaining time. Any way to do this?

A: So I found a solution. I just set the maxHeight to the offsetHeight before triggering closing of my dropdown.
I also needed to use setTimeout of 0 milliseconds for triggering closing it though after running the below function.
export function retreatDropdown(e: HTMLElement) {
  e.style.maxHeight = `${e.offsetHeight}px`;
}

I could do a similar trick for opening animation, but you won't know the correct maxHeight until it is opened, so my guess this is more tricky (but less important than closing animation IMO).
EDIT: Complete (TypeScript) solution for both closing/opening dropdown
const defaultTransitionTime = 200;

export function toggleDropdown(
  e: HTMLElement,
  value: boolean = null,
  toggleAction: () => void = null // Function that toggles true/false for accordion open
) {
  if (value) {
    openDropdown(e, toggleAction);
  } else {
    retreatDropdown(e, toggleAction);
  }
}

export function openDropdown(
  e: HTMLElement,
  openAction: () => void = null
) {
  if (openAction) setTimeout(() => openAction(), 0);
  e.style.display = "block";
  setTimeout(() => {
    const offsetHeight = e.offsetHeight;
    e.style.maxHeight = "0px";
    setTimeout(() => {
      e.style.maxHeight = `${offsetHeight}px`;
    }, 5);
  }, 5);
  setTimeout(() => {
    e.style.maxHeight = "none";
  }, defaultTransitionTime);
}

export function retreatDropdown(
  e: HTMLElement,
  closeAction: () => void = null
) {
  e.style.maxHeight = `${e.offsetHeight}px`;
  if (closeAction) setTimeout(() => closeAction(), 0);
}

Dropdown CSS class:
.dropdown {
  transition: opacity 200ms linear, max-height 200ms linear;
  will-change: opacity, max-height;
}

Angular ngStyle (applied on open/close of accordion):
elementStyle(e: HTMLElement) {
    return this.isOpen(HTMLElement) // I use a map of booleans for open state here...
      ? { display: "block", "max-height": "none" }
      : { "max-height": 0, opacity: 0 };
  }


text:
Q: Do I need an object within an object in java? Need to keep track of multiple things in array. Alright well I have one method that gets the name and wage of a worker..
in my class definition I have where it creates an object whether they input nothing, a name, or a name and wage.
So then for each worker I need to ask for tips (which there can be multiple clients who tip). I have this in another method and I prompt for the tip but I'm not sure how to only add the tips to the specific worker.. ie. when I run the program, the output is correct for this first worker (salary, tips, avg tips) and if I add another worker the tips are wrong because it is not separated, rather it is continuing to add all the tips from each worker
private static void addWorker(){

    name = JOptionPane.showInputDialog("Name?");
    wage = Double.parseDouble(JOptionPane.showInputDialog(null,"Wage?"));

    worker object = new worker(name, wage);
    workerArray[count] = object;

    addWorkerTip();

    count++;
}

private static void addWorkerTip(){
    do{
            tip = Double.parseDouble(JOptionPane.showInputDialog(null,"tip?"));

                            numTips++;
                totalWorkerTips = tip + totalWorkerTips;
            worker.addTips(totalWorkerTips);

    }while (JOptionPane.showConfirmDialog(null,"Another Worker?") == JOptionPane.YES_OPTION);
}

A: Try to reset tip back to 0 at the end of the do loop so it can accept a new value without adding the previous value.
tip = 0;

or you could create a tip array and store each tip value in the array

A: You should make a class called worker with proper instance variables.
public class Worker{
private String name;
private double wage;
private double tip;

public Worker(){
name=null;
wage=null;
tip=0;
}

public Worker(String n){
name=n;
tip=0;
}

public Worker(String n, double w){
name = n;
wage = w;
tip=0;
}

public void setWage(double newWage){
wage = newWage;
}

public void addTip(double newTip){
tip+=newTip;
}
}

A: Here is how I would approach your class structure,
private static class Worker {
  private String name;
  private double wage;
  private double tip = 0;

  Worker(String name, double wage) {
    this.name = name;
    this.wage = wage;
  }
  public String getName() {
    return name;
  }
  public double getWage() {
    return wage;
  }

  public void addTip(double tip) {
    this.tip += tip;
  }
  public double getTipe() {
    return this.tip;
  }
}

// Use a Collection of Worker(s) - not an array.
private List<Worker> workers = new ArrayList<Worker>();

public void addWorker() {
  String name = JOptionPane.showInputDialog("Name?");
  double wage = Double.parseDouble(JOptionPane
      .showInputDialog(null, "Wage?"));

  Worker worker = new Worker(name, wage);
  double tip = Double.parseDouble(JOptionPane
      .showInputDialog(null, "tip?"));
  worker.addTip(tip);
  workers.add(worker); // Add the worker to the List.
}


text:
Q: VSTO Outlook: Custom Task Pane height Why the custom task pane height is set in points?
What do points mean? If I want to set the custom pane height to work with all the display resolutions, how do I need to set this? using some kind of formula? For example I set as below in a screen resolution of 3024x1890 and it is shown correctly:
ctp.Height = 160;

However when I visualize it in a screen resolution of 1920x1080 the custom task pane is not shown correctly, I mean, height is bigger that the one in 3024x1890.

A: Pixels and points are static measurements - they don't change based on other factors: 1 pixel is always 1 pixel and is the smallest piece of a screen that can display colors. 1 point is always 1 point and is an abstract unit, only having meaning when referenced in relation to other points.
You need to set up the AutoScaleMode of the UserForm to the Dpi which specifies the different types of automatic scaling modes supported by Windows Forms. Then you can try to use dock and anchor properties to auto resize and adjust controls. That may work only for standalone applications and not in Outlook (depends on Outlook version). So, additionally you need to detect the DPI level and set up the UI accordingly.
Take a look at the following pages for more information about scaling in Windows:

*

*Windows Forms DPI scaling

*Creating a DPI-Aware Application

*Automatic scaling in Windows Forms


text:
Q: Windows Phone 8.1 receive SMS event My simple program must be working in the background and react to an event receiving SMS. Can it be done on this platform? I did not find any useful information before.

A: There is something called SmsReceived trigger but I think it's only for operator apps.
So unless you work on an app for a mobile operator, it's not possible.


text:
Q: Getting java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer) I am new to android.
I am getting an error while updating through HttpClient like  java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)
public static String newupdateProf(String memid, String gender,
                String pdata, String dob, String pimg) throws IOException,
                JSONException {
            // System.setProperty("http.keepAlive", "false");
            final HttpClient httpClient = new DefaultHttpClient();
            final HttpPost httpost = new HttpPost(websrv.trim() + "/newUpdtProf");

            JSONStringer img = new JSONStringer().object().key("prof").object()
                    .key("memid").value(memid.trim()).key("gender")
                    .value(gender.trim()).key("pdata").value(pdata.trim())
                    .key("dob").value(dob.trim()).key("pimg").value(pimg.trim())
                    .endObject().endObject();
            StringEntity se = new StringEntity(img.toString());
            httpost.setEntity(se);
            httpost.setHeader("Accept", "application/json");
            httpost.setHeader("Content-type", "application/json");

            HttpResponse httpResponse = httpClient.execute(httpost);

            HttpEntity httpEntity = httpResponse.getEntity();

            InputStream stream = httpEntity.getContent();
            String result = convertStreamToString(stream);
            return result.trim();

        }

Please help me.
I also tried
System.setProperty("http.keepAlive", "false");

but it's not working.

A: Set the http.keepAlive system property to false before issuing any HTTP requests.
System.setProperty("http.keepAlive", "false");


text:
Q: Private prerender server wont render angularjs scripts? I want to create prerendered pages for search engines. I am using MEAN stack (Mongo,Express,Angular,Node). I decided to create my own prerender server.
I have deployed it to Heroku with following commands:
$ git clone https://github.com/prerender/prerender.git
$ heroku create
$ git push heroku master

And now I have my own prerender server, that work if you add /https://www.google.com or /http://stackoverflow.com.
But it doesn't work with my angular app, that is also deployed on heroku.
I can write http://mysites.com/?_escaped_fragment_=thinkpad/t-400
And get bunch of {{not rendered angular}}
I have <meta name="fragment" content="!"> in my index.html.
I have
app.use(require('prerender-node').set('prerenderServiceUrl', 'prerender-server-url'));

in my express.js.
How can I make it work?

A: Verify that you are not using newer ES6 features that are supported by the browsers, but not yet supported by prerender JS engine.


text:
Q: How do I replace several values of a column in a data frame? I have a data frame with several columns, here is an example of one of the columns:
df <- data.frame(x=1:3)
The number 1 stands for "Yes", 2 stands for "No" and 3 stands for "Maybe".
One solution that I came up with was to change the class of the variable and then used:
df$x <- replace(df$x, "1", "Yes") and repeat it for the "No" and "Maybe".
However one of the columns have 27 different values that stands for 27 different words, the code would be too big doing by this way.
Any ideas of how to replace the numbers by the words efficiently?

A: You could use mapvalues() from plyr:
library(plyr)
x <- c("a", "b", "c")
mapvalues(x, c("a", "c"), c("A", "C"))

[1] "A" "b" "C"

In your case,
df <- data.frame(x=1:3)
mapvalues(df$x, c(1,3,2), c("Yes","Maybe","No"))

[1] "Yes"   "No"    "Maybe"

Since plyr is retired, you can do it without calling the package using the following (copied straight from body(mapvalues)).
my_mapvalues <- function(x, from, to, warn_missing = TRUE) {
    if (length(from) != length(to)) {
        stop("`from` and `to` vectors are not the same length.")
    }
    if (!is.atomic(x)) {
        stop("`x` must be an atomic vector.")
    }
    if (is.factor(x)) {
        levels(x) <- mapvalues(levels(x), from, to, warn_missing)
        return(x)
    }
    mapidx <- match(x, from)
    mapidxNA <- is.na(mapidx)
    from_found <- sort(unique(mapidx))
    if (warn_missing && length(from_found) != length(from)) {
        message("The following `from` values were not present in `x`: ",
            paste(from[!(1:length(from) %in% from_found)], collapse = ", "))
    }
    x[!mapidxNA] <- to[mapidx[!mapidxNA]]
    x
}