MySQL error when using a column from a query in a subquery

Question: I have the following code:
select count(*) as points
from question
where (select count(*)
       from answer inner join answer_test
       on answer_test.id_r = answer.id_r
           and answer_test.right = answer.right
           and  question.id_i=answer.id_i ) = 4

I get this error:

#1054 - Unknown column 'question.id_i' in 'on clause'
How should I access question.id_i in the subquery without getting that error?

I need to calculate the grade from a test. Each question has 4 answer possibilities so you get a point if you have all right. 'Right' column is a boolean and question.id_i must match the answer.id_i but it says it does not recognize it even if it does exist. How should I modify it to make it work?
Comment: Please provide sample data and desird results.
Comment: You're putting  table 'question' in the join condition, but you're not asking to join it.
Comment: Give table `question` an alias and use it in that way in sub-query. (like this `from question q` and in join condition instead of `question` use `q`.
Comment: @farbiondriven I need that question.id_i from the outside query, that's why I didnt specify it there. It must match the outside one
Comment: @michal.jakubeczy unfortunately it is still the same.. I get the error with q.id_i
Answer: select count(*) as points
from question as q
where (select count(*)
       from answer inner join answer_test
       on answer_test.id_r = answer.id_r
           and answer_test.right = answer.right
           and  q.id_i=answer.id_i ) = 4

Comment: While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
Answer: I am not sure but put your condition with question table in where clause as follows:
select count(*) as points
from question
where (select count(*)
       from answer inner join answer_test
       on answer_test.id_r = answer.id_r
           and answer_test.right = answer.right
           Where question.id_i=answer.id_i ) = 4 -- condition in where


Error: while querying a tables with has many through relationship in rails

Question: I am trying to pop up a modal which should display the user with role "player", I implemented three tables user role and userrole where user and role has, has many through association by userrole table.
the condition is as follows
one user can be a player or admin or both,
while displaying we should display users with the role, player only.
schema
 create_table "roles", force: :cascade do |t|
    t.string "name"
    t.boolean "active"
    t.integer "counter"
 end
  create_table "user_roles", force: :cascade do |t|
    t.integer "role_id"
    t.integer "user_id"
    t.index ["role_id"], name: "index_user_roles_on_role_id"
    t.index ["user_id"], name: "index_user_roles_on_user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "first_name"
    t.string "last_name"
    t.string "email"
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
    t.index ["team_id"], name: "index_users_on_team_id"
  end

the table model is as follows
class User < ApplicationRecord
  has_many :user_roles
  has_many :roles, through: :user_roles, :dependent => :destroy
end
class UserRole < ApplicationRecord
  belongs_to :role
  belongs_to :user
  validates :user_id, :uniqueness => { :scope => :role_id }
end

class Role < ApplicationRecord
    has_many :user_roles
    has_many :users, through: :user_roles ,:dependent => :destroy
end

in team controller i have
def load_users
              @user = User.includes(:userroles).where('userroles.name = ?',"Player")

                respond_to do |format|
                  format.html
                  format.js
                  format.json
                end

            end

log shows following error

Error (SQLite3::SQLException: no such column: userroles.name: SELECT
  "users".* FROM "users" WHERE (userroles.name = 'Player')):
Comment: should not `userroles` be `user_roles` ?
Answer: By default, includes doesn't perform left join and performs two separate DB queries instead. You can easily force left join though, in this case it's enough to do:
@user = User.includes(:user_roles).where(user_roles: { name: 'Player' })

By using user_roles: { } notation you let ActiveRecord know that you want to query DB also by user_roles column and ActiveRecord decides to perform left join. If you don't have the condition easily translatable to this notation, you can force left join using eager_load:
@user = User.eager_load(:user_roles).where('some complex SQL query including user_roles column(s)')

Comment: @gangothri, sorry, I was inattentive to your answer. Yes, it is correct, because user_roles table has no `name` field
Comment: this worked for me @user = User.includes(:roles).where(roles: { name: 'Player' })
Answer: You need to keep your table names consistent:
Wrong:
User.includes(:userroles).where("userroles.name = ?","Player")

Right (with underscore)
User.includes(:user_roles).where("user_roles.name = ?","Player")

Addendum (I'm not not on my dev machine right now, so this is untested)
User.joins(:user_roles).where("user_roles.name = ?", "Player")


Can this plugin gstreamer1.0-libav be used in india?

Question: While playing a video on default player in Ubuntu, I got a error message saying that it needs to install an extra plugin gstreamer1.0-libav.  There is a warning besides it saying that the plugin is restricted in some countries. Can this be used in India?
Comment: Can anyone tell if this can be used in India or if there are any restrictions applicable?
Answer: There is no technical problem here, but a legal one. Some countries have illiberal laws called "Digital restrictive management" and software patents, if you country has these laws then it is probably illegal for you to use this software.
Therefore you question is a legal one. You need to find out about local laws.


How can I setup my SSD+HDD-setup the best way?

Question: I have recently build a new system with a 256GB SSD and a 3TB HDD. I want to save all my files on my HDD while my programs and Ubuntu 14.04 should run on my SSD to boost the performance.
I might also be installing a Windows version later, but I am not so sure about that...
How can I do that? Is it possible to do that without reinstalling Ubuntu?
edit:
When I installed Ubuntu 14.04 64-bit on my system I chose Ubuntu to get installed on my SSD with the auto-partitioner.
I have not yet copied my data from my ext. hard drive to my internal storage, as I want it to go to the HDD, while all my installs should go to my SSD.
Later I might want another SSD-partition for Windows (if I install it) to use as my oprating system for gaming.
Comment: Please include more details: what partitions you currently have on both drives? By asking "Is it possible to do it without reinstalling Ubuntu?" do you mean after Windows installation or you have already installed Ubuntu?
Answer: If you have already installed Ubuntu on SSD then after Windows installation you will need to run Boot Repair. The steps you take are described here:
How to install the Boot-Repair tool in an Ubuntu live disc?
If you already have Ubuntu on HDD, so I would recommend just to remorarily save your /home folder to another partition, then manage your partitions (maybe you want to delete the previous one which contained Ubuntu)  with Gparted, which is included in Ubuntu and Live CD. The thread below has explanations how to manage partitions with Gparted.
How to resize partitions?
During the installation you could create or choose a partition for your /home folder, so you could place home on HDD having the / on SSD.
If you have already installed Ubuntu and want to move your home partition from SSD to HDD rather than reinstall Ubuntiu, then have a look at this thread:
How can I move my /home directory to another partition if it's already part of the / partition?
Comment: In installation stage I chose ubuntu to get installed on my ssd and then let the auto-partitioner do the rest. Now I just want to move my home folder to my hdd so I wont block space on my ssd. I might look into installing Windows as my second operating system in one or to month, but I would only use it for gaming so I would just run it of my SSD.
Comment: I added some additional answer about `/home` folder to the answer.


Can't talk to QnAMaker bot in Azure or Teams, but can locally with emulator

Question: I created a QnAMaker bot through the website https://www.qnamaker.ai, which then took me through the steps creating the bot in Azure.
When I click on the Test in Web Chat section of the bot in Azure, before I've even typed anything, an error message arrives in  Channels > Web Chat > Issues that states: "There was an error sending this message to your bot: HTTP status code Unauthorized"
I have download the code of the bot locally, and running it with npm, using ngrok and the Bot Emulator, I have successfully managed to connect to the bot and it works.
I haven't touched the AppID or Password in the Bot's settings in Azure, and these are the same credentials I used for the local bot that works.
Could someone please help?
Thanks
Answer: I solved this by removing the bot entirely and creating a brand new one. I think the issue with some sort of mix up with the AppID and AppPassword, even though they were both correct in the settings


Wifi does not work on Ubuntu 13.04

Question: I have a Dell Latitude E5510 I dual boot with Windows 7 and the wifi works good with Windows 7 but when I load in on Ubuntu it fails to make a connection I had to put a USB Wifi adapter in to get wifi. I would really like to know how to fix this so I don't have to use a USB Wifi stick.
Comment: Welcome to Ask Ubuntu! We need more hardware information to help you, can you look at [this question](http://askubuntu.com/questions/14008/i-have-a-hardware-detection-problem-what-logs-do-i-need-to-look-into) and then edit your question adding the information.
Answer: Upon running Additional Drivers, if you have broadcom STA driver activated, try removing it.  Restart and see if your wireless works.

Wifi does not work on Ubuntu 13.04


Java source code parser which supports annotations

Question: I need a Java source code parsing library for Java to programmatically extract method definitions and annotations.
Specifically, given code like :
<code>@WebMethod(operationName = "MyOperation")
public String myOperation(String param1,int param2) { ....
}
</code>
I have the following requirements:
1. Extract the name, return type and names and types of the method parameters
2. Extract the annotations associated with the method
3. Finally, create a new source file by removing the annotations
I am currently using JaxMeJS http://ws.apache.org/jaxme/js/jparser.html which satisfies 1. but not 2. or 3.
Could you recommended a parsing library that can fulfill all 3 requirements ?
Answer: Annotation processing is part of the Annotation processing tool in Java which runs as part of the Java compiler. I'm not sure how you can remove the annotations from the source code. This is not supported by APT. (It might be easier to remove the annotations from the compiler byte code than from the source code.)
I've implemented a source code generator based on annotations using APT in the Quickcheck project.
Another root could be to use ASM (or any other byte code manipulation tool) to read the annotations.
Answer: I think APT, as suggested by Thomas Jung is what you need. Still, if you want to look into other options, do check Java 6 grammar for antlr
Answer: JavaCC comes with a 1.5 parser.
Comment: javaparser http://code.google.com/p/javaparser/ based on JavaCC satisfies all my requirements.
Answer: How about using JDT parser?
JDT means Java Development Tools.
Eclipse use this.
I also did my project with it.
It is really nice. And there is much info about it.


Visualising RDF Triples using D3.js and Vue

Question: I found a pretty good example online of how to visualize RDF triples using D3. The output looks like this:

I'm trying to recreate the example in Vue, but I'm not succeeding in generating a proper visualization, nor making my nodes draggable. I'm sure I'm missing a couple of important steps in the mounted method (I have basic Vue knowledge). My entire code is available on GitHub, but I have also added the most important code below. Any help would be very much appreciated. Current output looks like this:

This is my main code:
<template>

    <svg></svg>

</template>

I found this also a very useful link: https://observablehq.com/@d3/force-directed-graph/2?intent=fork
Answer: There are a few things going on here. The major problem is that the version of d3 that the repository is using is d3 v3, while what you import in your repository is d3 v7, so the syntaxes are very different. And then the links, linkTexts, nodeTexts, etc. should be initiated before the ticked function. Then, you did mention that the dragging is not working, well that's because you commented the line:
// .call(force.drag)

But after uncommenting that, somehow force.drag is still error, so we need to implement our own draggable (taken from this example):
    function dragstart() {
      d3.select(this).classed("fixed", true);
    }

    function clamp(x, lo, hi) {
      return x < lo ? lo : x > hi ? hi : x;
    }

    function dragged(event, d) {
      d.fx = clamp(event.x, 0, width);
      d.fy = clamp(event.y, 0, height);
      force.alpha(1).restart();
    }

    const drag = d3.drag().on("start", dragstart).on("drag", dragged);

And then we can uncomment the line I mentioned and pass the drag variable:
    var nodes = svg
      .selectAll(".node")
      .data(graph.nodes)
      .enter()
      .append("circle")
      .attr("class", "node")
      .attr("r", 8)
      .call(drag);

Finally, you can also copy-paste the CSS from the example you provided.
This is the full demo in codesandbox if you want to see it live:
Comment: thanks for the explanation and the detailed response! Great work!


How to use MCPE /give command with add enchant attribute?

Question: The new beta 1.0.5 has introduced /give command.
How do I add the enchant attribute?
Comment: Just to clarify, are you asking how to to /give a weapon object that has an enchantment on it?
Comment: Yup in minecraft pocket edition
Answer: Components are in JSON format. However, some of the ones on PC don't exactly work as suspected.
Example of JSON format:
<code>{"fieldname":"field content"}
</code>
or
<code>{"field":123}
</code>
Comment: Does this make use of the give command? How? Can you illustrate that?
Comment: After a couple years, I have determined that my answer is, in fact, probably a bad answer. I was attempting to illustrate the format used in Pocket Edition commands (and also in Java commands). In short, this ain't it, chief, it does not help to answer the question.
Answer: Say you want a sword with max sharpness and unbreaking, this is the command:
<code>/give @p diamond_sword 1 0 {ench:[{id:16,lvl:32767},{id:21,lvl:32767}]}
</code>
If it doesn't work, then I don't know.


Run many java applications via ssh in a bash script

Question: I'm trying to optimize some experiments with a Java application. The same application is on many machines. I want to run all of them via a bash script with ssh.
I have a bash script that has a while loop to run the application. Like this
while [ $COUNTER -lt $WORKERS ]
do
  ssh  ubuntu@host "java java-app.jar" > /data/some-logs.log
  ((COUNTER++))
  ((IP_BEGINS++))
done

However when I run the script I have to wait a moment and press Ctrl+C for every machine. How can I run every aplication on background?
Comment: I'm a big fan of Fabric for remote execution: see https://docs.fabfile.org/en/1.12.1/usage/parallel.html
Comment: Thank you, I only need to use bash.
Comment: Read this https://www.maketecheasier.com/run-bash-commands-background-linux/
Answer: prefix with nohup and append a & to the command, that will run it in the background.
while [ $COUNTER -lt $WORKERS ]
do
  ssh  ubuntu@host "nohup java -jar java-app.jar > /data/some-logs.log 2>&1 &"
  ((COUNTER++))
  ((IP_BEGINS++))
done

You might need to muck around with the quotes and placements of the & to make sure the remote ssh command gets backgrounded and not your local ssh
EDIT - I fixed the answer based on your comment. Also added the stderr redirect to the same log file, that might help when things go wrong
Comment: Thank you! It worked. However I had to change the prefix and & as you mentioned.
 ssh  ubuntu@host "nohup java java-app.jar  > /data/some-logs.log &"


Object Variable not set on Comments within Cells

Question: I'm trying to determine the length of a cell's comment but I get an object variable not set when there is no comment within the Cell.
Len(Range("C8").Comment.Text)
Comment: What is that you are trying to do>?
Answer: This happens because in that case Range("C8").Comment is Nothing, so the code fails when trying to retrieve the Text property of Nothing.
You need a null check:
If Not Range("C8").Comment Is Nothing Then
    length = Len(Range("C8").Comment.Text)
End If


wxPython Paint Damaged, Clipped area

Question: I have the following simple code (click the pink box and you can move it around with your mouse while holding down the left mouse button).
import wx

class AppPanel(wx.Panel):

    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, id)
        p = MovablePanel(self, -1)
        self.i = 0
        self.Bind(wx.EVT_PAINT, self.OnPaint, self)

    def OnPaint(self, event):
        dc = wx.PaintDC(self)
        self.i = self.i+10
        c = self.i % 255
        c = (0, 0, c)
        dc.SetPen(wx.Pen(c))
        dc.SetBrush(wx.Brush(c))
        dc.DrawRectangle(0, 0, 10000,10000)

class MovablePanel(wx.Panel):

    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, id)
        self.SetMinSize((500,500))
        self.SetSize((500,500))
        self.SetBackgroundColour("PINK")
        self.LEFT_DOWN = False
        self.Bind(wx.EVT_MOTION, self.OnMove, self)

        self.Bind(wx.EVT_LEFT_DOWN,
                         self.OnClickDown,
                         self)

        self.Bind(wx.EVT_LEFT_UP,
                         self.OnClickUp,
                         self)

    def OnClickUp(self, event):
        self.LEFT_DOWN = False
        self.Refresh()

    def OnClickDown(self, event):
        self.LEFT_DOWN = True
        self.Refresh()

    def OnMove(self, event):
        if self.LEFT_DOWN:
            p = self.GetTopLevelParent().ScreenToClient(wx.GetMousePosition())
            self.SetPosition(p)

if __name__ == "__main__":
    app = wx.App(False)
    f   = wx.Frame(None, -1, size = (700, 700))
    p   = AppPanel(f, -1)
    f.Show()
    f.Maximize()
    app.MainLoop()

and it is suppose to look like the following (simply resize the frame)

However after moving the pink box around you will see it really looks like this

I have tried the following
dc.Clear()

dc.DestroyClippingRegion()

wx.FULL_REPAINT_ON_RESIZE

wx.EVT_ERASE_BACKGROUND

I'm pretty sure it has to do with it being a panel, and therefore the PaintEvent only marking it partially damaged. This part is colored differently making the 'ghosting' or 'smearing' obvious. Perhaps I'm using the wrong words because I was unable to find a solution (and I this seems to be a non complex issue simply having to do with the 'damaged' region).
Answer: Ok I found the problem, but I'll try to post more details later.
Basically the goal of this code is to move a panel around and then update the parent panel. SetPosition calls Move which going through the wxWidget code calls DoMoveWindow, all of this leads to a change in position and a repaint call (not sure what calls the repaint yet). Great. However the repaint only marks a certain 'area' as it tries to be efficient. That is why some of the issue can be solved by having the panel go over the 'ghosted' area. What you have to do is after the SetPosition, call GetParent().Refresh(), which will send a 'full' paint without any excluded area.
Another thing to note is there are TWO terms for this 'damaged' or 'clipped' area. One is 'damage' however there is another, 'dirty'.  Damage is used in the wx PaintDC information

Using wx.PaintDC within EVT_PAINT handlers is important because it
  automatically sets the clipping area to the damaged area of the
  window. Attempts to draw outside this area do not appear.

Trusting the documentation you will be mostly lost. However in one of the wxPython DoubleBuffer how to's the lingo changes (but it is the same thing as 'damage')

Now the OnPaint() method. It's called whenever ther is a pain event
  sent by the system: i.e. whenever part of the window gets dirty.

Knowing this if you Google wx Window dirty you will get the following

Mark the specified rectangle (or the whole window) as "dirty" so it
  will be repainted. Causes an EVT_PAINT event to be generated and sent
  to the window.

Take the following three print cycles where an EVT_PAINT was fired after a SetPosition call (this is WITHOUT the GetParent().Refresh() call)
# first EVT_PAINT
Drawing
Panel Size (1440, 851)
Clipping Rect (0, 0, 1440, 851)
Client Update Rect (x=0, y=6, w=500, h=501) # the only place getting update is
                                            # directly below the panel
                                            # (that is (500, 500) )

# second
Drawing
Panel Size (1440, 851)
Clipping Rect (0, 0, 1440, 851)
Client Update Rect (x=0, y=6, w=910, h=845) # however this time the update area is
                                            # bigger, this is also right before
                                            # the move
                                            # i believe what it is doing is
                                            # drawing from (0,6) to (910, 851)
                                            # why? because the panel is moving to
                                            # (410, 390) and the bottom right
                                            # corner of the panel (after moved)
                                            # is (410+500, 390+461) = (910, 851)
                                            # or about where the edge of the panel
                                            # will be

# third
Drawing
Panel Size (1440, 851)
Clipping Rect (0, 0, 1440, 851)
Client Update Rect (x=410, y=390, w=500, h=461)

Here is the update code to play around with, hopefully this will help others.
import wx

instructions = """
How to use.
1) Hover your mouse over the pink panel.
2) Click down (left click)
3) While holding down drag mouse around
4) Release mouse button to stop.

"""

class AppPanel(wx.Panel):

    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, id)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.settings_sizer = wx.BoxSizer(wx.HORIZONTAL)
        p = MovablePanel(self, -1)

        self.c = wx.CheckBox(self, -1, label = "Ghosting On?")
        self.p = p
        self.i = 0

        self.settings_sizer.Add(self.c)

        self.sizer.Add(self.settings_sizer)
        self.sizer.Add(self.p)
        self.SetSizer(self.sizer)
        self.Layout()

        self.Bind(wx.EVT_CHECKBOX, self.OnCheck, self.c)
        self.Bind(wx.EVT_PAINT, self.OnPaint, self)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnErase, self)

    def OnCheck(self, event):
        print "CHECK\n\n\n\n\n"
        v = self.c.GetValue()
        self.p.r = v
        print v

    def OnErase(self, event):
        pass

    def OnPaint(self, event):
        print "Drawing"
        dc = wx.PaintDC(self)
        print "Panel Rect, ", self.p.GetPosition(),
        print self.p.GetSize()
        print "Clipping Rect", dc.GetClippingBox()
        print "Client Update Rect", self.GetUpdateClientRect()
        print "----------------------------"
        self.i = self.i+10
        c = self.i % 255
        c = (0, 0, c)
        dc.SetPen(wx.Pen(c))
        dc.SetBrush(wx.Brush(c))

        dc.DrawRectangle(0, 0, 10000,10000)
        self.SetBackgroundColour(c)

        dc.SetPen(wx.Pen("WHITE"))
        dc.SetBrush(wx.Brush("WHITE"))

        dc.DrawRectangle(0, 0, self.GetSize()[0], self.c.GetSize()[1])

class MovablePanel(wx.Panel):

    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, id)
        self.SetMinSize((300,300))
        self.SetSize((300,300))

        txt = wx.StaticText(self, -1, label = "CLICK AND DRAG ME!")
        inst = wx.StaticText(self, -1, label = instructions)

        font = wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD)
        txt.SetFont(font)
        inst.SetFont(font)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(txt, flag = wx.ALIGN_CENTRE_VERTICAL | wx.ALIGN_CENTRE_HORIZONTAL)
        sizer.Add(inst, flag = wx.ALIGN_CENTRE_VERTICAL | wx.ALIGN_CENTRE_HORIZONTAL)
        self.SetSizer(sizer)

        self.SetBackgroundColour("PINK")
        self.LEFT_DOWN = False
        self.r = False
        self.Bind(wx.EVT_MOTION, self.OnMove, self)

        self.Bind(wx.EVT_LEFT_DOWN,
                         self.OnClickDown,
                         self)

        self.Bind(wx.EVT_LEFT_UP,
                         self.OnClickUp,
                         self)

    def OnClickUp(self, event):
        self.LEFT_DOWN = False
        self.Refresh()

    def OnClickDown(self, event):
        self.LEFT_DOWN = True
        self.Refresh()

    def OnMove(self, event):
        if self.LEFT_DOWN:
            p = self.GetTopLevelParent().ScreenToClient(wx.GetMousePosition())
            self.SetPosition(p)
            if not self.r:
                self.GetParent().Refresh()

if __name__ == "__main__":
    app = wx.App(False)
    f   = wx.Frame(None, -1, size = (700, 700))
    p   = AppPanel(f, -1)
    f.Show()
    app.MainLoop()

wxPython Paint Damaged, Clipped area


How to download an ISO file for Ubuntu?

Question: I want to create an USB-stick with Ubuntu! I follow your example and download the start file. I get it as ubuntu-14.04.5-desktop-i386.iso.torrent. When I start Rufus to create the USB stick, it will not find any ISO-file.
How do I get the ISO file for Ubuntu?
Comment: A torrent is not the ISO file itself. It is a means of getting the ISO file if you have installed a torrent client such as Bittorrent, uTorrent or Transmission. If you haven't, use the real ISO download link that can be found elsewhere on the page.
Comment: The following link may help you select a suitable iso file (version and flavour of Ubuntu) for your computer, [How to select the version and flavour of Ubuntu](https://ubuntuforums.org/showthread.php?t=2230389&p=13540865#post13540865)
Comment: Ubuntu 14 is very old, the latest is 18.04. What version do you want?
Comment: I'm just to unpatient trying to get it down to start learning about Linux. I found it out my self and have now downloaded the file!

I installed BitTorrent and it downloaded it for me with the Torrent-file I got!
Comment: "14.05.5" ???? That can not be a correct number.
Comment: You're absolutely right 14.04.5 is the right number! ;-)
Answer: .torrent is a torrent file using that file you should be able to download .iso file of ubuntu and locate iso file on rufus and you will be able to create ubuntu on usb.  To download torrent file use any torrent client software like utorrent bittorrent or transmission etc.
I hope this will help you.
Comment: Thank you so much for answering me. I hope some day be able to contribute my self in some way. some day.
Comment: If this answer helped then please mark as verified answer.
Answer: I have downloaded a lot of Ubuntu .iso images over the years and every time I downloaded an Ubuntu .iso image it maxed out all the available capacity from my internet service provider, except for the single time I tried downloading the Ubuntu .iso file from a torrent mirror site which was a lot slower. Your mileage may vary, so if you don't want to waste your time waiting for the Ubuntu .iso to finish downloading you should try downloading it with both http and torrent, and cancel the download that is slower.
btw I always download all Ubuntu iso images from the official Ubuntu website and I use a download tool that has resume interrupted download functionality like wget has using wget -c file.iso or GNU Wget for Windows, so I don't have to download the same bits twice.
-c
--continue
    Continue getting a partially-downloaded file. This is useful when
    you want to finish up a download started by a previous instance of
    wget or by another program.
An alternative to wget that works on all platforms (Windows/Mac/Linux) is the popular DownloadThemAll extension for Firefox. DownloadThemAll will help you select, queue, sort and run your downloads faster. It comes with advanced ways to select what links to download, and will remember your previous decisions so that you can queue more downloads with just one click. DownloadThemAll can also automatically or manually restart interrupted downloads in the same place where they were interrupted so you don't lose the part of the file that you already downloaded.
Answer: If you want to use Ubuntu 18.04 then use this link http://releases.ubuntu.com/18.04/
Or you can try Ubuntu 16.04
http://releases.ubuntu.com/16.04/
16.04 is also a LTS version and its 32bit flavour is also available

How to download an ISO file for Ubuntu?


In React/Redux reducer, how can I update a string in an nested array in an immutable way?

Question: My store looks like this,
{
  name: "john",
  foo: {},
    arr: [
      {
        id:101,
        desc:'comment'
      },
      {
        id:101,
        desc:'comment2'
      }
    ]
}

My textarea looks like this
<textarea
  id={arr.id} //"101"
  name={`tesc:`}
  value={this.props.store.desc}
  onChange={this.props.onChng}
/>

My action is
export const onChng = (desc) => ({
  type: Constants.SET_DESC,
  payload: {
    desc
  }
});

My reducer
case Constants.SET_DESC:
  return update(state, {
    store: {
      streams: {
        desc: { $set: action.payload.desc }
      }
    }
});

It works only if arry is an object, I had to make changes to the stream to an array and I am confused how I can update to an array, also how does get the right value from the store.
Comment: How do you want to update the array? Modify an element in the array or add a new element, remove one, etc?
Comment: How do you determine the id?
Comment: So you want to add a new object to the `streams` array every time you type in the textarea, with the textarea's id and value as the description?
Comment: I want to add a new element? next to   `{ id:101, here }`
Comment: I have udpated the textarea to have the same id as inside the stream array
Comment: Yes, - but i am open to other better implementations
Answer: The following example taken from the redux documentation might help you in the use case how to update items in an array. For more on this you can read on here http://redux.js.org/docs/recipes/StructuringReducers.html
state structure is something like this
{
  visibilityFilter: 'SHOW_ALL',
  todos: [
    {
      text: 'Consider using Redux',
      completed: true,
    },
    {
      text: 'Keep all state in a single tree',
      completed: false
    }
  ]
}

and reducer code is like below
function updateObject(oldObject, newValues) {
    // Encapsulate the idea of passing a new object as the first parameter
    // to Object.assign to ensure we correctly copy data instead of mutating
    return Object.assign({}, oldObject, newValues);
}

function updateItemInArray(array, itemId, updateItemCallback) {
    const updatedItems = array.map(item => {
        if(item.id !== itemId) {
            // Since we only want to update one item, preserve all others as they are now
            return item;
        }

        // Use the provided callback to create an updated item
        const updatedItem = updateItemCallback(item);
        return updatedItem;
    });

    return updatedItems;
}

function appReducer(state = initialState, action) {
    switch(action.type) {
        case 'EDIT_TODO' : {
            const newTodos = updateItemInArray(state.todos, action.id, todo => {
                return updateObject(todo, {text : action.text});
            });

            return updateObject(state, {todos : newTodos});
        }
        default : return state;
    }
}

Comment: I was hoping to do it in the structure i have asked. Meaning how do u access an array in a store
Comment: `state.todos` is array
Comment: unfortunately i dont understand.. but thanks for trying
Answer: If you have to update an element in a array within your store you have to copy the array and clone the matching element to apply your changes.
So in the first step your action should contain either the already cloned (and changed) object or the id of the object and the properties to change.
Here is a rough example:
export class MyActions {
    static readonly UPDATE_ITEM = 'My.Action.UPDATE_ITEM';

    static updateItem(id: string, changedValues: any) {
        return { type: MyActions.UPDATE_ITEM, payload: { id, changedValues } };
    }
}

export const myReducer: Reducer<IAppState> = (state: IAppState = initialState, action: AnyAction): IAppState => {
    switch (action.type) {
        case MyActions.UPDATE_ITEM:
            return { ...state, items: merge(state.items, action.payload) };

        default:
            return state;
    }
}

const merge = (array, change) => {
    // check if an item with the id already exists
    const index = array.findIndex(item => item.id === change.id);
    // copy the source array
    array = [...array];

    if(index >= 0) {
        // clone and change the existing item
        const existingItem = array[index];
        array[index] = { ...existingItem, ...change.changedValues };
    } else {
        // add a new item to the array
        array.push = { id: change.id, ...change.changedValues };
    }

    return array;
}

Comment: what would the `array` look like in your example?
Comment: The `array` contains your objects. E.g. `{ id: string, desc: string }`. If your object contains also an array of further objects you have to nest the above logic one level more and your `changedValues` object would also contain an id property. If this is your case and you don't know how to accomplish this, give me a hint and I'll update my answer.
Answer: To update an array, I would use immutability helper and do something like this - to your reducer
 let store = {"state" : {
"data": [{
    "subset": [{
        "id": 1
    }, {
        "id": 2
    }]
}, {
    "subset": [{
        "id": 10
    }, {
        "id": 11
    }, {
        "id": 12
    }]
}]
}}

case Constants.SET_DESC:
  return update(store, {
  "state" : {
  "data": {
      [action.indexToUpdate]: {
        "subset": {
             $set: action.payload.desc
        }
      }
  }
 }
  })
  });

Comment: This is how I want to implement it.. I have downloaded immutable-helper into my project but it not working - not finding indexToUpdate


How to sort HashMap as added in Android with ArrayAdapter

Question: I have a HashMap<String,String> and there is a static method which returns this map to an Activity.
Method looks like this:
public static HashMap<String, String> getAll() {
    HashMap<String, String> map = new HashMap<String,String>();

    map.put("ab", "value1");
    map.put("bc", "value2");
    map.put("de", "value3");

    return map;
}

I want to use that map with a spinner. So activity looks like this:
List list = new ArrayList<String>();
HashMap<String, String> map = Constants.getAll();

for (String key : map.keySet()) {
    list.add(Constants.getAll().get(key).toString());
}

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

spinTest = (Spinner)findViewById(R.id.spinTest);

spinTest.setOnItemSelectedListener(new OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        urlDebug.setText(list.get(arg2).toString());
    }

    public void onNothingSelected(AdapterView<?> arg0) {

    }
});

spinTest.setAdapter(adapter);

When I tried to run my application, no problem at all. But when I clicked on spinner, items not ordered as I added on getAll() method. I mean, order has to be ab - bc -de but it's ordered randomly.
What's not true?
Answer: in hashmap, insertion order is not maintained, so item inserted last may accessed first. If you want to maintain order of insertion, use linkedhashmap instead.
Comment: Or, just use a TreeMap. It's what it's there for you know.
Comment: You just saved my hours!
Answer: Update : Answer by jitendra sharma is the best :
A treemap costs a lot more than a linkedhashmap and adds nothing to your project if you only need to keep original insertion order.
Hashmap cannot get sorted. That's part of their efficiency.
If you need sorting, then use a TreeMap.
Good luck.
Comment: A TreeMap is not especially inefficient for a normal number of items - considering the fact that there's apparently few items enough to use a spinner.
Comment: I just added the update to be sure futur reader know what to expect and for good practices. From the Oracle Java doc : "This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashMap (and Hashtable), without incurring the increased cost associated with TreeMap" : http://docs.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashMap.html
Answer: You should either call adapter.notifyDataSetChanged() or spinTest.setAdapter(adapter) after you sorted your list.
spinTest.setOnItemSelectedListener(new OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        urlDebug.setText(list.get(arg2).toString());
    }

    public void onNothingSelected(AdapterView<?> arg0) {

    }
});

spinTest.setAdapter(adapter);
// TODO: Sort the list
// Some code here
adapter.notifyDataSetChanged();


Ubuntu 16.04 doesn't see second monitor daisy chained through displayport

Question: I have two Dell U2414H monitors connected in chain to AMD R7 250X. Today I installed Ubuntu 16.04 and in settings I see only one monitor while screen is duplicated on second monitor.
Is there a way to make both monitors work in this config?
Answer: It a bug which has been reported.
Answer: The Daisy Chain require Intel HD Graphics. Details in Dell's KB.


breezejs: issue with FetchFromLocalCache strategy when using Skip

Question: Consider the following code :
<code> function search(filter) {
            var query = breeze.EntityQuery
                .from("Mandates").skip(offset).take(pageSize).inlineCount(true);

            if (queryParamCache[cacheObj] > 0) {
                query = query.using(breeze.FetchStrategy.FromLocalCache);
            } else {

                query = query.using(breeze.FetchStrategy.FromServer);
            }

            return manager.executeQuery(query.using(service)).then(function (result) {

                return result;
            });
        }
</code>
queryParamCache is used as a flag to find out if the query results are already in cache.
Now, if I call this method and set offset to 120 in order to skip the first 12 pages (10 records per page), a call is made to the server and results are displayed.
Then, I make the same call for page 13, which works, and I go back to page 12. This time records are fetched from the cache, which is what I want.
But in breezejs code, in the function executeQueryLocally, the following code is executed:
<code> var skipCount = query.skipCount;
    if (skipCount) {
        result = result.slice(skipCount);
    }
</code>
skipCount is set to 120, but obviously this just deletes everything in the array, since I only had 20 records (page 12 and page 13).
Is this not a bug ? Or did I miss something ?
Answer: You didn't miss anything, and this is NOT a bug.
It's just that if breeze is executing a local query then all it has to work with is the data in the local query cache.  With that constraint, breeze is returning exactly the correct answer.  Basically, a local query is simply a query against the local cache, so if the local cache contains 40 records and you tell it to skip 120 and give you the next 10, then no records will be returned.
In general, if you want to use a query with 'skip' against the local cache, then you must understand the restrictions.  i.e. either bring all of the data into the cache or remove the 'skip' or insure that the 'to be skipped' records are already in the cache.
Comment: wow, ok. That's going to be a lot of boiler-plate code to write, not sure it's worth it. But I understand the issue is not with breeze. Thanks !


Micromax 353G Modem in Ubuntu 12.04

Question: I am using MMX 353g modem in windows and its working well but no matter what i do i cannot make it work in Ubuntu 12.04. I have made a connection but it doesnt show up in connection list. I tried lot of things from different forums nothing seems to work for me, please help.
Comment: Just now i did the following reducing my problem a bit,      sudo gedit /etc/modules
At the bottom of the file, make two new lines, like this:
usbserial
option                                                            Since I was running from usb stick I used the following commands to load these modules:
sudo modprobe usbserial
sudo modprobe option                                                         Now connection is detected when i try to connect it gets connected as well but surprisingly i cannot access the net no webpage can be browsed ??? please solve this for me
Answer: Try adding these lines to /etc/modules file:
lp
usbserial
option

Micromax 353G Modem in Ubuntu 12.04


To show for following sequence $\lim_{n \to \infty} a_n = 0$ where $a_n$ = $1.3.5 ... (2n-1)\over 2.4.6...(2n)$

Question: How can I show
$\lim_{n \to \infty} a_n = 0$
$a_n = {1.3.5 ... (2n-1)\over 2.4.6...(2n)}$
I have shown that $a_n$ is monotonically decreasing. I thought to shown sequence is bounded from below then it automatically would converge and hence my question will be solve. But I'm unable to show its boundedness... Or there maybe another method to prove this. Thanks
Comment: That the limit is zero is intuitively obvious, seeing as $a_n=\binom{2n}n/4^n$is the probability of getting exactly $n$ heads in $2n$ independent tosses of a fair coin.
Comment: Try to prove using induction that:$$a_n\lt\frac{1}{\sqrt{3n+1}}$$
Comment: Clarification request: what do you mean by $1.3.5...$? Are these numbers being added?
Comment: I think is multiplication of odd numbers. Isn't $\pi$ in the answer? I vaguely remember a result like this from Euler.
Comment: It is certainly bounded below, since all terms are positive, so it converges. But that does not show it converges to $0$. The Stirling approximation will show convergence to $0$, but one can do it with less machinery.
Comment: @user121270 Can u pls justify ur comment . Why have u choosen that specific thing ?
Comment: @mapierce271 imean by 1.3.5 is numbers are being multiplied
Comment: @AndréNicolas I havent studies stirlings approximation . If u know this by other means pls let me know
Comment: This limit is somewhat related: http://math.stackexchange.com/questions/1024290/how-to-evaluate-lim-n-to-infty-sqrtn-frac1-cdot3-cdot5-cdot-ldots-cdot2
Comment: @MartinSleziak Thanks!!
Comment: This question is very close to the OP: http://math.stackexchange.com/questions/584456/limit-of-a-fraction-of-double-factorials
Answer: $\forall k\in\mathbb{N}$
$k^2+2k<k^2+2k+1\Rightarrow k(k+2)<(k+1)^2\Rightarrow\frac{k}{k+1}<\frac{k+1}{k+2}$

$\therefore a_n=\frac{1\cdot3\cdot5...(2n-1)}{2\cdot4\cdot6...2n}=\frac{1}{2}\cdot\frac{3}{4}...\frac{k}{k+1}...\frac{2n-1}{2n}<\frac{2}{3}\cdot\frac{4}{5}...\frac{k+1}{k+2}...\frac{2n}{2n+1}=\frac{2\cdot4\cdot6...2n}{1\cdot3\cdot5...(2n+1)}$where, $k$ is an odd natural number.
$\Rightarrow {a_n}^2<\frac{1\cdot3\cdot5...(2n-1)}{2\cdot4\cdot6...2n}\cdot\frac{2\cdot4\cdot6...2n}{1\cdot3\cdot5...(2n+1)}=\frac{1}{2n+1}$

$\Rightarrow 0<a_n<\frac{1}{\sqrt{2n+1}}$

Using Squeeze theorem, we get $\underset{n\rightarrow\infty}{\lim} a_n=0$.
Comment: I know this is a dumb question, but can you please tell me how did you infer $\therefore a_n=\frac{1\cdot3\cdot5...(2n-1)}{2\cdot4\cdot6...2n}<\frac{2\cdot4\cdot6...2n}{1\cdot3\cdot5...(2n+1)}$ from
$n(n+2)<(n+1)^2\Rightarrow\frac{n}{n+1}<\frac{n+1}{n+2}$? Thanks!!
Comment: thanks so much. Now I get it!
Comment: @NatashaJ I hope you have understood how we get $\frac{k}{k+1}<\frac{k+1}{k+2}$. Now check that, for $n=1$ you get $\frac{1}{2}<\frac{2}{3}$, for  $n=3$ you get $\frac{3}{4}<\frac{4}{5}$, and so on. In other words for an odd $k$, you see that $\frac{k}{k+1}<\frac{k+1}{k+2}$.
Comment: @NatashaJ I have modified the step, hope it clears your doubt.
Answer: Using $\boldsymbol{1+x\le e^x}$
Since $1+x\le e^x$ for all $x\in\mathbb{R}$,
$$
\begin{align}
a_n
&=\prod_{k=1}^n\frac{2k-1}{2k}\\
&=\prod_{k=1}^n\left(1-\frac1{2k}\right)\\
&\le\prod_{k=1}^ne^{-\large\frac1{2k}}\\[3pt]
&=e^{-\frac12H_n}\tag{1}
\end{align}
$$
where $H_n$ are the Harmonic Numbers. Since the Harmonic Series diverges, $(1)$ tends to $0$.

Using Gautschi's Inequality
$$
\begin{align}
a_n
&=\prod_{k=1}^n\frac{2k-1}{2k}\\
&=\prod_{k=1}^n\frac{k-\frac12}{k}\\
&=\frac{\Gamma\!\left(n+\frac12\right)}{\sqrt\pi\,\Gamma(n+1)}\\[6pt]
&\le\frac1{\sqrt{\pi n}}\tag{2}
\end{align}
$$

Commentary
Gautschi's Inequality also says that
$$
\begin{align}
a_n
&=\frac{\Gamma\!\left(n+\frac12\right)}{\sqrt\pi\,\Gamma(n+1)}\\
&\ge\frac1{\sqrt{\pi\left(n+\frac12\right)}}\tag{3}
\end{align}
$$
Therefore,
$$
\lim_{n\to\infty}\sqrt{n}\,a_n=\frac1{\sqrt\pi}\tag{4}
$$
Putting the second line of $(1)$ and the limit in $(4)$ together, we can show that
$$
\gamma+\sum_{n=2}^\infty\frac{\zeta(n)}{n2^{n-1}}=\log(\pi)\tag{5}
$$
where $\gamma$ is the Euler-Mascheroni Constant and $\zeta$ is the Riemann Zeta Function.
Answer: Let's prove using induction that $$a_n\le\frac{1}{\sqrt{3n+1}}.$$ For $n=1$ it is true. Now we just need to prove that$$\frac{(2n+1)^2}{(2n+2)^2}\le\frac{3n+1}{3n+4}$$or $$(4n^2+4n+1)(3n+4)\le(4n^2+8n+4)(3n+1)$$or$$12n^3+28n^2+19n+4\le12n^3+28n^2+20n+4.$$
Comment: If we are not given the limit it converges to then how would we go about it
Comment: I don't know. Maybe we could find asymtothics using Stirling's formula, then try to find this inequality.
Comment: (+1) It's neater with $n - 1$ in place of $n$:
$$
\left(\frac{2n - 1}{2n}\right)^2 \leqslant \frac{3n - 2}{3n + 1}
\iff \frac{4n - 1}{4n^2} \geqslant \frac3{3n + 1} \iff
(4n - 1)(3n + 1) \geqslant 12n^2 \iff n \geqslant 1.
$$
Answer: Multiply the numerator by the denominator; so $$a_n=\frac{1\times3\times5\times ... \times(2n-1)}{ 2\times4\times6\times...\times(2n)}=\frac{1\times2\times3\times ... \times(2n)}{\Big(2\times4\times6\times...\times(2n)\Big)^2}=\frac{(2n)!}{4^n(n!)^2}$$ If now you use Stirling approximation $$m! \approx \sqrt{2 \pi } e^{-m} m^{m+\frac{1}{2}}$$ and then $$a_n \approx \frac{1}{\sqrt{\pi n} }$$ A more detailed approach would show for the asymptotic behavior $$a_n \approx \frac{1}{\sqrt{\pi n} }\Big(1-\frac{1}{8n}\Big)$$
Comment: In first step how have u written in denominatorof last inequality as $4^{n}(n!)^{2}$ ..
Comment: Factor $2$ inside the brackets of denominator and square.
Comment: @ClaudeLeibovici in stirlings aproximstion  as you have mentioned in order to find formula for 2m! I just have to replace m by 2m in above formula .if i do this then im not getting to answer, thanks
Comment: @JessicaGtb. I don't know whee you had a problem since if you use Stirling, you should get $$(2n)! \approx \sqrt{\pi } 2^{2 m+1} e^{-2 m} m^{2 m+\frac{1}{2}}$$ Post if you still have problems. Cheers :-)
Comment: How did you get that expression for 2n! .it  is not same when you replace n by 2n in formula you mentioned in answer
Comment: It is the same (just expanded accordingly).
Answer: Your sequence can be rewritten as
$$a_n=\frac{1\cdot3\cdot...\cdot(2n-1)}{2\cdot4\cdot...\cdot2n}=\frac{1\cdot2\cdot3\cdot...\cdot(2n-1)\cdot2n}{(2\cdot4\cdot...\cdot2n)^2}=\frac{(2n)!}{2^{2n}(n!)^2}$$
Using Stirling's approximation we get
$$a_n=\frac{(2n)!}{2^{2n}(n!)^2}\sim\frac{1}{2^{2n}}\cdot\frac{\sqrt{2\pi 2n}\cdot(\frac{2n}{e})^{2n}}{(\sqrt{2\pi n}(\frac{n}{e})^n)^2}=\frac{1}{2^{2n}}\cdot\frac{\sqrt{2}\cdot2^{2n}}{\sqrt{2\pi n}}=\frac{\sqrt{2}}{\sqrt{2\pi n}}\to 0$$
as $n\to\infty$.
Comment: i havent studied stirlings approximation yet . Can u show me another way which uses sequence series concepts


Remove part of col names in list of data frames - R

Question: In this dummy list of data frames, all column names have a prefix followed by an underscore. Each data frame in the list has a different prefix, but they all include an underscore.
How can I remove the underscore and the text before it in the column names of all data frames in the list? I can do it individually, but my real list contains many more data frames. Thank you
#add diferent prefixes to all col names
colnames(iris)<-paste('iris_',colnames(iris), sep='')

colnames(mtcars)<-paste('mt_',colnames(mtcars), sep='')

colnames(ToothGrowth)<-paste('TG_',colnames(ToothGrowth), sep='')

#create list of data frames

mylist<-list(iris, mtcars, ToothGrowth)

#name elements of list

names(mylist)<-c('iris','mtcars','ToothGrowth')

#remove prefix from colnames individually for each data frame

colnames(mylist['iris']$iris)<-sub('[^.]+\\_', '', colnames(mylist['iris']$iris))

Comment: You just need to do this for each element of the list. https://stackoverflow.com/questions/12297859/remove-all-text-before-colon
Answer: We can use lapply to loop through the list, remove the prefix of the column names with sub, and set the names with setNames
lapply(mylist, function(x) setNames(x, sub("^[^_]*_", "", names(x))))

Or using tidyverse, loop through the list with map and remove the substring of the column names with str_remove inside rename_all
library(tidyverse)
map(mylist, ~  .x %>%
                  rename_all(~ str_remove(.x, "^[^_]*_")))


CakePHP Default values for date select

Question: I have a set of selects for a date of birth:
<?php echo $this->Form->input('Profile.dob', array('label' => 'Date of Birth'
                                    , 'dateFormat' => 'DMY'
                                    , 'minYear' => date('Y') - 100
                                    , 'maxYear' => date('Y') - 13)); ?>

and want to set the defaults to be the words "DAY MONTH YEAR" in the selects.
I have managed to do this with the gender with:
<?php echo $this->Form->input('Profile.gender', array('label' => 'Gender', 'type' => 'select',
         'options' => array('Male'=>'Male','Female'=>'Female'),'empty'=>'Select Sex')); ?>

but I don't see how to do this with the automagic date input...
Can anyone help? Thanks
Comment: You could potentially add a few lines of JS to append to the beginning of the  the text? Short of modifying the form helper - I can't think of a less "hackish" way.
Answer: Simply add:
'selected'=>date('Y-m-d')
to your array of options.
That example will show the current date. If you need to have a static date, replace it as required. eg:
'selected'=>'2011-12-10'
Obviously for the date and time, use:
'selected'=>date('Y-m-d H:i:s')
or
'selected'=>'2011-12-10 11:13:45'
Comment: What about DAY MONTH YEAR as in the actual words!
Comment: 'selected' is the keyword I was looking for, thanks for sharing :)
Answer: This way works:
<?php
echo $this->Form->input(
    'Profile.dob',
    array(
        'label'         => 'Date of Birth',
        'dateFormat'    => 'DMY',
        'minYear'       => date('Y') - 100,
        'maxYear'       => date('Y') - 13,
        'empty'         => array(
            'day'       => 'DAY',
            'month'     => 'MONTH',
            'year'      => 'YEAR'
            )
        )
    );
?>

Comment: Nice! This exactly answers the original question (which I had as well) and does it without switching to three separate statements.
Answer: If you don't mind 2 more lines, you can try doing this?
<?php
echo $this->Form->year('Profile.dob', date('Y') - 100, date('Y') - 13, array('empty' => "YEAR"));
echo $this->Form->month('Profile.dob', array('empty' => "MONTH"));
echo $this->Form->day('Profile.dob', array('empty' => 'DAY'));

?>

Comment: Gives me this error: `Fatal error: Unsupported operand types in /Users/cameron/Sites/social/lib/Cake/View/Helper/FormHelper.php on line 1816`
Comment: @Cameron, may be I am missing some braces or you wanna try $this->Form->year(....).
Comment: @Cameron, I apologize I should have mentioned. It would work only for cake 1.3+
Comment: This is the correct answer, but on the year() call you should do this: `echo $this->Form->year('Profile.dob', array('minYear' => date('Y') - 100, 'maxYear' => date('Y') - 13, 'empty' => "YEAR"));`
Answer: I implemented it like this in cakephp 2.0 above
echo $this->Form->dateTime('dob', 'DMY','', array(
    'value'=>'1987-02-12',
    'empty'=>false,
    'label'=>'Date Of Birth',
    'minYear'=>date('Y')-60,
    'maxYear'=>date('Y')-15)
);

'value' attribute has been added after 2.0 api of cakephp and 'selected' is remove.
Cakephp manual says :The $selected parameter was removed from several methods in FormHelper. All methods now support a $attributes['value'] key now which should be used in place of $selected. This change simplifies the FormHelper methods, reducing the number of arguments, and reduces the duplication that $selected created. The effected methods are:
FormHelper::select()
FormHelper::dateTime()
FormHelper::year()
FormHelper::month()
FormHelper::day()
FormHelper::hour()
FormHelper::minute()
FormHelper::meridian()

Answer: Also, are you really sure about what you really mean?
You seem to be confusing default value and empty value. If you set default value as DAY MONTH YEAR using 'selected', your code won't work because DAY MONTH YEAR isn't a valid date.
Using
'empty' => array(
  'day' => 'DAY',
  'month' =>'MONTH',
  'year' =>'YEAR'
);

looks like what you're looking for, inviting the user to enter a date.
Answer: Cakephp set selected to the empty value if the corresponding date request data is null, therefore simply set it to null prior to echoing the date input fields:
$this->request->data['Profile']['dob'] = null;

echo $this->Form->month('Profile.dob', array('empty' => "MONTH"));
// do the same for year and day

the empty value (in your case "DATE", "MONTH", "YEAR" fields) will be pre-selected in the input form
Answer: This is what currently works for me in cakephp 2.5:
echo $this->Form->input('fecha_pos_fijacion', array(
    'label' => 'Fecha de fijación',
    'dateFormat' => 'DMY',
    'minYear' => date('Y'),
    'maxYear' => date('Y')+5,
    'orderYear' => 'asc',
    'selected' => date('Y-m-1')
    )

);
This is a bit more elaborated, it'd give you a default value set to the 1st day of current month. Possible values for year are between current and 5 years ahead, displayed in ascending order.
Even more complete:
echo $this->Form->input('fecha_transporte', array(
                    'label' => '',
                    'dateFormat' => 'DMY',
                    'minYear' => date('Y'),
                    'maxYear' => date('Y')+5,
                    'orderYear' => 'asc',
                    'selected' => date('Y-m-1', strtotime("+30 days"))
                    )
            );

Here default is 1st day of next month

CakePHP Default values for date select


Round list avatar

Question: I'm trying simple list app with avatar. While I added my own picture it had been rectangle. I checked enternet but I didn't solved my problem.
Rectangle avatars

This is code:
from kivy.lang import Builder

from kivymd.app import MDApp
from kivymd.uix.list import OneLineListItem, ImageLeftWidget, OneLineAvatarIconListItem

KV = '''
MDBoxLayout:
    orientation: "vertical"
    MDTopAppBar:
        title: "Telegram"
    MDScrollView:
        MDList:
            id: container
'''

class Example(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Light"
        return Builder.load_string(KV)

    def on_start(self):
        for i in range(20):
            def pr(self):
                print(self.id)
            self.root.ids.container.add_widget(
                OneLineAvatarIconListItem(ImageLeftWidget(
        source="sniper.jpg", on_release=pr), id=str(i), text=f"Single-line item {i}", on_release=pr))#.add_widget()

Example().run()

Comment: You can edit `sniper.jpg` and make it transparent in the areas not within the round area.
Comment: @JohnAnderson I appreciate your reply.  But I think there should be a way to do it in kivymd.  I left your answer as a last resort.
Answer: You can use FitImage form kivymd to create your Rounded avatar and make your own avatar list. Here is how you can achieve this.
Py File:-
class Card(RoundedRectangularElevationBehavior, MDFloatLayout):
    pass

class DisplayPic(CircularElevationBehavior, ButtonBehavior, FitImage):
    pass

class ButtonLayout(RectangularRippleBehavior, ButtonBehavior, MDFloatLayout):
    pass

class UserCard(ButtonBehavior, Card):
        def __init__(self, name, dp, **kwargs):
            super().__init__(**kwargs)
            self.name = name
            self.dp = dp

KV File:-
<UserCard>
    size_hint: .9, None
    height: dp(80)
    elevation: dp(6)
    md_bg_color: 1,1,1,1
    soft_shadow_cl: [0, 0, 0, .05]
    radius: dp(20)
    name: ""
    dp: ""

    MDLabel:
        text: root.name
        bold:  True
        pos_hint: {'center_x': .75, 'center_y': .65}

    ButtonLayout:
        pos_hint: {'center_x': .5, 'center_y': .5}
        radius: root.radius

    DisplayPic:
        source: root.dp
        elevation: dp(3)
        size_hint: None, None
        size: dp(45), dp(45)
        radius: dp(360)
        pos_hint: {'center_x': .12, 'center_y': .5}
        on_release: print("clicked")

Now You have your own avatar list element just Use for loop to add your UserCard (avatar list element) to add it into a scroll view.
How to use this element:-
usercard = UserCard(u.display_name, u.photo_url)

Now add it to the ScrollView
Full Code With your example:-
from kivy.lang import Builder
from kivymd.uix.behaviors import RoundedRectangularElevationBehavior, CircularElevationBehavior, RectangularRippleBehavior, CircularRippleBehavior
from kivy.uix.behaviors import ButtonBehavior
from kivymd.uix.floatlayout import MDFloatLayout
from kivymd.uix.fitimage.fitimage import FitImage
from kivymd.app import MDApp
from kivymd.uix.list import OneLineListItem, ImageLeftWidget, OneLineAvatarIconListItem

KV = '''

<UserCard>
    size_hint: .9, None
    height: dp(80)
    elevation: dp(6)
    md_bg_color: 1,1,1,1
    soft_shadow_cl: [0, 0, 0, .05]
    radius: dp(20)
    name: ""
    dp: ""

    MDLabel:
        text: root.name
        bold:  True
        pos_hint: {'center_x': .75, 'center_y': .65}

    ButtonLayout:
        pos_hint: {'center_x': .5, 'center_y': .5}
        radius: root.radius

    DisplayPic:
        source: root.dp
        elevation: dp(3)
        size_hint: None, None
        size: dp(45), dp(45)
        radius: dp(360)
        pos_hint: {'center_x': .12, 'center_y': .5}
        on_release: print("clicked")

MDBoxLayout:
    orientation: "vertical"
    MDTopAppBar:
        title: "Telegram"
    ScrollView:
        MDGridLayout:
            id: container
            cols: 1
            col_force_default: False
            spacing: dp(6)
            size_hint: 1, .8
            adaptive_height: True
            pos_hint: {'center_x': .5}

'''

class Card(RoundedRectangularElevationBehavior, MDFloatLayout):
    pass

class DisplayPic(CircularElevationBehavior, ButtonBehavior, FitImage):
    pass

class ButtonLayout(RectangularRippleBehavior, ButtonBehavior, MDFloatLayout):
    pass

class UserCard(ButtonBehavior, Card):
    def __init__(self, name, dp, **kwargs):
        super().__init__(**kwargs)
        self.name = name
        self.dp = dp

class Example(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Light"
        return Builder.load_string(KV)

    def change_screen(self, screen, receiver_name, receiver_uid, *args):
        receiver.name = receiver_name
        receiver.uid = receiver_uid
        self.manager.current = screen

    def on_start(self):
        for i in range(20):
            scrn_change = partial(self.change_screen, "Chat", u.display_name, u.uid)
            usercard = UserCard(u.display_name, u.photo_url)
            btn_layout = usercard.children[1]
            btn_layout.bind(on_release = scrn_change)
            self.root.ids.container.add_widget(usercard)

Example().run()

Output:-
Comment: can you convert it to my example? I don't understand
Comment: added full code with your example...

Round list avatar


Interpretation of the Following Summation

Question: I wanted to invert the following Laplacian expression which was not possible with simple manipulation.
$$ \frac{s}{s^2 + \omega^2}\exp\bigg(-\sqrt{\frac{s}{\alpha}}x\bigg) $$
Thus, I used the Taylor Series on each part and simplified it as shown:
$$ \implies \frac{1}{s} \bigg( 1 + \frac{\omega^2}{s^2}\bigg)^{-1}\exp\bigg(-\sqrt{\frac{s}{\alpha}}x\bigg) \implies \frac{1}{s}\bigg( \sum_{k = 0}^{\infty} \bigg(\frac{-\omega^2}{s^2}\bigg)^k \bigg) \cdot \bigg( \sum_{n = 0}^{\infty} \frac{1}{n!}\bigg( -\sqrt{\frac{s}{\alpha}}x \bigg)^n \bigg) $$
$$ \sum_{k = 0}^{\infty} (-\omega^2)^k \sum_{n=0}^{\infty} \frac{1}{n!} \bigg( \frac{-x}{\sqrt{\alpha}}\bigg)^n \frac{1}{s^{2k - n/2 + 1}} $$
Now, I simply have to apply Inverse Laplace transform on only 1 term $1/s^a$ which is simply $t^{a-1}/\Gamma(a)$. Thus, I get
$$ \sum_{k = 0}^{\infty} (-\omega^2)^k \sum_{n=0}^{\infty} \frac{1}{n!} \bigg( \frac{-x}{\sqrt{\alpha}}\bigg)^n \frac{t^{2k - n/2}}{\Gamma(2k - n/2 + 1)} $$
This can be re-arranged into
$$ \implies \boxed{\sum_{k = 0}^{\infty} (-\omega^2 t^2)^k \sum_{n=0}^{\infty} \frac{1}{n!} \bigg( \frac{-x}{\sqrt{\alpha t}}\bigg)^n \frac{1}{\Gamma(2k - n/2 + 1)}} $$
Now the issue is about how to interpret this summation. This is not a double summation but just a product of 2 different summations. And even bigger issue is about how to handle values where n > 2(2k + 1).
How do I handle this expression, do I take a particular k and then sum the whole expression till n is a large expression???
Comment: It is in fact a double summation, not a product. Note that the variable $k$ also appears in the inner summand.
Answer: The correct formula for the double sum is
$$\sum _{k=0}^{\infty } \color{red}{(-1)^k} (\omega t)^{2 k} \sum _{n=0}^{\infty } \frac{\left(-\frac{x}{\sqrt{\alpha  t}}\right)^n}{n! \Gamma \left(2 k-\frac{n}{2}+1\right)}$$
The inner infinite sum evaluates to
$$\sum _{n=0}^{\infty } \frac{\left(-\frac{x}{\sqrt{\alpha  t}}\right)^n}{n! \Gamma \left(2 k-\frac{n}{2}+1\right)}=\frac{\, _1F_1\left(-2 k;\frac{1}{2};-\frac{x^2}{4 t \alpha }\right)}{\Gamma (2 k+1)}-\frac{x \sqrt{\alpha  t} \, _1F_1\left(\frac{1}{2}-2 k;\frac{3}{2};-\frac{x^2}{4 t \alpha }\right)}{\alpha  t \Gamma \left(\frac{1}{2} (4 k+1)\right)}$$
Finally we get
$$\sum _{k=0}^{\infty } (-1)^k (\omega t)^{2 k} \left(\frac{\, _1F_1\left(-2 k;\frac{1}{2};-\frac{x^2}{4 t \alpha }\right)}{\Gamma (2 k+1)}-\frac{x \sqrt{\alpha  t} \, _1F_1\left(\frac{1}{2}-2 k;\frac{3}{2};-\frac{x^2}{4 t \alpha }\right)}{\alpha  t \Gamma \left(\frac{1}{2} (4 k+1)\right)}\right)$$
HINT: $_1F_1(a;b;z)$ is the Kummer confluent hypergeometric  function of the first kind.
Visualize sum expression with $\alpha=1, \omega=2\pi, 0\le k \le 20$:
Comment: Due to my lack of knowledge, I cannot understand the 2nd equation/line in which you have written a single summation into 2 terms. I could not understand what 'F' with weird indexing meant. Or else, maybe you can just give me a reference where I can understand this myself.
Comment: [Hypergeometric function of the first kind](https://mathworld.wolfram.com/ConfluentHypergeometricFunctionoftheFirstKind.html)
Comment: I have coded this in Python but I am getting answers in order of $10^{53}$ at (x, t) = (0.1, 60) for $\alpha = 1$ and $\omega = 2\pi$. [Here](https://ibb.co/mvNNGX8) is the code. Do you think I made any mistake???
Answer: Using only Mathematica with The Convolution Theorem:
$$\mathcal{L}_s^{-1}\left[\frac{s}{s^2+\omega ^2}\right](t)=\cos (t \omega )$$
and
$$\mathcal{L}_s^{-1}\left[e^{-x \sqrt{\frac{s}{\alpha }}}\right](t)=\frac{e^{-\frac{x^2}{4 t \alpha }} x \alpha }{2 \sqrt{\pi } \sqrt{t^3 \alpha ^3}}$$
then:
$$\int_0^t \frac{e^{-\frac{x^2}{4 \alpha  \tau }} x \alpha  \cos ((t-\tau ) \omega )}{2 \sqrt{\pi } \sqrt{\alpha ^3 \tau ^3}} \, d\tau$$
This integral Mathematica can compute.
$\mathcal{L}_s^{-1}\left[\frac{e^{-x \sqrt{\frac{s}{\alpha }}} s}{s^2+\omega ^2}\right](t)=\\\frac{1}{4} e^{-i t \omega -x \sqrt{\frac{i \omega }{\alpha
   }}} \left(e^{x \left(\sqrt{-\frac{i \omega }{\alpha }}+\sqrt{\frac{i \omega }{\alpha }}\right)} \text{erfc}\left(\frac{x+2 t \sqrt{-i \alpha
   \omega }}{2 \sqrt{t \alpha }}\right)+e^{2 i t \omega } \left(\text{erfc}\left(\frac{x-2 t \sqrt{i \alpha  \omega }}{2 \sqrt{t \alpha
   }}\right)+e^{2 x \sqrt{\frac{i \omega }{\alpha }}} \text{erfc}\left(\frac{x+2 t \sqrt{i \alpha  \omega }}{2 \sqrt{t \alpha }}\right)\right)+e^{i
   \sqrt{2} x \sqrt{\frac{\omega }{\alpha }}} \text{erfc}\left(\frac{x+2 (-1)^{3/4} t \sqrt{\alpha  \omega }}{2 \sqrt{t \alpha }}\right)\right)$
Code:
1/4  E^(-I t \[Omega] -  x Sqrt[(I \[Omega])/\[Alpha]])  (E^( x (Sqrt[-((I \[Omega])/\[Alpha])] + Sqrt[(I \[Omega])/\[Alpha]])) Erfc[(x + 2 t Sqrt[-I \[Alpha] \[Omega]])/( 2 Sqrt[t \[Alpha]])] +  E^(2 I t \[Omega])  (Erfc[(x - 2 t Sqrt[I \[Alpha] \[Omega]])/( 2 Sqrt[t \[Alpha]])] +  E^(2 x Sqrt[(I \[Omega])/\[Alpha]]) Erfc[(x + 2 t Sqrt[I \[Alpha] \[Omega]])/( 2 Sqrt[t \[Alpha]])]) +  E^(I Sqrt[2] x Sqrt[\[Omega]/\[Alpha]]) Erfc[(x + 2 (-1)^(3/4) t Sqrt[\[Alpha] \[Omega]])/( 2 Sqrt[t \[Alpha]])])
Comment: I feel like I am misinterpreting but when you said that the integral can be computed by Mathematica, I assume you meant it would be give me a solution for every input I give instead of giving me a closed form solution. Am I correct??
Comment: If not, can you explain how you got the last equation??
Comment: @KNVCSG Use this code: `Integrate[(InverseLaplaceTransform[s/(s^2 + \[Omega]^2), s, t] /.
    t -> (t - \[Tau]))*(InverseLaplaceTransform[
     Exp[-x*Sqrt[s/\[Alpha]]], s, t] /. t -> \[Tau]), {\[Tau], 0, t},
 Assumptions -> {\[Alpha] > 0, \[Omega] > 0, x > 0, t > 0}]` in Mathematica. I executed in version **14.0** and work fine for me give the answer.
Comment: Could you recommend few good sources for learning all about Mathematica
Comment: @KNVCSG At first here: https://www.wolfram.com/mathematica/


How To Create PHP Array to JSON Array using json_encode();

Question: I've encoded an Array I've made using the inbuilt json_encode(); function. I need it in the format of an Array of Arrays like so:
{
  "status": "success",
  "data": [
    {
      "Info": "A",
      "hasil": "AA"
    },
    {
      "Info": "B",
      "hasil": "BB"
    },
    {
      "Info": "C",
      "hasil": "CC"
    },
    {
      "Info": "D",
      "hasil": "DD"
    },
    {
      "Info": "F",
      "hasil": "FF"
    },
    {
      "Info": "G",
      "hasil": "GG"
    },
    {
      "Info": "H",
      "hasil": "HH"
    },
    {
      "Info": "I",
      "hasil": "II"
    },
    {
      "Info": "J",
      "hasil": "JJ"
    }
  ]
}

I need it is returning as:
{
  "status": "success",
  "data":
    {
      "Info": "A",
      "hasil": "AA"
    },
    {
      "Info": "B",
      "hasil": "BB"
    },
    {
      "Info": "C",
      "hasil": "CC"
    },
    {
      "Info": "D",
      "hasil": "DD"
    },
    {
      "Info": "F",
      "hasil": "FF"
    },
    {
      "Info": "G",
      "hasil": "GG"
    },
    {
      "Info": "H",
      "hasil": "HH"
    },
    {
      "Info": "I",
      "hasil": "II"
    },
    {
      "Info": "J",
      "hasil": "JJ"
    }

}

Comment: Why do you want some invalid, grotesque version of JSON instead of actual JSON? You presumably want to transport data from PHP to JavaScript; why deliver something that JSON.parse() can't parse?
Comment: Please show the code you have actually tried.
Comment: What s wrong with an Object that contains a Property called `data` which is an array of other Objects. Thats perfect for using in Javascript. Which afterall is the point of JSON
Answer: Your example of what you want it to look like is not valid JSON. It needs to be outputted like how you see it currently being outputted. You have multiple items under data and as such they need to be in an array. Think of JSON like it's a normal variable you have. You can't store a list of items like that without it being an array.
Comment: `json_encode` will not make it like that for you as it is not valid JSON and it will not be usable JSON.
Comment: how to make it like that


JQuery addClass to element based on selected option

Question: How to add a class to element based on selected option
So I got this select option generated by php looping
code 1
<?php for ($i=1; $i <= $jml_penumpang; $i++) { ?>

      <label for="penumpang_<?php echo $i ?>" class="control-label">Nama Penumpang <?php echo $i ?>
      <input type="text" class="form-control" id="penumpang_<?php echo $i ?>" placeholder="Nama Penumpang <?php echo $i ?>" name="penumpang_<?php echo $i ?>" value="<?php echo set_value('penumpang_'.$i); ?>">

    <label for="kode_kursi_<?php echo $i ?>" class="control-label">Kursi <?php echo $i ?>
    <select name="kode_kursi_<?php echo $i; ?>" class="form-control form-group">
          <option>-- Pilih Kursi --</option>
      <?php
        $kode_kursi = explode(",", $jml_kursi[0]->kode_kursi);
        foreach ($kode_kursi as $k) {
      ?>
          <option value="<?php echo $k; ?>"><?php echo $k; ?></option>
      <?php
        }
      ?>
    </select>
<?php } ?>

now I want to add some css to below element that also generated by php looping
code 2

   Denah Tempat Duduk

Depan

    <?php
      $kode_kursi = explode(",", $jml_kursi[0]->kode_kursi);
      foreach ($kode_kursi as $k) {
    ?>

   <?php echo $k ?>

    <?php
      }
    ?>

Belakang

I want to add inline css style to this element (from code 2)

Based on selected option value from code 1
So the logic is like:
I want to add inline css style (style="background:yellow") to the element in code 2 that has a text equals to selected option value on code 1
How to that using JQuery?
Thank you so much
and sorry for my grammar
UPDATED
this is the generated select option from code 1 ( NOTE: i don't include the )
<select name="kode_kursi_1" class="form-control form-group">
  <option>-- Pilih Kursi --</option>
  <option value="T003-1">T003-1</option>
  <option value="T003-2">T003-2</option>
  <option value="T003-3">T003-3</option>
  <option value="T003-4">T003-4</option>
  <option value="T003-5">T003-5</option>
  <option value="T003-6">T003-6</option>
</select>

<select name="kode_kursi_2" class="form-control form-group">
  <option>-- Pilih Kursi --</option>
  <option value="T003-1">T003-1</option>
  <option value="T003-2">T003-2</option>
  <option value="T003-3">T003-3</option>
  <option value="T003-4">T003-4</option>
  <option value="T003-5">T003-5</option>
  <option value="T003-6">T003-6</option>
</select>

and this is the generated element from code 2

T003-1

T003-2

T003-3

T003-4

T003-5

T003-6

I Also get rid the   to be more readable
Comment: Well could you paste the outputs you get instead of the PHP?
Answer: Guessing there may be dynamic select elements and the number of yellow div should be equal to number of select, try:
$(document).ready(function(){
    //call select_changed() function if any 'select'
    //element with name starting from 'kode_kursi_' is changed
    $("select[name*='kode_kursi_']").change(function(){
        select_changed();
    });
});

function select_changed(){
    //remove yellow backgrounds from all div
    $("div[id*='T003-']").each(function(){
       $(this).removeClass('yellow');
    });
    //match the id with the selected option and
    //add background css class
    $("select[name*='kode_kursi_']").each(function(){
        var selected = $(this).val();
        $('#'+selected).addClass('yellow');
    });
}

Fiddle Demo
Answer: I think this will give a hint, havent tested it yet
$(".kode_kursi").on("change",function(){

   $this_val = $(this).val();

   $(".div_kode2").each(function(){

      $v_text = $(this).text();

         if($this_val ==$text){

           $(this).css("background","yellow");
       }

   });

 });

Comment: agan @ngakak, Ok I'll try your hint, and soon I will posted my fiddle, thanks


Which current raid bosses have the potential for being shiny to catch after it's defeated?

Question: Ex: If I take down a Snorunt raid boss, is there a chance it could be shiny when it's catch time?   Or is a shiny snorunt only possible by catching in the wild? (Same question for  Sableye, Swablu, etc )
Answer: General rule for this is that if the Pokemon has the possibility to be shiny when encountered in the wild, it can also be shiny in the catch-phase of the raid. The current possible shiny raid bosses are:

Aggron
Absol
Mawile
Sableye
Magikarp
Swablu
Snorunt

Which current raid bosses have the potential for being shiny to catch after it’s defeated?


Intersection of decreasing sequence of sets

Question: In an exam, my teacher wrote this problem, I proved it in a similar way to the answer in that post, but he pointed out to me that a step in the proof is wrong.
What my teacher says
Let $A_1 \supset A_2 \supset A_3 \supset \dots$ sequence of decreasing sets
We can construct the following sequence of disjoint sets
$B_1 = A_1 - A_2$
$B_2 = A_2 - A_3$
$B_3 = A_3 - A_4$
$\dots$
let $A = \cap_{k \in \mathbb{N}} A_k$, then $A$ and $\cup_{k = N}^{\infty} B_k$ do not form a partition of $A_N$, are not disjoint, in fact $A$ is contained in the union $\cup_{k = N}^{\infty} B_k$.
But I think he is wrong, and I have this proof to prove that step.
My proof
$A_1 - \cap_{k \in \mathbb{N}} A_k  = A_1 \cap (\cap_{k \in \mathbb{N}} A_k)^c = A_1 \cap (\cup_{k \in \mathbb{N}} A_k^c)$
The intersection is distributed over the union, then
$A_1 \cap (\cup_{k \in \mathbb{N}} A_k^c) = \cup_{k \in \mathbb{N}} (A_1 \cap A_k^c) = $
$= \emptyset \cup (A_1 - A_2) \cup (A_1 - A_3) \cup (A_1 - A_4) \cup ... = $
since the sequence is decreasing, finally
$= \emptyset \cup (A_1 - A_2) \cup (A_1 - A_3) \cup (A_1 - A_4) \cup ... = $
$= \emptyset \cup (A_1 - A_2) \cup (A_2 - A_3) \cup (A_3 - A_4) \cup ... =$
$= \cup_{k \in \mathbb{N}} B_k$
This is $A_1 - \cap_{k \in \mathbb{N}} A_k  = \cup_{k \in \mathbb{N}} B_k$.
The case $A_N - \cap_{k \in \mathbb{N}} A_k  = \cup_{k = N}^{\infty} B_k$ is analogous.
Is my proof correct?
Answer: If your teacher says that the sets $A,B_N,B_{N+1},\dots$ do not form a partition of $A_N$ then he is wrong.
It is evident that the sets $B_N, B_{N+1},\dots$ are disjoint.
Further if $x\in A$ then $x\in A_n$ for every $n$ implying, that no $n$ exists with $x\in B_n$.
This because $B_n\subseteq A_{n+1}^c$ by definition.
This makes it evident that the sets $A,B_N,B_{N+1},\dots$ are disjoint, and it is evident as well that their union coincides with $A_N$.

Your proof is correct and confirms that $A_N-A=\bigcup_{k=N}^{\infty}B_k$.
This combined with $A\subseteq A_N$ and disjointness of the $B_i$ (again) proves that $A,B_N,B_{N+1},\dots$ form a partition of $A_N$.
Answer: Your teacher's claim that $A\subseteq \bigcup B_{k}$ is definitely wrong because if we assume that $x\in A$ then x lies in every $A_{k}$. So , if we assume, as the claim says, that lies in some $B_{m}$ then lies in $A_{m}/A_{m+1}$ which implies $x\notin A_{m+1}$ which is a contradiction. Your proof seems correct. I checked the claim $A_{1}/\bigcap_{1}^{\infty }A_{k}=\bigcup B_{k}$ using a proof of my own and I agree with your result. I suppose the other cases are also correct!


how can I add options to the right-click drop down menu in gnome?

Question: GNOME Shell 3.26.2 | Ubuntu 17.10 | Bash 4.4.12
How can I add options to the right-click drop down menu in GNOME GUI? I want to place an item in the mouse right-click menu that will do echo "$variable" >> ~/notes/notepad.txt where $variable is the currently highlighted text. Is there a way to apply this to the right-click menu globally, like copy/paste? I want to have this option basically anywhere a cut/copy option for text is available.
Answer: As far as I know the dropdown menus are program-specific, so to add a system-wide dropdown menu item you would need to adjust nearly every single program's menu accordingly, and there may very well be programs where the menu is hard-coded and not easily modifiable.
I suggest you define a global keyboard shortcut instead, there are several question on this topic here, e.g. GNOME 3 Shell keyboard/mouse shortcuts for GNOME Shell. To capture the currently selected text I recommend xclip, the command is:
xclip -o >>~/notes/notepad.txt

Note that this does not append the content of the clipboard buffer (which is filled e.g. with Ctrl+C) to the file, but the content of the primary buffer instead, which always contains the text you mark(ed). More about this important difference can be found on Unix.SE: What's the difference between Primary Selection and Clipboard Buffer?,
 wiki.archlinux.org and in this excellent article.
If you want to append the content of the clipboard buffer, use:
xclip -se c -o >>~/notes/notepad.txt

Explanations

-se c – short for -selection clipboard, uses the clipboard buffer instead of the (default) primary one
-o – output from the selected buffer instead of writing to it (default)
>>~/notes/notepad.txt – redirect the output to the file ~/notes/notepad.txt appending to its content

See man xclip for more information.


Test for connected graph

Question: I have implemented a union find algorithm that finds and joins an undirected graph with vertexes that are represented by integers. I want to know if someone has any psuedocode or an idea on how to see if components "connected" ie there is a path that goes from one node to another. For example, I have the following vertexes:
7 (source vertex), 9 (destination vertex) and 8 (source vertex), 7 (destination vertex) are all connected. However, something like 3 (source vertex), 5 (destination vertex) would not be connected to the previous set of components. Could anyone guide me in the right direction or give me an idea on how to test this? Thanks!
Comment: Try a [flood fill](http://en.wikipedia.org/wiki/Flood_fill). Also see [this page](http://en.wikipedia.org/wiki/Connected-component_labeling).
Answer: Yes, all you do is test whether the two nodes have the same root.  If you use path compression when you build your graph, this turns out to be very fast.

I think it is because I am trying to incorporate it into an
  implementation of Kruskal's algorithm with it. After I have found all
  connected components, I want to sort output something that will denote
  each disjoint set from each disjoint set. Sorry to bother you so much
  but if possible might you have any psuedo code to explain what you
  mean?

The sets are already identified by a common root node.  After you have done all your unions, each unique set will have a single root.  So you then run through each node and call Find on it.  How about this:
typedef std::list< Node* > TNodeList;
typedef std::map< Node*, TNodeList > TSetMap;

TSetMap mysets;

// Assuming you have nodes stored in the list type I declared above...
for( TNodeList::iterator n = nodes.begin(); n != nodes.end(); n++ )
{
    Node *thisnode = *n;
    Node *rootnode = Find(thisnode);

    // Add to list for root.  Using the [] operator on map will create a new
    // list if none exists for that node.
    mysets[rootnode].push_back(thisnode);
}

Now you have a map containing all your sets as individual lists, and you can do what you like...
std::cout << "Number of disjoint sets: " << mysets.size() << std::endl;
int count = 0;

for( TSetMap::iterator s = mysets.begin(); s != mysets.end(); s++ )
{
    TNodeList & nl = s->second;
    std::cout << "Set " << ++count << " contains " << nl.size() << " nodes\n";
}

To make all these calls to Find efficient, you should implement path compression in your Union function.
Comment: The thing is I used path compression to build my graph but I can't seem to find if things have the same root or not... do you mind explaining a way to see if things have the same root or not with some psuedocode?
Comment: Shouldn't need to explain this with pseudocode.  If you have implemented path compression then you know that each node has a parent and that the path compression algorithm will ensure that the parent of every node (except a root node) is a root.  So it is very easy to test whether two nodes are in the same set, because you search for their root (either the parent or the node itself) and test if they are equal.
Comment: Hm, okay. Thank you for this. To clarify things: you simply search for the root of the node itself and test the node is equal to the root? Or am I wrong? Thanks for your patience..
Comment: No, you are trying to test whether *two* nodes are in the same set (*ie* connected).  For that, you find the root of *each* node (that's the `Find` operation of Union-Find) and test whether they are equal.  The path compression is optional -- it just makes it more efficient to do repeated `Find` operations.
Comment: Sorry I'm still not 100% on this. So would I simply use the Find function on the first node, and then use the find function on the next node, and if they're equal, then we'd have the same root, correct? I would have to have some sort of double for loop for this then to compare the first node to every other node, then compare the 2nd node to every other node, etc?
Comment: Sorry, you said that you have implemented Union-Find.  If you have, you have a function `Union(x,y)` that joins two nodes, and you have a function `Find(x)` that finds the root node of a set.  If you want to know whether `x` and `y` are related you test if `Find(x) == Find(y)`.  I don't think I can be clearer than this.
Comment: Okay. I think things are a little bit more clear... I'm just not sure what order to call my functions now. Would I simply do

Union(Find(x),Find(y)); then followed by a if(Find(x) == Find(y)){ cout << "in a set" << endl; }
Comment: `Find` is already part of `Union`.  You need to go back to the implementation details.  Wikipedia has a good description.  Then you need to work out whether Union-Find is actually appropriate for the problem you are trying to solve.
Comment: I think it is because I am trying to incorporate it into an implementation of Kruskal's algorithm with it. After I have found all connected components, I want to sort output something that will denote each disjoint set from each disjoint set. Sorry to bother you so much but if possible might you have any psuedo code to explain what you mean? So sorry...
Comment: I have edited my answer with a C++ code example that should help you understand.  In this case, I simply create a list for each unique disjoint set, and added every set member to it.  Modify as you see fit.
Comment: Thanks! This was really useful. I realized I was definitely overthinking things and things make sense now. Thanks!
Comment: Ah just one question. So lets say we couldn't use maps or the STL in general. How would you do the line  mysets[rootnode].push_back(thisnode); with using only using arrays? I say this because you said in a map, using the [] operator creates a new list when none exist for that node.
Comment: Well, in that case you'd obviously have to implement your own list type.  And the easiest thing then would be to store a pointer to it on the root node of a disjoint set.  Whenever you found that the root does not yet have a list, you'd create it and add either the root node or its list to another list.  If that makes sense.  This is starting to go beyond the scope of your question, which was tagged as C++...  I would expect the STL to be part of C++.
Comment: Hm okay. I'm having trouble finding all the nodes with the same root. I was trying a double for loop (take one root, search through all the edges to see if they had the same root, move to the next root, do the same thing) but it seems repetitive and unnecessary. Is there a more efficient way to do it? Also with regards to the list class do you mind providing any psuedocode for how to do it? I've been struggling and struggling with it. I have my code posted on another post.
Comment: The code I gave you IS an efficient way to do it.  Even more efficient is my suggestion to build lists directly on the nodes, because that involves no searching and is `O(N)` in calls to `Find`.  Do not perform an `O(N^2)` loop.  If you are implementing union find, it is expected that you already understand lists.  But if not, there are *countless* examples of list implementations for both C and C++ on the web, just one search away.  If you have posted a question about lists, the correct place to answer is there, not here.
Answer: It sounds as if you graph is directed in which case union-find doesn't really help with connectivity (it is generally used to determine a minimum spanning tree in Kruskal's Algorithm if I recall correctly but this is for undirected graphs). If your graph happens to be undirected, you can use Union-Find to determine all connected components using a two-pass over all nodes:

For each node union the node with all nodes to which it has an edge.
For each node find the representing node and check if it was reported. If not, report it and put it, e.g., into a std::set<T> (for T being the type used to identifying the representative).

It may actually be easier to use a search algorithm like DFS:

For each node check if it was visited already.
If it wasn't visited, it is part of a new connected component: Start a DFS at the node and mark every node thus found (you can also report all the nodes encountered as being part of the connected component).

This algorithm has the advantage that it is also O(n) (the other algorithm is O(n log n) in the worst case where each connected component consists of just one node). Neither algorithm deals gracefully with directed graphs.
Comment: Yes, exactly I have a directed graph that is used to determine a minimum spanning tree via Kruskal's algorithm. Do you mind posting some psuedocode about implementing a DFS? Would a DFS be possible without using pointers? I have each vertex and length stored as an integer right now. I was thinking of using DFS but wasn't 100% sure on how to implement it...

Test for connected graph


What embedded HTTP server library options should I look at?

Question: I'm looking to write a small proxy server for kicks and giggles.
Apart from the options in libWWW, can anyone recommend any opensource options for the HTTP server and client code? Thinking of a library of some kind similar to libWWW.
Chosen language is C/C++ but open to Java, C#, Python... etc. :-)
Answer: If you choose the Java way, take a look at Jetty. It's full featured HTTP server which is very easy to embed and pretty lightweight.
Answer: Jetty is great indeed. However, if you want a proxy server, take a look at RabbIT proxy. It is well designed and amenable to modifications. e.g. We implemented a filter that serialized certain XML text in requests to Java objects, and similarly deserialized responses.
There's a wide array of choices depending on what you want to do. For example, to handle NTLM authentication, you have cNTLM (C) or NTLMAPS (Python) or jCIFS library (Java).
Answer: If you're considering to make your proxy server in Asynchronous way in C/C++.
Here's some of open source projects you might want to check out:

libevent provides one - good choice for light use. but recursion on large data is not provided..
mongoose - nice API, good abstraction, but it uses select() and realloc() based i/o buffer, Also dual license for commercial use.
libevhtp - developed as a replacement of libevent's http module.
GNU's libmicrohttpd - good feature set.
libasyncd - I'm the author. It features general asynchronous framework and comes with HTTP handler.

I'm only able to make 2 links on my answer, but you can easily find the project homes by googling them.


FILTER range must be a single row or a single column. when trying to apply a condition across several columns at once

Question: Here is a regular filter function that works as expected:
=filter(
data!$A$2:$A,
date!$D$2:$D>=$A$16,
data!$D$2:$D<=$B$16,
data!$EC$2:$EC=$A23
)

This returns the subset of values in data!$A$2:$A that match the conditions. Great.
I would like to add a condition to a range of columns, that all that data!$CD$2:$CN are all equal to one. Tried:
=filter(
data!$A$2:$A,
date!$D$2:$D>=$A$16,
data!$D$2:$D<=$B$16,
data!$EC$2:$EC=$A23,
data!$CD$2:$CN=1
)

Then tried:
=filter(
data!$A$2:$A,
date!$D$2:$D>=$A$16,
data!$D$2:$D<=$B$16,
data!$EC$2:$EC=$A23,
sum(data!$CD$2:$CN)=11 # there's 11 columns in this range
)

I get the error above. I could manually add a condition for each of the 11 columns:
=filter(
data!$A$2:$A,
date!$D$2:$D>=$A$16,
data!$D$2:$D<=$B$16,
data!$EC$2:$EC=$A23,
data!$CD$2:$CD=1,
data!$CE$2:$CE=1,
... lost more in here all the way to ...
data!$CN$2:$CN=1
)

But that's going to get pretty repetitive.
Is there a way to filter across a range of columns, in this case I want to filter to only include rows where everything in data!$CD$2:$CN equals 1?
Answer: You can use MMULT function to combine multiple columns into one criteria.
Ex:

In your case it would be:
=FILTER(data!$A$2:$A,MMULT(--(data!$CD$2:$CN=1),{1;1;1;1;1;1;1;1;1;1;1})=11)

Comment: @DougFir it is way to convert bool to int value.
Comment: Fantastic, thanks a lot.
Comment: Interesting syntax there with the two dashes `MMULT(--` what's going on there? Am reading docs https://support.google.com/docs/answer/3094292
Comment: you can replace `{1;1;1;1;1;1;1;1;1;1;1}` by `sequence(columns(data!$CD$2:$CN),1,1,0)`


How do you insert MathJax (Latex) dynamically through JavaScript?

Question: I have a LaTeX (which I am using MathJax to replicate) formula which works perfectly in HTML but when I try to inject it via .innerHTML this fails.
Under normal HTML I get this:

But when I use this code in JS:
document.getElementById("si_suvat_equation").innerHTML =
"\begin{gather} s = ut + \frac{1}{2}  at^{2}\\ \notag end{gather}";

Then I get this:

So how do I get it so that my injected HTML looks like the original HTML? I am assuming JS is reading something as though it is code instead of just injecting it raw. But I am not sure how to change that so it is injecting the raw code only.
Answer: Some things to do:

In a JavaScript string literal, the backslash has a special meaning. There are several ways to get around this, but since in LaTeX syntax backslashes are very common, it is probably best to use String.raw so that backslashes are seen as literal backslashes.

You have a backslash missing before end{gather}

Mathematics needs to be surrounded with a delimiter, which by default is $$.

MathJax has a function typeset with which you can let the MathJax engine process the web page again to typeset newly added content. Please take note of the referenced documentation, as you may need to use typesetPromise instead.

Here is a demo, where the static content is loaded correctly, and the div where the dynamic formula should appear is initialised with a button. When you click it, the dynamic code is executed and typeset is then called. As you can see this dynamic content is now also correctly typeset:

document.querySelector("button").addEventListener("click", () => {
    document.getElementById("si_suvat_equation").innerHTML =
String.raw`<span>$$\begin{gather} s = ut + \frac{1}{2}  at^{2}\\ \notag \end{gather}$$</span>`;
    MathJax.typeset();
});

$$\begin{gather} s = ut + \frac{1}{2}  at^{2}\\ \notag \end{gather}$$

<button>Load</button>

This snippet shows a message in the "console", which is related to the sandboxed environment of this Stack Snippet. It wouldn't be displayed in a more standard environment.


This can not be done in Dota 2 tournaments?

Question: Is it true that in every professional tournament of Dota 2 , two teams cannot choose the same hero? And all your teammates also cannot choose the same hero?. In other words we MUST use 10 distinct heroes in total for each game ? For example if I use Invoker then all other players including my teammates are not allowed to play Invoker?
Answer: That's correct. In most Dota 2 game modes, duplicate hero selections are not allowed. This includes Captain's Mode, which is the the primary mode used in tournaments.
The exception is Mid Only mode, which can only be played in private lobbies. In Mid Only mode,

Creeps only spawn in the middle lane. Duplicate heroes allowed.
Comment: @PinkWhale while mirror matches in some games are compelling, the large variety of heroes, played exclusively, has always been a feature. Drafting, counter-picking, and hero variety are more heavily valued than "maining" a hero, or mirror matchups. Before all-pick was added to DotA, Sentinel players could only pick among the Sentinel heroes, and Scourge only the Scourge heroes. Mirrors in a moba, to my knowledge, were an invention of League of Legends and don't have a place in classic Dota gameplay.
Comment: If I use Invoker and my opponents also use Invoker , may be allowed in some modes ?
Comment: @PinkWhale No. The only exception to this, as I noted, is Mid Only mode (sometimes called "same hero only mid" mode).
Comment: Is it interesting to see Invoker vs Invoker , Your Invoker against my Invoker , and see who's the best Invoker ?
Comment: In most Dota 2 game modes, duplicate hero selections are not allowed. This already mention above..... This is Dota2 not League of Legend.....
Comment: Ryu vs Ryu , Ken vs Ken...  you know?
Comment: Also, in the "lore" of the gamemode-what there is of it-there is only "one" Invoker, so  there also is the benefit of keeping the heroes unique and "special."


How can I add loading text/image to images that are still loading with jQuery?

Question: I need to apply this to images that are selected by jQuery selector for example $("img"), should apply this to all images in page.
Answer: jquery loading image while elements loads
https://stackoverflow.com/.../adding-a-loading-image-to-dynamic-images-comming-from-flickr
Answer: I guess you can do like this.
create an initial layout with the following:

Image that you are loading with visibility:hidden;
div with loading message.
jQuery's domready show the image and hide the div.

Is this okay?
Answer: There is a tutorial at
http://jqueryfordesigners.com/image-loading/
that you would want to supplement with an each() loop in $("img")


How is the Themosis framework able to call a function in a class that doesn't exist?

Question: I was taking a look a the Themosis framework for WordPress and saw in their docs that to make a custom post type you would call:
PostType::make('slug-books', 'Books', 'Book')->set();

I assumed that PostType must be a class with a static function make. However, looking at their code I found no PostType class.
How are they able to call a function in a class that doesn't exist?
I can kind of see how the Application class is being used to store instances of the classes when they are called, but I don't see how the code above would trigger the classes creation.
Answer: I'm the developer behind the Themosis framework. This "trick" is highly inspired by the Laravel framework where all credits are.
We're using a facade pattern in order to make this working. Basically we use a PHP magic method __callStatic() and behind we make it link the static method to an instance method.
Check documentation over here: http://php.net/manual/en/language.oop5.overloading.php#object.callstatic


Sidebar pushes content right when minimized, sticks when maximized

Question: I am very, very new to front-end (I've been doing it for a week)
I currently have some JS/React, and CSS code that makes a basic website. Everything works and I've fixed all the bugs but one:
When the screen is full-size, the sidebar is automatically open. I don't really care if it is or isn't (and my problem may be solved if it wasn't), but it is. When I minimize, the sidebar collapses and opens as normal. The content of the main page and the navigation bar on the top push to the right using JQuery. However, if I leave the sidebar open and maximize the screen, the contents stay pushed to the right because the sidebar stays open on the larger screen.
I have no idea what you need to see to be able to help me, so I'll post the sidebar JS and CSS and the App.js JQuery code.
App.js
  const [sidebarOpen, setsidebarOpen] = useState(false);
  const openSidebar = () => {
    setsidebarOpen(true);
    $('.main__container').toggleClass("open");
    $('.navbar').toggleClass("open");
    $('.navbar__left').toggleClass("open");
  };
  const closeSidebar = () => {
    setsidebarOpen(false);
    $('.main__container').toggleClass("open");
    $('.navbar').toggleClass("open");
    $('.navbar__left').toggleClass("open");
  };

I did try to do an if/else up there ^, something like if the sidebar is already open and you try to open again, then toggle twice, but that didn't work.
sidebar.js
const Sidebar = ({sidebarOpen, closeSidebar}) => {

    return (

name

 stuff

                 closeSidebar()}
                className="fa fa-times"
                id="sidebarIcon"
                aria-hidden="true"
                >

    **menu items**

sidebar.css
#sidebar {
    background: #263f8e;
    grid-area: sidebar;
    overflow-y: auto;
    padding: 20px;
    -webkit-transition: all 0.5s;
    transition: all 0.5s;
    height: 100vh;
  }

  .sidebar__menu > h2 {
    color: #69BF87;
    font-size: 16px;
    margin-top: 15px;
    margin-bottom: 5px;
    padding: 0 10px;
    font-weight: 700;
  }

  .sidebar_responsive {
    display: inline !important;
    z-index: 9999 !important;
    left: 0 !important;
    position: absolute;

  }

  @media only screen and (max-width: 978px) {
    #sidebar {
      display: none;
    }

    .sidebar__title > i {
      display: inline;
    }
  }

I only included what I thought might help ^^
Small edit: If I make the sidebar display = None, then it loads it without a sidebar. If I minimize, open the sidebar, then maximize, the sidebar stays. I feel like I'm going in a circle!
Small edit 2: this works $(window).resize(function(){window.location.reload();}); but isn't very smooth and would rather have a better solution :)
Answer: It seems that most, if not all, websites refresh their screen on resize. I added this line:
$(window).resize(function(){window.location.reload();});

and it refreshes as it should. It's a little slower than regular websites but I think that's because I am using NPM. I am going to say this is the solution since it's the standard.