text:
Q: How to expand in taylor series a composition of functions? I would like to expand in taylor series a function of type : f(x+f(x)) around x=a in the case where f(a)=0.
(%i1) atvalue(f(x),[x=a],0)$

The direct calculus yields :
(%i2) taylor(f(x+f(x)),x,a,2);

(%o2)/T/ f(a)+(at('diff(f(f(x)+x),x,1),x=a))*(x-a)+((at('diff(f(f(x)+x),x,2),x=a))*(x-a)^2)/2+...

If I define a intermediate function :
(%i3)define(tf(x),taylor(f(x),x,a,2))$

Then a expand in Taylor series I get :
(%i4) taylor(f(x+tf(x)),x,a,2);

(%o4) 0+...

I expect the following result :
f(1+f'(a))f'(a)(x-a)+(x-a)^2 f''(a)[f'(a)+(1+f'(a))^2/2]+o(x-a)^2
How could I solve this problem?

A: You can use gradef to simplify notation.
gradef(f(x),  f1(x)) $
gradef(f1(x), f2(x)) $

atvalue(f(x), x = a,  0) $

e: f(x+f(x)) $
e: taylor(e, x, a, 2) $
e: expand(e, 0, 0)$ /* 'taylor' form to ordinar expression */
e: ev(e, nouns);    /* f(a) to 0 */

returns
          2                                          2
       (f1 (a) f2(a) + 3 f1(a) f2(a) + f2(a)) (x - a)
(%o7) -----------------------------------------------
                              2
                                                          2
                                                     + (f1 (a) + f1(a)) (x - a)

A: A solution is as follow :

    gradef(f(x),  f1(x)) $
    gradef(f1(x), f2(x)) $
    atvalue(f(x), x = a,  0) $

    e: f(x+f(x)) $
    e: taylor(e, x, a, 2) $
    e: expand(e, 0, 0)$ /* 'taylor' form to ordinar expression*/
    e: ev(e, nouns);    /* f(a) to 0 */
    taylor(e,x,a,2); /* Becomes again a taylor serie which could be reused*/

For example, if I want to find the order of the Steffensen method which is defined, for function f which is C^2 and f(a)=0,f'(a)!=0, by :

    Sf(x)=x-f(x)^2/(f(x+f(x)-f(x))

If I straight expand this function around a I get :

Sf(x)=a+(x-a)-(f1(a)^2*(x-a)^2)/f(a)+...

which diverges since f(a)=0.

So this must be proceed in two steps. First I expand the denominator :

    den:f(x+f(x))-f(x)$
    t:taylor(den,x,a,2);
    t: expand(t, 0, 0)$
    t: ev(t, nouns)$
    t:taylor(t,x,a,2);

Then I expand the function Sf:

    Sf:x-f(x)^2/(t)$/*Introducing the taylor serie of den*/
    taylor(Sf,x,a,2);

which provides the wanted result :

    Sf(x)=a+((f1(a)+1)*f2(a)*(x-a)^2)/(2*f1(a))+...


text:
Q: 100 students in two classrooms.
Given 100 distinct students and two classrooms: A and B, of 60 and 45 seats respectively. In how many ways can a professor split the students into the two classrooms with respect to their capacities?

I've went as far as considering how to "distribuite" the 5 empty seats into the two class rooms:
6!/5! = 6
which are the cases in which the occupied seats are:

*

*60 - 40

*59 - 41

*58 - 42

*57 - 43

*56 - 44

*55 - 45

Now, considering for example the first case, since the order in which they are chosen doesn't matter, we just have to pick 60 students from the group of 100 and place them in A; then for the second case, similarly, pick 59 from the 100; and so on, leading us to:
$$\binom{100}{60} + \binom{100}{59} + \binom{100}{58} + \binom{100}{57} + \binom{100}{56} + \binom{100}{55}$$
for a total of:
$$6 * (\binom{100}{60} + \binom{100}{59} + \binom{100}{58} + \binom{100}{57} + \binom{100}{56} + \binom{100}{55})$$
I feel like I'm missing something, though. Is this correct? If not, how so?

A: The sum $\binom{100}{60}+\cdots +\binom{100}{55}$ is a correct expression for the answer. A clear explanation has been given for why it is right. There is no reason to multiply by $6$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Windows 10 Pro Hyper-V Manager Missing I have the full release version of Win10 Pro (64bit) as a fresh install to a laptop that I previously used as a Hyper-V server running Win8.1 Pro.
I have selected to install all Hyper-V features from Control Panel\Programs\Programs and Features. This prompted a reboot which was done with no errors reported. If I now view the "Windows Features" dialog then I can see the "Hyper-V" checkbox and child check boxes are all ticked. However, when I search for "Hyper-V" from the search toolbar I can see no sign of Hyper-V manager. Anyone know a way around this problem?

A: Windows search seems to have some problems indexing sometimes in Windows 10. Is the file actually installed? Check %windir%\System32\virtmgmt.msc and see if the file exists and if the snap-in will launch for you.

A: Before the first execution my start menu search could not find Hyper-V-Manager as well.
So, after launching Hyper-V once through one of these options, Windows search now always finds it (not sure which one helped immediately)

*

*Either use the shortcut Hyper-V-Manager in the folder Windows Administrative Tools of the start menu

*Or type virtmgmt.msc in the start menu and execute it

A: I looked looked for %windir%\System32\virtmgmt.msc and it wasn't there.  I installed Microsoft Remote Server Administration Tools (RSAT) as described on www.petri.com
https://www.petri.com/workaround-finding-missing-hyper-v-tools-windows-10

A: If it's missing just because Windows Indexing is being rubbish, then you might be able to find the shortcut in the Public Start Menu folder: %ProgramData%\Microsoft\Windows\Start Menu\Programs\Administrative Tools\Hyper-V Manager.lnk
From there you can right-click it and pin it to the Taskbar, which is what I usually do.

A: Expanding on Politus' Comment and Burgi's request.
I already had RSAT tools installed before I tried installing Hyper-V manager.  I could not find HyperV Manager in any of the locations I had found online (Program Data, Start Menu, System32, or through MMC as mentioned in the petri link.)
I downloaded and installed the x64 RSAT Tools again and when my computer finished rebooting. Hyper V Manager was available through the Start Menu.
I say 'again' because I had already installed RSAT tools.
Today I installed: WindowsTH-RSAT_WS2016-x64.msu
I had installed: WindowsTH-RSAT_TP5_Update-x64.msu on 10/3/2016 and tried to install HyperV on 10/19.
Hope this helps someone else.


text:
Q: How can I write a loop to set the value of sum[i] and delete datatable columns where sum[i] <= 0 int i = 0;
string[] sum = new string[256];

for (i = 1; i < 256; i++)
{
    sum[i] = sum[i].ToString();
    sum[i] = Convert.ToInt32(dt.Compute("Sum(BIN" + i.ToString() + ")", string.Empty));

    if(sum[i] == 0)
    {
        dt.Columns.Remove("BIN"+i.ToString()+"");
    }
}

A: There is a problem where you're trying to assign an int to sum[i], because sum is a string[], and you can't assign an int to one of the items.
Instead, it seems you want to get the return value from the method and save it in a variable so you can compare it. In order to do this, we can modify the code like:
string[] sum = new string[256];

for (int i = 1; i < 256; i++)
{
    int result = Convert.ToInt32(dt.Compute("Sum(BIN" + i.ToString() + ")", string.Empty));

    if (result <= 0)
    {
        dt.Columns.Remove("BIN" + i.ToString() + "");
    }
}

This can be simplified further by using the return value of the method directly in the if condition. We can also use interpolated strings instead of concatenation:
string[] sum = new string[256];

for (i = 1; i < sum.Length; i++)
{
    if(Convert.ToInt32(dt.Compute($"Sum(BIN{i})", string.Empty)) <= 0)
    {
        dt.Columns.Remove($"BIN{i}");
    }
}


text:
Q: Need to show parent and child from JSON on search in Javascript or Angular I need to show parent and child from Nested JSON data. Please find the following sample JSON data
[
        {
            "name": "India",
            "children": [
                {
                    "name": "Delhi",
                    "children": [
                        {
                            "name": "South Delhi"
                        },
                        {
                            "name": "North Delhi"
                        }
                    ]
                },
                {
                    "name": "Tamil Nadu",
                    "children": [
                        {
                            "name": "Chennai"
                        },
                        {
                            "name": "Coimbatore"
                        }
                    ]
                }
            ]
        },
        {
            "name": "America",
            "chilren": [
                {
                    "name": "California",
                    "children": [
                        {
                            "name": "Trinity"
                        },
                        {
                            "name": "Yolo"
                        }
                    ]
                },
                {
                    "name": "Florida",
                    "children": [
                        {
                            "name": "Bradford"
                        },
                        {
                            "name": "Calhoun"
                        }
                    ]
                }
            ]
        }
    ]

In the above json data. If i search name "Yolo" i need to get as America -> California -> Yolo as a result . Can you please help.
Please find the below code i written, This is displaying only child, but i need Parent as well
searchRecursive(value) {
        for (var i = 0; i < value.length; i++) {
            let lowerCaseName = value[i]['name'].toLowerCase();
            if (lowerCaseName.includes('yolo')) {
                this.searchedItems.push(value[i]);
            } else if (value[i]['children']) {
                if (value[i]['children'].length > 0) {
                    this.searchRecursive(value[i]['children']);
                }
            }
        }

        return this.searchedItems;
    }

A: Based on the array you provided you could do something like this:
let searchTerm = 'Yolo';

let reduced = countries.reduce((acc, val) => {
  let city = val.children[0].children.filter(city => (city.name == searchTerm)).pop();
  let country = val.name;
  let state = val.children[0].name;

  if (city) {
    return {
      country,
      state,
      city: city.name
    }
  }
});

the variable reduce would hold the value:
{ country: 'America', state: 'California', city: 'Yolo' }

A: This works for all cities:
let search = "Chennai";

    const transform = (dArray, parent) => {
    return dArray.map(item => [item.children, item.name, parent]);
    }

    transformed = [].concat.apply([], (data.map(contry => transform(contry.children,contry.name))));
    transformed2 = [].concat.apply([], (transformed.map(item => transform(item[0], item[1]))));

    query1 = transformed2.filter(item => item[1] === search);
    query2 = transformed.filter(item => item[1] === query1[0][2])

   console.log(query2[0][2] + ' -> ' + query1[0][2] + ' -> ' + query1[0][1])

It's ugly but it works. The idea is to transform the data to two data structures
transformed:
(4) [Array(3), Array(3), Array(3), Array(3)]
0: (3) [Array(2), "Delhi", "India"]
1: (3) [Array(2), "Tamil Nadu", "India"]
2: (3) [Array(2), "California", "America"]
3: (3) [Array(2), "Florida", "America"]
length: 4
__proto__: Array(0)

transformed2:
(8) [Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3), Array(3)]
0: (3) [undefined, "South Delhi", "Delhi"]
1: (3) [undefined, "North Delhi", "Delhi"]
2: (3) [undefined, "Chennai", "Tamil Nadu"]
3: (3) [undefined, "Coimbatore", "Tamil Nadu"]
4: (3) [undefined, "Trinity", "California"]
5: (3) [undefined, "Yolo", "California"]
6: (3) [undefined, "Bradford", "Florida"]
7: (3) [undefined, "Calhoun", "Florida"]
length: 8
__proto__: Array(0)

And then join the two structures with the .filter functions. Town  name must be unique for it to work


text:
Q: File upload with ServletFileUpload's parseRequest? I upload the file which I browse with input type="file" in my web App. The issue is I  get the FileItem list size as 0 though I can see all uploaded file info  under
request -> JakartaMutltiPartRequest -> files attribute
Here is java code that reads the file
public InputStream parseRequestStreamWithApache(HttpServletRequest request)
  throws FileUploadException, IOException {
  InputStream is = null;
  FileItemFactory factory = new DiskFileItemFactory();
  ServletFileUpload upload = new ServletFileUpload(factory);
  List items = upload.parseRequest(request);
  // here the item size is 0 ,i am not sure why i am not getting my file upload in browser with type="file"
  // but If inspect request in debugger i can see my file realted info in request--->JakartaMutltiPartRequest----->files attribute
  Iterator iter = items.iterator();
  while (iter.hasNext()) {
    FileItem item = (FileItem) iter.next();

    if (!item.isFormField()) {
      is = item.getInputStream();
    }
  }

  return is;
}

EDIT:
Here is JSP part:
<form NAME="form1" action="customer/customerManager!parseRequestStreamWithApache.action" ENCTYPE="multipart/form-data"   method="post" >

              Upload File

                   <input name="fileUploadAttr" id="filePath"  type="file" value="">

                 <Input type="submit" value ="uploadFile"/>

</form>

A: You should check for multipart content
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

if (isMultipart) {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        List items = upload.parseRequest(request);
        Iterator iterator = items.iterator();
        while (iterator.hasNext()) {
            FileItem item = (FileItem) iterator.next();
            if (!item.isFormField()) {
                String fileName = item.getName();

                String root = getServletContext().getRealPath("/");
                File path = new File(root + "/fileuploads");
                if (!path.exists()) {
                    boolean status = path.mkdirs();
                }

                File uploadedFile = new File(path + "/" + fileName);
                item.write(uploadedFile);
            }
        }
    } catch (Exception e) {

A: As I said in a comment to the same question, you posted earlier, this is most likely because you have parsed the request already before.
The files are part of the request body and you can parse it only one time.
Update:
I usually do use commons-upload in that way:
if (ServletFileUpload.isMultipartContent(request)) {
    ServletFileUpload fileUpload = new ServletFileUpload();
    FileItemIterator items = fileUpload.getItemIterator(request);
    // iterate items
    while (items.hasNext()) {
        FileItemStream item = items.next();
        if (!item.isFormField()) {
            is = item.openStream();
        }
    }
}

A: How big are the files you are uploading? You might be over the default threshold. I think the default is 10K
factory.setSizeThreshold(maxSizeYouWantToHandle);

A: If you are using weblogic 12 then check whether the patch_wls1211 is insatlled or not. I was having the same issue and it resolved after applying patch_wls1211.


text:
Q: \url{} links with percent (%) signs and overfull hbox error I have looked at the first comment to this question on % in urls and found that I didn't need to type \ ahead of each %. However, in WinEdt 7.1, everything from the first % in the first URL is now greyed out and I do not know if this is why I am getting an error with the overfull \hbox when I compile to PDF.
The problem in LaTeX is
proposal P293 (see \url{http://www.foodstandards.govt.nz/code/proposals/documents/Reanalysis%20of%20Nutriti.pdf} and \url{http://www.foodstandards.govt.nz/code/proposals/documents/P293_SD3.pdf} for the full analysis reports of the experiments).

The auto linebreak for the second URL should be after /code and not after /proposals as /proposals is going past the right hand margin in my document.
How can I force the linebreak to occur in the correct place in the second URL and still have the link work correctly?
The start of my report class is
\documentclass[11pt,PhD]{muthesis}
\usepackage[english]{babel}
\usepackage{amsmath,amsthm}
\usepackage{amsfonts}
\usepackage[a4paper,layout=a4paper,
        bindingoffset=4cm,left=0cm,right=2cm,
        head=2.5cm, bmargin=2cm]{geometry}
\usepackage{microtype}
\usepackage{verbatim}
\usepackage{graphicx}
\usepackage{url}
\usepackage[round]{natbib}
\usepackage{listings}
\usepackage{booktabs}
\usepackage{multirow}
\RequirePackage[l2tabu, orthodox]{nag}
\usepackage{cleveref}

A: Use the hyperref package to improve the behavior of the \url command. Use it with hidelinks option to view black links. If you don't use \% (using the url or hyperrefpackages) all that happens is that WinEdt means a comment but nothing wrong happens to the output document.
Add the \sloppy command to solve the problem with overfull boxes.
\documentclass[11pt,PhD]{muthesis}
\usepackage[english]{babel}
\usepackage{amsmath,amsthm}
\usepackage{amsfonts}
\usepackage[a4paper,layout=a4paper,
        bindingoffset=4cm,left=0cm,right=2cm,
        head=2.5cm, bmargin=2cm]{geometry}
\usepackage{microtype}
\usepackage{verbatim}
\usepackage{graphicx}
\usepackage[round]{natbib}
\usepackage{listings}
\usepackage{booktabs}
\usepackage{multirow}
\RequirePackage[l2tabu, orthodox]{nag}
\usepackage{cleveref}
\usepackage[hidelinks]{hyperref}
\begin{document}
    \sloppy
    proposal P293 (see \url{http://www.foodstandards.govt.nz/code/proposals/documents/Reanalysis\%20of\%20Nutriti.pdf} and \url{http://www.foodstandards.govt.nz/code/proposals/documents/P293_SD3.pdf} for the full analysis reports of the experiments).
\end{document}

You can read what the sloppy command does.

A: I would just reformulate the sentence;
\documentclass[11pt]{muthesis}

\usepackage[hidelinks]{hyperref}

\begin{document}

\noindent Proposal~P293 (where the documents for the full analysis reports of the experiments can be found at \url{http://www.foodstandards.govt.nz/code/proposals/documents/Reanalysis%20of%20Nutriti.pdf} and \url{http://www.foodstandards.govt.nz/code/proposals/documents/P293_SD3.pdf}).

\end{document}

If this is not an option, use the sloppypar environment as mentioned by barbara beeton in a comment to OSjerick's answer.


text:
Q: How to get Masonry to work with Bootstrap 5 Cards inside of Tabs? (Without jQuery) Has anyone figured out how to get Masonry to work with Bootstrap 5 Cards inside the Tabs component and without jQuery?
Currently, when you navigate each tab except the first tab, all content becomes stack instead of showing the Masonry layout like the first tab

<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/css/bootstrap.min.css" rel="stylesheet"/>

      <button class="nav-link active" id="nav-home-tab" data-bs-toggle="tab" data-bs-target="#nav-home" type="button" role="tab" aria-controls="nav-home" aria-selected="true">Home</button>
      <button class="nav-link" id="nav-contact-tab" data-bs-toggle="tab" data-bs-target="#nav-contact" type="button" role="tab" aria-controls="nav-contact" aria-selected="false">Contact</button>

      Home tab

          <svg class="bd-placeholder-img card-img-top" width="100%" height="200" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Image cap" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#868e96"/><text x="50%" y="50%" fill="#dee2e6" dy=".3em">Image cap</text></svg>

Card title that wraps to a new line

This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

A well-known quote, contained in a blockquote element.

              Someone famous in Source Title

          <svg class="bd-placeholder-img card-img-top" width="100%" height="200" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Image cap" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#868e96"/><text x="50%" y="50%" fill="#dee2e6" dy=".3em">Image cap</text></svg>

Card title

This card has supporting text below as a natural lead-in to additional content.

Last updated 3 mins ago

A well-known quote, contained in a blockquote element.

              Someone famous in Source Title

Card title

This card has a regular title and short paragraph of text below it.

Last updated 3 mins ago

          <svg class="bd-placeholder-img card-img" width="100%" height="260" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Card image" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#868e96"/><text x="50%" y="50%" fill="#dee2e6" dy=".3em">Card image</text></svg>

A well-known quote, contained in a blockquote element.

              Someone famous in Source Title

Card title

This is another card with title and supporting text below. This card has some additional content to make it slightly taller overall.

Last updated 3 mins ago

    Contact tab

          <svg class="bd-placeholder-img card-img-top" width="100%" height="200" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Image cap" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#868e96"/><text x="50%" y="50%" fill="#dee2e6" dy=".3em">Image cap</text></svg>

Card title that wraps to a new line

This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

A well-known quote, contained in a blockquote element.

              Someone famous in Source Title

          <svg class="bd-placeholder-img card-img-top" width="100%" height="200" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Image cap" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#868e96"/><text x="50%" y="50%" fill="#dee2e6" dy=".3em">Image cap</text></svg>

Card title

This card has supporting text below as a natural lead-in to additional content.

Last updated 3 mins ago

A well-known quote, contained in a blockquote element.

              Someone famous in Source Title

Card title

This card has a regular title and short paragraph of text below it.

Last updated 3 mins ago

          <svg class="bd-placeholder-img card-img" width="100%" height="260" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Card image" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#868e96"/><text x="50%" y="50%" fill="#dee2e6" dy=".3em">Card image</text></svg>

A well-known quote, contained in a blockquote element.

              Someone famous in Source Title

Card title

This is another card with title and supporting text below. This card has some additional content to make it slightly taller overall.

Last updated 3 mins ago

CodePen: https://codepen.io/imzenko/pen/GRMvZKw
Thanks.

A: just add ".active" class on all div where ".tab-pane" is:

      Home tab

    Contact tab

<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/css/bootstrap.min.css" rel="stylesheet"/>

      <button class="nav-link active" id="nav-home-tab" data-bs-toggle="tab" data-bs-target="#nav-home" type="button" role="tab" aria-controls="nav-home" aria-selected="true">Home</button>
      <button class="nav-link" id="nav-contact-tab" data-bs-toggle="tab" data-bs-target="#nav-contact" type="button" role="tab" aria-controls="nav-contact" aria-selected="false">Contact</button>

      Home tab

          <svg class="bd-placeholder-img card-img-top" width="100%" height="200" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Image cap" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#868e96"/><text x="50%" y="50%" fill="#dee2e6" dy=".3em">Image cap</text></svg>

Card title that wraps to a new line

This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

A well-known quote, contained in a blockquote element.

              Someone famous in Source Title

          <svg class="bd-placeholder-img card-img-top" width="100%" height="200" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Image cap" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#868e96"/><text x="50%" y="50%" fill="#dee2e6" dy=".3em">Image cap</text></svg>

Card title

This card has supporting text below as a natural lead-in to additional content.

Last updated 3 mins ago

A well-known quote, contained in a blockquote element.

              Someone famous in Source Title

Card title

This card has a regular title and short paragraph of text below it.

Last updated 3 mins ago

          <svg class="bd-placeholder-img card-img" width="100%" height="260" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Card image" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#868e96"/><text x="50%" y="50%" fill="#dee2e6" dy=".3em">Card image</text></svg>

A well-known quote, contained in a blockquote element.

              Someone famous in Source Title

Card title

This is another card with title and supporting text below. This card has some additional content to make it slightly taller overall.

Last updated 3 mins ago

    Contact tab

          <svg class="bd-placeholder-img card-img-top" width="100%" height="200" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Image cap" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#868e96"/><text x="50%" y="50%" fill="#dee2e6" dy=".3em">Image cap</text></svg>

Card title that wraps to a new line

This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

A well-known quote, contained in a blockquote element.

              Someone famous in Source Title

          <svg class="bd-placeholder-img card-img-top" width="100%" height="200" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Image cap" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#868e96"/><text x="50%" y="50%" fill="#dee2e6" dy=".3em">Image cap</text></svg>

Card title

This card has supporting text below as a natural lead-in to additional content.

Last updated 3 mins ago

A well-known quote, contained in a blockquote element.

              Someone famous in Source Title

Card title

This card has a regular title and short paragraph of text below it.

Last updated 3 mins ago

          <svg class="bd-placeholder-img card-img" width="100%" height="260" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Card image" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#868e96"/><text x="50%" y="50%" fill="#dee2e6" dy=".3em">Card image</text></svg>

A well-known quote, contained in a blockquote element.

              Someone famous in Source Title

Card title

This is another card with title and supporting text below. This card has some additional content to make it slightly taller overall.

Last updated 3 mins ago

If preview method don't give you the result you're looking for try this:
https://codepen.io/SitePoint/pen/GQoVey
with "imagesLoaded" here:
https://unpkg.com/imagesloaded@4.1.4/imagesloaded.pkgd.min.js


text:
Q: Ultraproduct question Prove that the ultraproduct of any infinite sequence of infinite
structures $(A_n : n ∈ N)$ with respect to an arbitrary ultrafilter U on $N$ is an
infinite structure.

A: Hint: given any natural number $k$, find a statement which is true in a model if an only if that model has at least $k$ distinct elements. Show that this statement is true in all of those models $A_n$. Then use Łoś' Theorem.


text:
Q: Google map - removing map name I'm styling up a Google map, API 3, and looking to remove the map name that reads "Practice Office" in the label at the top right on the map.
http://new.theredfrog.com/contact/
Is this possible? Here's the snippet of code that refers to the map name.
var styledMapType = new google.maps.StyledMapType(styles, { name: 'Practice Office' });
maphull.mapTypes.set('Styled', styledMapType);

A: See the documentation on mapTypeControl
var options = {
mapTypeControlOptions: {
    mapTypeIds: [ 'Styled']
},
    mapTypeControl: false,
//center: new google.maps.LatLng(53.741365, -0.3361),
center: new google.maps.LatLng(53.775906, -0.736771),
zoom: 9,
mapTypeId: 'Styled'
};


text:
Q: StringBuilder and For Loop MY QUESTION:
Is it possible to use a StringBuilder() inside a for loop?
I have this code:
text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    text.setTextColor(Color.WHITE);
                    text.setBackgroundColor(Color.parseColor("#c04485ed"));

                    String a = view.getTag().toString();
                    String b = text.getText().toString();
                    String formedWord = "";

                    StringBuilder word = new StringBuilder();

                    for(int i = 0; i <= 10; i++){
                        word.append(b);

                        if (word.length() == wordArray[i].length()){
                            formedWord = word.toString();

                            if(formedWord.equals(wordArray[i])){
                                break;
                            }
                        }
                    }

                }
            });

EXPLANATION OF THE CODE ABOVE
The function of this code is to form a string from the clicked textViews() and if that word is equal to the length() of the string on the index i of the string wordArray[] the system will check if the formedWord is equal to the string on the same index.
ERROR:

E/AndroidRuntime: FATAL EXCEPTION: main
                    Process: com.example.gabriel.salitaangpinoy10, PID: 8780
                    java.lang.ArrayIndexOutOfBoundsException: length=5; index=6
                        at com.example.gabriel.salitaangpinoy10.GameScreen$2.onClick(GameScreen.java:247)
                        at android.view.View.performClick(View.java:5210)
                        at android.view.View$PerformClick.run(View.java:21169)
                        at android.os.Handler.handleCallback(Handler.java:739)
                        at android.os.Handler.dispatchMessage(Handler.java:95)
                        at android.os.Looper.loop(Looper.java:148)
                        at android.app.ActivityThread.main(ActivityThread.java:5451)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

And when I checked the

com.example.gabriel.salitaangpinoy10.GameScreen$2.onClick(GameScreen.java:247)

It brings me to this line:
if (word.length() == wordArray[i].length())

A: Please check the below line from your code snippet. It has condition i <= 10 which means loop will run ten times if not broken. How did you know that the loop has to run till count of 10. Probably you should derive the loop counter value from event text length being passed to the method or it should be something like i <= wordArray.length to avoid exception
 for(int i = 0; i <= 10; i++){


text:
Q: Error while installing EJBCA 6.2.0 I'm trying to install EJBCA 6.2.0 on Ubuntu 12.04 but the following error comes out when I do "ant deploy" command.
Before doing "ant deploy", I installed JBoss 7.1.1 and ran it.
The installing EJBCA logs are like this.
jee:deployServices:

jee:deployDSJBoss5:

jee:deployDSJBoss7:
 [exec] Result: 1
 [exec] Result: 1
 [echo] data-source add --name=ejbcads --driver-name="h2" --connection-url="jdbc:h2:~/ejbcadb;DB_CLOSE_DELAY=-1" --jndi-name="java:/EjbcaDS"  --use-ccm=true --user-name="sa" --password="sa" --validate-on-match=true --background-validation=false --prepared-statements-cache-size=50 --share-prepared-statements=true --min-pool-size=5 --max-pool-size=150 --pool-prefill=true --transaction-isolation=TRANSACTION_READ_COMMITTED --check-valid-connection-sql="select 1"
 [exec] JBAS014803: Duplicate resource [
 [exec]     ("subsystem" => "datasources"),
 [exec]     ("data-source" => "ejbcads")
 [exec] ]

BUILD FAILED
/home/mjshin/ejbca_ce_6_2_0/build.xml:649: The following error occurred while     executing this line:
/home/mjshin/ejbca_ce_6_2_0/bin/jboss.xml:289: The following error occurred while executing this line:
/home/mjshin/ejbca_ce_6_2_0/bin/jboss.xml:556: exec returned: 1

Total time: 4 minutes 55 seconds
root@mjshin-VirtualBox:~/ejbca_ce_6_2_0#

I'm not familiar with web application server environment such as ant, JBOSS, etc. so I have no idea of what I should approach this problem.

A: I got the same error today when was trying to re-deploy EJBCA after changes in conf/web.properties file.
Looks like the problem is caused by having duplicate record somewhere in the JBOSS database/configuration file, could not locate where that record duplication occurs.
Resolved problem by deleting two lines in the jboss.xml which cause the problem (288 and 289).
As I understood, the line 288 (contains "data-source remove") tries to remove the old record, but it fails, the failure is ignored and execution is continued, and then and next line tries to add resource with the same name ejbcads, that operation fails, but this time failure is not ignored and deployment stops with error.
Make sure to save copy of the jboss.xml.


text:
Q: Post JSON to streak in excel vba I'm trying to update a large number of boxes on streak, and I have all these information in an excel sheet, however I realize when the request is sent, I ended up with "Sector12" on the website instead Sector12.value.
Can anyone help me with this?
Thank you in advance
        With CreateObject("Microsoft.XMLHTTP")
            .Open "POST", "https://www.streak.com/api/v1/boxes/" & boxK & "/fields/1007", False
            .SetRequestHeader "Accept", "application/json"
            .SetRequestHeader "Content-Type", "application/json"
            .SetRequestHeader "Authorization", "Basic " & EncodeBase64("xxxxxxxxxxxxxx")
            Sector12 = Application.WorksheetFunction.VLookup(JsonBox.Item(Index).Item("name"), ActiveSheet.Range("A:D"), 2, 0)

            .Send "{'value':Sector12}"

        End With

A: You are sending the literal string "{'value':Sector12}" as your JSON
Should be more like this:
.Send "{'value':" & Sector12 & "}"


text:
Q: Can I verify the weak order of convergence of a numerical scheme for SDEs by checking convergence in distribution? let $X_{t=0}^T$ be a continuous-time stochastic process defined by a certain stochastic differential equation
$$
X_t=a(t,X_t)dt+b(y,X_t)dW_t
$$
where W_t is a Wiener process.
Let $\tilde X_{i=0}^{N}$ be a discretization scheme with constant step size $\Delta = \frac{T}{N},\ N\in\mathbb{N}$. We say that the discretization scheme has a weak order of convergence $\beta$ if
$$
\sup_i\left|\mathbb{E}[f(\hat X(i\Delta)]-\mathbb{E}[f(X(i\Delta)]\right|\le k\ \Delta^\beta.
$$
It seems to understand that this kind of convergence is equivalent to the convergence in law $\hat X\to^{\mathcal{L}} X$. Would it therefore be possible for a Gaussian process to verify the alternative condition
$$
\sup_i\left|\text{Cov}\left(\hat X(i\Delta),\ \hat X((i+l)\Delta)\right)-\text{Cov}\left(X(i\Delta)\ X((i+l)\Delta)\right)\right|\le k\ \Delta^\beta.
$$
for some lag $l\in\mathbb{N}$.
This question arises to me because it can happen that I am not able to have the correct representation of the process $X$, but I know its distribution structure. Or I should just use the fact that $\mathbb{E}[f(X(i\Delta)]=\mu$?


text:
Q: Regular expression to remove the last column from a pipe delimited file I've got a file with 1000's of entries and 131 columns, the columns are pipe delimited. There is no pipe at the end so format is something like.
2010-10-04|Security|AMEND|20162214| ... lots more columns ... |Bloomberg
How can I remove the last column of the file say in Vim ?

A: Tou need
%s/|[^|]*$//

Note I am using [^|]* to allow for an empty column.

A: This regular expression will catch the last column: \|[^|]+$

A: Another way:
:%s/.*\zs|.*//

A: I would just use cut, or awk at a push


text:
Q: What to do when hydrating whole domain model is unnecessary for concrete operation? If some model can only exist if set of values are passed to it and validation on them are performed, then how to load such a model if only one of those values is needed for some action?
It seems a little overhead to do hydration of model all over again if only one value for action on that model is needed. That can be expensive.
I have an auction model. It has title, description, owner, current value, dates and bids. For particular operation like bid I only need current value and bids in this model to be populated. However, model, theoretically, cannot exist if other values are not received and validated (in constructor).
What to do? How to do separation? Is that normal/common for DDD and there is just some trade offs you cannot avoid?

A: I believe I understand your dilemma.
Though it may be a waste to rehydrate the entire aggregate for this, the aggregate serves the specific purpose of being the consistency boundary. If you had a subset of the domain just to handle the bids, and the full aggregate for other operations, how are you going to maintain consistency when you have potentially two objects servicing operations on the same AR? You no longer have a single consistency boundary. Are you positive that performance is going to be a problem if rehydrate the entire thing for this minor operation? Have you measured it?
If it becomes a problem, one thing you can do is to move your use cases up a level so that they are intercepted before the aggregate root is loaded. This is common in messaging-based systems where you issue commands to the domain (not call a method directly on a loaded aggregate). Commands are received by handlers, which hydrate the aggregate as appropriate for the use case (e.g. a deleted version of the aggregate which refuses to do perform any operation since it is deleted, or in your case a limited version which only accepts bids). Sometimes the handlers even load other aggregates (for information only, otherwise the consistency boundary is violated again) or prepare services to hand off to the aggregate to perform the given use case.
In a non-messaging system you could accomplish the same with the Facade pattern. Essentially, you make an object that is your interface into the domain. The object has a method per use case. Inside that method, you run handler code; hydrate your appropriate aggregate, wrangle the resources/services necessary for the user case, and call the aggregate's method. Maybe save the changes as well. Eventually, you may get too many parameters on the Facade methods and you will need to refactor them to an object. At that point, you have a command message as your parameter. :)
However, if you do something like this you need some infrastructure guarantees. For example, a specific aggregate can only run one use case at a time. My first infrastructure like this, each type of aggregate (not each instance) could only run one use case at a time -- in other words if I submitted 100 operations, each to a different auction, they would still be performed one at a time. In practice, this was not a performance problem at all as you will usually be bottle-necked by I/O more than running domain operations.

A: When you realize that most of the data an AR carries is not needed at all to fulfill some of it's commands then you are on the urge of discovering a new domain concept. Another analysis that may help the discovery process is doing a concurrency conflict analysis to see if your design introduces unnecessary concurrency conflicts.
e.g. Should changing the title of the auction conflict with someone who's trying to bid?
The fact that you are asking this question is a strong indicator that your aggregate boundaries are wrong and that your Auction concept is currently not very cohesive.
Most people will solve the data-loading part of this problem by introducing lazy-loading, but that's a code smell and doesn't address the heart of the problem.
I can't tell if that really fits with your domain, but what about having a Listing aggregate as well as an Auction aggregate. A Listing is sold through an Auction.
The Listing would handle the descriptive part of what's being sold while the Auction will handle the bidding process.
Both ARs can be created in the same transaction: the creation of the Auction is an immediate side-effect of the creation of a Listing.

"But there's a rule stating that one should not modify more than a
  single AR in a transaction".

Yes and it's very important to respect that rule, but here we aren't modifying ARs we are creating them and that's very different because no contention can exist during the creation process. Those ARs aren't shared resources yet.


text:
Q: How to test a function that return void with Jest? Tyepscript I have some function and a type in file retry.ts
export const retryNTimes =  (retryFunction: Function) => {
    let retry = 0;
    while(retry < MAX_NUMBER_OF_RETRIES){
        try {
            retryFunction()
            break
        } catch (err) {
            console.log(`Try ${retry}: ${err}`)
            retry += 1
        }
    }
}

type User = {
  userId: string
}

const TestUser = async ({
  userId,
}:User) => {
  console.log(`userid : ${userId} `)
}

I want to test test to make sure the function retryNTimes works.Then test to make sure it calls a function up to 3 times upon its failure. So I created a little TestUser function to do this with.
In file retry.test.ts,
describe('retry Function',() => {

test('retryNTimes function was call', () => {
    retryNTimes(function(){ TestUser()})
    expect(retryNTimes).toHaveBeenCalledTimes(1)
})

test('retry function to try 1 time', () => {
    retryNTimes(function(){ TestUser()})
    expect(TestUser).toHaveBeenCalledTimes(1)
})

 test('retry function to try 2 times', () => {
     retryNTimes(function(){ TestUser()})
     expect(TestUser).toHaveBeenCalledTimes(2)
 })

 test('retry function to try 3 times', () => {
     retryNTimes(function(){ TestUser()})
     expect(TestUser).toHaveBeenCalledTimes(3)
 })

})

However I recieve this error for the first 2 tests.
Matcher error: received value must be a mock or spy function

    Received has type:  function
    Received has value: [Function anonymous]

       9 | test('retryNTimes function was call', () => {
      10 |     retryNTimes(function(){ TestUser()})
    > 11 |     expect(retryNTimes).toHaveBeenCalledTimes(1)
         |                         ^
      12 | })

And I know the second two wont work with this set up because Im pretty sure I need to mock the function catching an error before it calls it again.
Ive been pretty bad with jest so far, so any help with setting up these tests is greatly appreciated.

A: You want to use a mock function:
describe('retry Function',() => {

  test('retry function to try 1 time', async () => {
    // create a mock function that rejects once, then resolves
    const func = jest.fn()
            .mockRejectedValueOnce(new Error('intentional test error)')
            .mockResolvedValueOnce(void 0);
    await retryNTimes(func)
    expect(func).toHaveBeenCalledTimes(2)
  })
})

Note that you've got some other issues, primarily that your retry function doesn't handle async functions. You'll need to await to handle that:
export const retryNTimes =  async (retryFunction: Function) => {
    let retry = 0;
    while(retry < MAX_NUMBER_OF_RETRIES){
        try {
            await retryFunction()
            break
        } catch (err) {
            console.log(`Try ${retry}: ${err}`)
            retry += 1
        }
    }
}


text:
Q: How can I specify an overload when passing an overloaded function to another? Simple example:
std::vector<std::string> strings{"1","2","3");
std::vector<double> doubles(3);
transform(begin(strings), end(strings), begin(doubles), std::stod);

This fails to compile because the compiler cannot decide which std::stod to use. The one that takes an std::string or the one that takes an std::wstring. We see that only one would work given how std::transform works, but the compiler doesn't.
Options (bad ones)

*

*Now, we cannot say std::stod<std::string> because std::stod is not a template but an overload. And even if it was a template, it would have to be a class template with a static non-templated function: Stod<std::string>::stod.

*What I usually do is use a lambda: [](std::string const& s) { return std::stod(s); } but that is quite a lot of code for nothing.

*There is also the option to cast the overloaded function to the specific type (double (*)(std::string const&)) but to do that, I have to know the return type. For std::stod that is simple, because it always returns a simple double but for other functions that might be a very complicated thing to write down.

Is there a more concise way than the lambda to select the correct overload or trick the compiler into figuring it out itself?

A: As you already know, you either resolve the overload upfront by casting, i.e. choosing one of the overloads, or you delay the overload resolution by wrapping the call in a function object (being it a lambda or something else).
The quickest way to take the latter approach, without writing any code of yours, is Boost.Hof's BOOST_HOF_LIFT.
So instead of passing this
std::stod

you pass this
BOOST_HOF_LIFT(std::stod)

Isn't it concise enough?
(Working example on Compiler Explorer.)

A: *

*You would need to help the compiler to select overload:
static_cast<double(*)(const std::string&, std::size_t*)>(std::stod)

*This does not work anyway. std::stod requires 2 arguments. The default value for the argument doesn't tag along with the function pointer you give to transform to work with.

*You also take the address of a function in the standard library which isn't allowed (with a few exceptions - but std::stod is not one of them).

The simplest solution for all is to package it in a lambda:
std::transform(std::begin(strings), std::end(strings), std::begin(doubles),
               [](const std::string& s) { return std::stod(s); });

Is there a more concise way than the lambda to select the correct overload or trick the compiler into figuring it out itself?

No, none that is portable.


text:
Q: How to cluster only the column in R heatmap.2? I have the a data which I want to plot a heatmap with dendrogram clustering only for the column.
How can I achieve that?
The data consist only one row but multiple columns.
Note that I literally want the cluster on the column and not transposing it into row cluster.
This is the code I have, which didn't work.
library(gplots)
library(RColorBrewer)
dat.all <- structure(list(Probes = structure(1L, .Label = "1419598_at", class = "factor"),
    XXX_LV_06.ip = 0.985, XXX_SP_06.ip = 0.932, XXX_LN_06.id = 2.115,
    XXX_LV_06.id = 1.753, XXX_SP_06.id = 2.668, ZZZ_KD_06.ip = 10.079,
    ZZZ_LG_06.ip = 2.323, ZZZ_LV_06.ip = 2.119, ZZZ_SP_06.ip = 4.157,
    ZZZ_LN_06.id = 1.371, ZZZ_LV_06.id = 1.825, ZZZ_SP_06.id = 1.457,
    ZZZ_KD_24.ip = 0L, ZZZ_LG_24.ip = 1.049, ZZZ_LV_24.ip = 1.372,
    ZZZ_SP_24.ip = 1.83, AAA_LN_06.id = 1.991, AAA_LV_06.ip = 2.555,
    AAA_SP_06.ip = 4.209, AAA_LV_06.id = 1.375, AAA_SP_06.id = 0.75,
    GGG_LV_06.ip = 5.938, GGG_SP_06.ip = 8.326, GGG_LN_06.id = 1.982,
    GGG_LV_06.id = 0.779, GGG_SP_06.id = 1.383, KKK_LN_06.id = 2.006,
    KKK_LV_06.ip = 1.253, KKK_SP_06.ip = 1.774, X333_LV_06.id = 1.792,
    X333_SP_06.id = 1.408, EEE_LV_06.in = 0.881, EEE_SP_06.in = 1.374,
    DDD_LN_06.id = 2.052, DDD_LV_06.id = 1.363, DDD_SP_06.id = 1.678), .Names = c("Probes",
"XXX_LV_06.ip", "XXX_SP_06.ip", "XXX_LN_06.id", "XXX_LV_06.id",
"XXX_SP_06.id", "ZZZ_KD_06.ip", "ZZZ_LG_06.ip", "ZZZ_LV_06.ip",
"ZZZ_SP_06.ip", "ZZZ_LN_06.id", "ZZZ_LV_06.id", "ZZZ_SP_06.id",
"ZZZ_KD_24.ip", "ZZZ_LG_24.ip", "ZZZ_LV_24.ip", "ZZZ_SP_24.ip",
"AAA_LN_06.id", "AAA_LV_06.ip", "AAA_SP_06.ip", "AAA_LV_06.id",
"AAA_SP_06.id", "GGG_LV_06.ip", "GGG_SP_06.ip", "GGG_LN_06.id",
"GGG_LV_06.id", "GGG_SP_06.id", "KKK_LN_06.id", "KKK_LV_06.ip",
"KKK_SP_06.ip", "X333_LV_06.id", "X333_SP_06.id", "EEE_LV_06.in",
"EEE_SP_06.in", "DDD_LN_06.id", "DDD_LV_06.id", "DDD_SP_06.id"
), row.names = 1L, class = "data.frame")

# Clustering and distance function
hclustfunc <- function(x) hclust(x, method="complete")
distfunc <- function(x) dist(x,method="maximum")

height <- 3;

outdir <- "./";

# Define output file name
heatout <-paste(outdir,base,"myplot.pdf",sep="");

# require(RColorBrewer)
col1 <- colorRampPalette(brewer.pal(12, "Set3"));
col2 <- colorRampPalette(brewer.pal(9, "Set1"));

cl.col <- hclustfunc(distfunc(t(dat.all)))

# extract cluster assignments; i.e. k=8 (rows) k=5 (columns)
gr.col <- cutree(cl.col, h=3)
gr.col.nofclust <- length(unique(as.vector(gr.col)));
clust.col.height <- col2(gr.col.nofclust);
hmcols <- rev(redgreen(2750));

pdf(file=heatout,width=50,height=25);
heatmap.2(as.matrix(dat.all),
                scale='row',
                trace='none',
                Rowv=FALSE,
                col=hmcols,
                symbreak=T,
                hclustfun=hclustfunc,
                distfun=distfunc,
                keysize=0.1,
                margins=c(10,200),
                lwid=c(1,4), lhei=c(0.7,3),
                ColSideColors=clust.col.height[gr.col])
dev.off();

The image will look like this:

A: Do you explicitly need to use the heatmap.2() function? If not, then I suggest you to consider function pheatmap() from the package pheatmap, since it allows you to accomplish the feat you're after with rather minimal gymnastics.
First of all, I would get rid of the first column in your dataset. However, to retain the information I'd put the Affymetrix ID as a row name in the data frame:
rownames(dat.all)<-dat.all[,1]
dat.all<-dat.all[,-1]

After that you could run the rest of your code up until the actual plotting of the heatmap. At that stage you resort to pheatmap(). It works very similarly to the heatmap.2(), but the names of the arguments are different. The following command should get you the rest of the way or close to it:
require(pheatmap)
pheatmap(dat.all, cluster_rows=FALSE, color=hmcols, scale="row",
annotation.colors=clust.col.height[gr.col], annotation=t(dat.all),
clustering_distance_cols=distfunc(t(dat.all)))

Arguments with annotation in their names add the column side colors. If you want to use your own distance function, you can specify its output as on input to pheatmap() with the argument clustering_distance_cols. Please consult the help for the pheatmap package for further details. Also, see an example plot below.

A: A bit of a hack to get around the 'each dimension must be two or more' constraint, you can rbind the single row to itself, along the lines of
heatmap.2(rbind(as.numeric(dat.all[,-1]),as.numeric(dat.all[,-1])),...

though you may need to adjust the labels manually.  I took the first column off dat.all (with the  [,-1] as the affymetrix id was getting in the way when I copied it across - you may not need to do that in the true version?


text:
Q: Standard Location Service battery drain on iOS I noticed that if I have an application using Significant Location Change it does take approximately 30% of my battery over 24H. I thought that SLC was not supposed to drain the battery.
Is this behaviour normal? We made our tests scientifically on an iPhone 6 with iOS 8.3 and 8.4. We also tried on an iPhone 5c (iOS 8.3 and 8.4).

A: There are several options on CLLocationManager and you must use them intelligently or you will see unanticipated battery drain.
1- when you invoke the  startMonitoringSignificantLocationChanges method be sure you have not already called startUpdatingLocation otherwise make sure you stop it with stopUpdatingLocation before you use significant distance.
2-  Check your settings for pausesAutomatically and allow deferred updates.  These will impact things substantially.
3-If you don't need beacons, visits or geofencing turn that off.  As these can force LM into higher battery drain modes.
4- You should also check to see what logic you execute when you receive a location update.  Notifications which turn on the screen and network calls which may spin up the wifi and cell service will add significantly more battery drain to your device than the location manager alone.
You might also checkout https://LocationKit.io for a cocoapod designed to optimize location services for high accuracy and low power.  Full disclosure I work for the company that makes LocationKit.


text:
Q: Flip second div and third div I have four div and my query is that i want to replace the order of second div and third div the output should come in this way 1324 instead of 1234

1

2

3

4

$(document).ready(function() {
    reverseChildren($('.bar'));
    if (document.body.offsetWidth < 600) {
        function reverseChildren($parent) {
            var listItems = $parent.children('div');
            console.log(listItems);
            $parent.append(listItems.get().reverse());
        };
    }
});

A: You can swap the position of two elements using jQuery's before method.
$('.bar div:nth-child(2)').before($('.bar div:nth-child(3)'));

Here's a jsfiddle of it using your html.
Also, function declarations should not be inside an if statement if you are trying to call the function outside of the if statement.

A: First of all: you've wrapped your function call within an if statement, which is very odd. You should wrap the function call with the if statement and make the function call itself globally available.
Second: your function now selects all children and reverses them, while you only want to select the last item of the two you would like to reverse and append it before it's immedeate previous sibling like so:
html

1

2

3

4

Javascript
function reverseChild($parent, index)
{
    // Retrieve the child item with the supplied (ZERO BASED!) index
    var childItem = $parent.children('div:eq(' + index + ')');

    // Place it in front of it's immedeate previous sibling.
    childItem.prev().before(childItem);
};

$(document).ready(function()
{
    reverseChild($('.bar'), 2);
});

JSFiddle demo: http://jsfiddle.net/mpcowmpb/

*

*Do note: i've removed the document.body.offsetWidth check within the JSFiddle demo as the body's less wide within that demo.


text:
Q: given two points find the slope- Python class I am new to python and I am trying to figure out why this code won't work.
class Point:
  def __init__(self, x, y):
    self.x = x
    self.y = y

  def slope_from_origin (self,p1,p2):
      slope=((p2.y-p1.y)/(p2.x-p1.x))
      return Point(slope)

  def __str__ (self):
      return str(slope)

p=Point(6,7)
q=Point(3,4)
print(p.slope_from_origin(q))

What should I change to make this code work? Thanks.

A: Your calculation is a bit mixed up:
slope_from_origin is the slope that a line segment passing through the origin Point(0, 0), and the given point makes.
slope_between_two_points is the slope that a line segment passing through the two given points makes.
slope is a scalar, you are trying to construct a Point with it, and return it
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def slope_between_two_points(self, p1=Point(0, 0)):  # uses default argument to define the origin
        if p1.x - self.x == 0:
            return float('inf')   # prevent dividing by zero when slope is infinite
       return (p1.y - self.y) / (p1.x - self.x)

    def slope_from_origin(self):
        return self.slope_between_two_points()

    def __str__ (self):
        return str(slope)

p = Point(6, 7)
q = Point(3, 4)
print(p.slope_between_two_points(q), p.slope_from_origin(), q.slope_from_origin())


text:
Q: Why does getWritableDatabase crashes on some devices? (sqlite3_open_v2 ... Failed) My application uses a database and works pretty well on all Android devices.
Recently some users pointed that it crashes on HTC Tattoo. I decided to give a try and got one in loan.
So, the error come when I call: this.getWritableDatabase();
09-27 18:26:22.292: ERROR/Database(1537): sqlite3_open_v2("/data/data/com.xxx.xxx/databases/radars.db", &handle, 6, NULL) failed
09-27 18:26:22.292: WARN/System.err(1537): android.database.sqlite.SQLiteException: unable to open database file

And I have checked, the Database is in the device:

I really cannot understand what happens....
Thank a lot for your help!
EDIT:
As noticed by LAS_VEGAS
# sqlite3 /data/data/com.xxx.xxx/databases/radars.db

Gives this result:
sqlite3: not found

Seem that the HTC Tattoo has serious SQL issues:

adb shell
   # cd /system/xbin
   # ls | grep sqlite3
//Nothing//

A: This is weird. I think this could happen when you try to access database file from multiple threads simultaneously. Could it be the case?
Also for testing purposes did you try getReadableDatabase(), maybe it gives a clue...
EDIT:
Can you access from remote shell?:
http://developer.android.com/guide/developing/tools/adb.html#sqlite
EDIT2:
So it seems that HTC tattoo has no sqlite3.


text:
Q: How to Construct a Maximum Likelihood Estimator for Parameter from a Beta Distribution? I have a question from my Stats Homework that is worded as follows:
Based on a random sample size n from the Beta(a,2), construct the MLE of a

I really don't know how to go about solving this, as the beta function in the pmf of the beta distribution is throwing me off. I would appreciate any input and guidance.


text:
Q: Page does not seem to load assets in containers I am running functional tests with nightwatch.js. I have things working fine in my local environment, but when I run the test in a container environment (so I can hook it up to my CI pipeline and run it on every release), I'm either getting an issue with assets loading or an issue with the screenshots.
When the test fails, it takes a screenshot, and I have the screenshot directory mapped to the host so I can see the screenshot easily. Without fail, I am getting an unstyled page in my screenshot, with the page javascript not seeming to have run. I suspect the page is really not loading assets of any kind: not my CSS being served from the same container, nor my client JS, and that's why the test is failing.
I have tried both chromedriver and firefox in a selenium container, and my app is a node.js app running in a container as well; when I connect to the container my app is in using a browser, I see exactly what I expect to see. I have tried both selenium standalone images and blueimp's images.  A test run against an external website runs fine.
ETA: I got my app to dump a message when it sees a request, and it's only seeing one request: the main url. No asset requests.

A: This turned out to be unrelated. Something had gone wrong during my asset compilation step, so the assets were 404ing on my dev machine but not in my other test environments. My apologies.


text:
Q: Conditional Density Function on Underlying Exponential Problem Statement: Suppose $Y_1, Y_2,\dots, Y_n$ are a random sample from an exponential distribution with mean $\theta.$ Let $\displaystyle U=\sum_{i=1}^n Y_i.$ Find the conditional density function for $Y_1$ given $U:\; f_{Y_1|U}(y_1|u).$
Note: This is essentially Exercise 9.86b in Mathematical Statistics with Applications, 5th Ed., by Wackerly, Mendenhall, and Scheaffer. The problem is posed in the context of $U$ as a sufficient statistic, and of using the Rao-Blackwell Theorem to find the MVUE of $e^{-t/\theta}.$
My Work So Far: The conditional density function is given by
\begin{align*}
f_{Y_1|U}(y_1|u)
&=\frac{f(y_1,u)}{f_U(u)}.
\end{align*}
Now the density function for $Y_1$ is given by
$$f_1(y_1)=\frac{1}{\theta}\,e^{-y_1/\theta},$$
and the sum function $U=\sum Y_i$ would then have, by virtue of the mgf,
\begin{align*}
m_U(t)
&=\prod_{i=1}^n(1-\theta t)^{-1}\\
&=(1-\theta t)^{-n},
\end{align*}
which is the mgf for a Gamma distribution with parameters
$\beta=\theta$ and $\alpha=n.$ It
follows that
$$f_U(u)=\frac{u^{n-1}\,e^{-u/\theta}}{\Gamma(n)\,\theta^n}.$$
Now $u=y_1+y_2+\cdots+y_n,$ so that $y_1=u-y_2-y_3-\cdots-y_n.$
By the logic we have already used, if we let $S=\sum_{i=2}^nY_i,$ then
the distribution function for $S$ is a Gamma with parameters
$\beta=\theta$ and $\alpha=n-1.$ Also, $u=y_1+s,$ or
$y_1=u-s.$ Note that $y_1$ and $s$ are independent. It follows that
\begin{align*}
f_{(Y_1,S)}(y_1,s)
&=f_{Y_1}(y_1)\,f_S(s)\\
&=\frac1\theta\,e^{-y_1/\theta}\,
 \frac{s^{n-2}\,e^{-s/\theta}}{\Gamma(n-1)\,\theta^{n-1}}\\
&=\frac{s^{n-2}\,e^{-(y_1+s)/\theta}}{\Gamma(n-1)\,\theta^n}.
\end{align*}
My Question: I think I'm on the right track, but I also think I'm missing something fairly straight-forward. How do I push through to get the desired conditional probability density function?
I have examined a few questions, especially this one. I do not understand the method of solution there, and the notation they are using is confusing: are they working with $U$ or $Y_n?$ This question is taking a different approach (doing the expectation without knowing the distribution function), and so doesn't help me.


text:
Q: Error in SSRS expression for false condition I want to generate my string in the following format:
Vancouer should be displayed as -> (  V) anc-ouer
Roberts Cut-Off Road -> Roberts Cu(t-O) ff-Road ... etc
So for the last 4 charaters I am using:
Right(Fields!NAME.Value, 4)

for the middle portion I am using IIF :
IIF(Len(Fields!NAME.Value) < 10,
Left(Fields!NAME.Value,.
(Len(Fields!NAME.Value)-7)),
 Mid(Fields!NAME.Value,Len(Fields!NAME.Value)-9,3))

But the above IIF condition gives me #Error whenever the length is less than 10. What could be the possible solution for it? Or its better if I could know the expression to generate the complete format in easiest way possible.

A: Even if you have the condition to check for 10 characters SSRS still evaluates the false part which is why you are getting the error, this is normally encountered when attempting to avoid divide by zero errors. more info here
divide by zero/null workaround
another article

A: To compensate for the issue that RegBes mentioned, use an additional IIF to workaround the error for the false part of the initial IIF.
IIF(Len(Fields!NAME.Value) < 10,
        Left(Fields!NAME.Value, Len(Fields!NAME.Value) - 7),
        Mid(Fields!NAME.Value, Len(Fields!NAME.Value) - IIF(Len(Fields!NAME.Value) < 10, 0, 9), 3)
    )

This will subtract 0 if the LEN is less than 10. The first IIF will ensure that this code doesn't display a value but worksaround the issue of the IIF evaluating the TRUE and FALSE parts of the IIF.


text:
Q: TimeoutError import error when using matlab engine with python 3.5 I am trying to run a function written in matlab in a python script using matlab.engine.
The first time I run the script everything works fine, but when I try to run the script again I get the error "ImportError: cannot import name 'TimeoutError'" on importing the matlab engine. Restarting the kernel allows me to run the script again. I am also using import matlab.engine and not from matlab.engine import to avoid circular importing.
Any suggestions on how I can solve the issue?
I am using Ubuntu 16.04 and working with spyder.
Many Thanks!

A: I get a similar running error. But after trying several times, I found that for the same *.py manuscript, the phrase import matlab.engine and eng = matlab.engine.start_matlab() should be implemented only once
I commented them, by doing this I can re-run the script *.py again.
Otherwise, it will post the error

ImportError: cannot import name 'TimeoutError'.

I think using the import matlab.engine to start a new MATLAB® process is just like to open a door before we close the door, everyone can enter the room or go out again and again, but do not need open the door again because it is not closed yet.
"Restarting the kernel" is just like close the door automatically (the Python stops the engine and its MATLAB process).


text:
Q: Postgresql json functions missing it seems like my postgres doesn't have the json functions.
to_json('Fred said "Hi."'::text)

generates:
ERROR:  syntax error at or near "to_json"
LINE 1: to_json('Fred said "Hi."'::text)
        ^
SQL state: 42601
Character: 1

Any idea on how to enable or get the functions to work? Thought they where supposed to be there out of the box.

A: Turns out I had misunderstood the syntas - it should include SELECT, so SELECT to_json('Fred said "Hi."'::text)works.


text:
Q: Lightweight Rules Engine in Javascript I am looking for suggestions for a lightweight rules engine implemented in Javascript.
The reason for such an implementation is to build a very lightweight but fast browser-based simulation using a small set of rules (less than 20). The simulation would take half a dozen parameters and run the rules and display results in the browser without any need to go back to the server. Think of a UI with a couple radio buttons, checkboxes, text boxes and sliders to control the parameters. The simulation would quickly re-run based on any parameter change.

A: Rule Reactor (https://github.com/anywhichway/rule-reactor) is a light weight, fast, expressive forward chaining business rule engine leveraging JavaScript internals, lazy cross-products, and Functions as objects rather than Rete. It can be used in the browser or on the server.

A: This is very simple rule engine, which use server side javascript(Mozilla's Rhino engine) (maybe it will be  helpfully to you)
http://jubyrajan.blogspot.com/2010/04/implementing-simple-deterministic-rule.html

A: I've implemented a (more complicated) version of what you are describing in c#, and thinking back through the code, all of it would be doable with JavaScript. I agree with the comments posted that writing your own is a viable option. It can be as simple or complex as you want it to be.
General observations for this type of rules engine (in no particular order):

*

*Non-linear lookups are your friend. In JavaScript, this would be easy using the obj[key] = val syntax. Once you determine the output of a rule for a given set of parameters, cache its results so that you can use it again without executing the rule again.

*Determine whether or not you need to process unique combinations of inputs. For example, let's say you allow the user to enter multiple names and ask for suggestions on XYZ. In reality, you now need to run all rules against each input value. This may be irrelevant, simple, or immensely complicated (imagine a hotel reservation system that takes multiple dates, times, locations, and criteria, and makes suggestions).

*setTimeout() can be used to smooth out UI behavior, but the rules you describe should execute in a few milliseconds or less, so worry about performance last. Performance is less of a concern than you might think with a basic rules engine.

*Rule definitions will be easiest to manipulate if they are objects (or even simple object trees).

*Don't tie UI elements to output results; meaning, put the results of the rule execution into a flexible object list so that you can create whatever visual output you want from it.

*Customized output messages are very useful to a user. Meaning, rather than triggering a generic message when a condition is met, try inserting a real value into the output message like, "Your credit score is only 550. You need a minimum of a 600 to continue."
That's it off the top of my head. Good luck.

A: Checkout the nools rule engine implemented in pure JavaScript for node.js. It has a pretty straightforward  syntax for rules definitions.

A: I've made an example html / javascript rule engine for a product configurator. The rule engine is based on if then statements. The if then statements will be checked with an array. This array is filled with all possible options every time an options is changed.
Check out my blog for the example.
Link to my blog "Forward chaining javascript rule engine"
I think the "obj[key] = val" is the key to a javascript rule engine. Jquery helps with javascript handling.

A: Please check out (JSL) https://www.npmjs.com/package/lib-jsl.
From the overview document, JSL is a JSON based logic programming library meant for embedded use in JS programs. It uses JSON as its syntax as well as I/O method, and provides callbacks into the host environment for performance optimisation.


text:
Q: Keep business/data logic for wcf library in separate assembly? I was thinking of have my wcf interface in its separate assembly and then the data/business logic in it's own assembly.  Is this over-architecture or is it just fine?  Does it make updating the services easier? or if their is an issue/bug, does it make fixing the bugs easier.

A: This is a good way to design your program.
This allows you to focus on business logic or display logic independently, which is called Separation of Concerns and is one of the most important principles in the development of quality software.
This doesn't help with "fixing" bugs so much as it helps in avoiding bugs altogether.
It also allows you to create different front-ends for the same business objects, just in case you would also like to have a scriptable Console interface or a web or Silverlight interface later on.


text:
Q: Sequence of foreign keys I have an object type SPORTS ARENA that is supposed to lists all the sports held in that arena and an object type  SPORT with all the infos about a sport:
SPORTS ARENA
name: string
sports: seq string

SPORT
name: string
disciplines: seq string

SPORTS ARENA <-->> SPORT (1:n) relationship, one sport can be held in only one arena (in this case it is like this)
and one arena can hold multiple sports.

This is an objects scheme and I want to convert it in a relational scheme with primary keys and foreign keys.
Usually in (1:n) relations you put in one table an attribute as foreign key refering the primary key of the other table.
In this case I have to deal with a sequence, so do I have to make an attribute that is a sequence of foreign keys? or how would the relational scheme look like?

A: -- Arena ARE exists.
--
arena {ARE}
   PK {ARE}

*

*Each sport can be held in exactly one arena;
for each arena, that arena may hold more than one sport.
-- Sport SPO is held in arena ARE.
--
sport {SPO, ARE}
   PK {SPO}

FK {ARE} REFERENCES arena {ARE}

Note:
All attributes (columns) NOT NULL

PK = Primary Key
FK = Foreign Key


text:
Q: Can we have both ARM and x86 images in the same Docker Hub repo? What's the best way to have both ARM and x86 images on Docker Hub so people can choose according to their platform? Both images should be in sync (i.e. :latest on ARM should bring the latest ARM image and :latest on x86 should bring the latest x86 image).

A: It's been supported now by docker a feature called manifest. Here is the reference news, FYI.


text:
Q: migrating from EC2 to Azure First of all, I have never used Amazon EC2 neither Windows Azure. But I have a task to move application from EC2 to Azure. App is a REST api written in node.js. Currently I know that there is one EC2 instance with ubuntu with runing app on it. App is deployed to server/instance using tool called Capper. App uses some database and redis. This api is used by mobile clients.
My question is what is the simplest way to move app from EC2 to Azure and what type of service to use on Azure for hosting such app?

A: You will need to either deploy a Linux-based VM in Azure's "Virtual Machines".  Check this article out for assistance: http://www.windowsazure.com/en-us/develop/nodejs/tutorials/getting-started/
Alternatively, you can deploy a node.js app on Windows Azure Websites, by adding a new "Web site" thru the management portal, and pick the node.js template from the gallery of predefined templates.
HTH


text:
Q: Can't convert object of type java.lang.String to type com.thesis.joinerapp.Model.Joins So i want to query my Firebase Database base on the value that i get from other activity.
private String tripID = "";
tripID = getActivity().getIntent().getStringExtra("tripID");
JoinRef = FirebaseDatabase.getInstance().getReference().child("Join").child(tripID);
FirebaseRecyclerOptions<Joins> options = new FirebaseRecyclerOptions.Builder<Joins>().setQuery(JoinRef,Joins.class).build();

Database Structure:

But it shows an exception

com.google.firebase.database.DatabaseException: Can't convert object
  of type java.lang.String to type com.thesis.joinerapp.Model.Joins

A: While FirebaseUI can perform look ups of data for you, your data has to be in a very specific format for that.
If you want to show a subset of the number of trips, the index has to look like this:
"myTrips": {
    "tripID1": true,
    "tripID2": true
}

Where tripID1 and tripID2 are the -L keys that you have under /Trip.
You can find another example of this data in the FirebaseUI documentation on showing indexed data.

A: when you want to use the FirebaseUi, your database structure should be like this.
{
    "Join" : {
        "tripID" : {
            "pushUid" : {
                "joinID" : "yourJoinID",
                "personCount" : "1",
                "tripID" : "yourTrioID",
                "uid" : "yourUid"
            }

        }
    }
}

You need to add new root child which is pushId.


text:
Q: Server-side socket in Socket.io returns wrong namespace when 'connect' I'm using Socket.io - 1.0.6 with express.
and trying below code.
Server
var io = require('socket.io')(http);
io.on('connect', function(socket){
     console.log("server nsp->%s", socket.nsp.name);
     //<-- printed always "server nsp->/", In my thought, it should print "/custom_nsp".
});

Client
var socket = io.connect("http://mysocket.io/custom_nsp");
socket.on('connect', function(){
     console.log("client nsp->%s", socket.nsp);
     //<-- printed correctly "client nsp->/custom_nsp"
});

I don't know why server socket's namespce is always "/".
Do i anything wrong?

A: This is because custom namespaces handling must be performed with .of method (see docs).
If you modify your server-side code as follows:
io.of('/custom_nsp').on('connect', function(socket) {
    console.log("server nsp->%s", socket.nsp.name);  //server nsp->/custom_nsp
});

you will get what you expect.
But it's still unclear why the default namespace handler fires even when connecting to /custom_nsp.


text:
Q: using sed to convert camelCase to under_score I have a sed script that can convert camelCase to under_score which works great for this example:
myvar="camelCase"
converted="$(echo $myvar | sed 's/\([A-Z]\)/_\L\1/g;s/^_//')"

echo converted
// result: camel_case

However, I have the following case:
myvar="camelCASE"
converted="$(echo $myvar | sed 's/\([A-Z]\)/_\L\1/g;s/^_//')"

echo converted
// result: camel_c_a_s_e

The result I need in this particular case is: camel_case.
to be clear, the final sed script should work for "camelCase" as well as "camelCASE", and "CAMELcase".
myvar shall never contain special characters or spaces

A: You must consider that case change is the mark of a word. Space _ have to be placed just before the case change
Try this :
$ echo 'CamelCASECamelCase' \
| sed 's/\([^A-Z]\)\([A-Z0-9]\)/\1_\2/g' \
| sed 's/\([A-Z0-9]\)\([A-Z0-9]\)\([^A-Z]\)/\1_\2\3/g' \
| tr '[:upper:]' '[:lower:]'

# will output this
camel_case_camel_case

A: The issue is that your \([A-Z]\) only captures a single uppercase letter at a time. To fix that in POSIX BRE sed, you can use \([A-Z]\{1,\}\) ex.
$ echo camelCASE | sed 's/\([A-Z]\{1,\}\)/_\L\1/g;s/^_//'
camel_case

At least in GNU sed, ou can avoid the special treatment of leading _ by only matching after a non-wordbreak
$ echo CamelCASE | sed 's/\B\([A-Z]\{1,\}\)/_\L\1/g'
Camel_case

It's slightly more readable in ERE
$ echo CamelCASECamelCase | sed -E 's/\B([A-Z]+)/_\L\1/g'
Camel_casecamel_case

or even (using & instead of the explicit grouping)
$ echo CamelCASECamelCase | sed -E 's/\B[A-Z]+/_\L&/g'
Camel_casecamel_case


text:
Q: Expose theme colors to css variables in vuetify not working I enabled custom properties:
Vue.use(Vuetify, {
    options: {
        customProperties: true
    }
});

and trying to use through CSS variable :
<style>
    .custom{
        color:var(--v-primary-base);
    }
</style>

this is vuetify.js file where I am setting theme :
export default new Vuetify({
    icons: {
        iconfont: 'mdi',
    },
    theme: {
        themes: {
            light: {
                background: '#FFFFFF',
                primary: '#25316A',
                secondary: '#b0bec5',
                accent: '#25316A',
                error: '#E86674',
                orange: '#FF7A0D',
                golden: '#A68C59',
                badge: '#F5528C',
                customPrimary: '#085294',
            },
            dark: {
                primary: '#085294',
            }
        },
    },
})

None of the theme colors are accessible through variables. I tried many ways but hasn't worked and no error thrown. Any one can please help me?

A: You have to use the options in vuetify file but you have used it in wrong place like this...
export default new Vuetify({
    icons: {
        iconfont: 'mdi',
    },
    theme: {
        options: {
            customProperties: true,
        },
        themes: {
            light: {
                background: '#FFFFFF',
                primary: '#25316A',
                secondary: '#b0bec5',
                accent: '#25316A',
                error: '#E86674',
                orange: '#FF7A0D',
                golden: '#A68C59',
                badge: '#F5528C',
                customPrimary: '#085294',
            },
            dark: {
                primary: '#085294',
            }
        },
    },
})

After that when you want to use your custom CSS variable as you made it you have to use it like this..
<style>
    .custom{
        color:var(--v-golden-base);
    }
</style>

Here base is a default and I showed for the golden variable but You can use any of them.

A: You need to pass the options property to the Vuetify instance instead, not in the use function.
From the docs:
export default new Vuetify({
  theme: {
    options: {
      customProperties: true,
    },
    // ...
  },
})


text:
Q: How do I create a thread pool? Sometimes I want to run a maximum amount of IO actions in parallel at once for network-activity, etc. I whipped up a small concurrent thread function which works well with https://gist.github.com/810920, but this isn't really a pool as all IO actions must finish before others can start.
The type of what I'm looking for would be something like:
runPool :: Int -> [IO a] -> IO [a]

and should be able to operate on finite and infinite lists.
The pipes package looks like it would be able to achieve this quite well, but I feel there is probably a similar solution to the gist I have provided just using mvars, etc, from the haskell-platform.
Has anyone encountered an idiomatic solution without any heavy dependencies?

A: You need a thread pool, if you want something short, you could get inspiration from Control.ThreadPool (from the control-engine package which also provide more general functions), for instance threadPoolIO is just :
threadPoolIO :: Int -> (a -> IO b) -> IO (Chan a, Chan b)
threadPoolIO nr mutator = do
    input <- newChan
    output <- newChan
    forM_ [1..nr] $
        \_ -> forkIO (forever $ do
            i <- readChan input
            o <- mutator i
            writeChan output o)
    return (input, output)

It use two Chan for communication with the outside but that's usually what you want, it really help writing code that don't mess up.
If you absolutely want to wrap it up in a function of your type you can encapsulate the communication too :
runPool :: Int -> [IO a] -> IO [a]
runPool n as = do
  (input, output) <- threadPoolIO n (id)
  forM_ as $ writeChan input
  sequence (repeat (length as) $ readChan output)

This won't keep the order of your actions, is that a problem (it's easy to correct by transmitting the index of the action or just using an array instead to store the responses) ?
Note : the n threads will stay alive forever with this simplistic version, adding a "killAll" returned action to threadPoolIO would resolve this problem handily if you intend to create and trash several of those pool in a long running application (if not, given the weight of threads in Haskell, it's probably not worth the bother).
Note that this function works on finite lists only, that's because IO is normally strict so you can't start to process elements of IO [a] before the whole list is produced, if you really want that you'll have either to use lazy IO with unsafeInterleaveIO (maybe not the best idea) or completely change your model and use something like conduits to stream your results.


text:
Q: Issue with setTimeout () I'm pretty new to javascript, and I'm trying to create an automated slideshow. This is the first time I'm using setTimeout(). When I added the automation the last image is missing. There is a white/blank rectangle where the image should be and the dots indicating which slide the slideshow is on is not lighting up. Below, I have included what I have so far, and I would really appreciate any advice or guidance on how to fix this issue. Thank you!
Carousel.js
import React, {useState} from 'react'
import './Slider.css'
import BtnSlider from './BtnSlider'
import CarouselData from './CarouselData'

const delay = 3000;

export default function Carousel() {

      const [slideIndex, setSlideIndex] = useState(0)
      const timeoutRef = React.useRef(null);

      function resetTimeout() {
        if (timeoutRef.current) {
          clearTimeout(timeoutRef.current);
        }
      }

      React.useEffect(() => {
        resetTimeout();
        timeoutRef.current = setTimeout(
          () =>
          setSlideIndex((prevIndex) =>
              prevIndex === CarouselData.length - 1 ? 0 : prevIndex + 1
            ),
          delay
        );

      return () => {
          resetTimeout();
        };
      }, [slideIndex]);

    const nextSlide = () => {
        if(slideIndex !== CarouselData.length){
            setSlideIndex(slideIndex + 1)
        }
        else if (slideIndex === CarouselData.length){
            setSlideIndex(1)
        }
    }

    const prevSlide = () => {
        if(slideIndex !== 1){
            setSlideIndex(slideIndex - 1)
        }
        else if (slideIndex === 1){
            setSlideIndex(CarouselData.length)
        }
    }

    const moveDot = index => {
        setSlideIndex(index)
    }

    return (

            {CarouselData.map((obj, index) => {
                return (

                        <img
                        src={process.env.PUBLIC_URL + `/Imgs/img${index + 1}.jpg`}
                        alt="images"/>

                )
            })}
            <BtnSlider moveSlide={nextSlide} direction={"next"} />
            <BtnSlider moveSlide={prevSlide} direction={"prev"}/>

                {Array.from({length: 3}).map((item, index) => (

 moveDot(index + 1)}
                    className={slideIndex === index + 1 ? "dot active" : "dot"}
                    >

                ))}

    )
}

CarouselData.js
import { v4 as uuidv4 } from "uuid";

const CarouselData = [
  {
    id: uuidv4(),
    title: "Lorem ipsum",
    subTitle: "Lorem"
  },
  {
    id: uuidv4(),
    title: "Lorem ipsum",
    subTitle: "Lorem"
  },
  {
    id: uuidv4(),
    title: "Lorem ipsum",
    subTitle: "Lorem"
  },

];

export default CarouselData;


text:
Q: Focusrite Scarlett on Linux input mapping? Does anyone use these interfaces on Linux? If so, how do the inputs map (e. g. with ALSA/PulseAudio)?
E. g. the Scarlett 6i6 has the following connections.
Inputs:

*

*2x symmetric XLR inputs (one for each channel)

*2x symmetric phone connector inputs (one for each channel)

*1x coaxial SPDIF input (stereo signal over a single wire)

Outputs:

*

*4x symmetric phone connector output

*1x coaxial SPDIF output (stereo signal over a single wire)

Each input has its own ADC and each output has its own DAC, so there's nothing that goes "through" to another channel.
Now my question is: How does this map onto audio channels under Linux?

*

*Output-wise: Is it recognized as a single 6-channel card, so e. g. phone connector 1 is "front left", phone connector 2 is "front right", phone connector 3 is "rear left", phone connector 4 is "rear right", SPDIF channels are front and LFE or similar, "awkward" situation? Or is it recognized as three separate stereo audio cards? Or is even each output a single mono audio card? Or how?

*Input-wise: Do the 2x symmetric XLR inputs form a "stereo pair", so that when I plug a microphone into one, then record, I only get signal on, say, left channel, and the right one is silent? Or do they act as two separate mono inputs? What with the other inputs?
Would be great if someone had this interface running under Linux and could give me some insights. I plan plugging a condenser mic into the interface via XLR and would be interested if the two XLRs act as a "stereo input" and when I record, I get signal on one channel but not on the other or how this would turn out.

A: The way I use my Focusrite 6i6, I use jack/alsa as the backend, and plug pulseaudio into jack to play audio from applications that don't natively support jack.
All of the input/output ports are totally configurable in alsamixer. This hardware was designed with a very malleable hardware mixer to be controlled by software, and although Focusrite doesn't support linux, someone did figure out how to communicate with the device and implement this functionality through the Scarlett 6i6's alsa driver.
Right now, I see 12 playback ports on the Scarlett, and 6 capture ports. The capture ports are configurable in alsamixer, although they could line up to the four analog inputs + two SPDIF channel inputs, the user is free to do what they will. The playback ports as well as the monitor and headphone outputs are also totally configurable through alsamixer (ie, you can set playback ports 7,8 and 11,12 to play back through the monitor as a stereo mix and set playback ports 1,2 and 3,4 to play back through headphones as a different stereo mix). Pulseaudio plays normal system sounds back smoothly over the Scarlett through the jack interface, although the Scarlett does not even show up for output through Pulseaudio.
I'm not sure how alsa works with stereo vs mono channels, but in jack, it's natural to think of a stereo channel as made up of two mono channels. I'm not sure whether alsa works the same way, but I would expect that you would have to mix the input channels into stereo yourself. I absolutely recommend jack with alsa backend and alsamixer to utilize & control this audio interface on linux, as the device would be almost crippled without control over the hardware mixer functions.


text:
Q: jupyter notebook - Why notebook doesn't format this dictionary well? I'm using classification_report function which is supposed to return a dictionary, but it doesn't return a well-structured one. So how can I print it well in jupyter notebook?
from sklearn.metrics import classification_report
classification_report(test_preds, y_test)

Here is my output:
'              precision    recall  f1-score   support\n\n           0       0.81      0.97      0.88      1653\n
           1       0.76      0.28      0.41       533\n\n    accuracy                           0.80      2186\n   macro avg
       0.78      0.63      0.65      2186\nweighted avg       0.79      0.80      0.77      2186\n'

A: use print(classification_report(test_preds, y_test))


text:
Q: Computing colimit of $\bullet \rightarrow \bullet$ in Set? $\newcommand{\cSet}{\mathsf{Set}} \newcommand{\colim}{\operatorname{colim}}$
I'm trying to learn how to compute colimits in $\cSet$, so I'm testing out simple examples. Let's try a diagram $J \equiv \bullet \rightarrow \bullet$. Le $F: J \to \cSet$ be a functor whose image looks like $A \xrightarrow{f} B$. If I'm following nLab correctly, then the colimit is computed as $\colim F \equiv A \sqcup B / \sim$ where $\sim$ is the equivalence relation generated by the equations $a \sim f(a)$ for all $a \in A$.
As far as I can tell, this $\colim F$ is isomorphic to $B$ --- we have $a \in A$, which gets glued onto some $f(a) \in B$. So, every $a \in A$ is "annihilated" by being glued to a $f(a) \in B$. These don't even impose new relations, since each $a \in A$ gets mapped to a single $f(a) \in B$. So we must have $(A \cup B / \sim) \simeq B$?
I'm a little worried by this since the dual situation in the case of limits gives us $\lim F \equiv A \times B$ which is "more than" the colimit which seems to be equal to $B$.
Questions

*

*Is the assertion that $\colim F \simeq B$ correct?

*Is there some way to explain the "discrepancy" between the limit (being non-trivial) and the colimit (being trivial)?

A: The limit of $F$ is $A$, while the colimit of $F$ is $B$.
This is actually true for any functor $F : J \to C$ mapping to $A \to B$.
We first prove that the limit is $A$. For consider the maps $1_A : A \to A$ and $f : A \to B$. Suppose we have a third object $C$ and maps $g : C \to A$, $h : C \to B$ such that $h = f \circ g$. Then the unique map is $g : C \to A$. We see that $1_A \circ g = f$ and $f \circ g = h$.
To prove the same is true for the colimit, we simply take the limit in the opposite category.

A: $\newcommand{\cSet}{\mathsf{cSet}}$
To clarify, in terms of the general construction of limits in $\cSet$, we must compute the limit of the diagram $A \xrightarrow{f} B$ by constructing the set $\lim F \equiv \{ (a, b) : f(a) = b \}$. This set is isomorphic to $A$, since there is a unique b for each $a$ such that $f(a) = b$.


text:
Q: Alter only one branch properties I have a diagram in tikz-qtree like figure A, but I'd like something like figure B. Is it possible, to alter the properties of only one branch?
(these figures were made with Dia and arrows are not important)

edit: (added my modified code, based on Alan Munn's answer)
\begin{center}
\begin{tikzpicture}[grow'=right,level distance=1.45in,sibling distance=.2in]

\tikzset{edge from parent/.style=
{thick, draw, edge from parent fork right},
  every tree node/.style=
    {draw,minimum width=1.3in,text width=1.15in,align=center}
}
\Tree
  [.parent
    [.child0
      grandchild0-0
      grandchild0-1
      [[.{grandchild0-2}
        {greatgrandchild0}
        {greatgrandchild0}
        {greatgrandchild0}
        {greatgrandchild0}
      ]]
      grandchild0-3
    ]
    [.child1
      [.grandchild1-0 ]
      [.grandchild1-1 ]
    ]
  ]
\end{tikzpicture}
\end{center}

A: You can add extra brackets around a node to extend its branch:
\documentclass{article}
\usepackage{tikz}
\usepackage{tikz-qtree}
\usetikzlibrary{trees} % this is to allow the fork right path

\begin{document}

\begin{tikzpicture}[level distance=1.25in,sibling distance=.15in,scale=.75]
\tikzset{edge from parent/.style=
            {thick, draw,
                edge from parent fork right},every tree node/.style={draw,minimum width=1in,text width=1in, align=center},grow'=right}
\Tree
    [. parent
        [.{nice child0}
                [.{grandchild0-0 } ]
            [.{grandchild0-1 } ]
            [.{grandchild0-2 } ]
            [.{grandchild0-3 } ]
        ]
        [[[.child1
            [.{grandchild1-0 } ]
            [.{grandchild1-1 } ]
            [.{grandchild1-2 } ]
        ]]]
        [.child2 ]
        [.child3 ]
    ]
\end{tikzpicture}
\end{document}

A: Here's a solution using forest which is an extremely flexible and powerful package for drawing trees. It offers the automatisation of qtree plus the ability to customise the format and placement of individual nodes, branches and edges, when required.
It does an especially good job of automatically packing the nodes to make compact trees. [But you could further compress the tree with manual adjustments if required.]
\documentclass[tikz,border=10pt]{standalone}
\usepackage{forest}
\begin{document}
\begin{forest}
  for tree={
    grow'=0,
    parent anchor=east,
    child anchor=west,
    anchor=west,
    thick,
    draw,
    edge path={
      \noexpand\path [draw, thick, \forestoption{edge}] (!u.parent anchor) -- +(5pt,0) |- (.child anchor)\forestoption{edge label};
    },
    if level=1{
      tier=children,
      if n=2{
        for children={
          tier=grandchildren 2,
          delay={
            edge path={
              \noexpand\path [draw, thick, \forestoption{edge}] (!u.parent anchor) -| ([xshift=-5pt].child anchor) -- (.child anchor)\forestoption{edge label};
            },
          }
        },
      }{
        for children={tier=grandchildren 1}
      },
    }{},
  }
  [root
    [child 1
      [grandchild 1
        [,phantom, tier=grandchildren 2]
      ]
      [grandchild 2]
      [grandchild 3]
    ]
    [child 2
      [grandchild 4]
      [grandchild 5]
      [grandchild 6]
    ]
    [child 3
      [grandchild 7]
      [grandchild 8]
    ]
  ]
\end{forest}
\end{document}

Note that if you just want the grandchildren packed as shown in your answer, the solution is significantly simpler:
\begin{forest}
  for tree={
    grow'=0,
    parent anchor=east,
    child anchor=west,
    anchor=west,
    thick,
    draw,
    edge path={
      \noexpand\path [draw, thick, \forestoption{edge}] (!u.parent anchor) -- +(5pt,0) |- (.child anchor)\forestoption{edge label};
    },
  }
  [root
    [child 1
      [grandchild 1]
      [grandchild 2]
      [grandchild 3]
      [grandchild 4]
    ]
    [child 2]
    [child 3]
    [child 4
      [grandchild 7]
      [grandchild 8]
    ]
  ]
\end{forest}

A: I managed to find a solution to my problem without qtree based on this one: How to modify the distance between branches when drawing trees using TiKZ?
The code:
\documentclass[a4paper,12pt]{article}
\usepackage{tikz}
\usetikzlibrary{trees}%szögletességhöz kell
\begin{document}

\begin{tikzpicture}[grow'=right,level distance=90pt,sibling distance=30pt]

\tikzset{edge from parent/.style=
{thick, draw, edge from parent fork right}
}

    \node [draw] (z){parent}
        child {
            node[draw] (a) {child0}
            child {
                node[draw] (c) {grandchild0-0}
            }
            child {
                node[draw] (d) {grandchild0-1}
            }
            child {
                node[draw] (e) {grandchild0-2}
            }
            child {
                node[draw] (f) {grandchild0-3}
            }
        }
        child {
            node[draw] (b) {child1}
        }
        child {
            node[draw] (b) {child2}
        }
        child {
            node[draw] (b) {child3}
            child {
                node[draw] (c) {grandchild3-0}
            }
            child {
                node[draw] (c) {grandchild3-1}
            }
        }
        ;

    \path (z) -- (a);
    \path (z) -- (b);
    \path (a) -- (c);
    \end{tikzpicture}

\end{document}


text:
Q: C# No me deja consumir webservice de manera local Estoy trabajando con visual studio creando un webservice de ASP.net, de hecho estoy siguiendo un tutorial al pie de la letra, el método que viene por defecto al crear un ASMX es
[WebMethod]
    public string HolaMundo()
    {
        return "Hola a todos";
    }

Y siguiendo el mismo tutorial, ya publiqué el webservice de prueba en IIS, mi link queda como "http://localhost:8081/BackEndDescargaMasiva.asmx", (así le puse porque estaba pensando usarlo en otro proyecto, ignorar el nombre) ya estando publicado correctamente de manera local, al crear un cliente que lo consuma, se crea un proyecto de consola, se agrega la referencia y me detecta el método correctamente, al intentar consumirlo utilizo este código:
backend1.BackEndDescargaMasivaSoapClient client = new backend1.BackEndDescargaMasivaSoapClient();
        var result = client.HolaMundo();
        Console.WriteLine(result);
        Console.ReadLine();

Pero cuando ejecuto me arroja lo siguiente:

esto es lo que dice:
System.ServiceModel.FaultException
  HResult=0x80131501
  Mensaje = System.Web.Services.Protocols.SoapException: El servidor no puede procesar la solicitud. ---> System.InvalidOperationException: No se puede serializar System.Security.Cryptography.KeySizes porque no tiene un constructor sin parámetros.
   en System.Xml.Serialization.TypeDesc.CheckSupported()
   en System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo source, Boolean directReference, Boolean throwOnError)
   en System.Xml.Serialization.ReflectionAwareILGen.WriteReflectionInit(TypeScope scope)
   en System.Xml.Serialization.XmlSerializationWriterILGen.GenerateBegin()
   en   System.Xml.Serialization.TempAssembly.GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, Evidence evidence)
   en System.Xml.Serialization.TempAssembly..ctor(XmlMapping[] xmlMappings, Type[] types, String defaultNamespace, String location, Evidence evidence)
   en System.Xml.Serialization.XmlSerializer.FromMappings(XmlMapping[] mappings, Type type)
   en System.Web.Services.Protocols.SoapServerType..ctor(Type type, WebServiceProtocols protocolsSupported)
   en System.Web.Services.Protocols.SoapServerProtocol.Initialize()
   en System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)
   --- Fin del seguimiento de la pila de la excepción interna ---
  Origen = mscorlib
  Seguimiento de la pila:
   en System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   en System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   en Consumo_de_servicio.backend1.BackEndDescargaMasivaSoap.HolaMundo()
   en Consumo_de_servicio.backend1.BackEndDescargaMasivaSoapClient.HolaMundo() en C:\Users\DCL-Admin\source\repos\Consumo de servicio\Consumo de servicio\Connected Services\backend1\Reference.cs: línea 305
   en Consumo_de_servicio.Program.Main(String[] args) en C:\Users\DCL-Admin\source\repos\Consumo de servicio\Consumo de servicio\Program.cs: línea 14


text:
Q: Cómo hago que el scroll funcione en una position absolute Ya tengo toda una página con position absolute, sucede que cuando esta llega al final no baja, el resto del contenido se queda abajo y no puedo bajar a verlo, ya he intentado metiendo el contenido en una etiqueta div con el overflow pero nada, no puedo cambiar la posición porque se daña y porque ya todo está armado y no tengo tiempo para ponerme a crear esa página desde 0. ¿Qué puedo hacer?
div style="overflow-y: scroll;">---CONTENIDO CON POSITION ABSOLUTE---

A: Esto te debería funcionar

    .overflow{
       position: unset !important;
       overflow-y: scroll;
    }
    .contenido{
      position: absolute;
      width: 600px;
      height: 2000px;
      color: white;
      background-color: red;
    }

---CONTENIDO CON POSITION ABSOLUTE---