text:
Q: Create specific vector of colors How to create a vector of colors where one certain output receives a different color than the others?
Manually it can be done like in the following example:
pts.7 <- cbind(1:7, 1:7)
mycols <- c("black","black","black","red","black","black","black")
plot(pts.7, col=mycols)

However for bigger data set like the following it doesn't work:
pts.400 <- cbind(runif(400), runif(400))
df <- data.frame(a = 1:400)
pts.400.df <- SpatialPointsDataFrame(pts.400, df)

How could a vector of colors be build that all points plotted get a grayscale color except point$a==158 which should be plotted red?

A: A trick is to use logical indexing:
plot(pts.400.df, col = c('black', 'red')[(pts.400.df$a == 158) + 1])

Each FALSE will be black, each TRUE will be red.


text:
Q: How to render react components in a for loop? I would like to render components based on a number constant.
With an array that wouldn't be a problem, but I don't have a solution for the constant.
  const numberOfItems = 4;

  return (
      {/* The for loop should be here, with which 4 <Grid> components should then be rendered */}
        <Grid item xs={12} sm={6}>
          <TextField
            required
            id="quadrant-one"
            name="quadrant-one"
            label="Quadrant 1"
            fullWidth
          />
        </Grid>
   )

A: You can create an array and map it:
const numberOfItems = 4;

return [...Array(numberOfItems).keys()].map((key) => (
  <Grid key={key} item xs={12} sm={6}>
    <TextField />
  </Grid>
));

See related question for additional ways of creating an array.

A: You can use the Array constructor
{Array.from(new Array(4)).map((_, i) => (
  <Grid key={i} item xs={12} sm={6}>
          <TextField
            required
            id="quadrant-one"
            name="quadrant-one"
            label="Quadrant 1"
            fullWidth
          />
))}

A: You can use new Array(numberOfItems).fill(0) to define an array with a number of items based on a constant. If you have a dynamic number of items as props, you can do the following (using React.useMemo to only generate the itemsArray once when numberOfItems has changed):
const Component = ({ numberOfItems }) => {

  const itemsArray = React.useMemo(() => {
     return new Array(numberOfItems).fill(0);
  }, [numberOfItems]);

  return (

    {itemsArray.map((_, index) => (
       <Grid key={index} item xs={12} sm={6}>
          <TextField
            required
            id="quadrant-one"
            name="quadrant-one"
            label="Quadrant 1"
            fullWidth
          />
       </Grid>
    ))}

  );
}

Otherwise, with a constant defined:
const numberOfItems = 4;
const itemsArray = new Array(numberOfItems).fill(0);

const Component = () => {

  return (

    {itemsArray.map((_, index) => (
       <Grid key={index} item xs={12} sm={6}>
          <TextField
            required
            id="quadrant-one"
            name="quadrant-one"
            label="Quadrant 1"
            fullWidth
          />
       </Grid>
    ))}

  );
}

A: If you use something like Lodash you can use _.times:
  return (
      {_.times(4, index =>
        <Grid item xs={12} sm={6} key={index}>
          <TextField
            required
            id="quadrant-one"
            name="quadrant-one"
            label="Quadrant 1"
            fullWidth
          />
        </Grid>
      )}
   )

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create Windows XP LiveUSB using Ubuntu to replace it I am using an Acer Aspire One netbook with no CD-disk drive, and would like to uninstall Ubuntu 12.04 LTS and install Windows XP in its place. The problem here is that I can't seem to find a program that can put the windows boot files on a USB drive from an ISO file. I have Ubuntu fully installed and have tried using unetbootin. When I tried booting from unetbootin I got a screen with a blue box that had the word "default" in it highlighted. underneath the box there was a countdown that said "will boot from default in 10" after the countdown finished the number would revert to ten and nothing would happen. Can someone tell me another program that would be useful for this please?

A: Create a bootable Windows XP USB drive:
Download "ms-sys"
Install it.
Partition your USB drive to NTFS.
Now copy the files from your Windows XP ISO to the USB drive
Copy the Windows XP mbr to the USB drive
ms-sys -m /dev/sdX

Replace sdX with the number of your usb hard drive (for example: sda5).
After that, backup your data, then format your drive to NTFS from your Live USB.
You can now install Windows XP through the USB.

A: Creating a bootable USB installer for Windows on Ubuntu
Edit: Windows XP doesn't seem to be supported by WinUSB. This method works fine for Windows Vista and up. See here for a different method that works with Windows XP.
WinUSB automates the process of creating a bootable USB stick from a Windows installation disk or .iso file. You can install it either from the .deb package provided on the homepage or through a PPA:
sudo add-apt-repository ppa:colingille/freshlight
sudo apt-get update
sudo apt-get install winusb

The GUI should be straightforward and easy to use:

A: If you're trying to install Windows XP, you shouldn't need to "uninstall" Ubuntu.  You can just install Windows XP.  (You'll lose all your Ubuntu files, but I'm sure you know that.)
Installing Windows XP is another matter, and doesn't belong in askubuntu.com.

A: Unless you have a modified SETUPLDR.BIN, it won't work from USB.
Needed:

*

*Modified SETUPLDR.BIN

*special stuff in the bootsector of the partition (use ms-sys).

*Modified copy of txtsetup.sif copied to the root level

*NTDETECT.COM copied to root level
WinUSB does not do this, UNetBootin does not do this, the diskpart tutorial does not do this, WinToFlash does not do this, and bit-banging the iso onto the device with dd does not do this.
Rufus does this. However, it is a Windows-only utility (that is unsupported by Wine), so follow the tutorial here (the big post):
https://superuser.com/questions/99478/make-a-bootable-usb-to-install-windows-xp-from-linux
Though I suppose you could share your target drive to VirtualBox, go through the first part of the installer, and then, instead of rebooting, shutdown the VM. Then turn the computer off and actually boot into the hard drive.
I think that would work because Windows does not become specific to a given hardware configuration until the second phase, I believe.
You see, if you did the whole installation from VirtualBox, Windows would be configured for VirtualBox's emulated hardware platform, not your real hardware.
The method of loading the whole iso into memory and booting it usually results in a blue screen at some point. If you really want to do that method, see this: http://diddy.boot-land.net/firadisk/files/win_iso_install.htm


text:
Q: Api-Platform: Where can I reduce the content that is sent by my API? I have an Api-Platform project where I have a rest-api that shows certain data. Currently the api returns ALL information, which isn't good. Can someone push me in the right direction?
I found this for adding extra data: https://api-platform.com/docs/core/serialization/#decorating-a-serializer-and-add-extra-data
Should I use the decorator approach mentioned in the doc above and just unset the fields that I don't want displayed? Is there perhaps some annotation I could use above fields in the entities so that they are omitted?
Thanks.

A: So I found a simple solution if you are using annotations:
The "@Groups()" above each field in an entity decides whether or not the data for the given field is readable.
Before I had this annotated above each field "* @Groups({"READ"})", removing it will not display the fields data when calling the api.
More info here: https://api-platform.com/docs/core/serialization/#the-serialization-context-groups-and-relations


text:
Q: Copying response data from rxJs in Angular2/Typescript I'm using Observable from rxJS in my Angular2 with TypeScript application. I would like to take a copy of the http get response data.
Service:
getSizes(sku: number): Observable<SizeList[]> {
        let api = this.host + this.routes.sizes + sku;
        return this._http.get(api)
                .map((response: Response) => <SizeList[]>response.json())
                .catch(this.handleError);
}

Component:
getSizes() {
        this._productService.getSizes(this.productColour)
                .subscribe(
                sizes => this.sizes = sizes,
                error => this.errorMessage = <any>error);
}

How can I take a copy of this.sizes? If I try to take a copy at the end of my components getSizes(), it's undefined.

A: I think that your problem is related to the asynchronous aspect of observables. At the end of the getSizes method, the data are there yet. They will be available within the subscribe callback:
getSizes() {
    this._productService.getSizes(this.productColour)
            .subscribe(
            sizes => {
              this.sizes = sizes;
              console.log(this.sizes); // <------
            },
            error => this.errorMessage = <any>error);
}

If you want to return the value from the getSizes method, you need to return an observable and let the method caller subscribe on it:
getSizes() {
  return this._productService.getSizes(this.productColour)
            .catch(error => this.errorMessage = <any>error);
}

someOtherMethod() {
  this.getSizes().subscribe(sizes => this.sizes = sizes);
}

A: This is because HTTP requests are made asynchronously in JS/Angular 2, so logic at the end of your getSizes() method is probably running before the method this._productService.getSizes(...) has finished loading your content.
You should place your logic therefore in the subscribe() method like this:
getSizes() {
        this._productService.getSizes(this.productColour)
                .subscribe(
                sizes => {
                    this.sizes = sizes
                    // more logic here
                },
                error => this.errorMessage = <any>error);

        // code here gets executed before the subscribe() method gets called
}


text:
Q: Detect song ending in YTPlayer View in iOS I have used YTPlayer View to play song using videoID, now i want to detect the current song ending state, i have used a delegate but it isn't catching it.How i can detect when the song is finish so that i could play next song. This is my code,
func playerView(playerView: YTPlayerView!, didChangeToState state: YTPlayerState)
{
    switch (state) {
    case YTPlayerState.playing:
        print("Started playback");
        break;
    case YTPlayerState.paused:
        print("Paused playback");
        break;
    case YTPlayerState.ended:
        print("Ended playback");
        self.selectedIndex = selectedIndex + 1

        let videoId = playListArray[selectedIndex].videoId
        self.songView.load(withVideoId: videoId!, playerVars: playerVars)
        break;
    default:
        break;
    }
}

Have used this delegate also,YTPlayerViewDelegate. But it isn't coming inside end state.


text:
Q: Searching a file in 3 different ways I have been writing a program that searches a file in 3 different ways. But firstly, to choose which search program to use is differentiated in the command line.
For example in the command line I type:

Program 1 search: python file.py
  'search_term' 'file-to-be-searched'
program 2 search: python file.py -z
  'number' 'search_term'
  'file-to-be-searched'
program 3 search: python file.py -x
  'search_term' 'file-to-be-searched'

All 3 search scripts are in the file.py.
The coding I have so far is:
import re
import sys
#program 1
search_term = sys.argv[1]
f = sys.argv[2]

for line in open(f, 'r'):
    if re.search(search_term, line):
     print line,

# Program 2
flag = sys.argv[1]
num = sys.argv[2]
search_term = sys.argv[3]
f = sys.argv[4]

#program 3
flag = sys.argv[1]
search_term = sys.argv[2]
f = sys.argv[3]

for line in open(f, 'r'):
 if re.match(search_term, line):
  print line,

Program 1 works fine thats no problem. Program 2, finds the search-term in the file and prints out a number of lines before and after it defined by the 'number' parameter, but i have no idea about how to do this. Program 3 finds the exact match from the search-term and prints out all the lines after the search_term. re.match is inadequate because it only searches from the beginning of a string it does not consider the rest.
My final problem how would I differentiate between the three programs? using the flags or no flag from the command line?
Any help would be appreciated.
Thanks

A: First of all you should look at two very useful Python modules:

*

*fileinput: Iterate over lines
from multiple input streams

*optparse: A powerful command
line option parser

fileinput will help you read lines from several files and even modify them if you need. You'll program will be much easier to extend and read with these tools
Here is an example:
import fileinput
import optparse

if __name__ == '__main__':
    parser = optparse.OptionParser()
    parser.add_option("-z", dest="z", help="Description here")
    parser.add_option("-x", dest="x", help="Description here")
    options, args = parser.parse_args()
    search_term = args[0]
    for line in fileinput.input(args[1:]):
        process(line)

For matching you can use re.search instead of re.match. An example from the docs:
>>> re.match("o", "dog")  # No match as "o" is not the first letter of "dog".
>>> re.search("o", "dog") # Match as search() looks everywhere in the string.
<_sre.SRE_Match object at ...>

Edit: answering Jessica's comment

say for example in my in my file i had
  the words: zoo, zoos and zoological.
  If i typed zoo as my search type all 3
  would be retured rather than just zo0

You could wrap the search term in \b to only match the word for example:
>>> re.search(r'\bzoo\b', 'test zoo')
<_sre.SRE_Match object at 0xb75706e8>
>>> re.search(r'\bzoo\b', 'test zoos')
>>> re.search(r'\bzoo\b', 'test zoological')

\b matches an empty string, but only at the beginning or end of a word.
So in your script you can do this:
searchterm = r'\b%s\b' % searchterm

Note: the r here is important otherwise you have to escape the '\'

A: Maybe it's a little to heavy for a short script, but in pythons standard library, you'll encounter the getopt and the more convenient optparse module.

getopt This module helps scripts to parse the command line arguments in sys.argv.
optparse is a more convenient, flexible, and powerful library for parsing command-line options than the old getopt module. optparse uses a more declarative style of command-line parsing: you create an instance of OptionParser, populate it with options, and parse the command line. optparse allows users to specify options in the conventional GNU/POSIX syntax, and additionally generates usage and help messages for you.


text:
Q: Approximation of finite Lebesgue measurable set by closed subset From Bass, Real Analysis for Graduate Students:

Let $m$ be the Lebesgue measure and $A$ a Lebesgue measurable subset of $\mathbb{R}$ with $m(A)< \infty$. Let $\epsilon>0$. Show there exist $G$ open and $F$ closed such that $F\subset A\subset G$ and $m(G\setminus F)<\epsilon$.

Using the definition of Lebesgue measure as an outer measure I can easily build an open $G$ such that  $A\subset G$ and $m(G\setminus A)<\epsilon/2$.
I'm stuck with finding a closed set $F$ such that $F\subset A$ and $m(A\setminus F)<\epsilon/2$.
I know how to build one whenever $\textbf A$ is bounded. Nevertheless, $m(A)<\infty$ need not imply that $A$ is bounded ($A=\mathbb Q$ is an example).
Is there a way to circumvent this looser setting ?

A: Since $A$ is measurable so $A^c$ is measurable
Hence there exists an open set $A^c\subseteq O$ such that $m^*(O-A^c)<\epsilon$ for all $\epsilon>0$.
Now consider $O^c$ which is closed.Also $  O^c\subseteq  A$ and $m^*(A-O^c)=m^*(O-A^c)<\epsilon$

A: Using the definition of $m$ as an outer measure, there exist $A_i=(a_i,b_i]$ such that  $A\subset \cup_i A_i$ and  $\sum_i (b_i-a_i) \leq m(A) + \epsilon/2$. Let $b_i' = b_i + \epsilon 2^{-i-1}$. $G:=\cup_i (a_i,b_i')$ is an open set that contains $A$ and  $m(G)\leq \sum_i (b_i'-a_i) =\epsilon/2 + \sum_i (b_i-a_i) \leq m(A) + \epsilon   $.
Since $m(A)<\infty$, $m(G \setminus A)=m(G) - m(A)\leq \epsilon$.
Since $m(A)<\infty$, $A$ is approcheable by a bounded set. Indeed, $m(A) = m(\cup_n (A\cap [-n,n])) = \lim_n m(A \cap [-n,n])$. There is therefore some $N$ such that  $$m(A \cap [-N,N])\geq m(A)-\epsilon/2 \quad (\star)$$
Let $A' = A \cap [-N,N]$. Since $[-N,N]\setminus A'$ has finite measure, there exists some open $G'$ such that  $[-N,N]\setminus A' \subset G'$ and $m(G'\setminus ( [-N,N]\setminus A'))\leq \epsilon/2$.  Let us prove that the closed set $[-N,N]\setminus G'$ fits the bill.
It's easy to prove  $[-N,N]\setminus G'\subset A'$. Furthermore, $$\begin{aligned} m(A'\setminus ([-N,N]\setminus G')) &= m(A'\cap ([-N,N]^c \cup G'))\\ &= m(A'\cap G') \end{aligned}$$ and
$$\begin{aligned} \epsilon/2 \geq m(G'\setminus ( [-N,N]\setminus A')) &= m((G'\cap [-N,N]^c) \cup (G'\cap A'))\\ &\geq m(G'\cap A')\end{aligned}$$
Hence $m(A'\setminus ([-N,N]\setminus G')) \leq \epsilon/2$. Let $F = [-N,N]\setminus G'$, then $$m(A') - m(F) \leq \epsilon/2 \quad (\star \star)$$
$(\star)$ and $(\star \star)$ yield $$m(A\setminus F) = m(A) - m(F) \leq (m(A') - m(F)) + \epsilon /2 \leq \epsilon $$
Finally,  $F\subset A \subset G$ and $m(G\setminus F)  = m(G\setminus A) + m(A\setminus F) \leq 2\epsilon$


text:
Q: Python Create boxplot chart in Excel Using df I need to create boxplot chart in Excel. Thera are many examples how to create charts like ScatterChart but not boxplot.
I do as do succeded to create it as png but not as active chart into excel


text:
Q: jQuery nav menu doesn't update first element I'm trying to build a custom navigation menu with 3 options. Initially, only the active option is visible. Clicking on the active option shows the other options, and upon clicking on another one, it is prepended at the beginning of the menu and the other list items are once again hidden.
// html

Option 1

Option 2

Option 3

// css
li {
    display: block;
}
li:not(:first-child) {
    display: none;
}

// js
$(function(){
    $('li:first-child').on('click', function(){
        $(this).siblings().toggle()
    });

    $('li').not(':first-child').on('click', function(){
        $(this).prependTo('ul')
        $(this).siblings().hide()
    });
});

http://jsfiddle.net/H85Yj/
However, the only issue is that after it executes once, it won't run again. I'm guessing that the li:first-child still remains as the first option. Any way I can work around this?

A: The (undocumented, so far as I can see, in the API for prependTo()) problem you appear to be experiencing is that, once you move the li element from the HTML, the event-binding is not transferred with them; therefore clicking on the li no longer triggers an event. The easiest way around that is to bind the events to the parent ul element, and handle the events there (as the click events bubble up through the DOM and are acted upon by the ancestor).
Therefore, I'd suggest:
$('ul').on('click', 'li', function(){
    var self = $(this),
        siblings = self.siblings();
    if (siblings.filter(':visible').length) {
        self.prependTo(self.parent());
        siblings.hide();
    }
    else {
        siblings.toggle();
    }
});

JS Fiddle demo.
Although, on reflection, the following seems more simple:
$('ul').on('click', 'li', function(){
    var _self = $(this);
    if (_self.is(':first-child')) {
        _self.siblings().toggle();
    }
    else {
        _self.prependTo(_self.parent()).siblings().hide();
    }
});

JS Fiddle demo.
Note that I've adjusted the CSS a little, too (to use simple CSS rather than SCSS); setting the display: none as the default rule for the li elements, and display: block for the li:first-child element (as opposed to the needlessly-complex :not(:first-child) rule you used originally).
References:

*

*:first-child selector.

*:visible selector.

*filter().

*is.

*on().

*parent().

*prependTo().

*siblings().


text:
Q: boa constructor frame not launching This is my first application in Boa Constructor and my first time using wxPython.
#Boa:Frame:Frame1

import wx

choiceList = ['DAR', 'Impex', 'Endon', 'Astro', 'Ansell', 'Other']

def create(parent):
    return Frame1(parent)

[wxID_FRAME1, wxID_FRAME1BUTTONSELECTDIR, wxID_FRAME1BUTTONSELECTFILE,
 wxID_FRAME1CHOICESUPPLIER,
] = [wx.NewId() for _init_ctrls in range(4)]

class Frame1(wx.Frame):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
              pos=wx.Point(517, 20), size=wx.Size(400, 492),
              style=wx.DEFAULT_FRAME_STYLE, title='Frame1')
        self.SetClientSize(wx.Size(392, 458))

        self.choiceSupplier = wx.Choice(choices=choiceList, id=wxID_FRAME1CHOICESUPPLIER,
              name=u'choiceSupplier', parent=self, pos=wx.Point(48, 176),
              size=wx.Size(120, 21), style=0)
        self.choiceSupplier.Bind(wx.EVT_CHOICE, self.OnChoiceSupplierChoice,
              id=wxID_FRAME1CHOICESUPPLIER)

    def __init__(self, parent):
        self._init_ctrls(parent)

    def OnChoiceSupplierChoice(self, event):
        supplier = choiceList[self.choiceSupplier.GetSelection()]
        print supplier

My code runs fine when I click run application. However when I try to edit it in designer I get an error:
16:17:06: Traceback (most recent call last):
16:17:06:   File "C:\Python27\Lib\site-packages\boa-constructor\Models\wxPythonControllers.py", line 78, in OnDesigner     self.showDesigner()
16:17:06:   File "C:\Python27\Lib\site-packages\boa-constructor\Models\wxPythonControllers.py", line 143, in showDesigner     designer.refreshCtrl()
16:17:06:   File "C:\Python27\Lib\site-packages\boa-constructor\Views\Designer.py", line 399, in refreshCtrl     self.initObjectsAndCompanions(objCol.creators[1:], objCol, deps, depLnks)
16:17:06:   File "C:\Python27\Lib\site-packages\boa-constructor\Views\InspectableViews.py", line 127, in initObjectsAndCompanions     self.initObjCreator(constr)
16:17:06:   File "C:\Python27\Lib\site-packages\boa-constructor\Views\Designer.py", line 529, in initObjCreator     InspectableObjectView.initObjCreator(self, constrPrs)
16:17:06:   File "C:\Python27\Lib\site-packages\boa-constructor\Views\InspectableViews.py", line 155, in initObjCreator     constrPrs.comp_name, constrPrs.params)
16:17:06:   File "C:\Python27\Lib\site-packages\boa-constructor\Views\Designer.py", line 483, in loadControl     compClass=CtrlCompanion, evalDct=self.model.specialAttrs)
16:17:06:   File "C:\Python27\Lib\site-packages\boa-constructor\Views\Designer.py", line 62, in setupArgs     args = InspectableObjectView.setupArgs(self, ctrlName, params, dontEval, evalDct=evalDct)
16:17:06:   File "C:\Python27\Lib\site-packages\boa-constructor\View \InspectableViews.py", line 63, in setupArgs     evalDct)
16:17:06:   File "C:\Python27\Lib\site-packages\boa-constructor\PaletteMapping.py", line 158, in evalCtrl     return eval(expr, globals(), localsDct)
16:17:06:   File "<string>", line 1, in <module>
16:17:06: NameError: name 'choiceList' is not defined

A: Stumbled across this question while looking for something else boa-constructor related, sorry if answering to kinda-dead posts here is considered faux pas, I'm new here.
Anyway, my best guess is you messed with the _init_ctrls yourself even tho there's that "don't edit" comment. Tried that one myself a couple times, well boa doesn't handle that too well. After changing
self.choiceSupplier = wx.Choice(choices=choiceList

to
self.choiceSupplier = wx.Choice(choices=''

you can enter the designer once again, and to be able to have that AND populate the wx.Choice item I moved the list inside the init :
#Boa:Frame:Frame1

import wx

def create(parent):
    return Frame1(parent)

[wxID_FRAME1, wxID_FRAME1CHOICESUPPLIER,
] = [wx.NewId() for _init_ctrls in range(2)]

class Frame1(wx.Frame):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
              pos=wx.Point(517, 20), size=wx.Size(408, 496),
              style=wx.DEFAULT_FRAME_STYLE, title='Frame1')
        self.SetClientSize(wx.Size(392, 458))

        self.choiceSupplier = wx.Choice(choices=self.choiceList,
              id=wxID_FRAME1CHOICESUPPLIER, name=u'choiceSupplier', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(392, 21), style=0)
        self.choiceSupplier.Bind(wx.EVT_CHOICE, self.OnChoiceSupplierChoice,
              id=wxID_FRAME1CHOICESUPPLIER)

    def __init__(self, parent):
        self.choiceList = ['DAR', 'Impex', 'Endon', 'Astro', 'Ansell', 'Other']
        self._init_ctrls(parent)

    def OnChoiceSupplierChoice(self, event):
        supplier = choiceList[self.choiceSupplier.GetSelection()]
        print supplier

if __name__ == '__main__':
    application = wx.PySimpleApp()
    someFrame = Frame1(None)
    someFrame.Show()
    application.MainLoop()

Probably the issue is how the designer session analyzes the file, missing out on the list that's external to the class.


text:
Q: $n^{th}$ derivative of $\sqrt{ax+b}$? What is the $n^{th}$ derivative of $\sqrt{ax+b}$?
I don't understand where does $1.3.5.....(2n-1)$ factorial comes from. Except this
I have understood the whole question.
Please help me to solve this problem.I shall be very thankful for the help.

A: Hint: Write $$f(x)=(ax+b)^{1/2}$$ then
$$f'(x)=\frac{1}{2}(ax+b)^{-1/2}a$$
$$f''(x)=\frac{a}{2}(ax+b)^{-3/2}a=…$$
Can you proceed?

A: The successive derivatives of a power go like
$$x^r\to rx^{r-1}\to r(r-1)x^{r-2}\to r(r-1)(r-2)x^{r-3}\to\cdots$$
Now if $r$ is a half-integer, semi-factorials appear.
Ignoring the signs,
$$\frac12\frac12\frac32\frac52\frac72\cdots$$
PS: the same holds for $(ax+b)^r$, provided you add a factor $a$ each time.


text:
Q: Is it possible to prevent unused Visualforce Components from using View State? Components appear to use View State even if they are not rendered.
i.e. there is almost no difference in the View State size between the following two options:
<c:my_component rendered="true"/>
<c:my_component rendered="false"/>

I have a component that conceptually does the following:
<apex:component>
    <apex:attribute name="viewType" description="The view type" type="String" required="true"/>

    <c:my_sub_component_1 rendered="{!viewType='A'}"/>
    <c:my_sub_component_2 rendered="{!viewType='A'||viewType='B'}"/>
    <c:my_sub_component_3 rendered="{!viewType='A'||viewType='C'"/>
    <c:my_sub_component_4 rendered="{!viewType='B'||viewType='c'"/>
    ....
</apex:component>

With the downside that the View State increases from ALL the components, not just the ones that are intended to be shown.
Besides creating a separate parent Component / Page for each of the many combinations, is there any way to completely exclude some sub-components based on the attribute, such that they don't affect the View State size?

A: You could choose to render your page dynamically. It's not normally recommended because... reasons.

Dynamic Visualforce components are not intended to be the primary way to create new Visualforce pages in your organization. Existing Visualforce pages shouldn't be rewritten in a dynamic manner and, for most use cases, standard Visualforce components are acceptable and preferred. You should only use dynamic Visualforce components when the page must adapt itself to user state or actions in ways that can't be elegantly coded into static markup.

But, if you need the extra performance, you can do so, it just takes some effort.
<apex:page controller="MyController">
    <apex:repeat value="{!components}" var="component">
        <apex:dynamicComponent componentValue="{!component}"/>
    </apex:repeat>
</apex:page>

public class MyController{
    public ApexPages.Component[] components { get; set; }
    public MyController() {
        components = new ApexPages.Component[0];
        // ... //
        if(viewType == 'a') {
            components.add(new Component.sub_component_1());
        }
        if(viewType == 'a' || viewType == 'b') {
            components.add(new Component.sub_component_2());
        }
        if(viewType == 'a' || viewType == 'c') {
            components.add(new Component.sub_component_3());
        }
        if(viewType == 'b' || viewType == 'c') {
            components.add(new Component.sub_component_4());
        }
    }
}

As always, I recommend reading the manual, because there are some special rules and whatnot, depending on the parameters, etc, but this should get you started.


text:
Q: Can SQL Server avoid subqueries or joins if other where clauses return enough results? Consider this as example:
SELECT TOP 1 FROM customers
WHERE firstname LIKE 'John%'
   OR id IN (SELECT id_customer
             FROM customer_emails
             WHERE email like 'john.doe@%' )

Does query optimizer manage to prioritize the first clause, avoiding to do the subquery if the simpler clause is true for at least 1 record (from using Top 1)?
I am mainly asking this because the above query can be rewritten as Join, which technically would be faster according to Join vs. sub-query. However if the subquery is avoided, the above example is clearly superior to a Join one in situations where the first clause is likely to be true.

A:
Does query optimizer manage to prioritize the first clause, avoiding
  to do the subquery if the simpler clause is true for at least 1 record.

It can do
create table customers(id int identity primary key, firstname varchar(10)) ;
insert into customers values ('John'),  ('Johnathan'), ('George');
create table customer_emails(id_customer int, email varchar(100));
insert into customer_emails values (1, 'John@example.com'),  (2, 'Johnathan@example.com');

In the plan I got the first row matched the LIKE 'John%' predicate and the scan against customer_emails was not executed at all.

However your question is phrased as

if the simpler clause is true for at least 1 record

That would imply that the simpler WHERE clause is evaluated in its entirety and only if that fails is the second one evaluated.
For
SELECT TOP 1 *
FROM customers
WHERE firstname LIKE 'George%'
   OR id IN (SELECT id_customer
             FROM customer_emails
             WHERE email like 'George.doe@%' );

Three rows were processed before one was found matching LIKE 'George%'and there were two ensuing scans on customer_emails
Rewriting as follows...
create index ix on customers(firstname) include(id)

SELECT TOP 1 *
FROM customers with(forceseek)
WHERE firstname LIKE 'George%'
   OR  firstname NOT LIKE 'George%' AND  id IN (SELECT id_customer
             FROM customer_emails
             WHERE email like 'George.doe@%' );

...  happens to give a plan where the operators in the shaded area for the IN part don't get executed if the simpler predicate returns a row but this plan isn't guaranteed.

A: You said join and I don't think this can be done with an inner join
Top 1 is non deterministic without an order by
Typically you want to let the query optimizer do its job
It will use statistics and other logic to build an efficient plan
I think this is how I would write it
The way to test is to look at the query plans
SELECT distinct c.*
FROM customers c
LEFT JOIN customer_emails ce
  on ce.id_customer = c.ID
 and ce.email like 'john.doe@%'
WHERE c.firstname LIKE 'John%'
   OR ce.ID is not null

Or
SELECT c.*
FROM customers c
WHERE c.firstname LIKE 'John%'
   OR exist ( select 1
              from customer_emails ce
                on ce.id_customer = c.ID
               and ce.email like 'john.doe@%' )


text:
Q: Force Maven to install both .esb and .jar I have 2 JBoss Soa-p 5 services.
1st service pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>my.service</groupId>
<artifactId>First</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>  <!-- to build .jar file -->
<name>${project.artifactId}</name>

<!-- dependencies and properties here -->

<build>
    <finalName>${project.artifactId}</finalName>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*</include>
            </includes>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <!-- to build .esb file -->
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>jboss-packaging-maven-plugin</artifactId>
            <version>2.1.1</version>
            <extensions>true</extensions>
            <configuration>
                <archiveName>${project.artifactId}</archiveName>
            </configuration>
            <executions>
                <execution>
                    <id>build-esb</id>
                    <goals>
                        <goal>esb</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${maven-compiler-plugin.version}</version>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>
    </plugins>
</build>
</project>

2nd service is using a model from 1st one so I add 1st one to dependency:
   <dependencies>
    <dependency>
        <groupId>my.service</groupId>
        <artifactId>First</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <scope>compile</scope>
    </dependency>
   </dependencies>

However this situation require to install .jar file of First service to local repository.
Unfortunately when I do mvn clean install on First service both .jar and .esb are built, but only .esb file is installed to local repo. I need to remove an jboss-packaging-maven-plugin to force maven to install .jar.
How to change a pom.xml of First service to install both packages on clean install?

A: I figured it out... here is a parts of 1st service's pom.xml:
<groupId>my.service</groupId>
<artifactId>First</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!--
     <packaging>jar</packaging> we don't need it,
     after removing <goal>esb</goal> in jboss-packaging-maven-plugin
     .jar will be build automatically
-->
<name>${project.artifactId}</name>

<!-- dependecies and other stuff -->

<plugins>
    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jboss-packaging-maven-plugin</artifactId>
        <version>${jboss.packaging.maven.plugin.version}</version>
        <extensions>true</extensions>
        <configuration>
            <deploymentDescriptorFile>${basedir}/src/main/resources/META-INF/jboss-esb.xml</deploymentDescriptorFile>
            <archiveName>${project.build.finalName}</archiveName>
            <archive>
                <manifestEntries> <!-- manifestEntiries are optional -->
                    <Build-Time>${maven.build.timestamp}</Build-Time>
                    <Specification-Title>${project.name}</Specification-Title>
                    <Specification-Version>${project.version}</Specification-Version>
                    <Implementation-Title>${project.name}</Implementation-Title>
                    <Implementation-Version>${project.version}</Implementation-Version>
                </manifestEntries>
            </archive>
        </configuration>
    </plugin>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
            <!-- most important part, we got .jar builded already,
            now we need to create esb in other way then <goal>esb</goal> -->
            <descriptor>src/assembly/esb.xml</descriptor>
            <finalName>${project.build.finalName}</finalName>
            <archive>
                <manifest>
                    <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                    <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
                </manifest>
                <manifestEntries>
                    <Build-Time>${maven.build.timestamp}</Build-Time>
                    <Created-By>${project.createdBy}</Created-By>
                    <LastModify-By>${project.lastModifyBy}</LastModify-By>
                    <Project-GroupId>${project.groupId}</Project-GroupId>
                    <Project-ArtifactId>${project.artifactId}</Project-ArtifactId>
                </manifestEntries>
            </archive>
        </configuration>
        <executions>
            <execution>
                <phase>package</phase>
                <goals>
                    <goal>single</goal>
                </goals>
            </execution>
        </executions>
        <dependencies>
            <dependency>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>jboss-packaging-maven-plugin</artifactId>
                <version>${jboss.packaging.maven.plugin.version}</version>
            </dependency>
        </dependencies>
    </plugin>
</plugins>

and esb.xml (basicaly we package jar into esb file)
    <assembly>
        <formats>
            <format>esb</format> <!-- to build esb -->
        </formats>
        <includeBaseDirectory>false</includeBaseDirectory>
        <fileSets>
            <fileSet>
                <directory>src/main/resources/META-INF</directory>
                <outputDirectory>/META-INF</outputDirectory>
            </fileSet>
            <fileSet>
                <directory>${basedir}/src/main/resources/xsd</directory>
                <outputDirectory>/xsd</outputDirectory>
                <includes>
                    <include>*.xsd</include>
                </includes>
            </fileSet>
            <fileSet>
                <directory>${basedir}/target</directory>
                <outputDirectory>/</outputDirectory>
                <includes>
                    <include>First.jar</include>
                </includes>
            </fileSet>
        </fileSets>

        <dependencySets>
            <dependencySet>
                <includes>
                    <include>commons-beanutils:commons-beanutils</include>
                </includes>
                <outputDirectory>/</outputDirectory>
            </dependencySet>
        </dependencySets>
    </assembly>


text:
Q: what does this expression/function mean? This is a really short question i was just wondering what the expression
$F_x(\sin^2(\pi k_0 x))(k)$
means is it just a function f that is $sin^2(\pi k_0x)$ or is it something else?


text:
Q: Ionic 5 not loading my external javascript I have an external script  inside  my index.html in my ionic 5 application, but when i load the application on IOS phone it doesnt load this script into my project, but when i load on android device it works just fine.
Please i need help
i have tried to add the following into my meta tags from my research but still no luck
<meta http-equiv="Content-Security-Policy" content="default-src 'unsafe-inline' 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">


text:
Q: angularFire can't remove data I am creating a practice application using angularFire to integrate Angular.js with firebase. So far, I am able to pull down data, display it, and add to it. But for some reason I can't delete existing data. I've added a button that uses ng-click to point to removeProject, and when clicked, the entry will disappear from the list, but if the page is refreshed, the entry reappears as if it had never been deleted. I've tried this locally and hosted externally and both have the same results.
Here is the working code that adds entries:
$scope.addProject = function() {
    $scope.projects.add({name: $scope.newName, status: $scope.newStatus});
    $scope.newName = "";
    $scope.newStatus = "";
};

And here is the broken code the should remove entries:
$scope.removeProject = function(project) {
    $scope.projects.splice($scope.projects.indexOf(project), 1);
};

I took this pattern from the todo example, just changing the names, yet it's not working.


text:
Q: Could not load file or assembly Microsoft.Data.SqlClient, Version=5.0.0.0 Facing following issue after deploying app to azure app service:

Unhandled exception. System.IO.FileNotFoundException: Could not load
file or assembly 'Microsoft.Data.SqlClient, Version=5.0.0.0,
Culture=neutral, PublicKeyToken=***********'. The system cannot find
the file specified.

Locally everything works as fine.
Microsoft.Data.SqlClient presented in site/wwwroot

Runtime Stack: Dotnetcore - 6.0
Main app and all class libs on .net6
Server Operating System: Linux
Microsoft.Data.SqlClient presented as reference from Microsoft.EntityFrameworkCore.SqlServer (v.7.0.2)
Tried different kinds of Nuget Packages versions - still have same issue
Tried to install Microsoft.Data.SqlClient (latest version & 5.0.0.0) directly into projects - still the same

A: The solution for us was to:

*

*Locate the actual DLL file (Microsoft.Data.SqlClient.dll) on the developer's desktop filesystem (easy to find; once you're referenced it using NuGet it gets copied to multiple places)

*Add it to the web project (we placed it right in the root)

*Mark it (via Properties tool window) as Copy Always

Step 3 results in our .csproj file looks like this:
<ItemGroup>
   <None Update="Microsoft.Data.SqlClient.dll">
     <CopyToOutputDirectory>Always</CopyToOutputDirectory>
   </None>
</ItemGroup>


text:
Q: having difficulties with less I'am new with LESS and i'm trying to sort things out. This is my question for example i have a less file that looks like this
style.less
.FontAttr(@f-color: red, @f-weight: bold, @f-size: 12px) {
   color: @f-color;
   font-weight: @f-weight;
   font-size: @f-size;
}

from what i know i can use this like this in style.less
.fakelinkfont {
   .FontAttr(red, bold, 14px);
}

then use .fakelinkfont like this in my actual page

Some Characters

my question is can i use .FontAttr() {...} in my actual page and not in style.less or do i even doing everything correct. BTW i'm new with this so bear with me thank in advance.

A: You can't.
.fakelinkfont {
   .FontAttr(red, bold, 14px);
}

Gets compiled to:
.fakelinkfont {
   color: red;
   font-weight: bold;
   font-size: 14px;
}

And that is what browser uses.
You can try using client side less.js file, but I wouldn't recomend to use it in production.


text:
Q: Why is (AnObject).AField = AValue a syntax error in VB.NET? EDIT:  Modified code sample to explicitly declare return type of function.

Consider the following minimal example:
Class AClass
    Public AField As Integer

    Public Sub New(aField As Integer)
        Me.AField = aField
    End Sub

    Public Function AMethod() As Integer
        Return AField
    End Function
End Class

Module AModule

    Sub Main()

        Dim AnObject As AClass = New AClass(12)

        Dim n As Integer = (AnObject).AField  ' This is fine

        Dim m As Integer = (AnObject).AMethod() ' This is fine

        (AnObject).AField = 8 ' BC30035 Syntax Error

        AnObject.AField = 8 ' This is fine

    End Sub

End Module

How does the syntax of VB.NET work that there's a difference between these two cases?  It seems that if we're calling a method, or reading a field, the parentheses are allowed, but if we're writing a field, they're not.
I've tried looking at the Visual Basic Language Reference but I didn't see anything like a formal grammar.  I've also tried googling this, although it's a bit hard to come up with a good set of search keywords.

UPDATE
So I've looked over the language grammar that Jimi linked and I'm even more confused -- in particular we have
RegularAssignmentStatement  ::=  Expression  Equals  Expression  StatementTerminator

Expression  ::= SimpleExpression  |  MemberAccessExpression  | ...

MemberAccessExpression  ::=
    [ MemberAccessBase  ] Period  IdentifierOrKeyword
        [  OpenParenthesis  Of  TypeArgumentList  CloseParenthesis  ]

MemberAccessBase  ::= Expression  | ...

SimpleExpression  ::= LiteralExpression |
         ParenthesizedExpression  |
         SimpleNameExpression |
         ...

SimpleNameExpression  ::=  Identifier  [  OpenParenthesis  Of  TypeArgumentList  CloseParenthesis  ]

ParenthesizedExpression  ::=  OpenParenthesis  Expression  CloseParenthesis

According to this grammar, this isn't a syntax error!  To be specific,

*

*AnObject is an Identifier, hence a SimpleNameExpression, hence a Simple Expression, hence an Expression.  (I didn't include the definition of identifiers here, but according to the documentation strings of alphabetic characters definitely qualify.)

*Consequently, (AnObject) is a ParenthesizedExpression, hence a SimpleExpression, hence an Expression, hence a MemberAccessBase.

*AField is an Identifier.

*Putting these two together, (AnObject).AField is a MemberAccessExpression, hence an Expression

*8 is a LiteralExpression, hence an Expression

*The newline at the end of the line is a StatementTerminator

*As a result, (AnObject).AField = 8 is a RegularAssignmentStatement, according to this grammar.

So, according to the document, this statement ought to parse!

A: I'm purely guessing here but I'd say that this is an artefact of VB's feature to force value over reference passing by using parentheses:
Sub ChangeMe(ByRef x As Integer)
    x += 1
End Sub

Dim x = 1
ChangeMe(x)   ' x = 2
ChangeMe((x)) ' still x = 2

In your code, the compiler probably treats (AnObject) as a value rather than a reference to the original object, determines that an assignment to a field would therefore be discarded, and disallows the assignment.
Of course even when passing AnObject to a method by value, modifying AnObject.Field would still modify the original object. So, by analogy, the code should work. I'm guessing that the VB compiler is applying a faulty heuristic here.


text:
Q: Secret-Santa: Probability of two people drawing each other. When playing Secret Santa this year, where a group of $n$ people buy presents and these $n$ presents get randomly distributed to the other people, excluding the possibility of someone getting his or her own present (we did it with a online-distributer, so this possibility really is excluded), someone in this round asked the question about the probabilty of two people giving presents to each other. Since then I've been thinking about this problem, but I didnt get very far. The only thing that comes to my mind is working with the symmetric group $S_{n}$, and considering the possibilities $S_{n}\setminus F$, with $F$ being the set of all permuations with at least one fixpoint, as this is not possible in the game of Secret Santa. The probabilty I'm interested in now can be calculated by coming up with the cardinality of the set $\{\pi \in S_{n}\setminus F\ \mid \pi $ contains at least a two-cycle$\}$. Any futher ideas?

A: Define an $r$-derangement to be a permutation whose smallest cycle has length strictly greater than $r$. Let $D_{n,r}$ denote the number of $r$-derangements in $S_n$. It is a standard result that for fixed $r$, we have that $\frac{D_{n,r}}{n!} \sim e^{-H_{r}}$ where $H_r$ is the $r$-th Harmonic number. This is proven, for instance, in Analytic Combinatorics by Flajolet and Sedgewick.
The probability that two people do not give presents to each other should thus be approximately $\frac{e^{-H_{2}}}{e^{-1}} = e^{-1/2}$.

A: The numbers of ways to distribute $n$ gifts according to the rules are OEIS A000166. The numbers of those ways where two people give gifts to each other (i.e. there is a $2$-cycle) is OEIS A158243. The probability you seek is then an entry of the first sequence divided by that of the second.
Asymptotically, as given in the formulas section of both sequences, the numerator tends to $n!(e^{-1}-e^{-3/2})$ and the denominator to $n!(e^{-1})$, leading to a limiting probability of $1-\frac1{\sqrt e}=0.393469\dots$

A: Here's a fun fact: you might know that the probability that a random permutation has no fixed points is approximately $e^{-1}$ (and approaches this value quite rapidly). This generalizes: the probability that a random permutation has no cycles of length $\le \ell$ is approximately
$$e^{-H_{\ell}} = e^{- \left( 1 + \frac{1}{2} + \dots + \frac{1}{\ell} \right)}$$
where $H_{\ell}$ is the $\ell^{th}$ harmonic number. So the probability that a random permutation has no $2$-cycles given that it has no fixed points is approximately $e^{-\frac{1}{2}}$, which means the probability you want is the complement of this, namely
$$\boxed{ 1 - e^{- \frac{1}{2} } \approx 0.393 \dots }.$$
This can be proven using a result called the permutation form of the exponential formula, which implies that for fixed $\ell$ the sequence $f(n, \ell)$ counting the number of permutations of $n$ elements with no cycles of length $\le \ell$ has exponential generating function
$$\sum_{n \ge 0} f(n, \ell) \frac{t^n}{n!} = \exp \left( \sum_{k \ge \ell+1} \frac{t^k}{k} \right) = \frac{\exp \left( - \sum_{k=1}^{\ell} \frac{t^k}{k} \right)}{1 - t}.$$
The result follows (with very good error terms) from looking at the pole at $t = 1$. You can plug this generating function into a computer algebra system like WolframAlpha to compute specific coefficients and it will tell you, for example, that when $n = 8$ there are exactly $14833$ permutations without fixed points and $8988$ permutations without cycles of length $\le 2$, so the exact probability for $n = 8$ is
$$\frac{14833 - 8988}{14833} = 0.394 \dots$$
so the above is quite a close approximation already for this small value of $n$. We have $14833 = \left[ \frac{8!}{e} \right]$ where $[x]$ denotes the closest-integer function (this is a well-known formula for the number of derangements); we might hope that $8988$ is equal to $\left[ \frac{8!}{e^{1 + \frac{1}{2}}} \right]$ but this is actually equal to $8987$. So close but not quite! Probably a very slight adjustment to this will produce an exact formula for all but possibly very small $n$.


text:
Q: Install a plugin in Bitnami Redmine I want to install a plugin in Redmine:
I unziped the plugin and copied it into the plugins directory. Then I run the command bundle install but I get the following
error:
Some gems seem to be missing from your vendor/cache directory.
Could not find json-1.8.6 in any of the sources
I did 'gem install json1.8.6' and I looked at the Gemfile.lock and the json is there, but still getting the same error.
I looked at the Extensions section in my Redmine administration but I still get the message "No data to display"
Do you have any ideas?
Thanks in advance


text:
Q: Normal Form Planes Having a hard time solving this without a perpendicular line, would appreciate help.
Find an equation in normal form $ax+by+cz=d$ for the plane P that passes through point $(1,0,-1)$ and contains the line $(x,y,z)=(1-t,t,2)$

A: Well, it must be that
$$a-c=d\;\;\;,\;\;\;a(1-t)+bt+2c=d\,\,\,\,\,\forall\,t\in\Bbb R$$
So taking succesively the values $\,t=0\,,\,t=1\,,\,t=-1\,$ , we get the linear system:
$$a-c=d$$
$$a+b+3c=d$$
$$b+2c=d$$
$$-2a-b+2c=d$$
Substracting eq. 3 from 2 we get: $\,a+c=0\Longleftrightarrow a=-c\,$ , and together with eq. 1 we get $\,2a=d\,$...and etc.

A: First, we want to find 3 points in the plane.  One, $(1, 0, -1)$, is given in the question.  Two more can be found by plugging in arbitraty values for t:
$$t = 0 \Rightarrow (1, 0, 2)$$
$$t = 1 \Rightarrow (0, 1, 2)$$
Using these 3 points, we can find 2 vectors in the plane:
$$(1,0,-1) - (1,0,2) = \langle0,0,-3\rangle$$
$$(1, 0, -1) - (0, 1, 2) = \langle1, -1, -3\rangle$$
Now we take the cross product of <0, 0, -3> and <1, -1, -3> to find the normal vector to the plane, <-3, -3, 0>.
We now have an equation for a plane, $-3x -3y = c$, which is parallel to the desired plane.  Finally, plug in a point on the plane to solve for c:
$$-3*1 -3*0 = -3$$
Our final equation for the plane is:
$$-3x-3y=-3$$ which is equal to: $$-x-y=-1$$


text:
Q: how do I hide curl arguments from command line? I have a cronjob that runs this command:
curl -s -G -H Authorization: Bearer ${mysecret} ${myurl}

I'm a ding dong--I just realized everyone can see my password when they issue a "ps -ef | grep curl". I tried using the -d option, but was unsuccessful. Do you know how I can hide the value for $mysecret?

A: See curl - Read headers from file. You've got two options.

*

*For new versions (7.55 and newer) of curl:
curl -H @filename ${myurl}
Where filename holds header and the secrets: Authorization: Bearer mysecret

*For older versions create a config file:
curl -K filename ${myurl}
Where filename holds the option: -H "Authorization: Bearer mysecret"


text:
Q: How to make pandas groupby not lazy? It is mentioned in this tutorial that pandas groupby object is lazy.

it's lazy in nature. It doesn't really do any operations to produce a
  useful result until you say so.

and

It's also worth mentioning that .groupby() does do some, but not all,
  of the splitting work by building a Grouping class instance for each
  key that you pass. However, many of the methods of the BaseGrouper
  class that holds these groupings are called lazily rather than at
  init(), and many also use a cached property design.

So I made some tests to make sure that groupby is really lazy.
Let
df=pd.DataFrame(np.random.randint(1,10,size=(1000000,4)))

then
%timeit gg=df.groupby(1)
35.6 µs ± 110 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

which almost takes no time. And
%timeit res=gg.get_group(1)
2.76 ms ± 8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

timing is much longer and is just slightly faster than
%timeit res=df[df[1]==1]
6.87 ms ± 16.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

On the other hand, if we extract groups at first
%timeit gdict=df.groupby(1).groups
15.7 ms ± 35.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

then get group takes no time
%timeit gdict[1]
29.8 ns ± 0.0989 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

So my question is

*

*why pandas designs groupby as lazy? In real application, I think I almost always  need to do many further operations on group object. If group object is lazy in splitting the dataframe at first, then a waste of time happens every time when done some operation like get_group etc.

*I also don't understand " .groupby() does do some, but not all,of the splitting work by building a Grouping class instance for each key that you pass", what does it mean?

*Is it possible to make groupby object not lazy?

A: You need a bigger bechmark:
import numpy as np, pandas as pd
df=pd.DataFrame(np.random.randint(1,10,size=(100000000,4))) #3GB data
gg=df.groupby(1)
%time _ = gg.get_group(1) #first call slow
%time _ = gg.get_group(1) #fast
%time _ = gg.get_group(2) #other group lookup is also fast
%timeit _ = gg.get_group(1) #gives wrong result

Groupby is lazy in that it doesn't calculate groups right away. It does so on the first request to them. Or when you use IPython and hit tab with gg under the cursor. It can be seen if you track memory consumption of the process. Or you can feel it in the IPython case.
It is difficult to guess what goes on under the hood but get_group seem to have its own cache, while groups and methods like sum or min have shared one. Probably attempts to minimize memory usage for distinct use cases. Anyway, after the first usage the laziness is gone.
The final test is wrong. gg.groups contains indexex, not groups themselves:
%timeit df.loc[gdict[1]]  #It is actually the slowest
1.23 s ± 26.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit df[df[1]==1]
928 ms ± 23.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit gg.get_group(1)
510 ms ± 30.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Retrieving items from the dictionary is indeed thousands times faster, however you would be trading space for speed.
If you're absolutely sure you need to run functions on the same group more than once, you can try sorting the dataframe on the column and saving the group slices.
%time df = df.sort_values(1,ignore_index=True)
#Wall time: 10.3 s
%time ids = df[1].diff().to_numpy().nonzero()[0]
#Wall time: 1.88 s
%time gl = {df[1][v] : slice(v,ids[i+1] if (i+1)<len(ids) else None) for i,v in enumerate(ids)}
#Wall time: 112 µs
%timeit df[gl[1]]
#12.1 µs ± 208 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Sorted data may be fastest for some use cases.
%timeit {k:df[v].sum() for k,v in gl.items()}
1.16 s ± 42.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit gg.sum()
2.73 s ± 29.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit {x: gg.get_group(x).sum() for x in range(1,10)}
4.23 s ± 61.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


text:
Q: Clarification in template declaration, alias and specialization in regards to custom allocators and stl Sorry for the vague title, but I don't know exactly which is the correct term (and even if it's possible to do the following).
Let's say I have somewhere a template class (an allocator):
template<class Arena, typename T> Allocator
{
  public:
     Allocator(Arena a);
...
};

Then I have another class, which is in some kind of relation with Allocator, but can't specialize T param in instantiation.
The idea is declare a "not specialized alias" for it, and let the specialization be somewhere else.
Something like:
class MemoryArena
{
   using Allocator<T> = AnAllocatorStrategy<T>; //not legal, but just to give the idea

   void* Allocate(size_t);
};

The usage should be something like:
Arena anArena(...);
Arena::Allocator<int> allocInt; // some way declare a specialization of the alias

std::vector<int, Arena::Allocator<int>> myVec(allocInt);

The main idea behind that, is that because of stl container need a specialized allocator on the contained element's type, I can still use the same memory arena and let the specialized instances to forward the allocate call to it.
But I still would like that is the Arena itself controlling the base allocation strategy (eventually also parametrazing the not completely specialized AllocatorStrategy ).
Any hint on this? Is this possible?

EDIT
Thanks to the comment I fixed the declaration using alias templates this way:
class MemoryArena
{
   template<typename T> using MyAllocatorTemplate = Allocator<MemoryArena, T>;;

  void* Allocate(size_t);
};

I still need to figure out if it's possible make Allocator be part of MemoryArena definition, without fully specify T parameter. Something like:
template<class AllocatorType<MemoryArena,?> = DefaultAllocType<MemoryArena,?>> //is possible not to specify T on MemoryArena definition?
class MemoryArena<AllocatorType>
{
   template<typename T> using MyAllocatorTemplate = AllocatorType<MemoryArena,T>;

Alternatively, any other suggestion is appreciated. The main goal is to let the user specify the Arena's allocator type except for the T parameter (useful only for using the allocator inside containers).

A: template<template<class...>class Z, class...T0s>
struct partial_apply {
  template<class...T1s>
  using result = Z<T0s...,T1s...>;
};
template<template<class...>class A, template<class...>class B>
struct same_template : std::false_type {};
template<template<class...>class A>
struct same_template<A,A> : std::true_type {};

template<class...>class Default {};
template<
  template<class...>class AllocatorType=Default
>
class MemoryArena {
  template<class T>
  using MyAllocatorTemplate = std::conditional_t<
    same_template<AllocatorType, Default>{},
    DefaultAllocType<MemoryArena, T>,
    AllocatorType<T>
  >;
};

suppose there is some other alloc type besides DefaultAllocType, OtherAllocType<Chicken, T>.  Then:
template<class...Ts>
using OtherAllocChicken = partial_apply<OtherAllocType, Chicken>::template result<Ts...>;
using ChickenArena = MemoryArena< OtherAllocChicken >;

on the other hand, if you require that the argument passed to the incoming template be MemoryArena itself sometimes, things get more complex.
Before MemoryArena is parameterized, the type doesn't exist.  So you have to have some kind of placeholder that can tell you where you should inject it.
If you want it to always be MemoryArena, then things are easier: you already have that solution:
template<template<class...>class AllocatorType = DefaultAllocType>
class MemoryArena {
  template<typename T>
  using MyAllocatorTemplate = AllocatorType<MemoryArena,T>;
};


text:
Q: Bundle and run JavaScript module in the browser I want to run a JavaScript module with external dependencies in the browser. Is that possible? I know that Babel can be executed in the browser, so that should be possible.
Let's say that I have a following module:
const module = `
    import React from "react";
    import ReactDOM from "react-dom";

    ReactDOM.render(
Hello, world!
, document.body);
`

Now, how to "compile" it so that it can be executed in the browser? Also, the tricky part is that I want to preserve versions, so let's say that I want to use version 16 of React and ReactDOM.


text:
Q: Is there a NSNotificationCenter Notification for WiFi network changes? I'd like to subscribe to WiFi network changes in my Cocoa application, but I haven't been able to find an appropriate event to subscribe to.
Is there an NSNotificationCenter Notification for WiFi network changes?

A: Not to my knowledge. I would use CoreWLAN to get a list of all WiFi interfaces on the system, and then monitor their status using the SystemConfiguration framework.
Here's a command-line example (error checking niceties elided, ARC required):
#import <Foundation/Foundation.h>
#import <CoreWLAN/CoreWLAN.h>
#import <SystemConfiguration/SystemConfiguration.h>

void wifi_network_changed(SCDynamicStoreRef store, CFArrayRef changedKeys, void *ctx)
{
  [(__bridge NSArray *)changedKeys enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
  {
    /* Extract the interface name from the changed key */
    NSString *ifName = [key componentsSeparatedByString:@"/"][3];
    CWInterface *iface = [CWInterface interfaceWithName:ifName];

    NSLog(@"%@ status changed: current ssid is %@, security is %ld",
          ifName, iface.ssid, iface.security);
  }];
}

int main(int argc, char *argv[])
{
  /* Get a list of all wifi interfaces, and build an array of SCDynamicStore keys to monitor */
  NSSet *wifiInterfaces = [CWInterface interfaceNames];
  NSMutableArray *scKeys = [[NSMutableArray alloc] init];
  [wifiInterfaces enumerateObjectsUsingBlock:^(NSString *ifName, BOOL *stop)
  {
    [scKeys addObject:
      [NSString stringWithFormat:@"State:/Network/Interface/%@/AirPort", ifName]];
  }];

  /* Connect to the dynamic store */
  SCDynamicStoreContext ctx = { 0, NULL, NULL, NULL, NULL };
  SCDynamicStoreRef store = SCDynamicStoreCreate(kCFAllocatorDefault,
                                                 CFSTR("myapp"),
                                                 wifi_network_changed,
                                                 &ctx);

  /* Start monitoring */
  SCDynamicStoreSetNotificationKeys(store,
                                    (__bridge CFArrayRef)scKeys,
                                    NULL);

  CFRunLoopSourceRef src = SCDynamicStoreCreateRunLoopSource(kCFAllocatorDefault, store, 0);
  CFRunLoopAddSource([[NSRunLoop currentRunLoop] getCFRunLoop],
                     src,
                     kCFRunLoopCommonModes);
  [[NSRunLoop currentRunLoop] run];
}

A: As long as you are holding open a CWInterface, you can use the CWLinkDidChangeNotification et al notifications.  In the following code, i_interfaces is an ivar which stores an array of CWInterface, monitorWifi should be called at the start, listInterfaces lists the interface values, and handleInterfaceNotification is called whenever anything changes.
Note that iface.ssid / iface.bssid will be nil when the interface is not connected.
Also note that handleInterfaceNotification will be called multiple times for each connect/disconnect due to the various notifications.
This code comes largely from NSNotification troubles
-(void) listInterfaces;
{
    NSLog(@"listInterfaces");
    [i_interfaces enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
     {
         CWInterface *iface = obj;
         NSLog( @"iface %@, SSID %@, BSSID %@", iface, iface.ssid, iface.bssid );
     }];
}

-(void) handleInterfaceNotification:(NSNotification*) notification;
{
    NSLog(@"Notification Received");
    [self listInterfaces];
}

- (void) monitorWifi;
{
    NSLog(@"monitorWifi");

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterfaceNotification:) name:CWModeDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterfaceNotification:) name:CWSSIDDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterfaceNotification:) name:CWBSSIDDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterfaceNotification:) name:CWCountryCodeDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterfaceNotification:) name:CWLinkDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterfaceNotification:) name:CWPowerDidChangeNotification object:nil];

    NSMutableArray* ifaces = [NSMutableArray new];
    NSSet *wifiInterfaces = [CWInterface interfaceNames];
    [wifiInterfaces enumerateObjectsUsingBlock:^(NSString *ifName, BOOL *stop)
     {
         CWInterface *iface = [CWInterface interfaceWithName:ifName];
         if ( iface ) {
             [ifaces addObject:iface];
         }
     }];
    i_interfaces = ifaces;

    [self listInterfaces];
}

A: Highly appreciated. I needed to do this from Swift so here is a bit of Swift code to get you started:
func callback(store: SCDynamicStore, changedKeys: CFArray,
              context: UnsafeMutableRawPointer?) -> Void {
    // Do the magic
}

// Connect to the store
guard let store = SCDynamicStoreCreate(nil, "myapp" as CFString, callback, nil) else {
    print("Could not connect to store")
    abort()
}

// Setup the notification mechanism for any IPv4 event
var keys = [CFString]()
keys.append("State:/Network/Global/IPv4" as CFString)
SCDynamicStoreSetNotificationKeys(store, keys as CFArray, nil)

// Go into the loop
let runloop = SCDynamicStoreCreateRunLoopSource(nil, store, 0)
let currentLoop = RunLoop.current.getCFRunLoop()
let modes = CFRunLoopMode.commonModes
CFRunLoopAddSource(currentLoop, runloop, modes)
RunLoop.current.run()


text:
Q: Use ARM template to create custom github "workflow action" yaml file Normally there are questions and tutorials about using github "workflow action" yml files for deploying ARM templates.  I need the opposite capability.  For example, if I create an Azure App Service (or Azure static website) using an ARM template, a "workflow action" file will be auto-generated and added to the github repo that I referenced within the ARM template.
That "reverse" behavior is fine, but I want to have some control over the workflow yml file that the ARM template is implicitly creating or using.  This is because I am building an Azure "Managed App" (which will eventually become an Azure Marketplace offering)...which requires the entire build/deploy be handled from an ARM template(s). Furthermore, I need the auto-generated "workflow" yml file to be customized to include an Entity Framework (EF) data migration.
In short, when deploying an Azure App Service from an ARM template, how can I influence the auto-generated github workflow actions to incorporate EF database migrations?
The option to simply modify the github workflow activity after it is created, isn't what I'm lookin for.


text:
Q: Wild card, adding to a list throws UnsupportedOperationException public static void wildCard2(List<? super Base> lst){
    for (int i=0; i<2; i++){
        System.out.println(lst.get(i));
    }
    lst.add(new Base());

}

As shown in the  code above, I have a class called Base.
Can anyone explain why this fails at RunTime and throws UnsupportedOperationException ?

A: The add(E e) method defined on the List<E> interface is specified as an optional operation.
If you're getting an UnsupportedOperationException at runtime, this means that the List implementation that you're using does not support this operation.
It might be an unmodifiable type created by calling Collections.unmodifiableList(), an instance of a Guava ImmutableList, or something else entirely. Check the runtime type to find out:
System.out.println(lst.getClass().getName());

A: You cannot .add() from such a List, you can create a copy of the list to a known-modifiable implementation like ArrayList.


text:
Q: Which Class Lib for ASP.NET Core tag helpers when .Net Core Web App targets Full .Net Framework? I have created a Asp.Net Core Web Application that targets the full .Net Framework. This was accomplished by using the Visual Studio ASP.NET Core Web Application (.NET Framework) template.
I'd like to create some tag helpers that I use in this Web Application and I'd like to place them in a library dll.  Initially I tried adding a new project to my solution of type  Class Library (.NET Core) to place them in but I was unable to reference that library from the web project.  When I tried to reference it via Visual Studio I received a dialog that said the project reference was not supported because the Class Library has a target framework that is incompatible with the targets in my Website Project.
So as an alternative, I added a regular Class Library project to the solution via the Visual Studio Class Library template.  I am able to add a reference from my Web Project to this class library successfully.  However, in this Class Library project I can't find a way to reference Microsoft.AspNetCore.Razor.Runtime which is necessary if I'm going to be able to put my tag helpers in the library.
So I'm at a dead end with both approaches.  How can I put my ASP.NET Core tag helpers in a class library that I can reference from my ASP.NET Web Project that targets the full .net framework?

A:
When I tried to reference it via Visual Studio I received a dialog that said the project reference was not supported because the Class Library has a target framework that is incompatible with the targets in my Website Project.

This usually means you both libraries target different things, i.e. if your Class library targets netstandard1.6 and your web application targets net452 its not going to work.
Either your web application needs to target netcoreapp1.0 or your class library has to target netstandard1.0. Use the .NET Standard Library matrix here to see which netstandard1.x moniker supports which platform.
So if your web application targets net452, you have to target netstandard1.0, netstandard1.1 or netstandard1.2. netstandard1.3 and higher don't work, because it requires .NET Framework 4.6.
If you use a library which requires netstandard1.3 or higher, you have to target multiple platforms. i.e. net452 and netstandard1.3.
Then net452 will be used in projects which target net452 and netstandard1.3 will be used in netcoreapp1.0 applications or other class libraries which target netstandard.


text:
Q: fstab defaults not working as expected I want to mount a partition to /media/files so that every user can read, write and execute in it. I first tried:
UUID=6c95b3f6-90a5-4092-b30f-7a41210595f4   /media/files    ext4          defaults       0       2

which did not solve it.
I now have tried:
UUID=6c95b3f6-90a5-4092-b30f-7a41210595f4   /media/files    ext4          exec,rw,user       0       2

Without any success either. What should I do? As a sidenote, I want Steam to create a library folder in there.

Update
I now have also chmod-ed the folder /media/files to a+rwx which allows Steam to create a folder /media/files/SteamLibrary. However, it complains that the partition was without execution permissions.
iamuser@desktop:/media$ ls -l
drwxrwxrwx  4 root root 4096 May 21 19:32 files

iamuser@desktop:/media/files$ ls -l
drwx------ 2 root    root    16384 Mai 21 18:58 lost+found
drwxrwxrwx 3 iamuser iamuser  4096 Mai 21 19:39 SteamLibrary

Still using the aforementioned fstab options exec,rw,user

A: Ok... I got this now. What I did with chmod was good, what I did before in fstab was the issue. Now defaults in fstab solves the problem.
So, as a reminder for anybody struggeling:
chmod a+rwx /media/files

will do the trick!
If anybody as something to add about the rigorous permissions, I am happy to hear.

A: The mount option user resets some other options. From man 8 mount:
user   Allow an ordinary user to mount the filesystem.  The name of the
       mounting  user  is  written  to  mtab so that he can unmount the
       filesystem again.   This  option  implies  the  options  noexec,
       nosuid,  and  nodev (unless overridden by subsequent options, as
       in the option line user,exec,dev,suid).
…

users  Allow  every  user  to  mount  and unmount the filesystem.  This
       option implies the options noexec,  nosuid,  and  nodev  (unless
       overridden   by  subsequent  options,  as  in  the  option  line
       users,exec,dev,suid).
So, you need to specify exec after user:
UUID=6c95b3f6-90a5-4092-b30f-7a41210595f4   /media/files    ext4          rw,user,exec       0       2

If you want every user to be able to read, write and execute, that's not a job for ext4 mount options, but for permissions, as you have applied them using chmod.
As a side note, you might have been better off chowning /media/files to your user, instead of giving everybody rwx, or using the user mount option, and set rwx only for you:
sudo chown iamuser:iamuser /media/files
sudo chmod a=rX,u+w /media/files

That should let Steam (running as your user) create files in the disk.


text:
Q: Does gravity do work on suspended objects? A block is suspended from a string; does the gravitational force do any work on it?

A: Work is performed when the point of application of a force travels through a distance in the direction of the force.
An object suspended by a string in a gravitational field experiences the force of gravity but if it does not move, then no work is being done on it.

A: No, if the block is still, there is no work being done on it. There is a force on it, yes, but no work. Work is really a function of a period of time i.e. in 1 second, it did 1 Joule of work. It does not make sense to ask the value of such a quantity for any given moment.


text:
Q: Slow Boot time apt-daily-upgrade.service and apt-daily.service on Xubuntu 18.04 - ASUS K70IO laptop I'm on Xubuntu 18.04, yet recently my

old laptop is very slow to boot

.
I've been hunting on the internet but I am unable to find any solution.
Please help,
ASUS K70IO
NVIDIA GeForce GT 120M
320GB scsi HDD
Intel(R) Core(TM)2 Duo CPU     T5900  @ 2.20GHz
2 x 2GiB DIMM SDRAM Synchronous 2048 MHz (0,5 ns)

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.1 LTS
Release:    18.04
Codename:   bionic

$ systemd-analyze blame
1min 48.606s apt-daily-upgrade.service
     48.437s apt-daily.service
     11.508s dev-sda6.device
      8.186s networkd-dispatcher.service
      8.082s keyboard-setup.service
      6.290s NetworkManager.service
      5.793s grub-common.service
      5.128s udisks2.service
      4.815s snapd.service
      4.327s accounts-daemon.service
      4.175s apparmor.service
      4.040s wpa_supplicant.service
      3.674s thermald.service
      3.411s avahi-daemon.service
      3.376s pppd-dns.service
      3.374s gpu-manager.service
      3.373s rsyslog.service
      2.491s colord.service
      2.136s systemd-udevd.service
      2.105s systemd-journal-flush.service
      1.413s systemd-logind.service
      1.398s systemd-tmpfiles-setup-dev.service
      1.354s apport.service

$ systemd-analyze critical-chain
The time after the unit is active or started is printed after the "@" character.
The time the unit takes to start is printed after the "+" character.
graphical.target @27.327s
└─multi-user.target @27.327s
└─getty.target @27.327s
└─getty@tty1.service @27.327s
  └─system-getty.slice @27.325s
    └─setvtrgb.service @26.730s +594ms
      └─systemd-user-sessions.service @24.850s +661ms
        └─network.target @24.770s
          └─NetworkManager.service @18.479s +6.290s
            └─dbus.service @15.872s
              └─basic.target @15.858s
                └─sockets.target @15.858s
                  └─snapd.socket @15.838s +19ms
                    └─sysinit.target @15.781s
                      └─apparmor.service @11.605s +4.175s
                        └─local-fs.target @11.598s
                          └─local-fs-pre.target @11.598s
                            └─keyboard-setup.service @3.516s +8.082s
                              └─systemd-journald.socket @3.463s
                                └─system.slice @3.462s

$ sudo lshw -short
ASUS                        system      K70IO (To Be Filled By O.E.M.)
/0                          bus         K70IO
/0/0                        memory      64KiB BIOS
/0/4                        processor   Intel(R) Core(TM)2 Duo CPU     T5900  @ 2.20GHz
/0/4/5                      memory      64KiB L1 cache
/0/4/6                      memory      2MiB L2 cache
/0/1f                       memory      4GiB System Memory
/0/1f/0                     memory      2GiB DIMM SDRAM Synchronous 2048 MHz (0,5 ns)
/0/1f/1                     memory      2GiB DIMM SDRAM Synchronous 2048 MHz (0,5 ns)
/0/1/0.0.0      /dev/sda    disk        320GB ST9320423AS
/0/1/0.0.0/1    /dev/sda1   volume      100MiB Windows NTFS volume
/0/1/0.0.0/2    /dev/sda2   volume      140GiB Windows NTFS volume
/0/1/0.0.0/3    /dev/sda3   volume      832MiB Windows NTFS volume
/0/1/0.0.0/4    /dev/sda4   volume      156GiB Extended partition
/0/1/0.0.0/4/5  /dev/sda5   volume      20GiB Windows FAT volume
/0/1/0.0.0/4/6  /dev/sda6   volume      129GiB EXT4 volume
/0/1/0.0.0/4/7  /dev/sda7   volume      7812MiB Linux swap volume


text:
Q: How to get all the records whose updated date is less than 30 days in php I want to get all the records from mysql database who have updated their records within 30 days from the current date for that i have used the below query but it is not working properly. $tda is the current date and $prevmonth is the date of exactly
30 days back from the current date. Please help. Thanks.
$da=date('d');
$tda=date('d-m-Y');
$prevmonth = date(''.$da.'-m-Y', strtotime('-1 months'));
$sql_q=executeQuery("select * from ".reg." where 'uid' !=".$_SESSION['uid']." AND Updatedate >= '$prevmonth' AND  Updatedate <='$tda '");

A: I like doing something like this: AND UpdateDate > NOW() - INTERVAL 30 DAY AND UpdateDate < NOW().

A: You can do it in mysql as
`Updatedate` <  DATE(NOW() - INTERVAL 30 DAY)

OR
`Updatedate` <  DATE_SUB(CURDATE(), INTERVAL 30 DAY)

For Varchar
 STR_TO_DATE(Updatedate, '%Y-%m-%d') <  DATE_SUB(CURDATE(), INTERVAL 30 DAY)

UPDATE :
The query posted in the comment is wrong and should be
$sql_q=executeQuery("select * from registration
where
`uid` != ".$_SESSION['uid']."
AND STR_TO_DATE(Update_date, '%d-%m-%Y') < DATE_SUB(CURDATE(), INTERVAL 30 DAY)") ;

If you are looking for data within last 30 days then
$sql_q=executeQuery("select * from registration
where
`uid` != ".$_SESSION['uid']."
AND STR_TO_DATE(Update_date, '%d-%m-%Y') >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)") ;

A: If your Updatedate column is a DATETIME column then you can do the following:

SELECT *
FROM table
WHERE uid <> ?
AND Updatedate >= DATE_SUB(NOW(), INTERVAL 1 MONTH)
AND Updatedate <= NOW();

Or:
SELECT *
FROM table
WHERE uid <> ?
AND Updatedate BETWEEN DATE_SUB(NOW(), INTERVAL 1 MONTH) AND NOW();

Or if it's a timestamp then this:
SELECT *
FROM table
WHERE uid <> ?
AND FROM_UNIXTIME(Updatedate) >= DATE_SUB(NOW(), INTERVAL 1 MONTH)
AND FROM_UNIXTIME(Updatedate) <= NOW();


text:
Q: Allow access to a page for admins only I need to know how to make a page template in WordPress that can only be accessed by admins. How could I apply it to the following template?
<?php /*
Template Name: Agency Area
*/
?>
<?php get_header(); ?>

        <?php wp_nav_menu(); ?>

<?php get_footer(); ?>

I'd prefer to do it without plugins.

A: <?php
/*
Template Name: Agency Area
*/
get_header();

echo '
';

    global $current_user;

    if( in_array( 'administrator', $current_user->roles ) ) {
        echo '
';
            wp_nav_menu();
        echo '
';
    } else {
        // echo '
You do not have the rights required to view this page. Sorry.
';
        /* or with internationalization
           (uncomment either, adjust text domain if applicable) */
        echo '
' .
            __(
                'You do not have the rights required to view this page. Sorry.',
                'theme-text-domain'
            ) .
            '
';
    }

echo '
';

get_footer();
?>


text:
Q: polynomial multiplication using fastfourier transform I am going through the above topic from CLRS(CORMEN) (page 834) and I got stuck at this point.
Can anybody please explain how the following expression,
A(x)=A^{[0]}(x^2) +xA^{[1]}(x^2)

follows from,
n-1                       `
 Σ  a_j x^j
j=0

Where,
A^{[0]} = a_0 + a_2x + a_4a^x ... a_{n-2}x^{\frac{n}{2-1}}
A^{[1]} = a_1 + a_3x + a_5a^x ... a_{n-1}x^{\frac{n}{2-1}}

A: The polynomial A(x) is defined as
A(x) = a_0 + a_1 x + a_2 x^2 + a_3 x^3 + ...

To start the divide-and-conquer strategy of polynomial multiplication by the FFT, CLRS introduces two new polynomials: one of the coefficients of the even-powers of x called A[0] and one of the coefficients of the odd-powers of x called A[1]
A[0](x) = a_0 + a_2 x + a_4 x^2 + ...
A[1](x) = a_1 + a_3 x + a_5 x^2 + ...

Now if we substitute x^2 into A[0] and A[1], we have
A[0](x^2) = a_0 + a_2 x^2 + a_4 x^4 + ...
A[1](x^2) = a_1 + a_3 x^2 + a_5 x^4 + ...

and if we multiply A[1](x^2) by x, we have
x A[1](x^2) = a_1 x + a_3 x^3 + a_5 x^5 + ...

Now if we add A[0](x^2) and x A[1](x^2), we have
A[0](x^2) + x A[1](x^2) = (a_0 + a_2 x^2 + a_4 x^4 + ...) + (a_1 x + a_3 x^3 + a_5 x^5 + ...)
                        = a_0 + a_1 x + a_2 x^2 + a_3 x^3 + ...
                        = A(x)

Q.E.D.

A: If you divvy the polynomial up into "odd exponents" and "even exponents", you'll find the annoying fact that the A[1] polynomial (the one with odd exponents) has, well odd exponents! Even exponents are easier to work with, for FFT. So, one can simply factor out a single "x" from all of the values in A[1], and move it outside of the expression.
FFT likes working with even-exponented polynomials only. Thus, when you're dividing-and-conquering, you want to turn your A[1] expression into an "even-exponented" polynomial, and recurse on that, and then multiply-back-in that x. You will see that occur in the inner loop of the actual algorithm.
Edit: I realize that your confusion may stem from the fact that they're "passing in" (x^2) as the value in the polynomial. The "x" in A[1] and A[0] are different from the x in the (x^2) expression. You'll see how that must be, as while the original polynomial A goes up to exponent N, A[1] and A[0] both only go up to exponent (N/2).

A: I'm not going to answer your question because I feel that previous people have answered it. What I will do is try to explain the purpose of the FFT.
First, the FFT is a way to compute the convolution between two vectors. That is, suppose x = and y= are 1xn vectors then the convolution of x and y is
\sum_{i=0} ^n {xi y{n-i}}.
You will have to accept the fact that computing that value is EXTREMELY useful in a wide range of applications.
Now consider the following.
Suppose we construct two polynomials
A(z) = x0 + x1*z + x2 *z^2 + .. + xn^z^n
B(z) = y0 + y1*z + y2 *z^2 + .. + yn^z^n
then the multiplication is
AB(z) = A(z)B(z) = \sum_{i=0} ^ n (\sum_{k=0} ^ i xk*y{i-k}) z^i
where the inside sum is clearly a convolution of different size for different values of k.
Now we can clearly compute the coefficients (convolutions) of AB in n^2 time by a brute force method.
However, we can also be much more clever. Consider the fact that any polynomial of degree n can be described uniquely by n+1 points. That is given n+1 points we can construct the unique polynomial of degree n that goes through all n+1 points. Further more consider 2 polynomials in the form of n+1 points. You can compute their product by simply multiplying the n+1 y-values and keeping the x-values to result in their product in point-form. Now given a polynomial in n+1 point-form you can find the unique polynomial that describes it in O(n) time (actually Im not sure about this, it may be O(nlogn) time but certainly not more.)
This is exactly what the FFT does. However, the points that it picks to get the n+1 points to described the polynomials A and B are VERY carefully chosen. Some of the points are indeed complex because it just so happens that you can save time in evaluating a Polynomial by considering such points. That is if you were to choose just real points instead of the carefully chosen points that the FFT uses you would need O(n^2) time to evaluate the n+1 points. If you choose the FFT you only need O(nlogn) time. And thats all there is to the FFT. Oh and there is a unique side effect to the way that the FFT chooses points. Given an n-th degree polynomial, you must choose 2^m points where m is chosen such that 2^m is the smallest power of 2 greater than or equal to n.

A:
A(x) is broken in to even x^2, and odd x parts,

for example if A(x) = 21 x^5 + 17 x^4 + 33 x^3 + 4 x^2 + 8 x + 7

then A0 = 17 y^2 + 4 y + 7
     so that A0(x^2) = 17 x^4 + 4 x^2 + 7

and  A1 = 21 y^2 + 33 y + 8
     so that A1(x^2) = 21 x^4 + 33 x^2 + 8
     or  x * A1(x^2) = 21 x^5 + 33 x^3 + 8 x

clearly, in this case, A(x) = A0(x^2) + x A1(x^2) = even + odd parts


text:
Q: Woocommerce redirection gives me an critical error I have found this code that after adding an item to cart, if the customer isn't logged in they are redirected to a login page. At the moment I am getting an error, I think I haven't edited the code properly.
function wpse_131562_redirect() {
    if (
        ! is_user_logged_in()
        && (is_cart() || is_checkout())
    ) {
        // feel free to customize the following line to suit your needs
        wp_redirect('myshop.co.uk/sign-in'());
        exit;
    }
}
add_action('template_redirect', 'wpse_131562_redirect');

A: Yes, the function wp_redirect is wrong.
wp_redirect( 'https://myshop.co.uk/sign-in' ); should do the job

A: Without https:// it is giving error. you should use home url dynamic try the following code
wp_redirect(get_home_url().'/sign-in');


text:
Q: Angular routing in Spring Boot web application I'm developing some project using angular and spring boot and I have some confussing situation:
I have Spring Controller to share view file names with my application
@Controller
public class OfferViewController {

    @RequestMapping(value = "/addOffer", method = RequestMethod.GET)
    public String addView() {
        return "html/offer/addOffer";
    }

    @RequestMapping(value = "/showOffer/{offerId}")
    public String showOffer(@PathVariable("offerId") String offerId){
        return "html/offer/showOffer";
    }
}

And I have some other controller to handle REST calls:
@RestController
public class OfferRestController {

    private OfferRepository offerRepository;

    @Autowired
    public OfferRestController(OfferRepository offerRepository) {
        this.offerRepository = offerRepository;
    }

    @RequestMapping(value = "/showOfferJson/{offerId}", method = GET, produces = APPLICATION_JSON_VALUE)
    public Offer showOffertest(@PathVariable("offerId") String offerId) {
        Offer offer = offerRepository.findOne(offerId);
        return offer;
    }

    @RequestMapping(value = "/saveOffer", method = POST)
    public ResponseEntity<Offer> saveOffer(@RequestBody Offer offer) {
        Offer offerSaved = offerRepository.save(offer);
        return new ResponseEntity<Offer>(offerSaved, HttpStatus.OK);
    }
}

I use angular for develope my UI.
I find myself confused when I start to read about routing possibilities in angular (single page application stuff) so as I assume i dont need OfferViewController any more.
My question are:

*

*Should I have an single index.html page to manage all ng-routes?
For example ngRoute first to addOffer.html second to contact.html etc.?

*Do I still need Controller to provide my starting page with all ngRout'ings?

*Mby I'm wrong so please give me an advice how to do ngRouting right.
Thank You for any help!

A: Lets start with: What is a single page application?
A single page application is a page consisting on one single HTML-page. So there is only one HTML-File requested from your backend and the rest of the routing should be managed of the frontend.
For more detailed exaplanation of a single page application I am sure there is a lot of information in the web about that.
How does routing with AngularJS work?
Angular pathes to go to different routes are after the '#'. So they are in the fragment part of the url and this part is not transfered to the server. So there is no need to have a @Controller in the backend to serve different html.
To show different content depending on the current route you can specify controller and partial.html files which should be shown at the required route.
phonecatApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
  when('/phones', {
    templateUrl: 'partials/phone-list.html',
    controller: 'PhoneListCtrl'
  }).
  when('/phones/:phoneId', {
    templateUrl: 'partials/phone-detail.html',
    controller: 'PhoneDetailCtrl'
  }).
  otherwise({
    redirectTo: '/phones'
  });
}]);

this code example is right out of the AngularJS Tutorial - Routing Part. It shows how to specify a route and which content should be shown at this route.
This code snippet tells angular to include the partial HTML-File into every Element which uses the ng-view directive.
so your index.html could look like this (again copied out of the docs)
<!doctype html>
<html lang="en" ng-app="phonecatApp">
<head>
  <script src="bower_components/angular/angular.js"></script>
  <script src="bower_components/angular-route/angular-route.js"></script>
  <script src="js/app.js"></script>
  <script src="js/controllers.js"></script>
</head>
<body>

  <div ng-view></div>

</body>
</html>

if you visit yourdomain.com/#/phones now it loads your index.html and angular includes the html contained in the file "/partials/phone-list.html" into the div which uses the ng-view-directive
What is REST?
I think no one knows the EXACT answer to this question but what you do is definitly NOT REST. It's simply HTTP calls. Your endpoint looks like RPC.
A first step could be to use an endpoint /offers/{id} which accepts a GET-Request and an endpoint /offers which accepts a POST-Request. If you want to provide a way to expose all of your offers at once add an endpoint /offers which accepts a GET-Request.


text:
Q: How to convert octal decimal to decimal? I am trying to get user from database using spring boot REST controller.
I am passing the id as a request parameter. If i pass a value 0004 it treats it as 4 and the tests pass.
However if I pass a value as 0030 it treats as 24.
ControllerTest.java
@Test
public void get_user_by_id_should_return_user_with_id_0030() throws Exception {
    User user = new User(0030, "sample@example.com", LocalDate.parse("2018-12-27"), "Kitchen Assistant", Role.user);
    when(userServiceMock.searchByemployeeId(0030)).thenReturn(user);

    MockHttpServletRequestBuilder getUserByEmployeeId = get("/admin/user?employeeId=0030");
    getUserByEmployeeId.header("Authorization", "Bearer " + adminJwtToken);
    JSONObject expectedResponse = new JSONObject();
    expectedResponse.put("employeeId", 0030);
    expectedResponse.put("companyEmailId", "sample@example.com");
    expectedResponse.put("dateOfJoining", "2018-12-27");
    expectedResponse.put("designation", "Kitchen Assistant");
    expectedResponse.put("role", "user");

    mockMvc.perform(getUserByEmployeeId).andExpect(status().isOk());
    verify(userServiceMock, times(1)).searchByemployeeId(0030);
}

Controller.java
  @GetMapping(path = "/admin/user",params = "employeeId")
    public ResponseEntity<User> getUserWithEmploeeId(@RequestParam Integer employeeId) {
        User user = userService.searchByemployeeId(employeeId);
        return new ResponseEntity<>(user, OK);
    }

However, passing 0030 as a parameter does not treat as 30. It treats 30 as 24, I do not understand why.
Error:
Actual invocations have different arguments:
userService bean.searchByemployeeId(30);
-> at com.example.controller.AdminController.getUserWithEmploeeId(AdminController.java:85)

Comparison Failure:
<Click to see difference>

Argument(s) are different! Wanted:
userService bean.searchByemployeeId(24);
-> at com.example.controller.controller.AdminControllerTest.get_user_by_id_should_return_user_with_id_0030(AdminControllerTest.java:1595)
Actual invocations have different arguments:
userService bean.searchByemployeeId(30);
-> at com.example.controller.controller.AdminController.getUserWithEmploeeId(AdminController.java:85)


text:
Q: Remote access to couchDB not working I have a couchDB instance, running on my server.
Followed to the instructions on couchDB documentation i want to access the admin console of my couchdb from my pc, but it doesn't work.
I also restarted the couched after i changed the /etc/couchdb/local.ini file.
when i check the listening ports with:
netstat -ntulp
the output is:
tcp  0  0  0.0.0.0:5984  0.0.0.0:*  LiSTEN  -
So actually it should be accessible, but it isn't.
What i have to do, that i can access my couchdb from remote?
CouchDB Version: 1.5.0
Server: Ubuntu 14.04

A: I solved this Problem with the answer of this question: Access CouchDB Futon
I have only to create a ssh tunnel to my remote couchdb:
ssh -f -L localhost:15984:127.0.0.1:5984 user@remote_host -N


text:
Q: SQL dividing two columns not working properly Whenever I try dividing two tables with each other, it doesn't work. However, when I try to multiply, add or subtract them from each other it works. Since my list have plenty of books, I also want to not show all of the books that costs less than 1$ per page.
I want to divide the purchase price of a book with the pages of it, to calculate the price/page but it's not working out for me. This is what I've tried doing:
select purchase_price, pages, (purchase_price / pages) as pageprice
from books
where purchase_price >= pages
order by pageprice desc

Whenever I try do divide one purchase_price with anything, 2 for an example, I get 0 in return. However, when I try dividing pages it works fine. So what I'm having trouble with is that my purchase_price doesn't work to divide with. Under the values in my database it says that purchase_price is numeric, while pages and pageprice are integers.

A: Try this way please:
select purchase_price, pages, (cast(purchase_price as decimal) / pages) as pageprice
from books
where purchase_price >= pages
order by pageprice desc