How to get progressbar start() info from one window (class) to other?

Question: There is a main window with menu and the progressbar. A correspondence window with OK button opens upon menu command and the OK button starts the process (here: 3 sec. sleep).
The correspondence window is created via inheritance from a class I have not provided here (If required for answer, please let me know). The methods apply and ok override existing methods in the mother class.
Now my problem: Since the progressbar sits in the main window (class App) and progressbar(start) and progressbar(stop) in the correspondence window I somehow have to pass (start) and (stop) via the mother class tkSimpleDialog.Dialog to class App. So I thought I also override the __init__(self..) method, provide self. to progressbar.
How can I make this work?
import Tkinter, ttk, tkFileDialog, tkSimpleDialog, time, threading

class App:
  def __init__(self, master, progressbar):
    self.progress_line(master)

  def progress_line (self, master):
    self.progressbar = ttk.Progressbar(master, mode='indeterminate')
    self.progressbar.place(anchor = 'ne', height = "20", width = "150", x = "175", y = "30")

class AppMenu(object):

  def __init__(self, master, progressbar):
    self.master = master
    self.menu_bar()

  def menu_bar(self):
    menu_bar = Tkinter.Menu(self.master)
    self.menu_bar = Tkinter.Menu(self.master)
    self.master.config(menu=self.menu_bar)
    self.create_menu = Tkinter.Menu(self.menu_bar, tearoff = False)
    self.create_menu.add_command(label = "do", command = self.do)
    self.menu_bar.add_cascade(label = "now", menu = self.create_menu)

  def do(self):
    do1 = Dialog(self.master, progressbar)

class Dialog(tkSimpleDialog.Dialog):

  def __init__(self, parent, progressbar):

    tkSimpleDialog.Dialog.__init__(self, parent, progressbar)
    self.transient(parent)

    self.parent = parent
    self.result = None

    self.progressbar = progressbar

    body = Frame(self)
    self.initial_focus = self.body(body)
    body.pack(padx=5, pady=5)

    self.buttonbox()
    self.grab_set()

    if not self.initial_focus:
        self.initial_focus = self

    self.protocol("WM_DELETE_WINDOW", self.cancel)
    self.geometry("+%d+%d" % (parent.winfo_rootx()+50, parent.winfo_rooty()+50))
    self.initial_focus.focus_set()
    self.wait_window(self)

  def ok(self, event=None):
    self.withdraw()
    self.start_foo_thread()
    self.cancel()
  def apply(self):
    time.sleep(5)

  def start_foo_thread(self):
    global foo_thread
    self.foo_thread = threading.Thread(target=self.apply)
    self.foo_thread.daemon = True
    self.progressbar.start()
    self.foo_thread.start()
    master.after(20, check_foo_thread)

  def check_foo_thread(self):
    if self.foo_thread.is_alive():
        root.after(20, self.check_foo_thread)
    else:
        self.progressbar.stop()

master = Tkinter.Tk()
progressbar = None
app = App(master, progressbar)
appmenu = AppMenu(master, progressbar)
master.mainloop()

error messages:
first after clicking ok:
Exception in Tkinter callback
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1410, in __call__
  File "ask-progressbar.py", line 57, in ok
    self.start_foo_thread()
  File "ask-progressbar.py", line 66, in start_foo_thread
    self.progressbar.start()
AttributeError: Dialog2 instance has no attribute 'progressbar'

second: after closing app
Exception in Tkinter callback
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1410, in __call__
  File "ask-progressbar.py", line 26, in do
    do1 = Dialog2(self.master, progressbar)
  File "ask-progressbar.py", line 33, in __init__
    self.transient(parent)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1652, in wm_transient
TclError: can't invoke "wm" command:  application has been destroyed

Comment: Please include more than just the error message you're getting -- the whole Traceback with the offending line would be helpful.
Comment: It's not the problem you're specifically asking about, but you shouldn't be calling `self.foo_thread.start()` followed then by `self.apply()`, because the latter will happen when the first is called since it was given as the `target` the `Thread` instance was created.
Comment: ok, I have corrected that
Answer: Below is a working version of your code. There were a number of issues I had to fix because you didn't change a number of things in the code from my answer to your other question about progressbars.
The answer to your main question here is basically that you have to pass the instance around and remember it when necessary in the various class instances involved so that their methods will have it available through theself argument when they need it. Also, the way you were trying to derive and override the tkSimpleDialog.Dialog base class methods was both over-complicated and incorrect as well.
Usually the best (and simplest) thing to do is just supply your own validate() and apply() methods since that's how it was designed to work. If you also need your own __init__() constructor, it's important to only pass parameters to the base class' method that it understands from within the one in the subclass. If you need more functionality, it can usually be provided via additional derived-class-only methods, that only it or other classes you've also created know about.
Anyway, here's what I ended-up with:
import Tkinter, ttk, tkFileDialog, tkSimpleDialog, time, threading

class App:
    def __init__(self, master):
        self.progress_line(master)

    def progress_line(self, master):
        # the value of "maximum" determines how fast progressbar moves
        self._progressbar = ttk.Progressbar(master, mode='indeterminate',
                                            maximum=4) # speed of progressbar
        self._progressbar.place(anchor='ne', height="20", width="150",
                                x="175", y="30")
    @property
    def progressbar(self):
        return self._progressbar # return value of private member

class AppMenu(object):
  def __init__(self, master, progressbar):
      self.master = master
      self.menu_bar()
      self.progressbar = progressbar

  def menu_bar(self):
      self.menu_bar = Tkinter.Menu(self.master)
      self.master.config(menu=self.menu_bar)
      self.create_menu = Tkinter.Menu(self.menu_bar, tearoff=False)
      self.create_menu.add_command(label="do", command=self.do)
      self.menu_bar.add_cascade(label="now", menu=self.create_menu)

  def do(self):
      Dialog(self.master, self.progressbar) # display the dialog box

class Dialog(tkSimpleDialog.Dialog):
    def __init__(self, parent, progressbar):
        self.progressbar = progressbar
        tkSimpleDialog.Dialog.__init__(self, parent, title="Do foo?")

    def apply(self):
        self.start_foo_thread()

    # added dialog methods...
    def start_foo_thread(self):
        self.foo_thread = threading.Thread(target=self.foo)
        self.foo_thread.daemon = True
        self.progressbar.start()
        self.foo_thread.start()
        master.after(20, self.check_foo_thread)

    def check_foo_thread(self):
        if self.foo_thread.is_alive():
            master.after(20, self.check_foo_thread)
        else:
            self.progressbar.stop()

    def foo(self): # some time-consuming function...
        time.sleep(3)

master = Tkinter.Tk()
master.title("Foo runner")
app = App(master)
appmenu = AppMenu(master, app.progressbar)
master.mainloop()

Hope this helps.
Comment: fantastic, thanks a lot, it works. I now have to study your answer and the code you have given.
Comment: @solarisman: You're welcome, that's good to hear. I would also recommend reading (and following) PEP 8 [Style Guide for Python Code](http://www.python.org/dev/peps/pep-0008/) because it will make your code easier -- at least for others -- to read and modify ;-).
Comment: thanks for this also. i was in fact going to ask here at Stackoverflow (which I discovered a couple of days ago and find absolutely fascinating for learning) about code style..how to best..since i basically just started with programming and Python and I am uncertain about whether I go into the right direction. So I will study PEP8 thoroughly. thanks!
Comment: @martineau I tried adapting your both of your solutions to my [problem](https://stackoverflow.com/questions/57529033/how-to-run-and-update-tkinter-widgets-when-running-time-consuming-functions) but somehow it doesn't work; the UI elements only update after the prompt is completed by the user. Would you please take a look? Thank you!
Comment: @mashedpotatoes: It's most likely because you're using threading, which tkinter doesn't really support. You can create multiple threads, but only one of them — often the main thread — can interact with it and its widgets. The workaround is to use a threadsafe `Queue` to pass information between the threads. The main thread can use the universal widget [`after()`](http://web.archive.org/web/20190121045017id_/http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/universal.html) method to periodically check the queue's contents and update the GUI as necessary. I've posted several answers that do it.
Comment: I also tried your non-thread method, but I don't understand why mine doesn't work as intended. My problem is similar to this question, only that mine should run on button click, and the progress bar should pause when asking for user input, and continue after.. I'll look into your answers in the mean time, thanks!
Comment: @mashedpotatoes: Your threaded version is using `tkinter` in both the `run_foo()` thread _and_ the main thread — which is likely why it doesn't work. I am referring to both the `Progressbar` updating as well as the calling of `askdirectory()`. I think you might find the information about event-driven programming in the accepted answer to the question [Tkinter — executing functions over time](https://stackoverflow.com/questions/9342757/tkinter-executing-functions-over-time) helpful to understand.
Comment: @martineau I finally understood it, thanks, but in the end I had to use the non-threaded solution; trying to solve `tkinter` and `threading` using `Queue` brought up another problem- it doesn't play well with `tensorflow` too. The non-threaded solution is the most unintrusive way to do these in my case.
Answer: Here's another, simpler, solution that doesn't require the use of threading -- so could be easier to use/adapt in your case. It calls the progressbar widget's update_idletasks() method multiple times during the time-consuming foo() function. Again, it illustrates how to pass the progressbar around to the various parts of the code that need it.
import Tkinter, ttk, tkFileDialog, tkSimpleDialog, time

class App:
    def __init__(self, master):
        self.progress_line(master)

    def progress_line(self, master):
        self._progressbar = ttk.Progressbar(master, mode='indeterminate')
        self._progressbar.place(anchor='ne', height="20", width="150",
                                x="175", y="30")
    @property
    def progressbar(self):
        return self._progressbar # return value of private member

class AppMenu(object):
    def __init__(self, master, progressbar):
        self.master = master
        self.menu_bar()
        self.progressbar = progressbar

    def menu_bar(self):
        self.menu_bar = Tkinter.Menu(self.master)
        self.master.config(menu=self.menu_bar)
        self.create_menu = Tkinter.Menu(self.menu_bar, tearoff=False)
        self.create_menu.add_command(label="do foo", command=self.do_foo)
        self.menu_bar.add_cascade(label="now", menu=self.create_menu)

    def do_foo(self):
        confirm = ConfirmationDialog(self.master, title="Do foo?")
        self.master.update() # needed to completely remove conf dialog
        if confirm.choice:
            foo(self.progressbar)

class ConfirmationDialog(tkSimpleDialog.Dialog):
    def __init__(self, parent, title=None):
        self.choice = False
        tkSimpleDialog.Dialog.__init__(self, parent, title=title)

    def apply(self):
        self.choice = True

def foo(progressbar):
    progressbar.start()
    for _ in range(50):
        time.sleep(.1) # simulate some work
        progressbar.step(10)
        progressbar.update_idletasks()
    progressbar.stop()

master = Tkinter.Tk()
master.title("Foo runner")
app = App(master)
appmenu = AppMenu(master, app.progressbar)
master.mainloop()

Comment: to @martineau: I got my programme work now using the standard way of Threading. Thanks a lot for your help.
Comment: @solarisman: That's good news -- but why then did you change your accepted answer to this non-threading version?
Comment: to @martineau: I have corrected that. Why is the most recent answer not at the bottom? :) and why isn't (at)martineau not accepted at the beginning of this comment field? if i use something like "to" before, it works, right at the beginning it gets deleted once i hit "save"
Comment: @solarisman: I think unless there's an accepted answer, stackoverflow lists the most recent answer first. BTW, you might want to update your question and mention how you solved the problem you were having with the `self.input.get()`.
Comment: Thanks @martineau for that hint. I deleted that second question in my original post. To be honest, I can't recall what was wrong. I built everything up from scratch and then it worked.
Comment: hello @martineau, if you look at [this question](http://stackoverflow.com/questions/16531924/python-and-threading-why-does-large-list-entity-get-lost-when-accessing-from) you might think that I still have not understood threading sufficiently :(
Comment: @solarisman: Multi-threading can be tricky, especially when coupled with Tkinter. Maybe you should reconsider using it and switch to the single-threaded approach in this answer (which is the main reason I added it).


A regexp for finding enums in Delphi source files?

Question: The background is that I have a complicated memory issue in Delphi. But a theory is that an enum of 5 values can be the root of the bug. So my question to you is:
How do I write a regexpression to search sourcefiles for an enum with 5 values ?
An enum in Delphi looks like this
myEnum = (value1,value2,value3,value4,value5);

There can of course be any combination of spaces, tabs and newlines between the values.
Comment: You'll probably want to ask this on StackOverflow, and it will likely be moved there shortly.
Comment: I was not sure what forum was best. But my thought was that regexpressions is not for programmers only. It is handy to search all kinds of text. In this case it happens to be a source file for Delphi. But if the question was moved it is ok for me :)
Answer: this should give you all the lines you are searching for in your files:
perl -n -e 'if ($_ =~ m/\W*\w+\W*=\W*\(\W*\w+\W*,\W*\w+\W*,\W*\w+\W*,\W*\w+\W*,\W*\w+\W*\)\W*;/) { print $_; }'

just parse all you delphi source files through this perl one liner.
some more explanations:

\W => means non-word character
\w => means alphanumerical character including underscore
+ => at least one occurrence
* => zero or more occurrence
$_ => current line of which will be filled by -n

hope this helps.
Comment: Thanks! If I skip the perl stuff it seems to work just fine.


How to get custom input fields to show up on home page in Shopify

Question: I created a product that requires custom fields.  I went through the tutorial and I have them working on the product page.
Working Fields on Product Page

Not working fields on Featured Product
So there are two sessions.  Product-customizable-template (this is what this code is on).  When i create a product I have to select this template to be used.
The one used for the home page is a feature.  feature-product.liquid.  It clearly doesn't import any setting created on the product template.
 <form action="/cart/add" method="post" enctype="multipart/form-data" class="product-form product-form-{{ section.id }}{% unless section.settings.show_variant_labels %} product-form--hide-variant-labels{% endunless %}" data-section="{{ section.id }}">
        {% comment %}
        Custom Information
        {% endcomment %}

                Groom's First Name
                <input required type="text" id="groom_name" name="properties[groom_name]" placeholder="Groom">

                Bride's First Name
                <input required type="text" id="bride_name" name="properties[bride_name]" placeholder="Bride">

            Last Name
            <input required type="text" id="last_name" name="properties[Last Name]" placeholder="Last Name">
            Wedding Date
            <input required type="date" name="wedding_date">

            City
            <input required type="text" id="city" name="properties[City]" placeholder="City">
            State
            <input required list="state" name="state">
              <datalist id="state">
                <option value="AL">Alabama</option>
                <option value="AK">Alaska</option>
                <option value="AZ">Arizona</option>
                <option value="AR">Arkansas</option>
                <option value="CA">California</option>
                <option value="CO">Colorado</option>
                <option value="CT">Connecticut</option>
                <option value="DE">Delaware</option>
                <option value="DC">District Of Columbia</option>
                <option value="FL">Florida</option>
                <option value="GA">Georgia</option>
                <option value="HI">Hawaii</option>
                <option value="ID">Idaho</option>
                <option value="IL">Illinois</option>
                <option value="IN">Indiana</option>
                <option value="IA">Iowa</option>
                <option value="KS">Kansas</option>
                <option value="KY">Kentucky</option>
                <option value="LA">Louisiana</option>
                <option value="ME">Maine</option>
                <option value="MD">Maryland</option>
                <option value="MA">Massachusetts</option>
                <option value="MI">Michigan</option>
                <option value="MN">Minnesota</option>
                <option value="MS">Mississippi</option>
                <option value="MO">Missouri</option>
                <option value="MT">Montana</option>
                <option value="NE">Nebraska</option>
                <option value="NV">Nevada</option>
                <option value="NH">New Hampshire</option>
                <option value="NJ">New Jersey</option>
                <option value="NM">New Mexico</option>
                <option value="NY">New York</option>
                <option value="NC">North Carolina</option>
                <option value="ND">North Dakota</option>
                <option value="OH">Ohio</option>
                <option value="OK">Oklahoma</option>
                <option value="OR">Oregon</option>
                <option value="PA">Pennsylvania</option>
                <option value="RI">Rhode Island</option>
                <option value="SC">South Carolina</option>
                <option value="SD">South Dakota</option>
                <option value="TN">Tennessee</option>
                <option value="TX">Texas</option>
                <option value="UT">Utah</option>
                <option value="VT">Vermont</option>
                <option value="VA">Virginia</option>
                <option value="WA">Washington</option>
                <option value="WV">West Virginia</option>
                <option value="WI">Wisconsin</option>
                <option value="WY">Wyoming</option>
              </datalist>

What am I missing?
Comment: Please post a link to the tutorial you used - not sure what steps you have taken.
Comment: Here is the tutorial: https://help.shopify.com/themes/customization/products/get-customization-information-for-products
Answer: What you want to do is make the fields required inputs (see the steps in "Make customization form fields required") in that tutorial.  Then the customers will have to go to the Product page to add the item to their cart.


Php in_array() function doesn't work

Question: hell guys,
I have this code:
<code>$_SESSION['product'] value is(I var_dump it for you): array(2) {
[0]=>   string(51) "869-Satin bridal bouquet model "Ocean Sunset"-F0036"
[1]=>   string(47) "876-Satin Bridal bouquet model "Mexicana"-F0039"
}
$sproduct="876-Satin Bridal bouquet model "Mexicana"-F0039";
    if (in_array($sproduct, $_SESSION['product'])){
    echo 'aaaaaaaaaaaa';exit();
    }
</code>
Why it doesnt work? Is it possible this to be caused due not configured server settings? Thanks
Comment: try ````$sproduct="876-Satin Bridal bouquet model \"Mexicana\"-F0039";````
Comment: you array definition is invalid, you should get an error for that. The `(2)` does not make any sense... Same for the way you note down the keys: `[1]` is invalid... Try this instead: `$_SESSION['product'] = array {1=>"869-Satin bridal bouquet model \"Ocean Sunset\"-F0036", 2=>.....`. but as said: you should get a clear error from php.
Comment: Of course I will get error, this is just var_dump of $_SESSION['product'] to show you its value.. And this code is working on another server thats why I suppose this server i am currently using is not configured well and I was wondering which setting I need to change..
Comment: @arkascha, it wasn't the issue it's just a var dump of the Session. also you defined the variable wrong. you should have used `[]` instead (also dropping the keys which are not neccesary).
Comment: @DanRevah Ooops, right, wrong brackets. Still I think the comment makes sense, since the OP clearly wrote that what is posted is the code. Which is clearly invalid.
Answer: try this:
<code>$sproduct='"876-Satin Bridal bouquet model "Mexicana"-F0039"';
if (in_array($sproduct, $_SESSION['product']))
{
    echo 'aaaaaaaaaaaa';exit();
}
</code>
Answer: try escaping quotes
like this
<code>$_SESSION['product'] = array(
  0=> "869-Satin bridal bouquet model \"Ocean Sunset\"-F0036",

  1=> "876-Satin Bridal bouquet model \"Mexicana\"-F0039"
);
$sproduct="876-Satin Bridal bouquet model \"Mexicana\"-F0039";
if (in_array($sproduct, $_SESSION['product'])){
  echo 'aaaaaaaaaaaa';exit();
}
</code>
Answer: I'm assuming the $_SESSION you've showed in your question is a var_dump of the session variable, and not how you define the array (if it is how you define your array, you should learn how to define them properly).
your <code>$sproduct</code> string variable is defined wrong.
in PHP, strings which are defined by double quotes cannot contain a double quote without an escaping backslash ().
for ex:
<code>$s = "foo \"bar\" foo bar";
</code>
or you could use a single quote instead.
<code>$s = 'foo "bar" foo bar';
</code>
using single quotes is a bit more efficient since the double quotes takes longer to process, since the PHP parser has to read the whole string in advance to detect any variable inside and to concatenate it.
Comment: yes Dan this is just var_dump of the value, but this code is working on another server..

Php in_array() function doesn't work


Scrape yt formatted strings with beautiful soup

Question: I've tried to scrape yt-formatted strings with BeautifulSoup, but it always gives me an error. Here is my code:
import requests
import bs4
from bs4 import BeautifulSoup

r = requests.get('https://www.youtube.com/channel/UCPyMcv4yIDfETZXoJms1XFA')
soup = bs4.BeautifulSoup(r.text, "html.parser")
def onoroff():
    onoroff = soup.find('yt-formatted-string',{'id','subscriber-count'}).text
    return onoroff

print("Subscribers:  "+str(onoroff().strip()))

This is the error I get
AttributeError: 'NoneType' object has no attribute 'text'

Is there another way to scrape yt-formatted-strings?
Comment: Most of `Youtube` content is generated via JavaScript, capability that `BeautifulSoup` don't have. What info are you trying to get from that page? Subscriber count? You may get luck by scrapping the `json objects` on the source code, but not the `html` element directly.Update: The subscriber count, among other infos, is contained on a `json object`: https://i.imgur.com/ORk6xD8.jpg
Comment: I'll post an answer soon exemplifying my last comment.
Comment: How would I do that?
Comment: Oh ok I just saw your new comment, it didnt load when I was sending the one before
Answer: Most of Youtube content is generated via JavaScript, capability that BeautifulSoup don't have, but you can get luck by scraping the json objects on the source code, but not the HTML elements directly, i.e.:
import requests, json, re

h = {
    'Host': 'www.youtube.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0',
    'Accept': '*/*',
    'Accept-Language': 'en-US,pt;q=0.7,en;q=0.3',
    'Referer': 'https://www.youtube.com/channel/UCPyMcv4yIDfETZXoJms1XFA',
}
u = "https://www.youtube.com/channel/UCPyMcv4yIDfETZXoJms1XFA"
html = requests.get(u, headers=h).text

# lets get the json object that contains all the info we need from the source code and convert it into a python dict that we can use later
matches = re.findall(r'window\["ytInitialData"\] = (.*\}\]\}\}\});', html, re.IGNORECASE | re.DOTALL)
if matches:
    j = json.loads(matches[0])
    # browse the json object and search the info you need : https://jsoneditoronline.org/#left=cloud.123ad9bb8bbe498c95f291c32962aad2
    # We are now ready to get the the number of subscribers (among other info):

    subscribers = j['header']['c4TabbedHeaderRenderer']['subscriberCountText']['runs'][0]["text"]
    print(subscribers)
    # 110 subscribers

Demo
Comment: You're welcome. You can scarp almost anything using this technique, just get used to the `json` object keys and values structure and to match the `json` object on the source code of the page. Time, practice and patience will be your friends :)  GL!


How do I do a vlookup against fields in multiple columns

Question: I've got a column with multiple values, separated by columns and I need to lookup each individual value in the field as part of a VLOOKUP formula.
So it looks something like this:
Code_Column
NAAP,BTNA,SLGY,SKGY

The Lookup table looks something like this:
Code|Color
NAAP|Blue
BTNA|Green
SLGY|RED
SKGY|Purple

Now I don't believe that VLOOKUP can go through a list of multiple values, so I thought I would do a 'text to columns' in EXCEL, delimited by columns.  But now I'm not sure how to assign the vlookup value for each individual cell.  I've tried something like 'B2:E2' but it doesn't like that.  Any suggestions?
Comment: How do you want the output?
Comment: Good question.  I'd like it in a consolidated list.
Comment: Different cells same cell?
Comment: Same cell...if I could be greedy I'd like to know how to do both that and different cells.
Comment: Well, if you do not have Office 365 Excel it will require vba for the same cell.
Comment: Yeah I"m just using Excel for Mac...
Answer: to put them in different cells use this formula:
=VLOOKUP(TRIM(MID(SUBSTITUTE($A2,",",REPT(" ",999)),(COLUMN(A:A)-1)*999+1,999)),$H:$I,2,FALSE)

Comment: Thanks, but when I try this, I get one value.  Basically B2 with Blue but nothing else.  Any idea what I might be doing wrong?
Comment: Put the formula in B2, then copy/drag over and down.  Do not paste the formula in each cell.  The copy/drage will cause the relative ranges to change.  If you are doing that then make sure what is absolute and relative is the same as I have it.
Comment: Another amazing formula.  Two thumbs up.
Comment: Two things I'm noticing...and again, this is awesome, thanks so much.. It seems like the last value in each row gets a N/A and any row that has just one value (and thus not a comma) gets one as well.  Any way to tweak the formula for that.  I'm wondering why your example above doesn't have it and makes me think I've done something wrong.
Answer: Not sure entirely what you're looking for, but here is another example of how to put them in the same cell.
=VLOOKUP(F2,$C$8:$D$12,2,FALSE)&" "&VLOOKUP(G2,$C$8:$D$12,2,FALSE)&" "&VLOOKUP(H2,$C$8:$D$12,2,FALSE)&" "&VLOOKUP(I2,$C$8:$D$12,2,FALSE)&" "

Comment: This is good, but the number of values in the initial column is going to be dynamic.  Some rows might have 4 values, others might have ten.  Should I just find the max values and use that as the range?


Jquery- backslash character

Question: I am having a problem trying to replace the backslash character from a string:
var g = myReadString;
g = g.replace("\", "\\\\");

it is giving an error of unrecognized character.
How could a simple \ be replaced  with four \\\\?
I would appreciate any help,
thanks.
Pandy
Answer: The \ is the begin of an escape sequence. If you mean to write \ literally, you need to write \\ that is an escape sequence as well and will be interpreted as a single \. So if you want to replace one \ by four \\\\, you need to write this:
g.replace("\\", "\\\\\\\\")

But this will only replace the first occurrence of a single \. To do a global replace you need to use a regular expression with the global match modifier:
g.replace(/\\/g, "\\\\\\\\")

Comment: I think that OP actually wants to replace a single backslash with *four* literal backslashes.
Answer: g = g.replace(/\\/g, "\\\\");

I think that's what you're looking for. Let me know if not.
Comment: Hello my friend, it doesn't work. it doesn't replace the character.
For example, I would want:
IN: "myvalue\assa" (1 backslash)
OUT: "myvalue\\\\assa"
Comment: @Samuel Beckett In that case you must actually replace with eight(!) backslashes (i.e., four escaped backslashes).
Answer: The backslash also serves as an escaping character.  You can find a list of characters on this page... http://www.c-point.com/javascript_tutorial/special_characters.htm
So, in order to search for, or replace a backslash, you have to escape the backslash.  I actually just ran your code, and it doesn't work, as the backslash is escaping the first quote.  What exactly are you trying to do?  If you want to replace each single backslash with a double, you will need something like this.
var g = myReadString;
g = g.replace("\\", "\\\\");

Hope that helps!
Comment: Thanks!, well the solution that works is:
 g = g.replace("\\", "\\\\\\\\");
Comment: No problem at all! Glad to help.
Answer: In general make sure to always escape correctly.
In your first argument for replace() you intend to pass a string containing \ but it ends up as ",  (quote-comma-space)! This is because you're actually escaping the "closing" quote on the string:
g = g.replace("\", "\\\\");
              ^    ^
              s    e
              t    n
              a    d
              r
              t

Now the first argument is the string quote-comma-space. The rest gives a syntax error!
What you wanted:
g = g.replace("\\", "\\\\\\\\");
              ^  ^  ^        ^
              s  e  s        e
              t  n  t        n
              a  d  a        d
              r     r
              t     t

First argument: The string \
Second argument: The string \\\\

Jquery- backslash character


Is there any difference in solutions between $x^7-1^7=0$ and $x^7-1=0$?

Question: Is there any difference in solutions between $x^7-1^7=0$ and $x^7-1=0$?
Comment: No there isn't.
Comment: What made you think there might be a difference?
Comment: No. $x^7-1^7 = x^7-1^{-2} = x^7 - 1^{17}= x^7-1^{1/2} =x^7-1= .... 0$. (Sorry this comment was reposted here because it had a misleading typo, too late to edit.
Comment: When ever you have "statement having something to do with A" and you know A = B then you can always rephrase the sentence as "statement having something to do with B" because A and B are the exact same thing.  So $1 = 1^7$.  So $x^7 - 1^7 = x^7 - 1 = x^7 - (564 - 563) = x^7 - (\frac {2+3}{5}) = ......$" etc.
Comment: I found that 1)x^7=1^7,or,x^7=(cos(2kpi+0))+isin(2kpi+0))^7/7,or,(x^7)^1/7=(cos(2kpi)+isin(2kpi)or solutions of x=cos(2kpi)+sin(2kpi)(where k=0,1,..,6) ,but in the second situation, x^7=1,or,(x^7)^1/7=(cos(2kpi)+isin(2kpi))^1/7 so the solution of x=cos(2kpi)/7+isin(2kpi)/7 where k=0,1..6).So,that is my case.
Answer: Hint:
$$(1)^n=1$$
Where $n$ any real number
Comment: I find this a bit dismissive as an answer to this question. It does not explain anything.
Comment: Um.... what's to explain?  It might not be apparent to the OP $1^7 = 1$ when it is expressed as $x^7 - 1^7$.  The only thing that needs explaining (and this is a hint; not an answer) is that if A = B then f(A) = f(B) because they are the same thing.  The OP probably knows this but doesn't "get" it.  Pointing out the equality is enough of a hint for the OP say ... "oh, yeah...."  If the OP does need to have A= B means they are the same thing then we need a deep discussing on ontology and what the symbol "=" means and how it is not an operator.
Comment: @quid Indeed, but I think this is exactly the answer that the question, as-written, deserved. I have no idea why the OP would ask this, unfortunately.
Comment: @T.Bongers for instance somebody might have made a point in writing $x^7 -1^7 = (x-1)(x^6 + \dots + 1)$  then one might wonder what the point of that was.   "I think this is exactly the answer that the question, as-written, deserved" That's a problematic attitude. Don't answer, or make a serious effort.
Comment: @quid I really wish that the OP had responded to your comment asking *why* they asked the question - but since they didn't, there really isn't much to say beyond "no."
Comment: @T.Bongers That answer is not even a clear "no." It may be unintentional but I find this post rude. // On the non-response, it's not that long ago, and the comment came in a bit late. So I do not see why one would reproach a non-response.
Comment: @quid I'm just lamenting the fact that the OP didn't include the motivation of their question when they originally posted it. I don't find this answer to be rude, personally. (I am completely baffled as to why it received eight upvotes in under an hour, though...)
Comment: @quid, sorry, try to post your answer
Comment: @quid I think that is exactly why the op asked.  In which case $x^7 - 1 = x^7 - 1$ which is *also* $(x-1)(x^6 ..... + 1)$.
Comment: Thanks for the reply. And sorry for the possibly uncharitable reading of your answer. In the meantime another answer appeared. If OP replies to my question, I might add another one.
Answer: $1 = 1^7$ so "anything to do with $1$" = "anything to do with $1^7$".  So, no, no difference.
I think you are confused because
$x^n - a^n = (x - a)(x^{n-1} + x^{n-2}a + .... xa^{n-2} + a)=0$
has completely different solutions than
$x^n - a=0 \implies x = $ then $n$-th roots of $a$.
But in this case $1 = 1^7$ and
$x^7 - 1 = 0 \implies x = 1$  (Unless you are doing complex numbers, in which case there are 6 complex solutions.)
Also can be interpreted:
$x^7 - 1^7 = (x -1)(x^6 + x^5*1 + x^4*1^2 + x^3*1^3 + x^2*1^4+x*1^5 + 1^6) =0$
Which can be more easily written
$x^7 - 1 = (x -1)(x^6 + x^5 + x^4 + x^3 + x^2+x + 1) =0$
So $x = 1$ or $ (x^6 + x^5 + x^4 + x^3 + x^2+x + 1) =0$
So $x = 1$ as $(x^6 + x^5 + x^4 + x^3 + x^2+x + 1) =0$ has no real solutions (trust me).
(It does have 6 complex solutions, though, which are the exact same as the complex numbers that solve $x^7 = 1$.  [ trust me].)
Comment: IMO, \$\times\$ ( $\times$ ) has always been more clear than $*$.
Comment: I think that is *the answer*, apart from OP's expectations which are unknown
Answer: $1^n=e^{2n\pi i}=cos(2n\pi)+i \cdot sin(2n\pi)$
So 'one' is always 'one' while $n \in \Bbb Z$
Comment: Someone asking this question is going to have absolutely no idea what this answer is about. And I think that explaining arithmetic properties of $1$, which is the multiplicative identity, via complex numbers is completely missing the point.
Comment: @T.Bongers  The question is (and was originally) tagged "complex numbers" and an intro to complex numbers is the most plausible context I can imagine for the question.


Kernel panics after hitting a breakpoint during jtag debugging using gdb

Question: I am trying to debug linux kernel running on sabre lite board using jtag and gdb on my host machine. During debugging I insert a break point at "do_fork()" and allow the kernel to continue its execution.
As soon as I enter "ls" command on my sabre lite board the breakpoint gets hit after which the kernel panics.
Here is the log generated on the console terminal of sabre lite board:
root@mx6q:~# ls
[   94.725966] Unhandled prefetch abort: breakpoint debug exception (0x002) at 0x00094d74
[   94.733935] Internal error: : 2 [#1] PREEMPT SMP ARM
[   94.738918] Modules linked in: ov5642_camera ov5640_camera_mipi mxc_v4l2_capture ipu_g
[   94.754748] CPU: 1 PID: 406 Comm: sh Not tainted 3.10.45 #1
[   94.760343] task: dcb78f00 ti: dc8ec000 task.ti: dc8ec000
[   94.765781] PC is at do_fork+0x0/0x368
[   94.769554] LR is at SyS_clone+0x24/0x2c
[   94.773497] pc : [<c002ae3c>]    lr : [<c002b264>]    psr: 800f0013
[   94.773497] sp : dc8edf90  ip : b6f3d068  fp : dc8edfa4
[   94.784993] r10: 00000000  r9 : dc8ec000  r8 : c000e304
[   94.790235] r7 : 00000078  r6 : b6ec0000  r5 : 00000000  r4 : b6f3d068
[   94.796778] r3 : 00000000  r2 : 00000000  r1 : 00000000  r0 : 01200011
[   94.803325] Flags: Nzcv  IRQs on  FIQs on  Mode SVC_32  ISA ARM  Segment user
[   94.810477] Control: 10c5387d  Table: 2c89004a  DAC: 00000015
[   94.816240] Process sh (pid: 406, stack limit = 0xdc8ec238)
[   94.821830] Stack: (0xdc8edf90 to 0xdc8ee000)
[   94.826208] df80:                                     b6f3d068 c011aa24 00000000   dc8e8
[   94.834410] dfa0: c000e180 c002b24c b6f3d068 00000000 01200011 00000000 00000000 00000
[   94.842612] dfc0: b6f3d068 00000000 b6ec0000 00000078 b6f3d4c0 00000196 000e5e08 bed5c
[   94.850813] dfe0: 00000000 bed52940 b6f3d000 b6e25640 600f0010 01200011 fd3b4088 0000f
[   94.859001] Backtrace:
[   94.861512] [<c002b240>] (SyS_clone+0x0/0x2c) from [<c000e180>] (ret_fast_syscall+0x0)
[   94.869887] Code: e92dd800 e24cb004 e5801188 e89da800 (e1200070)
[   94.876596] ---[ end trace 3e3aa32a078125f3 ]---
     Stopping Serial Getty on ttymxc1...
[  OK  ] Stopped Serial Getty on ttymxc1.
     Starting Serial Getty on ttymxc1...
[   94.957982] Unhandled prefetch abort: breakpoint debug exception (0x002) at 0xb6e5e4a0
[   94.966066] Internal error: : 2 [#2] PREEMPT SMP ARM
[   94.971058] Modules linked in: ov5642_camera ov5640_camera_mipi mxc_v4l2_capture ipu_g
[   94.986894] CPU: 3 PID: 1 Comm: systemd Tainted: G      D      3.10.45 #1
[   94.993705] task: dc078000 ti: dc05c000 task.ti: dc05c000
[   94.999143] PC is at do_fork+0x0/0x368
[   95.002916] LR is at SyS_clone+0x24/0x2c
[   95.006859] pc : [<c002ae3c>]    lr : [<c002b264>]    psr: 80070013
[   95.006859] sp : dc05df90  ip : b6d2c068  fp : dc05dfa4
[   95.018355] r10: 00000000  r9 : dc05c000  r8 : c000e304
[   95.023596] r7 : 00000078  r6 : b6eed000  r5 : bef7cfc8  r4 : b6d2c068
[   95.030138] r3 : 00000000  r2 : 00000000  r1 : 00000000  r0 : 01200011
[   95.036685] Flags: Nzcv  IRQs on  FIQs on  Mode SVC_32  ISA ARM  Segment user
[   95.043837] Control: 10c5387d  Table: 2c57c04a  DAC: 00000015
[   95.049599] Process systemd (pid: 1, stack limit = 0xdc05c238)
[   95.055448] Stack: (0xdc05df90 to 0xdc05e000)
[   95.059827] df80:                                     b6d2c068 000b9ec1 00000000 dc058
[   95.068028] dfa0: c000e180 c002b24c b6d2c068 bef7cfc8 01200011 00000000 00000000 00000
[   95.076228] dfc0: b6d2c068 bef7cfc8 b6eed000 00000078 b6d2c4c0 00000001 00000000 bef74
[   95.084429] dfe0: 00000001 bef7cfc8 b6d2c000 b6e52640 60070010 01200011 fd7b4088 0000f
[   95.092616] Backtrace:
[   95.095125] [<c002b240>] (SyS_clone+0x0/0x2c) from [<c000e180>] (ret_fast_syscall+0x0)
[   95.103502] Code: e92dd800 e24cb004 e5801188 e89da800 (e1200070)
[   95.109750] ---[ end trace 3e3aa32a078125f4 ]---
[   95.116889] Kernel panic - not syncing: Attempted to kill init! exitcode=0x0000000b
[   95.116889]
[   95.126041] CPU0: stopping
[   95.128760] CPU: 0 PID: 163 Comm: systemd-journal Tainted: G      D      3.10.45 #1
[   95.136418] Backtrace:
[   95.138902] [<c0011f24>] (dump_backtrace+0x0/0x10c) from [<c0012138>] (show_stack+0x1)
[   95.147342]  r6:c0a70e40 r5:00000000 r4:00000005 r3:00000000
[   95.153072] [<c0012120>] (show_stack+0x0/0x1c) from [<c078d698>] (dump_stack+0x20/0x2)
[   95.161083] [<c078d678>] (dump_stack+0x0/0x28) from [<c00145d4>] (handle_IPI+0x124/0x)
[   95.169268] [<c00144b0>] (handle_IPI+0x0/0x14c) from [<c0008628>] (gic_handle_irq+0x5)
[   95.177718] [<c00085cc>] (gic_handle_irq+0x0/0x64) from [<c0793140>] (__irq_svc+0x40/)
[   95.185985] Exception stack(0xdc6e5df0 to 0xdc6e5e38)
[   95.191041] 5de0:                                     c0acb800 600f0013 00003d1d 00000
[   95.199224] 5e00: c0c7fb00 00000001 dc64b000 00000001 00000000 dc00e400 c0acb4c0 dc6e4
[   95.207405] 5e20: dc6e5e48 dc6e5e38 c00d8cd8 c0792858 a00f0013 ffffffff
[   95.214021]  r7:dc6e5e24 r6:ffffffff r5:a00f0013 r4:c0792858
[   95.219749] [<c079282c>] (_raw_spin_unlock_irqrestore+0x0/0x54) from [<c00d8cd8>] (re)
[   95.229676] [<c00d8b1c>] (release_pages+0x0/0x200) from [<c01006f8>] (free_pages_and_)
[   95.239345] [<c0100684>] (free_pages_and_swap_cache+0x0/0xac) from [<c00f38b8>]

and on my host side:
Breakpoint 4, do_fork (clone_flags=18874385, stack_start=0,
Sending packet: $mdc8edfa8,4#94...Packet received: 68d0f3b6
stack_size=stack_size@entry=0, parent_tidptr=0x0 <__vectors_start>,
child_tidptr=child_tidptr@entry=0xb6f3d068) at kernel/fork.c:1570
1570    kernel/fork.c: No such file or directory.

Comment: Can some one please guide me I am stuck on this issue..........
Comment: You could try with kgdb.
Comment: could it be because you are debugging a PREEMPT SMP configuration? http://lists.infradead.org/pipermail/linux-arm-kernel/2010-December/033443.html
Answer: kernal panic is when there is something exceptionally wrong with the kernal module. Also at times, the error messages displayed may be the effect of the error and not the cause.


Computing ACF of a causal AR(1) process

Question: We have a stationary time series {X_t} with zero mean and ACVF $\gamma_x(h)$. At each time $t$ with probability $p$ an error occurs, recording the value of $X_{t-1}$ instead of $t$. This happens independent each $t$ and probability $p$ does not vary.
We want to show that data series {$Y_t$} is stationary and compute it's ACVF $\gamma_Y(h)$.
We suppose that {$X_t$} is a causal AR(1) process with an ACF satifying $\rho_x(1) = 0.5$. Compute the ACF $\rho_Y(h)$for the value of $\rho$ that maximizes $\rho_Y(h)$
Using this information i find that
$\gamma_Y(h) = \gamma_x(h)$ for $h = 0$
$\gamma_Y(h) = \gamma_x(h) + p(1-p)(\gamma_x(h-1) + \gamma_x(h+1)-2\gamma_x(h))$ for $h \ge 1$
$\gamma_Y(h) = \gamma_y(-h)$ for $h \le -1$
For an AR(1) process with $\phi \in (0,1)$ for $h\ge1$. We have

Can anyone explain what we are doing below?
$\gamma_y(h) - \gamma_x(h) = p(1-p)(\phi^{-1} + \phi -2)\phi^{h}(1-\phi^2)^{-1}\sigma^2$
Since $\rho_x(1) = \phi = 0.5$ and $p(1-p)$ is maximized for $p = 0.5$ for $h \ge 1$ we get
$\rho_y(h) = (0.5)^h + 0.25(2+0.5-2)(0.5)^h = 1.125(0.5)^h = 1.125\rho_x(h)$
Why do we set $\gamma_y(h)-\gamma_x(h)$ and how do we find $\rho_y(h)?$
Comment: ACF  is the normalized ACVF ?
Comment: yes ofcourse ACVF.
Comment: Or rather we want to compute the ACF (autocorrelation function) using the ACVF (autocovariance functions). Hope this clarified things.
Answer: The notation is slighly confusing for me. I assume $\sigma^2$ is the variance of the noise that feeds the AR process.
You have $$\gamma_y(h) = \gamma_x(h) + p(1-p)\left(\gamma_x(h-1) + \gamma_x(h+1)-2\gamma_x(h)\right) \tag{1}$$
for $h \ge 1$
Now, if $X$ is AR(1), its ACVF must has the form of a two-sided decaying exponential - further, because we are given $\gamma_x(1)=0.5$ we can already write  $$\gamma_x(h) = \sigma^2_X \,  \phi^{|h|} \tag{2}$$
with $\phi = 0.5$ , and $\sigma^2_X = \sigma^2_n/(1-\phi^2)$ (see eg).
Replacing, we get
$$\begin{align}
\gamma_y(h) &= \gamma_x(h) + p(1-p) \sigma^2_n \frac{ (\phi^{h+1}+\phi^{h-1}-2\phi^h)}{1-\phi^2}\\
&= \gamma_x(h) + p(1-p) \sigma^2_n \frac{\phi^h (\phi -\phi^{-1} -2)}{1-\phi^2}
\end{align} \tag{3}$$
Because we want to maximize $\gamma_y(h)$, and because the fraction in $(3)$ is positive, we want $p(1-p)$ to be maximum, which occurs at $p=1/2$. I think  you can go on from here.

Computing ACF of a causal AR(1) process


What is the best way to filter list of custom datatype with other list (Iterate over it)

Question: I have a problem regarding filtering a list with my own type with one other.
I came from python so haskell is quite hard for me to understand.
type PersonId = Integer
type PersonName = String
type InfectionId = Integer
type InfectionName = String

data TerminationType = Recovered | Dead
                       deriving (Eq, Show)

data Person = Person PersonId PersonName
              deriving Show

data Infection = Infection InfectionId PersonId InfectionName
                 deriving Show

data Termination = Termination InfectionId TerminationType
                   deriving Show

type Persons = [Person]
type Infections = [Infection]
type Terminations = [Termination]

pers :: Persons
pers = [Person 1 "Augustin"
       ,Person 2 "Baltazar"
       ,Person 42 "Ctirad"
       ,Person 128 "Zdenek"
       ,Person 5 "Drahoslav"
       ]

infs :: Infections
infs = [Infection 2020 1 "COVID"
       ,Infection 2019 42 "COVID"
       ,Infection 1 5 "COVID"
       ,Infection 5 128 "rymicka"
       ,Infection 3 5 "astma"
       ,Infection 2 1 "astma"
       ,Infection 128 5 "zapal plic"
       ]

ters :: Terminations
ters = [Termination 2020 Dead
       ,Termination 2 Recovered
       ,Termination 2019 Recovered
       ,Termination 128 Dead
       ]

I am trying to make a function that would find all active cases. So it would make a list of recorded infections based on current infection and remove all terminations.
My idea was to get all IDs from Terminations using a map and then filtering items with that ID from Infections using something like "in" from python but that solution seems to be way too "OOP".
Something along those lines.
activeCases :: Infections -> Terminations -> [InfectionId]
activeCases infec term = filter (infec.id in (map getId term)) infec
    where getId (Termination y _) = y

The final result with the "pers,infs" and "ters" I have predefined would be
activeCases infs ters ~>*
[Infection 1 5 "COVID",Infection 5 128 "rymicka",Infection 3 5 "astma"]
Could someone tell me what is the right way to solve a problem like this?
Comment: Using a `Map` sounds perfectly appropriate - or actually a `Set`, if you only care about the ids. The operator you're looking for is called [`member`](https://hackage.haskell.org/package/containers-0.6.4.1/docs/Data-Map-Lazy.html#v:member) though, not `in`, and `map` needs to be changed to construct one.
Comment: Oh wait you actually meant to `map` the `getId` function over the list of `term`s to get a list with ids. Yes, that'll work just as well. In that case, use [`elem`](https://hackage.haskell.org/package/base-126.96.36.199/docs/Prelude.html#v:elem): `filter (\(Infections _ id _) -> id `elem` (map getId term)) infec`
Comment: That is great! Exactly what i need. Thanks
Answer:
My idea was to get all IDs from Terminations using a map and then filtering items with that ID from Infections using something like "in" from python but that solution seems to be way too "OOP".

Not at all, you have the right idea, in fact! It looks like you just need some help expressing it.
You can change your code to use the elem function, which is akin to Python's in operator, but works on any foldable container with equatable elements:
elem :: (Foldable t, Eq a) => a -> t a -> Bool

Here you'll be using it with t ~ [] and a ~ InfectionId, so it will have the specialised type elem :: InfectionId -> [InfectionId] -> Bool.
If you want to return just the IDs, not the whole Infection value, you can extract the IDs first with map.
activeCases :: Infections -> Terminations -> [InfectionId]
activeCases infections terminations

  -- Select the IDs that are *not* found in the list of termination IDs.
  = filter (\ i -> not (i `elem` terminationIds))

    -- Extract the ID from each Infection.
    (map infectionId infections)
  where
    terminationIds = map terminationId term
    terminationId (Termination y _) = y
    infectionId (Infection i _ _) = i

Recall that the filter condition indicates which elements to keep, not which ones to filter out, so for the active cases you want to add a not. My mnemonic for this is "a coffee filter lets coffee through" (so filter even lets even values through).
You can simplify this in a few ways, though. First, you can make the data types into records and give each field a name so you can extract it (or update it) more conveniently:
data Person = Person
  { personId :: PersonId
  , personName :: PersonName
  }
  deriving (Show)

data Infection = Infection
  { infectionId :: InfectionId
  , infectionPerson :: PersonId
  , infectionName :: InfectionName
  }
  deriving (Show)

data Termination = Termination
  { terminationInfection :: InfectionId
  , terminationType :: TerminationType
  }
  deriving (Show)

The mapping & filtering can be expressed with a list comprehension, and the not and elem functions can be combined into notElem for convenience. Putting these together:
activeCases :: Infections -> Terminations -> [InfectionId]
activeCases infections terminations =
  [ infectionId infection
  | infection <- infections
  , infectionId infection `notElem` terminationIds
  ]
  where
    terminationIds =
      [ terminationInfection termination
      | termination <- terminations
      ]

You can still use pattern-matching in the comprehension if you prefer:
-- Positional matching:

[ i
| Infection i _ _ <- infections
, i `notElem` terminationIds
]

-- Named matching:

[ i
, Infection { infectionId = i } <- infections
, i `notElem` terminationIds
]

There are higher-level approaches as well. Scanning linearly over the list of Termination IDs for each Infection ID is O(n2), but what you really want here is a set difference, which can be computed more efficiently using map & set data structures such as Data.Map and Data.Set (or Data.IntMap and Data.IntSet) from containers. For example, if you store your data as a map from the ID to the record for that ID:
import Data.Map (Map)
import Data.Set (Set)

type Persons = Map PersonId Person
type Infections = Map InfectionId Infection
type Terminations = Map InfectionId Termination

infs :: Infections
infs = Map.fromList
  [ (i, infection)
  | infection <-
    [ Infection 2020 1 "COVID"
    , Infection 2019 42 "COVID"
    , Infection 1 5 "COVID"
    , Infection 5 128 "rymicka"
    , Infection 3 5 "astma"
    , Infection 2 1 "astma"
    , Infection 128 5 "zapal plic"
    ]
  , let i = infectionId infection
  ]

Then the set of active cases is the key-set of the infections minus the set of terminated cases, which can be computed in O(n log n) time:
import qualified Data.Map as Map
import qualified Data.Set as Set

activeCases :: Infections -> Terminations -> Set InfectionId
activeCases infections terminations
  = infectionIds `Set.difference` terminatedInfections
  where
    infectionIds = Map.keysSet infections
    terminatedInfections = Set.fromList
      $ map terminationInfection
      $ Map.elems terminations

Or since a Termination is identified by an InfectionId as well, just the difference of the key sets:
Map.keysSet infections `Set.difference` Map.keysSet terminations

Comment: God bless your children. You, dear lord, just opened my third eye and allowed me to see everything the right way.


Filtrar objetos com critério no array dentro dele

Question: Por que não estou conseguindo retornar apenas os objetos que contenham a disciplina Matemática?
Estou utilizando os métodos map() , filter() e, dentro do filter(), o includes(), mas está retornando todos os objetos.
Será que não dá para utilizar encadeado como fiz, tendo que ser desencadeado os métodos:

let dados = [
  {nome: 'Noah', disciplinas: ['Matemática', 'Geografia', 'Inglês']},
  {nome: 'Gael', disciplinas: ['Química', 'Geografia', 'Português']},
  {nome: 'Caleb', disciplinas: ['Matemática', 'Física', 'Artes']}
]

let discip = dados.filter(a => a.disciplinas.filter(b => b.includes('Matemática')))

console.log(discip)
Answer: Quando quer filtrar algo basta fazer isso uma vez. Só faria sentido se quisesse ter um filtro dentro do filtro, mas não é o caso, você quer filtrar apenas as pessoas. A disciplina é um critério usado não é outro filtro (pelo que entendi). Então basta pegar a lista de disciplinas e ver se a que está buscando está entre as que a pessoa tem no seu cadastrado, de forma direta e simples.

let dados = [
  {nome: 'Noah', disciplinas: ['Matemática', 'Geografia', 'Inglês']},
  {nome: 'Gael', disciplinas: ['Química', 'Geografia', 'Português']},
  {nome: 'Caleb', disciplinas: ['Matemática', 'Física', 'Artes']}
]

let discip = dados.filter(a => a.disciplinas.includes('Matemática'))

console.log(discip)

Coloquei no GitHub para referência futura.
Comment: Certo então, entendi Maniero, realmente abusei do método. Obrigado!


Is it possible to create an Office365 account that sends emails on other people's behalf?

Question: I have an internal app that needs to send emails on other people's behalf.  For instance, I might need to send an email from firstname.lastname@example.com, firstname.lastname@example.com and firstname.lastname@example.com to email@example.com.
All our email is in Office365.  Basically, this is relaying email and it does sound close to what spammers do.
Is this possible to with Office365?  What permissions would the account need to have?
Answer: a lot has to do with how you are achieving this.
Using an "App", you would usually create a service account for this purpose, create a new role for this account and grant impersonation rights to the role.
Answer: Take a look at this question. The last answer references this technet guide that can walk you through the setup. We have accomplished this by adding a SMTP relay (mail flow connector) that validates our ip address.
Comment: Currently we are facing an issue when the sender domain is not an Authoritative domain within Exchange Online. It prevents the sender from  emailing recipients in multiple domains. Otherwise it should work for the use case specified.


CSS block with background image not including space after header

Question: I'm trying to create this box, but it's a little over my head. I can't get the spacing after the white header text to display correctly.
The live version is here, and the current CSS is below. A standard
 inside the div ignores the bottom padding on hblock and I can't help but think I'm going about this the wrong way. Is there a simpler way to create this element or something I'm missing in the code?
Many thanks.
#lheaderblock{display:block;
padding:0px 10px 0px 10px;
background-image:url('http://atlas.czg.net/atlas/wp-content/uploads/2012/12/caption_header_blue.gif');
height:160px;
width:90%;
border:1px solid #000000;
background-repeat:no-repeat;
overflow: hidden;}

hblock{position:absolute;
color:#FFFFFF;
font-size:14pt;
padding:10px 0px 20px 15px;}

Comment: remove the absolute positioning from the hblock.  Then you just need to tweak your padding.
Answer: I don't know what <hblock> is. When browsers don't know either, they will render them as inline element. You need to give it display: block and remove position: absolute. Tweak the padding and you'll be fine.
Comment: Thank you. I knew it had to be simple. Learn something new every day.
Comment: I'd suggest you to use an appropriate header tag like h1 or h2 instead. You need to accept this as an answer if it answered your question.


How to add a region block to the custom template contact form page?

Question: I trying to add a region block to custom template Contact Form page: "contact-message-feedback-form.html.twig"
Define a region (like: contact_info) to theme-name.info.yml and
add {{ page.contact_info }} in contact-message-feedback-form.html.twig
Contact form rendered successful but when add block to the region not display block in this region.
theme-name.theme:
/**
 * Implements hook_theme().
 */
function crown_ui_theme($existing, $type, $theme, $path) {
  return [
    'contact_message_feedback_form' => [
      'render element' => 'form',
    ]
  ];
}

theme-name.info.yml:
regions:
  contact_info: 'Contact Info'

contact-message-feedback-form.html.twig:

{{ page.contact_info }}

Answer: I used twig_tweak module to load and render a block on any where in Drupal.
Read more on the module docs:
https://www.drupal.org/docs/8/modules/twig-tweak/rendering-blocks-with-twig-tweak


Passing variables from one modal window to another in asp.net

Question: I have an asp.net application where I need to pass values from one modal windown to another modal window. I have tried session variables, but they return null 50% of the time.
What would be another alternative to pass paramaters from a modal window to another?
Cookies are not an option.
Thanks
Comment: What kind of modals?  Are these internally iframes, or is the content inline?  Seems like iframe scenario where it performs a navigational request?
Answer: I have found the only reliable way to do this is through javascript:
the child window can can set a value in the parent like this:
window.parent.setValue(x);

with this in the parent:
function setValue(x)
{
     document.getElementById(<% HiddenField1.ClientID %>).value = x;
}

The child has now set a value in the parent window which can be accessed form the parent's codebehind via the control HiddenField1.


Find a maximal ideal $I$ of $\mathbb{R} [x]$ such that $\mathbb{R} [x] / I$ not isomorphic as a ring to $\mathbb{R}$

Question: I want to find a maximal ideal $I$ of $\mathbb{R} [x]$ such that $\mathbb{R} [x] / I$ not isomorphic as a ring to $\mathbb{R}$. I can see that the maximal ideals of $\mathbb{R} [x]$ are ideals of the form $p \mathbb{R} [x] $ where $p$ is an irreducible polynomial, and I understand that the quotient of $\mathbb{R} [x]$ by a maximal ideal is a field. I am not sure how to show that it is not ismorphic to $\mathbb{R}$ though.
Comment: If $p(x)=x^2+1$, then in $\mathbb{R}[x]/(p)$ there is an element, $x$, which square is $-1$.
Comment: @totoro Why are you writing a perfectly good answer as a comment?
Comment: @Arthur Because I can and want (!?) I don't need any more reason than that minimal set.
Answer: If $F$ is a field, then the maximal ideals of $F[x]$ are exactly the principal ideals generated by irreducible polynomials.
If $f$ is irreducible of degree $1$, then $F[x]/(f) \cong F$.
If $f$ is irreducible of degree $n > 1$, then $F[x]/(f) \not\cong F$ because $F[x]/(f)$ contains a root of $f$ but $F$ doesn't.
When $F=\mathbb R$, the irreducible polynomials are those of degree $1$ and those of degree $2$ with negative discriminant.


Change language of date. Django

Question: I would like to know if there is a way to change the language of a date when we render it (the same way we can change the format: {{mydate|date:"d F Y - H:i"}}).
I looked at the doc : https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#date   but i didn't find anything.
Thank you for your help.
Answer: You could change the locale before rendering it as a string. Then change it back after. Although, I'm not sure why you want to have a date in a language different from your other output. Maybe explain what you are trying to accomplish with this, first. There is no built-in way to do it simply formatting the date.
Comment: Thank you for your help. I just try to display a date in a different language from the other dates. Let say I have {{mydate1}} and {{mydate2}} in english and {{mydate3}} in french (the three dates are different dates).
Comment: Gotcha, for this, you could suggest creating a custom template tag/filter. Output your dates in the template like {{ mydate1|displayEnglish }} and {{ mydate3|displayFrench }}. In the tag/filter you could change the locale and translate the date as a string. However, I think this should be done in the view. For mydate1 and mydate2 have the English locale and translate, then change locale for and translate mydate3. Since there are stored as strings and passed to the template, they should retain their language. Not totally sure this will work, but it's worth a shot.
Answer: In django, you need change the language in you setting.py like that:
LANGUAGE_CODE = 'es-PE'
for this example, i'm from Perú.

Change language of date. Django


Law of Iterated Expectations $\operatorname{E}\left[XYZ\right]=\operatorname{E}\left[\operatorname{E}\left[XYZ \mid X,Y\right]\right]$

Question: my doubt is actually pretty simple.
Considerer three random variables $X,Y,Z$. I wonder if I can use the LIE to do this: $$\operatorname{E}\left[XYZ\right]=\operatorname{E}\left[\operatorname{E}\left[XYZ \mid X,Y\right]\right]$$
Or the only way to condition the expected value for two variable is to use the other version of LIE, for example: $$E \left[ E \left(Y\mid X,Z \right) \mid X \right] =E \left[Y \mid X \right]$$
Thank you very much.
Answer: Please see if this helps?
\begin{align*}
\mathbb{E}[XYZ] &= \sum\limits_{x_i,y_j,z_k} x_i\cdot y_j\cdot z_k\cdot\mathbb{P}(X=x_i,Y=y_j,Z=z_k) \\
&= \sum\limits_{x_i,y_j,z_k} x_i\cdot y_j\cdot z_k\cdot\mathbb{P}(Z=z_k|X=x_i,Y=y_j)\mathbb{P}(X=x_i,Y=y_j) \\
&= \sum\limits_{x_i,y_j} \mathbb{E}_{Z|X,Y}[XYZ|X=x_i,Y=y_j] \cdot \mathbb{P}(X=x_i,Y=y_j) \\
&= \mathbb{E}_{X,Y}\left[\mathbb{E}_{Z|X,Y}[XYZ|X=x_i,Y=y_j]\right]
\end{align*}


Prove that $\delta^*(q,wv)=\delta^*(\delta^*(q,w),v)$

Question: Imagine we have a language like $L$ with alphabet $\Sigma$ and the set of words of $L$ called $\Sigma^*$ ( notice that a word can have zero characters).
We define $\delta^*$ recursively like this :
For each $a \in \Sigma$, $w \in \Sigma^*$ and $q \in Q$ :
$(1)$ $\delta^*(q,\lambda)=q$
$(2)$ $\delta^*(q,wa)=\delta(\delta^*(q,w),a)$
Now prove that for each two strings like $w$ and $v$, $\delta^*(q,wv)=\delta^*(\delta^*(q,w),v)$.
Note : what i tried was induction on $|v|$ but it didn't work.
For $|v|=0$ we have this: $\delta^*(q,wv)=\delta^*(q,w\lambda)=\delta^*(q,w)=\delta^*(\delta^*(q,w),\lambda)=\delta^*(\delta^*(q,w),v)$.
Assume that for $|v|=n-1$ its true that : $\delta^*(q,wv)=\delta^*(\delta^*(q,w),v)$.
Now i'm stuck on this : How to show that its true for $|v|=n$ ?
Comment: It should have. would you mind showing us what you tried so we can spot the mistake? induction on $|v|$ should works without problem.
Comment: Ok. Assume it's true for $|v|=n-1$. Take $v$ with $|v|=n$, $v=v'a$ with $|v'|=n-1$, then apply (2) on $wv'a$, use the induction hypothesis on $wv'$ (here you have lot of $\delta$ and $\delta^*$ but dont be afraid) you can now use (2) (in the other direction to obtain the desired form.
Comment: @wece for $|v|=0$ its obvious. i assumed that for $|v|=n-1$ its true and i don't know how to reach $|v|=n$. maybe it's just a mistake but i'm confused with many $\delta$'s & $\delta^*$'s
Comment: Did it help or are you still stuck?
Comment: @wece thank you dude :) it worked ... i don't know what to do with my question now ... should i delete it ?
Comment: Nah, keep it (imho).
Comment: I'll provide an answer so that the question is marked answered.
Answer: By induction on $|v|$.
If $v=\lambda$, then $\delta^*(q,wv)=\delta^*(q,w)=\delta^*(\delta^*(q,w),\lambda)=\delta^*(\delta^*(q,w),v)$.
Assume that for all $v$ such that $|v|=n-1$ the property is true.
Let $v$ be such that $|v|=n$, assume (without loss of generality) that $v=v'a$. Then:
using (1)
$$\delta^*(q,wv)=\delta^*(q,wv'a)=\delta(\delta^*(q,wv'),a)$$
using the induction hypothesis we know that:
$$\delta^*(q,wv')=\delta^*(\delta^*(q,w),v')$$
thus
$$ \delta^*(q,wv)=\delta(\delta^*(\delta^*(q,w),v'),a)$$
by applying (2) we obtain:
$$ \delta^*(q,wv)=\delta^*(\delta^*(q,w),v'a)$$
thus
$$\delta^*(q,wv)=\delta^*(\delta^*(q,w),v)$$


Problema com Desenvolvimento no Unity 5 3D

Question: Estou desenvolvendo um jogo usando o Unity 5 e ao executar (dar play no jogo), aparece o seguinte erro e eu não estou conseguindo entendê-lo, eu acho que tem haver com algum processo negado, mas não sei o que é.
Ai está o erro:
Unhandled Exception: System.UnauthorizedAccessException: Access to the path "C:\Users\Public\Documents\Unity Projects\Jogo Nightmare\Temp\Assembly-CSharp.dll.mdb" is denied.

  at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options) [0x00000] in <filename unknown>:0

  at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean isAsync, Boolean anonymous) [0x00000] in <filename unknown>:0

  at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access) [0x00000] in <filename unknown>:0

  at Mono.CompilerServices.SymbolWriter.MonoSymbolWriter.WriteSymbolFile (Guid guid) [0x00000] in <filename unknown>:0

  at Mono.CSharp.SymbolWriter+SymbolWriterImpl.WriteSymbolFile () [0x00000] in <filename unknown>:0

  at Mono.CSharp.SymbolWriter.WriteSymbolFile () [0x00000] in <filename unknown>:0

  at Mono.CSharp.CodeGen.Save (System.String name, Boolean saveDebugInfo, Mono.CSharp.Report Report) [0x00000] in <filename unknown>:0

  at Mono.CSharp.Driver.Compile () [0x00000] in <filename unknown>:0

  at Mono.CSharp.Driver.Main (System.String[] args) [0x00000] in <filename unknown>:0

Se alguém souber por favor me fale.
Comment: Por acaso você tem algum antivírus rodando (talvez o McAfee)? Uma busca rápida no Google parece demonstrar que tem sido comum os antivírus barrerem o acesso a esse arquivo. [Fonte 1](http://forum.unity3d.com/threads/internal-compiler-error-unhandled-exception-system-unauthorizedaccessexception.133493/). [Fonte 2](http://answers.unity3d.com/questions/491473/internal-compiler-error-8.html). Talvez se você configurar o antivirus para adicionar esses arquivos como de confiança (*trustee*) resolva.
Comment: Sim, foi o que eu sugeri: adicione o arquivo na lista de arquivos confiáveis do seu antivirus para ele parar de bloquear o acesso a esse arquivo. Eu não uso o McAfee, então não sei como faz isso nele. Mas se o problema é esse mesmo, esse tipo de configuração deve resolver. Aliás, se vc conseguir resolver com essa abordagem, por favor adicione você mesmo uma resposta detalhada aqui para ajudar outras pessoas no futuro. :)
Comment: Se é outro erro, abra outra pergunta. Aliás, [já tem uma pergunta sobre essa mensagem de erro](http://pt.stackoverflow.com/questions/62847/n%C3%A3o-consigo-fazer-com-que-o-personagem-do-nightmare-desapare%C3%A7a-depois-de-morto), mas o autor não deu mais detalhes como solicitado...
Comment: Luiz Vieira, eu tenho o McAfee instalado, mas eu não sabia que o problema seria ele, eu tava lendo as fontes que você me passou, e uma pessoa que tinha o mesmo problema que o meu, informou que, desabilitando a varredura em tempo real e o Firewall do windows resolveria o problema, mas com isso meu computador ficaria bastante vulnerável, sendo que eu não posso desinstalar pois tenho a versão paga dele. Você vê algum meio de eu resolver esse problema ? Desde já agradeço a sua ajuda.
Comment: Eu conseguir rodar ele desabilitando a opção varredura em tempo real, mas ao executar ele está aparecendo esse erro: " 'Player' AnimationEvent 'RestartLevel' has no receiver! Are you missing a component? " , você por um acaso, saberia o motivo desse erro ? Eu vou tentar procurar a opção de adicionar ele a lista de arquivos confiáveis e assim que eu conseguir, eu irei escrever uma resposta detalhada aqui.
Comment: Pronto. Vou dá uma olhada aqui, Obrigado.
Answer: Com a ajuda do Luiz Vieira e dando uma pesquisada no Google, descobrir que esse erro é causado pelo anti vírus, no meu caso o McAfee que bloqueia o acesso ao arquivo, pois acha que está se tratando de uma invasão/vírus. Eu não conseguir adicionar uma lista confiável, e como eu não posso desinstala-lo, pois tenho a versão paga, a saída mais viável, é, desabilitar a varredura em tempo real, rodar seu jogo e assim que termina habilitar de novo ou se possível trocar o anti vírus. Mais uma vez muito obrigado pela ajuda Luiz Vieira.


Does anyone have real-life examples of e-mail being intercepted?

Question: As anyone will tell you, e-mail is not secure. It travels around the Internet in plain text and we should not use it for sending passwords and other sensitive details.
For years I've been designing my systems around this mess - e.g. 'password reset' emails to users must always have an extra layer of authentication. However, I can never help wondering:
How often does e-mail actually become compromised while in transit?

Is this a real world problem or a
theoretical one?
Does anyone have
any case studies / links on real attacks?
What are the actual methods a hacker might use to steal an e-mail?
Answer: I personally have witnessed live, in-transit, email interception. It was at a technical conference and the session was all about sniffing networks. The instructor just fired her sniffer up on the conference wireless network and within 15 minutes had several POP3/SMTP authentication pairs complete with the retrieved and sent messages. These were laptops out in the conference halls polling their email over unencrypted protocols. Then in the 15-30 minutes after the session the session attendees were doing the same thing once they downloaded the right tools.
I would be very, very surprised if the same kinds of things are not ever done on our Campus WLAN.
As a side note, the instructor also admitted to sniffing her cable-neighbor's traffic. For educational purposes only.
In terms of SMTP processing email is vastly more likely to be intercepted close to the end points. The interested parties are on either end of that conversation. In the middle where the SMTP traffic is flowing over the greater Internet, the interested party is much more likely to be a government than evil hackers.
That said, the biggest interception cases are not grabbing the SMTP transaction in flight, it's grabbing the POP3/IMAP/SMTP/WebMail login which ensures complete interception ability in perpetuity (or at least until the password is changed). This is attempted daily on my network via Phishing. Once credentials are leaked email can be read willy nilly, or more commonly used to send spam by way of our trusted email servers.

To answer your questions, though,
1: Yes, this is a real problem. The biggest exposure is over untrusted (or trusted but unencrypted) wireless networks. And governments.
2: They're out there, but I'd have to google and I'm lazy this Saturday morning. Intercepting actual SMTP transactions not at the endpoint is generally the purview of Governments and corporate security. Hackers generally target mailboxes not the transactions, as they're a much richer target.
3: Sniffing wireless networks for unencrypted email transactions is by FAR the easiest method. Think coffee-shop type setups. Lesser methods like suborning mail servers to grab messages are more theoretical than actual, though much more harmful  when they do occur.

Stepping back one step to the topic of password reset emails, hackers who have compromised a mailbox can leverage such emails to compromise other sites. They compromise a gmail account and by looking at messages realize that this person does a lot of business with a certain ecommerce site known to store credit-card information. They go to that site and go through the forgotten-password process (since a LOT of sites now use the email address as the account-name these days) and get the password reset email. They reset the password, which starts the timer on when the account-owner will notice. Evil commences, especially if the ecommerce site is one that displays whole credit-card numbers in the profile.
The sad thing here is that it is entirely possible that the account-owner won't even see the inability to log in as a certain sign that evil has occurred. If they're not using a password-remembering program they could just chalk it up to creeping old age and just reset the password to one they know.

12.5 years later...
The risks here have evolved a lot. The anecdote I opened with happened in 2007 on an 802.11b network (not g, not ac, not...) that wasn't even secured with WEP. In the years since:

Mail moved to Gmail or Outlook.com, with a few holdouts on corporate networks and other mail service providers, mostly transacting over the browser.
Protocols like IMAP are seen as unworkably insecure due to their inability to support two factor authentication. Old-timers and self-hosting enthusiasts still use it, though.
More email is being transacted over phones and tablets than laptops, especially on conference networks, which talk over HTTPS.
Google (which controls between 30 to 50% of all email transactions, depending on how you count) has been pushing the use of STARTTLS in the SMTP conversation, which encrypts the contents of the email over the wire. This point more than any of the above makes sniffing SMTP conversations boring.

All of this makes intercepting the SMTP conversations less interesting. The parties most interested in this sort of interception are national security agencies, who are more interested in who is talking to whom using which keywords than attacking a specific individual. The risks here have moved into Phishing and credential stuffing attacks, since a compromised mailbox on a reputable service is valuable for spammers.
The more interesting question is:

How common is interception of webmail conversations?

The answer there is "more common than you think." Corporate surveillance tools like zScaler now offer TLS interception, which lets your corporate security department tell if you're emailing yourself company secrets. This is commercialized and on the market already.
Comment: Is it really that common for SMTP creds to be sent in the clear? Won't they be encrypted if either STARTTLS is used for the SMTP session or if an encrypted SMTP AUTH method is used, or am I missing something?
Comment: @acannon828 In 2007 or so when I witnessed that, very much so. In 2019 after Google started flagging email not sent over STARTTLSed SMTP, much, much less common. Also helping reduce the incidence is the almost complete appification of email from client devices, moving the 'send email' part of the transaction to HTTPSed API calls.
Answer: Your question is a little confusing (talking about emails being intercepted in transmit, but stating that your fix is to make it harder to retrieve the password - that's not transit).
Once the email leaves your network it's going to be divided up into several packets which are likely to take different routes to their destinations. The chances of the whole thing being intercepted along the way is slim.
However, it is trivial for it to be intercepted on either the originating network or the destination network, depending on the setups - especially if these are open wireless networks. They would be intercepted by packet sniffers.
So, the chances of your email being intercepted somewhere in the middle? Slim, but possible and is it a risk your business can take? It's much more likely that it will be either intercepted on one end or the other, or the account will be compromised by an easily guessable password.
EDIT: It's worth noting that just because the whole thing is unlikely to be intercepted, doesn't mean that parts of it won't be. Eg. a credit card number in the body could pass through an untrustworthy network (the Internet!), or the Subject ("I'd advise selling all your shares before our next AGM").
Comment: Thanks. Assume no open wifi network on either end?
Comment: Almost any wifi can be intercepted by someone connected to the network. Even if no wireless whatsoever, your network topology may still send it through an intermediary machine
Answer: An attacker can intercept your email via several ways. For example, compromising the destination mail server using DNS poisoning or by attacking the email server itself.
Also, compromising a router near the sender or the receiver will enable the attacker to steal your email.
The attacker can sometimes compromise your own machine!
Comment: If the attacker has compromised your machine, email is not the weakness. Any examples / more info on compromising routers?


How to map host port range (5000-5004) to the same port (80) in 5 different containers with docker-compose

Question: I want to run 5 independent instances of the service website on host. Each instance will run in a separate container. The containers are created using docker-compose. There are specific ports on host pre-allocated for this purpose (5000-5004). The service runs on port 80 in the container. And this should be then mapped to ports 5000, 5001, 5002,5003, and5004 on host.
Then I start the containers with docker-compose up --scale website=5 which should start 5 instances of the container and map the ports to those specified in the .yml.
But this fails with ERROR: Invalid published port: 5000-5004.
my docker-compose.yml:
version: '3.4'
services:
    website:
        image: php:apache
        volumes: ./website:/var/www/html
        ports:
            - "5000-5004:80"

Maybe this port mapping is not valid for docker-compose but how can I get it working otherwise?
Comment: Documentation suggests that you are legal. How old is your `docker-compose`? `docker-compose --version`
Comment: @spender docker-compose version 1.17.1, build unknown
Comment: Thanks, installed newest version (1.26.2) and it works! Feel free to post this as an answer and I will accept it.
Answer: It looks like this was fixed in later versions:
https://github.com/docker/compose/pull/5428
Are you sure you are using a recent version of docker-compose? You can check your current version with:
docker-compose --version


Prove $\left\{u \# v | u,v \in \{0,1\}^{*} \text{ and } u \text{ is a substring of } v \right\}$ is not context free

Question: I'm practising for my CS exam and got stuck on this problem
$\left\{u \# v | u,v \in \{0,1\}^{*} \text{ and } u \text{ is a substring of } v \right\}$
So I've tried using following pumping lemma:
Pumping Lemma would be: $0^n1^n\#0^n1^n$. v and x cannot contain #, otherwise when pumping more or less # appear and the new string is not in the language.
Now suppose $vwx$ are in the left $0^n1^n$, then $v^2$ and $x^2$ will make it longer than the R.H.S.;
However I'm not really sure how to proceed here, since u is a substring I believe the N on RHS must be lower than on LHS, am I going about it the right way or not?
Answer: I'm assuming that your $n$ is the pumping length, and that you're suppose that $0^n1^n\#0^n1^n$ can be decomposed as $uvwxy$ so that $|vwx|\le n$, $|vx|\ge 1$, and $uv^kwx^ky\in L$ for all $k\ge 0$, where $L$ is the language in question. This will work, but there are several cases to be considered.

If $vwx$ is contained in the first $0^n1^n$, taking $k=2$ gives you a word $z_1\#z_2$ with $|z_1|>|z_2|$, and such a word cannot be in $L$.
If $vwx$ is contained in the second $0^n1^n$, taking $k=0$ gives you a word that is not in $L$ for the same reason.
If the $\#$ is in $vx$, any $k\ne 1$ gives you a word that is not in $L$, since it does not have exactly one $\#$.

Those cover what you've already done.
Now show that the only other possibility is that $v=1^p$, $w=1^q\#0^r$, and $x=0^s$ for some $p,q,r,s\ge 0$ such that $p+q+r+s\le p$, and $p+s\ge 1$. Then split this into two case, $p\ne 0$ and $p=0$. In each case there is a way to choose $k$ so that $uv^kwx^ky\notin L$ for the same kind of reason that we've seen before.


Asymptotics for a partial sum of binomial coefficients

Question: Good afternoon,
I would like to ask, if anyone knows how to evaluate a sum
$$\sum_{k=0}^{\lambda n}{n \choose k}$$
for fixed $\lambda < 1/2$ with absolute error $O(n^{-1})$, or better.
In Concrete Mathematics (Graham, Knuth, Patashnik), it is shown how to evaluate this sum with absolute error $O(1)$, but it is not clear to me, how to obtain better absolute error in a straightforward manner.
Thank you in advance.
Answer: This is more of an extended comment than an answer, but you may find it useful.
In Exercise 9.42 of Concrete Mathematics (page 492 in the second edition),
the authors establish the asymptotic formula
$$\sum_{k=0}^{\lambda n} {n\choose k}=2^{n H(\lambda)-\lg(n)/2+O(1)}$$
where $0<\lambda< 1/2$,
$H(\lambda)= \lambda \lg({1\over \lambda})+(1-\lambda)\lg({1\over 1-\lambda})$, and
$\lg$ is the binary logarithm.
The sum on the left is a small fraction of the full sum $2^n$.
Note that this is a multiplicative approximation, the ratio of the
sum and the approximation remains bounded as $n\to\infty$, not the difference.
Their result has an interpretation using probability.
Write
$$\sum_{k=0}^{\lambda n} {n\choose k} =2^n\,\mathbb{P}(X_n/n\leq \lambda)$$
where $X_n$ is a binomial$(n,1/2)$ random variable.
The theory of large deviations suggests an approximation
$$\mathbb{P}(X_n/n\leq \lambda)\approx \exp(-nI(\lambda))$$
where $I$ is the rate function $I(x)=x\log(x)+(1-x)\log(1-x)+\log(2)$.
This gives the leading factor in their approximation; they also divide by $\sqrt{n}$
 for further accuracy.
If you are willing to use the standard normal distribution function
$\Phi(z)=\mathbb{P}(Z\leq z)$, then by the central limit theorem,
 we have
$$ \mathbb{P}(X_n\leq \lambda n)
  =\mathbb{P}\left({X_n-n/2\over\sqrt{n/4}}\leq {\lambda n-n/2\over\sqrt{n/4}} \right)
\approx\mathbb{P}\left(Z\leq \sqrt{n}(2\lambda-1) \right).$$
In other words, we have the approximation
$$ \sum_{k=0}^{\lambda n} {n\choose k} =2^n\, \Phi(\sqrt{n}(2\lambda-1)).$$
This seems to be at least as
accurate as the Concrete Mathematics approximation,
and you can get more accuracy by using the "continuity correction".
More detailed  asymptotic results for binomial tails can be found in this paper by
Andrew Carter and David Pollard. In particular, see Theorem 1. I hope you find what you want there; happy hunting!
Comment: Let me mention that CLT **cannot** yield large deviations estimates. (I remember having explained that to Qiaochu on the site hence this part of your answer indirectly confirms the surprising extent of this confusion.)
Comment: @ThomasAhle What I mean is that, in the present context, CLT provides the asymptotics of $P(X_n\le n/2+\lambda\sqrt{n}/2)$ when $n\to\infty$ **for every fixed** $\lambda$, but that CLT says nothing about the asymptotics of $P(X_n\le n/2+\lambda_n\sqrt{n}/2)$ when $n\to\infty$ if $\lambda_n$ varies with $n$, especially if $\lambda_n\to\infty$ or if $\lambda_n\to0$. There are tools to deal with the latter, but CLT is not one of them.
Comment: @Did Do you mean that CLT based approximations can only be sharp for $\lambda$ close to $1/2$, and not in the tail?
Comment: @Byron Would it be possible to expand the `O(1)` from concrete mathematics further?
Answer: Asked for is an approximation to the sum
$$\sum_{j=0}^{cn} {n\choose j}$$
for some fixed constant $c$.  We provide more than this,
an approximation to the finite sum over binomial coefficients
$$\sum_{j=a}^b {n\choose j}$$
for integers $0\le a \le b \le n$   The asymptotic approximation (which proves to be useful numerically, even for modest values of $n$) can be obtained
by combining two ideas.
First, the sum of a function $g$ over the integers can be written as an integral over $g$ plus an asymptotic series of the
odd derivatives of $g$ by using the midpoint form of the Euler-Maclaurin sum formula,
$$\sum_{j=a}^b g(j) \sim \int_{a-1/2}^{a+1/2}g(x)\,dx + \sum_{j=1}^{\cdots} {-(1-2^{1-2j})B_{2j}\over (2j)!}\big(g^{(2j-1)}(b+1/2)-g^{(2j-1)}(a-1/2)\big)$$
Here $B_{2j}$ is a Bernoulli number.
Second, the binomial coefficient itself is the real function
$$g(x) = {n\choose x} = {\Gamma(n+1)\over \Gamma(n-x+1)\Gamma(x+1)}\ ,\qquad\hbox{$x>-1$}$$
evaluated at the integers; and an asymptotic series for that real function can be developed using the asymptotic expansion of for the $\Gamma$-function (Stirling's approximation)
$$\ln \Gamma(x) \sim (x-1/2)\ln x - x + {1\over 2}\ln (2\pi) + \sum_{m=0}^{\cdots} {B_{2m}\over (2m)(2m-1) x^{2m-1}}$$
Combining the two series gives an asymptotic approximation to the desired sum
where all the terms are known, the various integrations required being tractable.
The lead approximation, as other contributors have noted, involves the error function
$${\rm erf}\,(x) = {1\over \sqrt{\pi}}\int_0^x e^{-t^2}\,dt$$
and we have
$$S \equiv {1\over 2^n}\sum_{j=a}^b {n\choose j}\sim {1\over 2} \,{\rm erf}\, (y_b) - {1\over 2}\,{\rm erf}\,(y_a) + O(1/n)$$
The advantage to working with $S$ and not the original sum is that $S$ is $O(1)$ as $n\to \infty$ (and $S=1$ for $a=0$ and $b=n$).
We have made the definitions
$$\eqalign{
\xi_a & = a-n/2-1/2  \cr
y_a &= \xi_a/\sqrt{n/2}\cr}
\qquad
\eqalign{
 \xi_b &= b-n/2+1/2\cr
y_b &= \xi_b/\sqrt{n/2}\cr}$$
Using Maple${}^{\rm TM}$ to do the necessary integrations exactly and to organize the necessary algebra, we can find the higher terms as
$$S \approx f(y_b)-f(y_a) + {\sqrt{2}\over 6\sqrt{\pi}}{1\over n^{3/2}}\big(h(\xi_b)-h(\xi_a)\big)$$
Here
$$f(y) = {1\over 2}\,{\rm erf}\,(y) + {1\over\sqrt{\pi}}\sum_{j=1}^{\cdots} {e^{-y^2}L_j\over n^j} $$
is a sum whose coefficients $L_j$ are all $O(1)$ for large $n$,  even if both $a$ and $b$ are $O(n)$.
We also find
$$h(y) = e^{-2\xi^2/n} \sum_{j=0}^{\cdots} {\xi M_j(\xi)\over n^j}$$
which is a more complicated sum; the coefficients $\xi M_j(\xi)$ can be large since we can have $\xi = O(n)$, but when $\xi$ is large
the contribution to $h$ is heavily suppressed by the lead factor of $e^{-2\xi^2/n}$, so that $h$ functions numerically as a series whose terms
diminish successively, though I do not know if they fall as $O(1/n)$ or not.   In practice a keeping few terms works well if $n$ is not too small.
The first few corrections are
$$\eqalign{
L_1 &= {1\over 12}\,(2y^2-3)y\cr
L_2 &= -{1\over 1440}\,(40y^6-292y^4+410y^2-45)y\cr
L_3 &={1\over 362880}\,(1120y^{10}-20048y^8+103248y^6-159768y^4+33390y^2+14175)y\cr
L_4 &= -{1\over 87091200}(22400y^{14}-745920y^{12}+8413728y^{10}-38540496y^8\cr
&\qquad\qquad\qquad\qquad\qquad\qquad+65383848y^6-19336212y^4-15416730y^2+893025)y\cr
}$$
and
$$\eqalign{
M_0(\xi) &=1\cr
M_1(\xi) &=-{9\over 10} + {43\over 15}\lambda -{4\over 3}\lambda^2\cr
M_2(\xi) &= +{25\over 224}-{1153\over 252}\lambda+{3296\over 315}\lambda^2-{268\over 45}\lambda^3+{8\over 9}\lambda^4\cr
M_3(\xi) &=+{49\over 64}-{69\over 160}\lambda-{12329\over 600}\lambda^2+{62506\over 1575}\lambda^3-{112636\over 4725}\lambda^4+{728\over 135}\lambda^5-{32\over 81}\lambda^6\cr
}$$
where $\xi$ and $\lambda = \xi^2/n$ can both be $O(n)$ if both $a$ and $b$ are $O(n)$.  With the terms up to $L_4$ and $M_3$ included, the first term missing from
the expansion has an error of $O(1/n^5)$.
Asymptotic series have the characteristic numerical defect that if one adds too many terms, the partial sum of the series departs from the function being approximated.
To check that, I have
evaluated the series with including the terms out to $L_7$ and $M_6$, when the first term missing from the series is $O(1/n^8)$;
and for $n$ as modest as $100$ then the absolute error in $S$  improves steadily with an increasing number of terms
to $<10^{-14}$ for $a=0$ and all $b$ with $0\le b\le n$.  So if the series begins to depart
from the true sum it will have to do so at higher order than that.    Evaluation is fast because the evaluation
to approximate a sum involves but two calls to ${\rm erf}$ (which are fast); two calls to $\exp$; and one call to sqrt, outside of the evaluation of a few polynomials.
Comment: @CharliesMungerJr: OP is asking for the asymptotic behaviour of a sum, where the number of summands increase with increasing $n$.
Comment: Would you mind to have a look at https://math.stackexchange.com/questions/3912163/sum-of-binomial-coefficients-so-that-the-sum-equals-n-choose-n-2/3912290#3912290 ? I think that you could bring a lot for the case $a=0$, $b=m$. I would enjoy to improve my continuous solution. Thanks and cheers :-)


Can I declare a variable of a 'protocol' type in an Objective-C interface?

Question: My idea is very similar to declare a variable of an interface type in java.
So for example,
header file 1:
@protocol Calculator

@end

I then define an @interface CalculatorImpl which implements the above Calculator protocol.
In header file 2:
@interface SomeViewController : UIViewController {

}

@property (weak, nonatomic) IBOutlet UITextField *txtResult;
@property (weak, nonatomic) Calculator* calculator;

@end

However, the xcode will flag an error at the calculator line
property with 'weak' attribute must be of object type

Is this  usage of protocol disallowed by objective-c?
Answer: A @protocol isn't a type so you can't use it for the type of a @property.
What you probably want to do instead is this:
@property (weak, nonatomic) id <Calculator> calculator;

This declares a property with no restriction on its type, except that it conforms to the Calculator protocol.
Comment: How would you create a property with no restriction on it's type in swift, by setting it to type anyobject?
Answer: You should use
@property (weak, nonatomic) id <Calculator> calculator;

In Objective-C you cannot instantiate a protocol, you can only be conform to it. Thus, instead of having an object of type Calculator, you should have a generic object that is conform to Calculator protocol.
Otherwise you can use
@property (weak, nonatomic) CalculatorImpl* calculator;

since CalculatorImpl is an interface, not a protocol.


Save game data not player data with datastore on roblox

Question: this is a general question using lua and roblox studio. I am at the point in my game in which I need to save some information in order to share it with players that join. Particularly, I am coding a platform game in which players jump on platforms and when they do, the platforms turn to the color of their team. I need the platforms colours to update for all players but also if a player joins mid game, the platforms that have already been 'conquered' need to be already of that colour. For this I am using getAsync and setAsync. For what I have seen, people mostly use datastores to save data in-between games, but in my case I want the data saved during the game to be retrieved during the game. Once the game is over, the data will be set to nil. I am assuming datastores are the way to go (...?). The problem that I have is that, as far as I can tell, datastores in roblox only allow to save one value per key and it saves it with the key being the player. But I need three values by key. These are: the row, the column and the colour of the platform conquered. I don't necessarily need to know the id of the player either. I want then every player to access this datastore when they join or when it updates. Ideally I would want something like this:
Set up:
local dataStoreService = game:GetService("DataStoreService")
local PlatformsScored = dataStoreService:GetDataStore('PlatformsScored')

inside a function when player scores:
PlatformsScored:SetAsync({col, row}, platformColor)

Then, retrieved and fired to all clients and/or when new player joins in:
local pScoredNow = PlatformsScored:GettAsync({col, row}, platformColor)

for k, platform in (myPlatforms) do
   if platform.col == col and platform.row = row do
   platform.BrickColor = BrickColor.new(platformColor)
end

The idea being that this for loop loops through all the platforms and sets the colours. I have been looking on the internet and I am unsure as if this is even possible. Can you save tables to datastore in Roblox studio? Can datastore be ''impersonal'' that is not associated necessarily with a player ID as the key? Thanks.
Answer: You've asked a lot of questions, so I'll try to address them all

Can you save tables to datastore in Roblox studio? ... I need three values by key. These are: the row, the column and the colour of the platform conquered.

Tables cannot be saved, but if your data can be serialized, you can convert the table to a string using HttpService:JSONEncode(), and back to a table using HttpService:JSONDecode().
local HttpService = game:GetService("HttpService")
local dataString = HttpService:JSONEncode({
    row = 5,
    column = 10,
    color = "Red",
})
print(dataString)

local reconstructedData = HttpService:JSONDecode(dataString)
print(reconstructedData.row, reconstructedData.column, reconstructedData.color)

Can datastore be ''impersonal'' that is not associated necessarily with a player ID as the key

Sure, you can store information under any key you want. But you should be very careful choosing keys because every single game server will be writing to those keys. This is why playerID is always recommended, because it is a guaranteed unique key, and players cannot be in two servers at the same time, so there is no risk of two servers accidentally writing to the same key at the same time.
If you have multiple game servers writing to the same key, there is a very very high chance that two servers are going to overwrite each other's data and someone's stuff is going to get lost.

I want the data saved during the game to be retrieved during the game... I want then every player to access this datastore when they join or when it updates.

This isn't a good use-case for DataStores. DataStores should be used for persistent storage of data about players or the world that must carry across multiple servers. For example, think of a global leaderboard, or a player's game progress, or how deep a hole is that has been dug by multiple people (assuming you want that hole to persist the next time the game starts up).
If you are trying to access game state information and you are still in an active game, you can just have a new player construct their game board based on the current state. There's no need to communicate this through DataStores.
A good way to handle active game state information is to make a "GameManager" object in a server Script, and make it the authority over changes that happen in the game. A player scores? Tell the GameManager, it will update the scoreboard. A player joins? Ask the GameManager what the current state of the platforms/game board is.
You can accomplish all of this with simple lua tables, RemoteEvents, and RemoteFunctions. I like to use a ModuleScript to make my GameManager class. I rough outline of the architecture would be something like this ...
local PlayerService = game:GetService("Players")

-- keep a list of RemoteFunctions and RemoteEvents that are fired by players when they do something
local GetState = game.ReplicatedStorage.Functions.GetState
local PlayerAction = game.ReplicatedStorage.Events.PlayerAction

-- keep a list of RemoteEvents that are fired by the GameManager when something should be communicated to the players
local StartGame = game.ReplicatedStorage.Events.StartGame
local UpdateBoard = game.ReplicatedStorage.Events.UpdateBoard
local EndGame = game.ReplicatedStorage.Events.EndGame

-- make an authority over the game state
local GameManager = {}
GameManager.__index = GameManager

function GameManager.new()
    local gm = {
        -- keep a list of players
        teams = { "red" = {}, "blue" = {} },

        -- keep a list of scores per team
        scores = { "red" = 0, "blue" = 0 },

        -- keep track of the board colors
        platforms = {},

        -- keep track of the state of the game
        currentGameState = "WaitingForPlayers", --InGame, PostGame

        -- as good housecleaning, hold onto connection tokens
        __tokens = {},
    }
    setmetatable(gm, GameManager)

    -- if anyone ever asks what the current state of the game is, let them know!
    GetState.OnServerInvoke = function()
        return gm.scores, gm.platforms, gm.currentGameState, gm.teams
    end

    return gm
end

function GameManager:waitForPlayers()
   -- wait for players to join to start the game
   while #PlayerService:GetPlayers() < 1 do
       wait(5)
   end

   wait(5)
   -- tell everyone the round is starting!
   self:startNewGame()
end

function GameManager:startNewGame()
    -- start listening to game events
    local playerActionToken = PlayerAction:OnServerEvent(function(player, ...)
        -- the player has done something, update the game state!
        local args = { ... }
        print("PlayerAction : ", player.Name, unpack(args))

        -- if a platform was taken, alert all players so they can update their stuff
        UpdateBoard:FireAllClients(self.platforms)
    end)
    table.insert(self.__tokens, playerActionToken)

    -- assign players to teams...

    -- tell all the players that the game has begun
    StartGame:FireAllClients()

    -- rather than code a game loop, just kill the game for now
    spawn(function()
        wait(30)
        -- tell everyone the game is over
        self:endGame()
    end)
end

function GameManager:endGame()
    self.currentGameState = "PostGame"

    -- communicate to all players that the game is over, and let them know the score
    EndGame:FireAllClients(self.scores)

    -- stop accepting actions from the game and clean up connections
    for _, token in ipairs(self.__tokens) do
        token:Disconnect()
    end

    -- start the game over again!
    spawn(function()
        wait(30)
        self:waitForPlayers()
    end)
end

return GameManager

Then in a server Script, just create the GameManager...
local GameManager = require(script.Parent.GameManager) -- or wherever you've put it
local gm = GameManager.new()
gm:waitForPlayers()

Then in a LocalScript, have the players request the game state when they join the game...
-- connect to all the game signals that the server might send
game.ReplicatedStorage.Events.StartGame:Connect(function(args)
    -- construct the local game board
    print("Game has started!")
end)
game.ReplicatedStorage.Events.UpdateBoard:Connect(function(newBoardState)
    print("Board state has changed!")
end)
game.ReplicatedStorage.Events.EndGame:Connect(function(scores)
    print("Game has ended!")
end)

-- request the current game state with a RemoteFunction
local GetState = game.ReplicatedStorage.Functions.GetState
local scores, platforms, currentGameState, teams= GetState:InvokeServer()

-- parse the current game state and make the board...
for k, v in pairs(scores) do
    print(k, v)
end
for k, v in pairs(platforms) do
    print(k, v)
end
print(currentGameState)
for k, v in pairs(teams) do
    print(k, v)
end

Answer: Going through your questions, I saw you asked if you could save tables in datastores. Yes, you can. I'm not sure if you can do it through SetAsync(), but I know from personal experience you can do it through UpdateAsync(), I've done it countless times. If you don't know how to do that, here's how:
PlatformsScored:UpdateAsync("Platforms",function()
     local returningTable = {col,row}
     return returningTable
end)

This also answers your question of having keys that don't revolve around players. You can. Also just do the same thing to make the datastore nil, just replace everything inside the table with nil.