text:
Q: JSF throws class does not have the property for DynamicEntity I want to use a DynamicEntity as a managed bean providing properties for my xhtml form.
When I use the above as backing bean for my xhtml page, I got the following exception:
The class 'com.invoice.Invoic' does not have the property 'sellerAddress'.
com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:111)
javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
javax.faces.component.UIOutput.getValue(UIOutput.java:169)
com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205)
com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355)
com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:164)
javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1786)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:125)
javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
org.ocpsoft.rewrite.faces.RewriteViewHandler.renderView(RewriteViewHandler.java:186)
javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
org.ocpsoft.rewrite.servlet.RewriteFilter.doFilter(RewriteFilter.java:200)
com.tsystems.odx.idm.authentication.web.AuthenticationFilter.doFilter(AuthenticationFilter.java:231)
org.ocpsoft.rewrite.servlet.impl.HttpRewriteResultHandler.handleResult(HttpRewriteResultHandler.java:38)
org.ocpsoft.rewrite.servlet.RewriteFilter.rewrite(RewriteFilter.java:263)
org.ocpsoft.rewrite.servlet.RewriteFilter.doFilter(RewriteFilter.java:188)
com.tsystems.odx.idm.authentication.web.AuthenticationFilter.doFilter(AuthenticationFilter

I put a debug breakpoint and looked into my DynamicEntity object, the sellerAddress object was there.
Here is a dummy example how I would like to use DynamicEntity as bean
package com.test.beans;

import java.io.InputStream;

import javax.annotation.PostConstruct;
import javax.enterprise.inject.Produces;
import javax.faces.bean.ViewScoped;
import javax.inject.Named;
import javax.xml.bind.JAXBException;

import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory;

@Named
@ViewScoped
public class CustomerHandler {

    DynamicJAXBContext jaxbContext;

    @PostConstruct
    public void init() throws JAXBException {
        InputStream xsdInputStream = getClass().getClassLoader().getResourceAsStream("customer.xsd");
        jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(xsdInputStream, null, null,
                null);
    }

    @Produces
    @Named("Customer")
    public DynamicEntity createCustomer() {
        DynamicEntity customer = jaxbContext.newDynamicEntity("org.example.Customer");
        customer.set("name", "Jane Doe");
        DynamicEntity address = jaxbContext.newDynamicEntity("org.example.Address");
        address.set("street", "1 Any Street").set("city", "Any Town");
        customer.set("address", address);
        return customer;
    }

    public void save()
    {
        // do something
    }
}

The customer.xsd file is in src/main/resources
<xsd:schema
   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   xmlns="http://www.example.org"
   targetNamespace="http://www.example.org"
   elementFormDefault="qualified">

   <xsd:complexType name="address">
      <xsd:sequence>
         <xsd:element name="street" type="xsd:string" minOccurs="0"/>
         <xsd:element name="city" type="xsd:string" minOccurs="0"/>
      </xsd:sequence>
   </xsd:complexType>

   <xsd:element name="customer">
      <xsd:complexType>
         <xsd:sequence>
            <xsd:element name="name" type="xsd:string" minOccurs="0"/>
            <xsd:element name="address" type="address" minOccurs="0"/>
         </xsd:sequence>
      </xsd:complexType>
   </xsd:element>

</xsd:schema>

And my test page is customer.xhtml
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets">

<h:head>
    <title>Welcome to Customer Page</title>
</h:head>

<h:body>
    <h:form>
        <h:inputText value="#{Customer.name}" />
        <h:inputText value="#{Customer.address.street}" />
        <h:commandButton value="Submit" action="#{customerHandler.save()}" />
    </h:form>
</h:body>
</html>

A: Documentation for DynamicEntity class shows us that it is an interface and nowhere states that this interface provides for good old POJO getters like getSellerAddress() that will return the desired property. As you're trying to manipulate the values as #{Customer.name} that is indeed not going to work, as there is no getName()/setName() method pair.
The methods exposed by the DynamicEntity interfaces are the following:

*

*DynamicEntity#get(propertyName) to retrieve the value and

*DynamicEntity#set(propertyName, value) to preset the value.

So there is clearly no way to use these methods to create a bilateral binding with a bean property in a standard JSF way.

You have the following choices to deal with your problem:

*

*Switch to JPA and create real entities like @Entity public class Customer as your model. This is clearly the best way to go further and the best practice;

*Create a placeholder/backing bean to a JSF form to keep the submitted values and create your dynamic entity in the action method for further manipulation. Be aware that you will miss all the points of JSF if you decide to follow this route;

*Most probably the implementation of DynamicEntity (that is, the instance returned from the call to DynamicJAXBContext#newDynamicEntity(String n)) is backed by a Map implementation. Debug to see what that call returns and apply that information to your use case. In case it's backed by a map with a public getter/setter pair with the name persistentMap your EL will become #{Customer.persistentMap['name']. Be aware that this is a discouraged practice and an example of tight coupling and is possible in case there are accessors for the backed collection.

To sum it up, I'd highly recommended to switch to JPA to solve your use case.


text:
Q: Specify which network interface to use for nfsroot I am running a server (Ubuntu 16.04) which has two network cards eno1 and eno2.

*

*eno1 is connected to the outside and receives a public IP address over dhcp

*eno2 is connected to a private network and receives a private IP address over dhcp (say 192.168.0.2 for simplicity)

The server netboots and receives everything from a second server on the private network (say 192.168.0.1). I follwed the Diskless Ubuntu HowTo and everything works pretty well.

*

*the server gets 192.168.0.2 as ip address

*then it loads the kernel and initramfs over tftp (from 192.168.0.1) and continues

*later it mounts / which is also located on 192.168.0.1

With the last step there is however a problem. More or less simultaneously the system tries to get IP addresses for both eno1 and eno2, and sometimes eno1 finishes first. Then the system tries to find 192.168.0.1 through eno1, which it of course can't and times out.
As stated in the tutorial I included iface eno2 inet manual in my /etc/network/interfaces, to prevent eno2 from losing its address, but this does not seem to help.
Any idea how to force it to use eno2 instead of whichever network interface to use first

A: For a long answer, look at the nfsroot documentation.
The default behavior is to use the first interface configured for the nfsroot. In your case it is somehow random, since you've got two interface connected to two different networks.
You can force the network interface used for the nfsroot by adding this to the kernel command line : ip=:::::eno2:dhcp.
In case of the netboot tutorial this goes in the  /tftboot/pxelinux.cfg/default file in the APPEND line. (Replaces the ip=dhcp)

redpajama_set_name: RedPajamaStackExchange


text:
Q: R Improve performance of function(s) This question is related to my previous one. Here is a small sample data. I have used both data.table and data.frame to find a faster solution.
test.dt <- data.table(strt=c(1,1,2,3,5,2), end=c(2,1,5,5,5,4), a1.2=c(1,2,3,4,5,6),
                   a2.3=c(2,4,6,8,10,12), a3.4=c(3,1,2,4,5,1), a4.5=c(5,1,15,10,12,10),
                   a5.6=c(4,8,2,1,3,9))

test.dt[,rown:=as.numeric(row.names(test.dt))]

test.df <- data.frame(strt=c(1,1,2,3,5,2), end=c(2,1,5,5,5,4), a1.2=c(1,2,3,4,5,6),
                   a2.3=c(2,4,6,8,10,12), a3.4=c(3,1,2,4,5,1), a4.5=c(5,1,15,10,12,10),
                   a5.6=c(4,8,2,1,3,9))

test.df$rown <- as.numeric(row.names(test.df))

    > test.df
  strt end a1.2 a2.3 a3.4 a4.5 a5.6 rown
1    1   2    1    2    3    5    4    1
2    1   1    2    4    1    1    8    2
3    2   5    3    6    2   15    2    3
4    3   5    4    8    4   10    1    4
5    5   5    5   10    5   12    3    5
6    2   4    6   12    1   10    9    6

I want to use the start and end column values to determine the range of columns to subset (columns from a1.2 to a5.6) and obtain the mean. For example, in the first row, since strt=1 and end=2, I need to get the mean of a1.2 and a2.3; in the third row, I need to get the mean of a2.3, a3.4, a4.5, and a5.6
The output should be a vector like this
> k
       1        2        3        4        5        6
1.500000 2.000000 6.250000 5.000000 3.000000 7.666667

Here, is what I tried:
Solution 1: This uses the data.table and applies a function over it.
func.dt <- function(rown, x, y) {
      tmp  <- paste0("a", x, "." , x+1)
      tmp1 <- paste0("a", y, "." , y+1)
      rowMeans(test.dt[rown,get(tmp):get(tmp1), with=FALSE])
      }
    k <- test.dt[, func.dt(rown, strt, end), by=.(rown)]

Solution 2: This uses the data.frame and applies a function over it.
func.df <- function(rown, x, y) {
  rowMeans(test.df[rown,(x+2):(y+2), drop=FALSE])
  }
k1 <- mapply(func.df, test.df$rown, test.df$strt, test.df$end)

Solution 3: This uses the data.frame and loops through it.
    test.ave <- rep(NA, length(test1$strt))
for (i in 1 : length(test.df$strt)) {
    test.ave[i] <- rowMeans(test.df[i, as.numeric(test.df[i,1]+2):as.numeric(test.df[i,2]+2), drop=FALSE])
    }

Benchmarking shows that Solution 2 is the fastest.
test replications elapsed relative user.self sys.self user.child sys.child
1 sol1          100    0.67    4.786      0.67        0         NA        NA
2 sol2          100    0.14    1.000      0.14        0         NA        NA
3 sol3          100    0.15    1.071      0.16        0         NA        NA

But, this is not good enough for me. Given the size of my data, these functions would need to run for a few days before I get the output. I am sure that I am not fully utilizing the power of data.table and I also know that my functions are crappy (they refer to the dataset in the global environment without passing it). Unfortunately, I am out of my depth and do not know how to fix these issues and make my functions fast. I would greatly appreciate any suggestions that help in improving my function(s) or point to alternate solutions.

A: Unless you can think of a way to do this with a clever subsetting approach,  I think you've reached R's speed barrier.  You'll want to use a low-level language like C++ for this problem.  Fortunately, the Rcpp package makes interfacing with C++ in R simple.  Disclaimer: I've never written a single line of C++ code in my life.  This code may be very inefficient.
library(Rcpp)

cppFunction('NumericVector MYrcpp(NumericMatrix x) {
  int nrow = x.nrow(), ncol = x.ncol();
  NumericVector out(nrow);

  for (int i = 0; i < nrow; i++) {
    double avg = 0;

    int start = x(i,0);
    int end = x(i,1);

    int N = end - start + 1;

    while(start<=end){

      avg += x(i, start + 1);

      start = start + 1;

    }

    out[i] = avg/N;

  }
  return out;
}')

For this code I'm going to pass the data.frame as a matrix (i.e. testM <- as.matrix(test.df))
Let's see if it works...
 MYrcpp(testM)
[1] 1.500000 2.000000 6.250000 5.000000 3.000000 7.666667

How fast is it?
Unit: microseconds
          expr      min        lq      mean   median       uq       max neval
          f2() 1543.099 1632.3025 2039.7350 1843.458 2246.951  4735.851   100
          f3() 1859.832 1993.0265 2642.8874 2168.012 2493.788 19619.882   100
          f4()  281.541  315.2680  364.2197  345.328  375.877  1089.994   100
 MYrcpp(testM)    3.422   10.0205   16.7708   19.552   21.507    56.700   100

Where f2(), f3() and f4() are defined as
f2 <- function(){
  func.df <- function(rown, x, y) {
    rowMeans(test.df[rown,(x+2):(y+2), drop=FALSE])
  }
  k1 <- mapply(func.df, test.df$rown, test.df$strt, test.df$end)
}

f3 <- function(){
  test.ave <- rep(NA, length(test.df$strt))
  for (i in 1 : length(test.df$strt)) {
    test.ave[i] <- rowMeans(test.df[i,as.numeric(test.df[i,1]+2):as.numeric(test.df[i,2]+2), drop=FALSE])
  }
}

f4 <- function(){
  lapply(
    apply(test.df,1, function(x){
      x[(x[1]+2):(x[2]+2)]}),
    mean)
}

That's roughly a 20x increase over the fastest.
Note, to implement the above code you'll need a C complier which R can access.  For windows look into Rtools.  For more on Rcpp read this
Now let's see how it scales.
N = 5e3
test.df <- data.frame(strt = 1,
                 end = sample(5, N, replace = TRUE),
                 a1.2 = sample(3, N, replace = TRUE),
                 a2.3 = sample(7, N, replace = TRUE),
                 a3.4 = sample(14, N, replace = TRUE),
                 a4.5 = sample(8, N, replace = TRUE),
                 a5.6 = sample(30, N, replace = TRUE))
test.df$rown <- as.numeric(row.names(test.df))

test.dt <- as.data.table(test.df)

microbenchmark(f4(), MYrcpp(testM))
Unit: microseconds
          expr       min         lq        mean     median          uq       max neval
          f4() 88647.256 108314.549 125451.4045 120736.073 133487.5295 259502.49   100
 MYrcpp(testM)   196.003    216.533    242.6732    235.107    261.0125    499.54   100

With 5e3 rows MYrcpp is now 550x faster.  This partially due to the fact that f4() is not going to scale well as Richard discusses in the comment.  The f4() is essentially invoking a nested for loop by calling an apply within a lapply.  Interestingly, the C++ code is also invoking a nested loop by utilizing a while loop inside a for loop.  The speed disparity is due in large part to the fact that the C++ code is already complied and does not need to be interrupted into something the machine can understand at run time.
I'm not sure how big your data set is, but when I run MYrcpp on a data.frame with 1e7 rows, which is the largest data.frame I could allocate on my crummy laptop, it ran in 500 milliseconds.
Update: R equivalent of C++ code
MYr <- function(x){
  nrow <- nrow(x)
  ncol <- ncol(x)
  out <- matrix(NA, nrow = 1, ncol = nrow)

  for(i in 1:nrow){
    avg <- 0

    start <- x[i,1]
    end <- x[i,2]

    N <- end - start + 1

    while(start<=end){

      avg <- avg + x[i, start + 2]

      start = start + 1

    }

    out[i] <- avg/N

  }

  out

}

Both MYrcpp and MYr are similar in many ways.  Let me discuss a couple of the differences

*

*The first line of MYrcpp is different from the MYr. In words the first line of MYrcpp, NumericVector MYrcpp(NumericMatrix x), means that we are defining a function whose name is MYrcpp which returns an output of class NumericVector and takes an input x of class NumericMatrix.

*In C++ you have to define the class of a variable when you introduce it, i.e. int nrow = x.row() is a variable whose name is nrow whose class is int (i.e. integer) and is assigned to be x.nrow() i.e. the number of rows of x.  (IGNORE if you're overwhelmed, nrow() is a method for instances of class `NumericVector.  Like in Python you call a method by attaching it to the instance.  The R equivalent is S3 and S4 methods)

*When you subset in C++ you use () instead of [] like in R.  Also, indexing begins at zero (like in Python).  For example, x(0,1) in C++ is equivalent to x[1,2] in R

*++ is an operator that means increment by 1, i.e. j++ is the same as j + 1. += is an operator that means add to together and assign, i.e. a += b is the same as a = a + b

A: I was curious how fast I could make this without resorting to writing custom C or C++ code. The best I could come up with is below. Note that using mean.default will provide greater precision, since it does a second pass over the data for error correction.
f_jmu <- compiler::cmpfun({function(m) {
  # remove start/end columns from 'm' matrix
  ma <- m[,-(1:2)]
  # column index for each row in 'ma' matrix
  cm <- col(ma)
  # logical index of whether we need the column for each row
  i <- cm >= m[,1L] & cm <= m[,2L]
  # multiply the input matrix by the index matrix and sum it
  # divide by the sum of the index matrix to get the mean
  rowSums(i*ma) / rowSums(i)
}})

The Rcpp function is still faster (not surprisingly), but the function above gets respectably close. Here's an example on 50 million observations on my laptop with an i7-4600U and 12GB of RAM.
set.seed(21)
N <- 5e7
test.df <- data.frame(strt = 1L,
                 end = sample(5, N, replace = TRUE),
                 a1.2 = sample(3, N, replace = TRUE),
                 a2.3 = sample(7, N, replace = TRUE),
                 a3.4 = sample(14, N, replace = TRUE),
                 a4.5 = sample(8, N, replace = TRUE),
                 a5.6 = sample(30, N, replace = TRUE))
test.df$strt <- pmax(1L, test.df$end - sample(3, N, replace = TRUE) + 1L)
test.m <- as.matrix(test.df)

Also note that I take care to ensure that test.m is an integer matrix. That helps reduce the memory footprint, which can help make things faster.
R> system.time(st1 <- MYrcpp(test.m))
   user  system elapsed
  0.900   0.216   1.112
R> system.time(st2 <- f_jmu(test.m))
   user  system elapsed
  6.804   0.756   7.560
R> identical(st1, st2)
[1] TRUE

A: My solution is the first one in the benchmark
library(microbenchmark)
microbenchmark(
  lapply(
    apply(test.df,1, function(x){
        x[(x[1]+2):(x[2]+2)]}),
    mean),
  test.dt[, func.dt(rown, strt, end), by=.(rown)]
)

      min        lq      mean   median       uq      max neval
  138.654  175.7355  254.6245  201.074  244.810 3702.443   100
 4243.641 4747.5195 5576.3399 5252.567 6247.201 8520.286   100

It seems to be 25 times faster, but this is a small dataset. I am sure there is a better way to do this than what I have done.


text:
Q: UITableView load more when scrolling to bottom using Rxswift I am working with web api which load array of data. But the size of data is big, So I want to apply lazy loading, data on demand technique so that I can quickly load small chunk of data and when user reach the last element of tableview cell then it can load next chunk of data. I want to know is it possible with Rxswift?

A: Maybe you could try this liabrary. Set query amount and index when loading data.
https://github.com/RxSwiftCommunity/RxPager


text:
Q: How can I limit the maximum number of lines in a page? My university's masters thesis template which I have to follow, limits the maximum number lines per page to 25 lines.
I used setspace package which is available in the revision of my question but it didn't help me. Also, I used the lines option of the geometry package as proposed in the answers but it does not set the line spacing. Instead it omits the content after the specified line number and consequently, the rest of the page will be remained. Here is the second code I used with geometry option.
\documentclass[a4paper,11pt,twoside,openany]{book}
\usepackage{lipsum}
\RequirePackage[top=35mm, outer=35mm, inner=25mm, lines=22]{geometry}
\begin{document}
\lipsum[1-10]
\end{document}

A: Use lines  option in geometry package. The following is taken from its documentation on page 16.

If you don't know how to display the documentation, type texdoc geometry on your terminal (Linux) or DOS prompt (MS Windows).

A: First, let us see how to show the edges of the margins (showframe option), the numbers of lines (with lineno package and \linenumbers command) and \the\textheightof the MWE:
\documentclass[11pt,a4paper,twoside,openany]{book}
\usepackage[lmargin=25mm,rmargin=35mm,tmargin=35mm, bmargin=35mm,showframe]{geometry}
\usepackage{lineno}
\usepackage{lipsum}
\begin{document}
\linenumbers
THE TEXT HEIGHT: \the\textheight\\

\lipsum[1-10]
\end{document}

There are 47 lines in roughly 646pt with the desired margins. The goal is obtain 22 lines without change the text height. Right?
Solution 1. Use the \setstretch{2.2} (need the setspace package)
\documentclass[11pt,a4paper,twoside,openany]{book}
\usepackage[lmargin=25mm,rmargin=35mm,tmargin=35mm, bmargin=35mm,showframe]{geometry}

\usepackage{setspace}
\setstretch{2.2}

\usepackage{lineno}
\usepackage{lipsum}
\begin{document}
\linenumbers
THE TEXT HEIGHT: \the\textheight\\

\lipsum[1-10]
\end{document}

Solution 2: set \baselineskip at 29pt in the body of the document
\documentclass[11pt,a4paper,twoside,openany]{book}
\usepackage[lmargin=25mm,rmargin=35mm,tmargin=35mm, bmargin=35mm,showframe]{geometry}

\usepackage{lineno}
\usepackage{lipsum}

\begin{document}

\baselineskip=29pt % not in the preamble

\linenumbers
THE TEXT HEIGHT: \the\textheight\\ %646pt

\lipsum[1-10]
\end{document}

Solution 3: fix \linespread  to 2.2 in the preamble
\documentclass[11pt,a4paper,twoside,openany]{book}
\usepackage[lmargin=25mm,rmargin=35mm,tmargin=35mm, bmargin=35mm,showframe]{geometry}
\linespread{2.2}

\usepackage{lineno}
\usepackage{lipsum}
\begin{document}
\linenumbers
THE TEXT HEIGHT: \the\textheight\\

\lipsum[1-10]
\end{document}

In solution 1,2 and 3: the ouput is the same:

Solution 4. Use the grid package with the options lines and baseline. Only useful if you are a fan of the grid format and the package limitations are not a problem in your document.
\documentclass[11pt,a4paper,twoside,openany]{book}
\usepackage[lmargin=25mm,rmargin=35mm,tmargin=35mm, bmargin=35mm,showframe]{geometry}
\usepackage[baseline=29.35pt,lines=22]{grid}

\usepackage{lineno}
\usepackage{lipsum}
\begin{document}
\linenumbers
THE TEXT HEIGHT: \the\textheight\\

\lipsum[1-10]
\end{document}

A: You can do this with setspace and geometry but you must use the spacing command before loading geometry. This still has a rather large margin at the bottom so it is probably best to allow geometry to figure the top and bottom margin and just specify a ratio if you do it this way:
\documentclass[a4paper,11pt,twoside,openany]{book}
\usepackage{setspace}
  \doublespacing
\RequirePackage[vmarginratio=1:2, outer=35mm, inner=25mm, lines=22]{geometry}
\usepackage{lipsum}
\begin{document}
  \lipsum[1-10]
\end{document}

stdpage apparently lets you specify a standard number of lines per page and will space them out. However, unless you want your thesis to look as if typed on a typewriter, this is probably not a good option.


text:
Q: What are the implications of superliminal neutrinos?
Possible Duplicates:
What would be the immediate effects if light does not go at the maximum speed possible?
Superluminal neutrinos

Do we re-write physics? Or can it be fitted in current theories? I always hear about Lorentz violation in Plank scale or somewhere there. But what about this?


text:
Q: TabviewController How to show the unread messages like as badges?
Here i am using the 4 tabViews, third one is chat button so here user unread messages how to show the badges
in #import "HomeTabViewController.h"
 - (void)viewDidLoad {
  [super viewDidLoad];
    NSString *badgeVal = @"5";
  [[[[self.tabBarController viewControllers] objectAtIndex:2]  tabBarItem] setBadgeValue:badgeVal];
  }

A: You need to simply set badgeValue property of tabBarItem for that.
NSString *badgeVal = @"5"; //Unread message count
[[[[self.tabBarController viewControllers] objectAtIndex:2] tabBarItem] setBadgeValue:badgeVal];

Note : I have access 3rd ViewController using objectAtIndex:2 because you want to set badge for the 3rd UITabBarItem.

A: Well, just use the badgeValue property of the UITabbarItem:
https://developer.apple.com/reference/uikit/uitabbaritem/1617065-badgevalue

A: Try this.
NSString *badgeVal = @"5"; //Unread message count
[[self navigationController] tabBarItem].badgeValue = badgeVal;

or
[[self.tabBarController.tabBar.items objectAtIndex:<your item position>] setBadgeValue:[NSString stringWithFormat:@"%d",badgeVal]];


text:
Q: How do I kick off an entity stored procedure in EF6 async and not wait for a return? I'd like to just punt a call over to the SQL Server and not wait for a return. I have an imported Entity Function from a Stored Procedure that I'd like to call asynchronously this way in Entity Framework 6.0.0-rc1.  Is this possible?  What's the syntax?
Entity Function: RecalculateBudgetNumbers(int id)

A: Start a new Task that creates a fresh data context and invokes that function. Just don't wait/await that task. Let it run by itself to completion.
Make sure to log errors. Don't swallow exceptions because they might be bugs you want to know about.
In an ASP.NET setting, be aware that the worker process can recycle at any time at all, so your background work can suddenly disappear (or be cancelled).

A: Ahh.  I was in Entity Framework land too long.  Thanks for the tips.  Here's what worked for me.  Do you see any problems with this?
    /// <summary>
    /// kicks off the LONG RUNNING calculations on a budget to regenerate all pre-cooked numbers.
    /// </summary>
    /// <param name="budgetId">Budget Id</param>
    public async System.Threading.Tasks.Task RecalculateBudgetNumbersAsync(int budgetId)
    {
        await System.Threading.Tasks.Task.Factory.StartNew(() => RecalculateBudgetNumbers(budgetId));
    }

    public static void RecalculateBudgetNumbers(int budgetId)
    {
        //this is static so we don't use the unit of work..
        using (BMTContext ctx = new BMTContext())
        {
            ctx.UpdateLifeOfBudgetNumbers(budgetId);
            ctx.UpdateIntervalNumbers(budgetId);
            ctx.UpdateIntervalActivityNumbers(budgetId);
            ctx.UpdateLifeOfBudgetActivityNumbers(budgetId);
        }
    }

And my test (I'm in Visual Studio 2012 so I can do an async test).
    [TestMethod]
    public async System.Threading.Tasks.Task RecalculateBudgetNumbersAsyncTest()
    {
        System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
        timer.Start();
        await repo.RecalculateBudgetNumbersAsync(budgetId);

        System.Console.WriteLine("RecalculateBudgetNumbersAsyncTest milliseconds: " + timer.ElapsedMilliseconds.ToString());
    }

After suggestions from Matt Smith and Usr, I changed RecalculateBudgetNumbersAsync to this. I hope this is what they meant:
    public void RecalculateBudgetNumbersAsync(int budgetId)
    {
        System.Threading.Tasks.Task.Factory.StartNew(() => RecalculateBudgetNumbers(budgetId));
    }


text:
Q: template method specialisation problem Can anyone help me with this code. I'm trying to specialise a method. At the moment it doesn't work with one specialisation (1) but I'd like to ultimately have lots of specialisations (2, 3, 4, 5 etc)
class X
{
public:

    // declaration
    template< int FLD >
    void set_native( char *ptr, unsigned int length );

    // specialisations

    template<> void set_native< 1 >( char *ptr, unsigned int length )
    {
    }

};

The error messages I'm getting are..
x.cpp:13: error: explicit specialization in non-namespace scope 'class X'
x.cpp:13: error: template-id 'set_native<1>' for 'void set_native(char*, unsigned int)' does not match any template declaration
x.cpp:13: error: invalid function declaration

A: Try the following
class X
{
public:

    // declaration
    template< int FLD >
    void set_native( char *ptr, unsigned int length );
};

// specialisations
template<> void X::set_native< 1 >( char *ptr, unsigned int length )
{
}

If it does not work, try adding a templated class behind set_native
template<int FLD> class SetNative;
class X
{
public:
    // declaration
    template< int FLD >
    void set_native( char *ptr, unsigned int length )
    { return SetNative()(ptr, length); }
};
template<> class SetNative<1>
{
  void operator()( char *ptr, unsigned int length ){...}
};

A: As Benoit proposed, you have to specialize the member function in the surrounding namespace:
struct X {
    template<int N> void f() {}
};

template<> void X::f<1>() {} // explicit specialization at namespace scope

This is because of §14.7.3 (C++03):

An explicit specialization shall be declared in the namespace of which the template is a member, or, for member templates, in the namespace of which the enclosing class or enclosing class template is a member.

VC however doesn't conform to the standard in that regard and thus creates some portability headaches.


text:
Q: Purely Laravel: I would like to generate a key (token) on the page and then tell users to insert the key in a form in order to process the form Who is asking? - Question is coming from less than 6 months old PHP developer who fell completely in love with PHP due to its awesomeness, also I just joined STACKOVERFLOW today 7th Dec, 2019.
Reason for the question: I have a form which I have completely built and validated with Laravel but I want to protect it from spam not with recaptcha but with a pin (a kind of generated key). I've seen it used on various websites and I also want to apply it.
Plan of action: The generated code will be placed at the end of the form with an input field and on filling it, it must match the code generated on every page refresh. If it doesn't match, I want to kill the page or perhaps, display a page with a "WELL DONE" message.
My thoughts: I'm new here and maybe the question might have been asked before, but honestly I've been on the computer for over a week (spending at least 18 hours searching and searching) but no really understandable solution.
What I can't do: Because I'm using Laravel, I don't know where to start this functionality and how to end it.
My helper: You are reading this and I believe you have the skills and techniques to help me without sweating at all. Just imagine a friend whose head is floating but the body is already in the ocean and about to drown. Also imagine a friend who has only one shot (2 days) to change his life, and if not done, only God knows what's to come. PLEASE HELP ME!
To everyone: Forgive me for the long message, I just believe that if I can express myself deeply enough, someone out there will help me out.
Thank you to all the awesome developers around the world.


text:
Q: Predictions using Support Vector Regression In my problem there are four features(X); a,b,c,d and two dependents(Y); e,f. I have with me a data set containing a set of values for all these variables. How can I predict the values through Support Vector Regression using scikit learn in python, for the e,f variables when new a,b,c,d values are given?
I'm very new to ML and I would really appreciate some guidance since I found it very difficult to follow the scikit learn documentation on SVR.
This is what I have done so far with the help of an example in the sklearn documentation.
train = pd.read_csv('/Desktop/test.csv')
X = train.iloc[:, 4]
y = train.iloc[:, 4:5]

svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0.1)
y_rbf = svr_rbf.fit(X, y).predict(X)

lw = 2
plt.scatter(X, y, color='darkorange', label='data')
plt.plot(X, y_rbf, color='navy', lw=lw, label='RBF model')
plt.xlabel('data')
plt.ylabel('target')
plt.title('Support Vector Regression')
plt.legend()
plt.show()

This gives the error,

ValueError: Expected 2D array, got 1D array instead:
  :
  Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

A: I'm assuming that your target variables need to be independently predicted here, so correct me if I'm wrong. I've slightly modified the sklearn doc example to illustrate what you need to do. Please do consider scaling your data before performing the regression.
import numpy as np
from sklearn import svm
import matplotlib.pyplot as plt

n_samples, n_features = 10, 4 # your four features a,b,c,d are the n_features
np.random.seed(0)
y_e = np.random.randn(n_samples)
y_f = np.random.randn(n_samples)

# your input array should be formatted like this.
X = np.random.randn(n_samples, n_features)

#dummy parameters - use grid search etc to find best params
svr_rbf = svm.SVR(kernel='rbf', C=1e3, gamma=0.1)
# Fit and predict for one target, do the same for the other
y_pred_e = svr_rbf.fit(X, y_e).predict(X)

A: Assuming your data file has 6 columns, and the feature values are in the the first 4 columns, and the targets (which you call 'dependents') are in the final 2 columns, then I think you need to do this instead:
train = pd.read_csv('/Desktop/test.csv')
X = train.iloc[:, 0:3]
y = train.iloc[:, 4:5]


text:
Q: Spring data lazy load not working I have the two entities similar to the ones below:
@Entity
@DynamicUpdate
public class EntityOne {
    @Id
    public long id;

    public String name;
    public String displayName;

    @JsonManagedReference
    @OneToMany(mappedBy = "id", cascade = CascadeType.ALL)
    @OrderBy(value = "name")
    public List<EntityTwo> entityTwoList;
}

entity two is
@Entity
@DynamicUpdate
public class EntityTwo {
    @Id
    public long id;

    @JsonBackReference
    @ManyToOne
    @JoinColumn(name = "id")
    public EntityOne entityOne;
}

service:
Lists.newArrayList(repository.findAll());
The service calls the findAll() method of the CRUDRepository. I don't want the list of entity two objects to load when calling findall() but this solution doesn't work.
Anything incorrect that i am doing here to lazy load the collection. I basically don't want the collection to be loaded until its specified.
By default the mappings are lazy load.

A: I am assuming jackson is trying to load your child objects.
Try followjackson-datatype-hibernate4:2.4.4
Add jackson-datatype-hibernate4:2.4.4 to your dependency and define following bean
@Bean
public Jackson2ObjectMapperBuilder configureObjectMapper() {
return new Jackson2ObjectMapperBuilder()
    .modulesToInstall(Hibernate4Module.class);
}

A: I don't know about jackson but according to jpa specs you can not force LAZY loading neither can you rely upon it ... you just provide the lazy load hint and it's totally up to the provider to load it lazily or not (unlike EAGER , it forces loading)

A: First try this,i think you need to specify fetch type lazy or Eager
   ManyToOne(fetch= FetchType.LAZY)


text:
Q: Смена вкладки при разных utm_term Выручайте пожалуйста... Есть три вкладки. По умолчанию активна первая. Как можно сделать, чтобы при определенной utm метке, были открыты разные вкладки. Например, если utm_term=tab3, чтобы активной была вкладка tab3. Кто разбирается подскажите пожалуйста. Буду очень признательным!

        Вкладка 1

        Вкладка 2

        Вкладка 3

        Контент вкладки 1

        Контент вкладки 2

        Контент вкладки 3

A: Сначала гуглим как получить URL-параметр в js.
Затем гуглим Bootstrap Tabs

function getParameter(parameterName) {
  var result = null,
    tmp = [];
  location.search.substr(1).split("&").forEach(item => {
    tmp = item.split("=");
    if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
  });
  return result;
}

// const tabName = getParameter("utm_term");
const tabName = "tab2"; // Для теста
if (tabName) {
  $(`a[data-toggle='tab'][href^='#${tabName}']`).tab('show');
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

    Вкладка 1

    Вкладка 2

    Вкладка 3

    Контент вкладки 1

    Контент вкладки 2

    Контент вкладки 3


text:
Q: RecyclerView store / restore state between activities I'm migrating my ListViews to RecyclerViews. With listviews I used the common technique described here to store and restore scroll position between activities.
How to do the same with RecyclerViews? the RecyclerView.onSaveInstanceState() seem to have protected access, so can't be used directly.

A: Ok, so to answer my own question. As I understand it, since they've decoupled the layout code and the view recycling code (thus the name), the component responsible one for holding layout state (and restoring it) is now the LayoutManager used in your recyclerview.
Thus, to store state you use same pattern, but on the layout manager and not the recyclerview:
protected void onSaveInstanceState(Bundle state) {
     super.onSaveInstanceState(state);

     // Save list state
     mListState = mLayoutManager.onSaveInstanceState();
     state.putParcelable(LIST_STATE_KEY, mListState);
}

Restore state in the onRestoreInstanceState():
protected void onRestoreInstanceState(Bundle state) {
    super.onRestoreInstanceState(state);

    // Retrieve list state and list/item positions
    if(state != null)
        mListState = state.getParcelable(LIST_STATE_KEY);
}

Then update the LayoutManager (I do in onResume()):
@Override
protected void onResume() {
    super.onResume();

    if (mListState != null) {
        mLayoutManager.onRestoreInstanceState(mListState);
    }
}

A: That's my solution, it restores both items and RecyclerView position
1) save recycler view state in onSaveInstanceState method
@Override
protected void onSaveInstanceState(Bundle outState) {
    Parcelable listState = myRecyclerView.getLayoutManager().onSaveInstanceState();
    // putting recyclerview position
    outState.putParcelable(SAVED_RECYCLER_VIEW_STATUS_ID, listState);
    // putting recyclerview items
    outState.putParcelableArrayList(SAVED_RECYCLER_VIEW_DATASET_ID,mDataset);
    super.onSaveInstanceState(outState);
}

2) Check savedInstanceState Bundle in onCreate method
@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState==null){
            getRemoteData(); // No saved data, get data from remote
        }else{
            restorePreviousState(); // Restore data found in the Bundle
        }
    }

3) Restore recycler view data if the screen has been rotated
public void restorePreviousState(){
    // getting recyclerview position
    mListState = mSavedInstanceState.getParcelable(SAVED_RECYCLER_VIEW_STATUS_ID);
    // getting recyclerview items
    mDataset = mSavedInstanceState.getParcelableArrayList(SAVED_RECYCLER_VIEW_DATASET_ID);
    // Restoring adapter items
    mAdapter.setItems(mDataset);
    // Restoring recycler view position
    mRvMedia.getLayoutManager().onRestoreInstanceState(mListState);
}

A: I found a better solution - this solution has the following benefits :

*

*RecyclerView state is saved and restored on rotation of phone

*RecyclerView state is saved and restored on returning to activity with RecyclerView (which wasn't destroyed whilst the other activity was showing - which means that onRestoreInstanceState() isn't called !!)

CODE
public class ActivityItemList extends AppCompatActivity
{
    private final String KEY_RECYCLER_STATE = "recycler_state";
    private RecyclerView mRecyclerView;
    private static Bundle mBundleRecyclerViewState;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);//set to whatever layout name you have

        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);//set to whatever view id you use
        // don't forget to set your adapter
    }

    @Override
    protected void onPause()
    {
        super.onPause();

        // save RecyclerView state
        mBundleRecyclerViewState = new Bundle();
        Parcelable listState = mRecyclerView.getLayoutManager().onSaveInstanceState();
        mBundleRecyclerViewState.putParcelable(KEY_RECYCLER_STATE, listState);
    }

    @Override
    protected void onResume()
    {
        super.onResume();

        // restore RecyclerView state
        if (mBundleRecyclerViewState != null) {
            Parcelable listState = mBundleRecyclerViewState.getParcelable(KEY_RECYCLER_STATE);
            mRecyclerView.getLayoutManager().onRestoreInstanceState(listState);
        }
    }
}

A: I know i am late but still if it helps!!
Storing the recycler view position is lot simpler than what other answers have made it look like
Here's how you can do it
First create a member variable
Parcelable state;

Now,
@Override
protected void onPause() {
    super.onPause();
    state = recyclerView.getLayoutManager().onSaveInstanceState();
}

@Override
protected void onResume() {
    super.onResume();
    recyclerView.getLayoutManager().onRestoreInstanceState(state);
}

overide on pause and on resume methods with the above code and you are good to go!!

A: Use this code in onPause() and onResume() to save and restore scroll position-
private Parcelable recyclerViewState;
recyclerViewState = mrecyclerView.getLayoutManager().onSaveInstanceState();//save
mrecyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);//restore

A: You can either use adapter.stateRestorationPolicy = StateRestorationPolicy.PREVENT_WHEN_EMPTY which is introduced in recyclerview:1.2.0-alpha02
https://medium.com/androiddevelopers/restore-recyclerview-scroll-position-a8fbdc9a9334
but it has some issues such as not working with inner RecyclerView, and some other issues you can check out in medium post's comment section.
Or you can use ViewModel with SavedStateHandle which works for inner RecyclerViews, screen rotation and process death.
Create a ViewModel with saveStateHandle
val scrollState=
    savedStateHandle.getLiveData<Parcelable?>(KEY_LAYOUT_MANAGER_STATE)

use Parcelable scrollState to save and restore state as answered in other posts or by adding a scroll listener to RecyclerView and
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
        super.onScrollStateChanged(recyclerView, newState)
        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
           // save here
        }
    }

A: When you use recyclerView.getLayoutManager().onSaveInstanceState() don't forget to check for null:
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);

    if (recyclerView != null) {
        outState.putParcelable(SCROLL_POSITION, recyclerView.getLayoutManager().onSaveInstanceState());
    }
}

A: Considering that you defined a RecyclerView (mRecyclerView) and a LayoutManager (mLayoutManager) in your code and all is working fine so far, the solution on saving the position (mPosition) of your RecyclerView looks like this:

*

*Variables and constants used:
private final String RECYCLER_POSITION_KEY = "recycler_position";
private int mPosition = RecyclerView.NO_POSITION;
private RecyclerView mRecyclerView;
private LinearLayoutManager mLayoutManager;
private static Bundle mBundleState;

*In onPause method:
@Override
protected void onPause()
{
    super.onPause();

    // Save RecyclerView state
    mBundleState = new Bundle();
    mPosition = mLayoutManager.findFirstCompletelyVisibleItemPosition();
    mBundleState.putInt(RECYCLER_POSITION_KEY, mPosition);
}

*In onResume method:
@Override
protected void onResume()
{
    super.onResume();

    // Restore RecyclerView state
    if (mBundleState != null) {
        mPosition = mBundleState.getInt(RECYCLER_POSITION_KEY);
        if (mPosition == RecyclerView.NO_POSITION) mPosition = 0;
        // Scroll the RecyclerView to mPosition
        mRecyclerView.smoothScrollToPosition(mPosition);
    }
}

*In onSaveInstanceState method:
@Override
public void onSaveInstanceState(Bundle outState) {
    // Save RecyclerView state
    outState.putInt(RECYCLER_POSITION_KEY,  mLayoutManager.findFirstCompletelyVisibleItemPosition());

    super.onSaveInstanceState(outState);
}

*In onRestoreInstanceState method:
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    // Restore RecyclerView state
    if (savedInstanceState.containsKey(RECYCLER_POSITION_KEY)) {
        mPosition = savedInstanceState.getInt(RECYCLER_POSITION_KEY);
        if (mPosition == RecyclerView.NO_POSITION) mPosition = 0;
        // Scroll the RecyclerView to mPosition
        mRecyclerView.smoothScrollToPosition(mPosition);
    }

    super.onRestoreInstanceState(savedInstanceState);
}

A: public class MainActivity extends AppCompatActivity {
Parcelable recyclerViewState;
.......
@Override
    protected void onPause() {
        super.onPause();
        recyclerViewState = MainAnecdotesView.getLayoutManager().onSaveInstanceState();//save
    }
    @Override
    protected void onResume()
    {
        super.onResume();
        if(recyclerViewState!=null)
            MainAnecdotesView.getLayoutManager().onRestoreInstanceState(recyclerViewState);//restore
    }
}


text:
Q: obtaining the info in Matlab's workspace window \ workspace panel I would like to document each time I run a specific script that I have, in particular a list of variables and their values.
Matlab has the function who for obtaining the variables name, and whos to get more info, but what I really want is just to save the info that I already have in the "workspace panel" that is visible on the screen, where the names and values of various variables are written (sometimes it's actually the value, sometimes the size and class are mentioned). just type workspace at the command prompt, if you don't understand what I mean.
I know I can just save the entire workspace as a .mat file (and I do so), but I just want a small txt file with that info so I wont need to load matlab to see what's in that file.
Is there a simple way you are aware of that allows to access that info?

A: You can use the diary command to save the information on a .txt file:
Updated answer
You can use the output of whos whitin a loop which uses eval to display the value of the variable and store it in the diary file.
Updated code
clear all

a=peaks;
b=magic(4);
c=size(b);
d=length(a);
v_str.n=1

diary('w.txt')
whos
zzz=whos;
for i=1:length(zzz)
   eval([zzz(i).name])
end
diary off

Hope this helps.

A: To add on @il_raffa answer, maybe another solution to display variable values just like they appear in workspace browser is to use workspacefunc('getshortvalue', eval(varname)) instead of direct call to eval(varname):
v = whos();
for idx = 1:length(v)
    name = v(idx).name;
    value = workspacefunc('getshortvalue', eval(name));
    fprintf(1, '%s\t\t\t\t\t\t%s\n', name, value);
end


text:
Q: Cycling the digits of a 5 digit number in a function I'm trying to solve this problem but I'm just stuck at the very end.
I need to make a function that cycles the 5 digit number around. So for example, the input is 12345 and then it should be 51234, 45123 etc. Then when it cycles it out, until it's at the beginning again which is 12345, it should print out the biggest number of all of the cycled ones.
def number_cycle(number):
    if number >= 99999 or number < 9999:#this is for limiting the number to 5 digits
        print('Error,number isnt in 5 digit format')
    else:
        e = number%10 #5th digit
        d = int(((number-e)/10)%10)#4th digit
        c = int(((((number - e)/10)-d)/10)%10)#3rd digit
        b = int(((((((number - e)/10)-d)/10)-c)/10)%10)#2nd digit
        a = int(((((((((number - e)/10)-d)/10)-c)/10)-b)/10)%10)#1st digit
        print(e,a,b,c,d)
        print(d,e,a,b,c)
        print(c,d,e,a,b)
        print(b,c,d,e,a)
        print(a,b,c,d,e)

   number = eval(input('Input number:'))

I can't figure out how to get the biggest number out of all these.
Can you help?

A: You can try this solution:
def get_largest(number):
    num_str = str(number)
    num_len = len(num_str)

    if num_len != 5:
        print(f"Error: {number} is not a 5 digit number")
        return

    largest = 0
    for i in range(num_len):
        cycled_number = int(num_str[i:] + num_str[:i])
        print(cycled_number)

        if cycled_number > largest:
            largest = cycled_number

    print("Largest: ", largest)

number = int(input("Input number: "))
get_largest(number)

It will basically convert your 5 digit number to a string using a for loop, and then rotate the string, compare the rotated numbers and print the largest one.
Note:
In your original code snippet I'd suggest not to use the built-in eval method as it can be quite dangerous if you don't know what you are doing so avoid it as much as you can except you really have no other way to deal with a problem. More here:

*

*https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html

*https://medium.com/swlh/hacking-python-applications-5d4cd541b3f1


text:
Q: Contigency table I am struggling to find the Java code for this problem. Firstly, I am in a beginner level and this question were hard for me to answer. I know that this used a 2D array right? But I having problem to write the Java code for this question.
Here is the question:

Write a Java program that

*

*queries a user for the number of rows and columns of a contingency table,

*read the data, row by row and

*displays the data in tabular form along with the row totals, column totals and grand
  total.

  For example if the six data of 2x3 table are
1,3,6,7,9, and 8.  the program displays these six numbers together
  with the appropriate totals as
1 3 6   | 10
7 9 8   | 24
8 12 14 | 34

The character '|' is used to separate the data from the row totals

A: I'll start by recommending that you forget about "array" and think more about "class".  Java's an object-oriented language.  Encapsulate the behavior you want in a class.  Let's call it Tableau.
You have at least four different behaviors that your class needs to get right:

*

*Reading values into a Tableau from a Stream or Reader of some kind (e.g. PrintStream, FileInputStream)

*Calculating the row and column sums for the Tableau

*Rendering the Tableau as a String.

*Writing a Tableau to an OutputStream or Writer of some kind.

Computer science is about breaking complex tasks into smaller, more manageable pieces.  It's called "decomposition".  Here's a good opportunity to learn it.
So here's a start:
package model;

public class Tableau {
    private int numRows;
    private int numCols;
    private int[][] values;

    public Tableau(int numRows, int numCols) {
        if (numRows <= 0) throw new IllegalArgumentException("numRows must be positive");
        if (numCols <= 0) throw new IllegalArgumentException("numCols must be positive");
        this.numRows = numRows;
        this.numCols = numCols;
        this.values = new int[numRows+1][numCols+1];
    }

    // You add the rest
    public String toString() {
        StringBuilder builder = new StringBuilder();

        return builder.toString();
    }
}

A: Well, in your example:
First create a 2x3 array,
Then ask the user for the inputs of each cell (hint: two for loops)
Then, as you print the rows, go over the rows and add them up to print he last number.
At the end go over the columns and add them. Hen print.
Actual code will be doing the homework for you, but if you can translate these steps into java you hold be fine and would gt a good understanding of 2D arrays.
Best.


text:
Q: How can I change CPU multiplier or CPU base Clock in real? I have i7 950 with X58_T3H6(motherboard) and I tried to increase my clock.as you can see, I change my CPU multiplier in BIOS and set it to x21, but in throttle stop, u can see that my cpu freq is 12*133MHZ. as you can see that, my CPU multiplier wasn't change!!!its stuck in x12!
also, i could change my cpu base clock(now its 133MHZ), but i cant change my cpu multiplier in real!
its just change in bios, but in real, it doesn't change after all.
i really need your Hint :)
enter image description here

A: Enable SpeedStep and press the Turn On button. You also need to enable the core C states in the BIOS, at least C3, if you want your CPU to use the maximum turbo boost multipliers.


text:
Q: HTML default value fo radio button input type based on python variable so im making a Flask app where a user uploads a spreadsheet and then can play with the parameters of that spreadsheet on a html page. One parameter is a value which can only be 1, 2 or 3. The user is able to change this value by selecting a radio button with these options.
This all works fine but i would like the default value of the radio button to be whatever was in the initial spreadsheet that the user uploaded.
my idea was to do something like this:
main.py
@app.route('/', methods=['GET','POST'])
def params_form():

    value = 2
    value_dict = {'1': 1==value, '2': 2==value, '3': 3==value}

    return render_template('home/sheet.html', value_dict)

sheet.html

    <input type="radio" id="n1" name="nyears" value=1 checked={{value_dict["1"]}}>
         1

    <input type="radio" id="n2" name="nyears" value=2 checked={{value_dict["2"]}}>
         2

    <input type="radio" id="n3" name="nyears" value=3 checked={{value_dict["3"]}}>
         3

But unfortunately, any use of the 'checked' attribute will check the box (in this case number 3, as it is the last to use the checked attribute). It seems that the only way to have a default checked value is to only use the checked attribute on one input line.
Any help getting this to work will be greatly appreciated
Thanks in advance!

A: You need to set the variable name in render_template by passing it as keyword:
@app.route('/', methods=['GET','POST'])
def params_form():

    value = 2
    value_dict = {'1': 1==value, '2': 2==value, '3': 3==value}

    return render_template('home/sheet.html', value_dict=value_dict)

    <input type="radio" id="n1" name="nyears" value=1  {{ 'checked' if value_dict["1"] else '' }} >
         1

    <input type="radio" id="n2" name="nyears" value=2  {{ 'checked' if value_dict["2"] else '' }} >
         2

    <input type="radio" id="n3" name="nyears" value=3  {{ 'checked' if value_dict["3"] else '' }} >
         3


text:
Q: Vim: colon appends .,.+3 Sometimes when entering :, vim appends .,.+3 to it, preventing me from executing a command. I couldn't find anything about this behaviour online, is there a way to get do away with it? At the moment, I use vim 8.0 (in iTerm2) but it also used to occur in earlier versions.

A: This happens when you typed a number before the colon. Vim interprets it as the number of lines on which you want your ex command to operate.
If you press 4: you get :.,.+3 which is a range that covers the current line (.) and the three lines below the current line (.+3).
That behavior is old and documented in :help N: (:help :range is an interesting read, too).
If you want to get rid of that range, see :help <C-u>.


text:
Q: Data Designer - Link Data Extension to Contact Model via "Domain" link I have a data extension, which contains useful attributes at a domain level (e.g. # of products owned on a given domain, account level, etc) and I'm trying to link this into the data model via data designer.
Is there an easy way to link my new DE to the contact model? I don't see any standard "domain" field on the existing contact model and I was hoping to avoid creating an email address -> domain mapping data extension.
Cheers

A: Cardinal relationships in Contact Builder are based on matching Attribute values; you can't use a substring.
The only solution would to create a Query Activity that extracts the domain part of an email address to a separate field, then you can include that Data Extension in your Contact Model.


text:
Q: gitignore pattern for autogenerated folder I run a script in my project that would generate a temporary folder in the project root. For example _MEIxX7G6H, and ts-node-94a6b447580330f9f2b609422537b04239ff3a39df9137e32efd559f1a2935cb.
That temporary folder is not meant to be in source control (Git).
It makes no sense to add those names to .gitignore because the names change after each execution.
Is there any way to add some pattern to partially match those file names?

A: Answering my own question:
# Will ignore folders prefixed with underscore
_*
# Will ignore folders prefixed with ts-node
ts-node*


text:
Q: react call method within render I'm trying to call my method onModelSelect automatically if there is only 1 item in the this.props.models array
{this.props.modelCheck &&
{this.props.modelCheck.map(item => {()=>this.onModelSelect(item.id)} )}
}
If I attach the method to an onClick event handler it works, but on it's own I'm unsure of the syntax to use as it does nothing when the component renders
 export default class App extends Component {
        onModelSelect = (modelId) => {
          this.props.selectModel(modelId);
          this.props.setModelSelected(true);
          console.log('test')
          console.log('modelId',modelId)
        }
        render() {

          return(

                {this.props.modelCheck &&
{this.props.modelCheck.map(item => {()=>this.onModelSelect(item.id)} )}
}
              {this.props.models.map(model =>

 this.onModelSelect(model.id)}>Select Model

              )}

          )
        }
      }

      const mapStateToProps = (state) => {
        const modelCheck = getFilteredSelectableModels(state).length === 1 && getFilteredSelectableModels(state)

        return {
          modelCheck,
        };
      };

      const mapDispatchToProps = (dispatch) => {
        return bindActionCreators({
          ...settingDropActions,
        }, dispatch);
      };

      export default connect(mapStateToProps, mapDispatchToProps)(SettingDropModel);

A: Why are you adding this line into your render method:
{this.props.models.length === 1 && this.props.models.map(model => ()=>this.onModelSelect(model.id))}

First of all .map in react JSX should be used to generate array of elements, which is not happening here. So this implementation is not correct.
To call onModelSelect method if there is only one model, you should call it in componentDidMount react lifecycle method.
componentDidMount(){
    if(this.props.models.length === 1){
        this.onModelSelect(this.props.models[0].id);
    }
}

A: It didn't work when placed in componentDidMount() but it did work when placed into componentWillReceiveProps()
componentWillReceiveProps(nextProps) {
    if(this.props.models.length === 1){
      this.onModelSelect(this.props.models[0].id);
    }
  }


text:
Q: Resizing the boxplot I am displaying the following boxplot and would like to give it style features like: resize it to 400x800px , display it in the middle of the html file... Now I cant see the x axis labels for example because of the size... Any help?
Please check the complete code on this plunker.
The script is starting like this:
var labels = true; // show the text labels beside individual boxplots?

var margin = {top: 25, right: 25, bottom: 25, left: 25};
var  width = 800 - margin.left - margin.right;
var height = 400 - margin.top - margin.bottom;

var min = 0,
    max = 10;

// parse in the data
d3.csv("boxplot_year.csv", function(error, csv) {

    var data = [];
    data[0] = [];
    data[1] = [];
    data[2] = [];
    data[3] = [];
    data[4] = [];
    data[5] = [];

    data[0][0] = "Y2010";
    data[1][0] = "Y2011";
    data[2][0] = "Y2012";
    data[3][0] = "Y2013";
    data[4][0] = "Y2014";
    data[5][0] = "Y2015";

    data[0][1] = [];
    data[1][1] = [];
    data[2][1] = [];
    data[3][1] = [];
    data[4][1] = [];
    data[5][1] = [];

    csv.forEach(function(x) {
        var v1 = Math.floor(x.Y2010),
            v2 = Math.floor(x.Y2011),
            v3 = Math.floor(x.Y2012),
            v4 = Math.floor(x.Y2013),
            v5 = Math.floor(x.Y2014),
            v6 = Math.floor(x.Y2015);

        var rowMax = Math.max(Math.max(v1,v2), Math.max(Math.max(v3,v4), Math.max(v5,v6)));
        var rowMin = Math.min(Math.min(v1,v2), Math.min(Math.min(v3,v4), Math.min(v5,v6)));

        data[0][1].push(v1);
        data[1][1].push(v2);
        data[2][1].push(v3);
        data[3][1].push(v4);
        data[4][1].push(v5);
        data[5][1].push(v6);

        if (rowMax > max) max = rowMax;
        if (rowMin < min) min = rowMin;
    });

    var boxplot = d3.box()
        .whiskers(iqr(1.5))
        .height(height)
        .domain([min, max])
        .showLabels(labels);

    var svg = d3.select("#boxplot").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .attr("class", "box")
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    // the x-axis
    var x = d3.scale.ordinal()
        .domain( data.map(function(d) { console.log(d); return d[0]; } ) )
        .rangeRoundBands([0 , width], 0.7, 0.3);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

    // the y-axis
    var y = d3.scale.linear()
        .domain([min, max])
        .range([height + margin.top, 0 + margin.top]);

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");

    // draw the boxplots
    svg.selectAll(".box")
        .data(data)
       .enter().append("g")
       .attr("transform", function(d) { return "translate(" +  x(d[0])  + "," + margin.top + ")"; } )
        .call(boxplot.width(x.rangeBand()));

    // draw y axis
    svg.append("g")
            .attr("class", "y axis")
            .call(yAxis)
        .append("text") // and text1
            .attr("transform", "rotate(-90)")
            .attr("y", 6)
            .attr("dy", ".71em")
            .style("text-anchor", "middle")
            .style("font-size", "10px")
            .text("Grade");

    // draw x axis
    svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + (height  + margin.top + 10) + ")")
            .call(xAxis)
        .append("text") // text label for the x axis
            .attr("x", (width / 2) )
            .attr("y",  10 )
            .attr("dy", ".71em")
            .style("text-anchor", "middle")
            .style("font-size", "10px")
            .text("Year");
});

// Returns a function to compute the interquartile range.
function iqr(k) {
    return function(d, i) {
        var q1 = d.quartiles[0],
            q3 = d.quartiles[2],
            iqr = (q3 - q1) * k,
            i = -1,
            j = d.length;
        while (d[++i] < q1 - iqr);
        while (d[--j] > q3 + iqr);
        return [i, j];
    };
}

A: Remove the width and height attributes on your svg and make it expand to full size of its outer container using the viewBox attribute, replace the var svg part as follows, I hard coded the viewBox, change it as you see fit:
var svg = d3.select("#boxplot").append("svg")
        .attr("viewBox","0 0 800 800")
        .attr("preserveAspectRatio","none")
        .style("display","block")
        .style("width","100%")
        .style("height","100%")
        .attr("class", "box")
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

Since you now make your svg expand as much as possible, only modify the outer div as you see fit, either on "resize", periodically etc. To better understand what viewBox does: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewBox

A: You can adjust the bottom margin to 100. This is sufficient to show the bottom y-axis.
var margin = {top: 25, right: 25, bottom: 100, left: 25};

Based on your comment, to make both axis unite at 0 add a transform to your y-axis
svg.append("g")
        .attr("class", "y axis")
        .attr("transform", "translate (0,10)")
        .call(yAxis)

To get rid of the Y from Y2010 add a slice to your labels like below. However be aware that it is changing your data so in your console log you will see years as 2010, 2011 etc.
// the x-axis
var x = d3.scale.ordinal()
    .domain( data.map(function(d) { d[0] = d[0].slice(1); console.log(d); return d[0]; } ) )
    .rangeRoundBands([0 , width], 0.7, 0.3);

Hope this helps.


text:
Q: Python convert HEX number digits ASCI representation into string I want to make function doing exactly this:
#This is my imput number
MyNumberDec = 114
MyNumberHex = hex(MyNumberDec)

print (MyNumberDec)
print (MyNumberHex)

#Output looks exactly like this:
#114
#0x8a

HexFirstDigitCharacter = MagicFunction(MyNumberHex)
HexSecondDigitCharacter = MagicFunction(MyNumberHex)
#print (HexFirstDigitCharacter )
#print (HexSecondDigitCharacter )

#I want to see this in output
#8
#A

What is that function?
Why I need this?
For calculating check-sum in message sending towards some industrial equipment
For example command R8:
N   |   HEX |   ASC
1       52      R
2       38      8
3       38      8
4       41      A

Bytes 1 and 2 are command, bytes 3 and 4 are checksum
Way of calculating checksum: 0x52 + 0x38 = 8A
I have to send ASCII 8 as third byte and ASCII A as fourth byte
Maybe I dont need my magicfunction but other solution?

A: You can convert an integer to a hex string without the preceding '0x' by using the string formatter:
MyNumberDec = 114
MyNumberHex = '%02x' % MyNumberDec
print(MyNumberHex[0])
print(MyNumberHex[1])

This outputs:
7
2


text:
Q: Why is failed job not logged in SQL Server Agent Error Log? I have a failed job which is logged in SQL Server Logs but not logged in SQL Server Agent Error Logs. The job is executed as user: NT SERVICE\SQLSERVERAGENT. Limit size of job history and Remove agent history boxes are unchecked in properties of SQL Server Agent. Here are the results of SQL Server Logs:

When it comes to SQL Server Agent Error Logs, it does not contain any information about this failure. I thought that if a job fails then it should be necessarily logged into SQL Server Agent Error Logs. Why this happens?


text:
Q: laravel 4 insert data and if user has file directly update data I have following code
$produk = Produk::create(array(
  'nama_produk'     => $nama_produk,
  'deskripsi'           => $deskripsi
));
$id_produk = DB::getPdo()->lastInsertId();

when user has file (image) too i want to  update last insert data
if (Input::hasFile('produk_image')) {
    $file                   = Input::file('produk_image');
    $destinationPath        = "img/produk/";
    $destinationPathThumb   = "img/produk/thumb/";

    //display thumb for list admin
    $fileName               = $file[0]->getClientOriginalName();
    $display_thumb          = $destinationPathThumb.'thumb-'.$fileName;
    $produk = Produk::where('id_produk', "=", $id_produk)->get();
    $produk->thumbImage     = $pathThumb
    $produk->save();
}

when i used get() i got this error
Call to undefined method Illuminate\Database\Eloquent\Collection::save()

if i used first() i got error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update `produk` set `nama_produk` = produk1, `deskripsi` = deskripsiproduk1, `updated_at` = 2015-06-24 03:02:19 where `id` is null)

i really sure my script already found last insert data
when i use count() and return $produk
i got result 1
but somehow when i try to change script from
$produk = Produk::where('id_produk', "=", $id_produk)->get();

to become insert new produk like this
$produk = new Produk;

it's running well
any idea?

A: Model in Laravel need to have field id as the primary key.
If you use another field name, you need to override properties of Model with primaryKey property.
In your case (if id_produk is your primary key) then you need to add this into your Produk class :
protected $primaryKey = 'id_produk';


text:
Q: Sum of all data different than sum of individual data sets What would cause SQL Server 2016 Express to return different results for the same data set when run individually vs summed all at once?
All transactions which are sales:
SELECT sum(transactionamount)
FROM [NewPOS].[dbo].[Transaction]
WHERE TransactionDateTime >= '2016-11-26 00:00:00'
  AND TransactionDateTime <= '2017-11-27 0:0:0'
  AND transactiontype = 0

Results in 134253
All transactions which are sales paid with payment type of cash:
SELECT sum(transactionamount)
FROM [NewPOS].[dbo].[Transaction]
WHERE TransactionDateTime >= '2016-11-26 00:00:00'
  AND TransactionDateTime <= '2017-11-27 0:0:0'
  AND transactiontype = 0
  AND TransactionId IN (SELECT TransactionId
                        FROM payment
                        WHERE payment.PaymentType = 0)

Results in 56318.5
All transactions which are sales paid with payment type of credit card:
SELECT sum(transactionamount)
FROM [NewPOS].[dbo].[Transaction]
WHERE TransactionDateTime >= '2016-11-26 00:00:00'
  AND TransactionDateTime <= '2017-11-27 0:0:0'
  AND transactiontype = 0
  AND TransactionId IN (SELECT TransactionId
                        FROM payment
                        WHERE payment.PaymentType = 2)

Results in 54054.5
All transactions which are sales paid with payment type of debit card:
SELECT sum(transactionamount)
FROM [NewPOS].[dbo].[Transaction]
WHERE TransactionDateTime >= '2016-11-26 00:00:00'
  AND TransactionDateTime <= '2017-11-27 0:0:0'
  AND transactiontype = 0
  AND TransactionId IN (SELECT TransactionId
                        FROM payment
                        WHERE payment.PaymentType = 3)

Results in 28738.5
Add 56318.5 + 54054.5 + 28738.5 to get 139111.5
139111.5 is obviously != 134253
There is an extra 4858.5 in the summation of those three transaction types individually.
To validate I wasn't missing a payment type:
SELECT sum(transactionamount)
FROM [NewPOS].[dbo].[Transaction]
WHERE TransactionDateTime >= '2016-11-26 00:00:00'
  AND TransactionDateTime <= '2017-11-27 0:0:0'
  AND transactiontype = 0
  AND TransactionId NOT IN (SELECT TransactionId
                            FROM payment
                            WHERE payment.PaymentType = 0
                               OR payment.PaymentType = 2
                               OR payment.PaymentType = 3)

It's probably something simple but I have been staring at these results, calculating things and can't figure out how these numbers are not adding up..
Edit:
Another verification query that the data being summed should be the same as individual queries:
SELECT sum(transactionAmount)
FROM [NewPOS].[dbo].[Transaction]
WHERE TransactionDateTime >= '2016-11-26 00:00:00'
  AND TransactionDateTime <= '2017-11-27 0:0:0'
  AND transactiontype = 0
  AND TransactionId IN (SELECT TransactionId
                        FROM payment
                        WHERE payment.PaymentType = 0
                           OR payment.PaymentType = 2
                           OR payment.PaymentType = 3)

This query also results in 134253
Edit 2:
It appears that the check for multiple payment types failed to detect it --  I found the issue is most likely exactly that described in steenbergh's answer:
There are -cash and +debit transactions (cash back removes cash from drawer by adding a -cash payment, and a +debit payment for full amount + cash back..
This leads to really wacky numbers without filtering the cashback transaction numbers out, since there are transactions getting added twice once in cash, and once in debit..

A: Your payment table has multiple records for some of your TransactionIDs. This means that people paid in part with creditcard and in cash for the same transaction, for instance.
You can find this out with
select distinct TransactionID, count(*)
from Payment
group by TransactionID having count(*) > 1
order by 2 desc

This will show you all the Transactions where more than 1 method of payment was used.
This then influences your sum, because the payment table is only concerned with a part of those transactions, and the record in Transactions holds the full transaction amount. When you check that cash was used for (part of the) payment, and then take the full amount of the transaction, you also sum up the part paid for with a creditcard.

Assuming there's a column Amount or similar in the payment table, you could solve this problem with a JOIN:
SELECT sum(t.transactionamount) as Incorrect
, sum(p.amount) as Correct
FROM [NewPOS].[dbo].[Transaction] t
INNER JOIN [NewPOS].[dbo].[Payment] p on p.TransactionID = t.TransactionID
WHERE t.TransactionDateTime >= '2016-11-26 00:00:00'
  AND t.TransactionDateTime <= '2017-11-27 0:0:0'
  AND t.transactiontype = 0
  AND p.PaymentType = 0

To further make a breakdown to demonstrate how these tables interact:
SELECT distinct t.TransactionID
, p.PaymentType
, sum(p.amount) as [Amount paid with this type]
FROM [NewPOS].[dbo].[Transaction] t
INNER JOIN [NewPOS].[dbo].[Payment] p on p.TransactionID = t.TransactionID
WHERE t.TransactionDateTime >= '2016-11-26 00:00:00'
  AND t.TransactionDateTime <= '2017-11-27 0:0:0'
  AND t.transactiontype = 0

This query will list per transaction which types of payment were used, and for which amounts.
To further clarify, I've drawn you a picture:

It's very important to have a good understanding of JOINS, in any given database. for any type of system. Read up om 'm, do courses, search on YouTube.


text:
Q: Does there exist two infinite subsets of naturals $A, B$ such that each $n \in A + B$ uniquely determines $a \in A, b \in B$ such that $a + b = n$? Does there exist two infinite sets of naturals $A, B$ such that each $n \in A + B = \{ a + b : a\in A, b\in B\}$ has a unique solution $a + b = n$ in which $a \in A, b \in B$?
For example:
$$
A = \{0,3,6\} \\
B = \{0,2,7\} \\ \implies \\
0 = 0 + 0 \text{ is unique } \\
0 = 0 + 2 \text{ is unique } \\
\vdots \\
6 + 7 = 13 \text{ is unique }
$$
But I need the sets $A, B$ to be infinite.
I need it so that when multiplying two numbers in binary:
$$
(\sum_{i \in A}^{\infty} a_i 2^i)(\sum_{j \in B}^{\infty} b_j 2^j)
$$
Each coefficient is of the form $a_i b_j$ for some $i, j$ and so that the position $i$ that $a_i$ came from and the position $j$ that $b_j$ came from is uniquely determined by the value $i + j$.

I only need to always be able to determine two finite sets $A, B$ of roughly the same size such that $|A||B| = |A + B| = N^2$ for any $N \in \Bbb{N}$, which is why infinity came to mind, but an algorithm that returns the two finite sets given $N$ is sufficient for my purposes.

A: Sure. Let $A$ be the powers of 10, and $B$ be $\{2, 22, 222, 2222, \dotsc\}$.
Numbers in $A+B$ are either of a form like 1000022222, or like 2223222, and in either case you can determine what $a$ and $b$ are.
If you want more numbers in the sets, we can generalize quasi's answer:
Let $A$ be the sums of distinct odd powers of two, and $B$ be the sums of distinct even powers of two. Then each set has 32 elements below 1000, which is better than the 3 each in my answer, or the 5 each in quasi's answer. $A$ starts with $\{0, 2, 8, 10, 32, 34, \dotsc\}$ and $B$ starts with $\{0, 1, 4, 5, 16, 17, 20, \dotsc\}$.
Then the number of elements in $A$ or $B$ less than any given $N$
is about $2^{\log_2(N)/2}$: for half the available bit positions (either the even or odd ones), you make a choice between putting a 0 or 1 there.
This is about $\sqrt{N}$.
By the pigeonhole principle, the best you can do is less than $\sqrt{2N}$, so this is close to optimal.

A: Define $A,B$ as follows . . .

*

*Let $A$ be the set of positive integers of the form $2^s$ where $s$ is even.

*Let $B$ be the set of positive integers of the form $2^t$ where $t$ is odd.

If for $a\in A$ and $b\in B$, we have
$$n=a+b=2^s+2^t$$
where $s$ is even and $t$ is odd, then $s,t$ are uniquely determined by $n$, hence so are $a,b$.


text:
Q: how to merge fragmented packets comming from same source? I have fragmented packets coming from multiple sources stored in a *.pcap file. I need to merge all these payloads coming from the same source and extract the payloads in a file.
I need to do the above task using tcpdump or tshark commands.
Please let me know if I have missed something or if you need more clarification.

A: With pdml2flow (pypi) you can merge/aggregate frames based on any fields extracted by tshark / wireshark and print them as JSON, XML or any other format. You can also easily create a new plugin which extracts, rearranges and saves the payload for your use-case.
For example if you'd like to aggregate all frames with the same source and destination mac and print them as JSON you could do:
tshark -i interface -Tpdml | pdml2flow -f eth.src -f eth.dst +json

This might help if you can find a set of fields based on which you would like to merge/aggregate.
Disclosure: I am the author of pdml2flow.


text:
Q: AWS Timestream DB - AWS IOT I am building out a simple sensor which sends out 5 telemetry data to AWS IoT Core. I am confused between AWS Timestream DB and Elastic Search to store this telemetries.

*

*For now I am experimenting with Timestream and wanted to know is this the right choice ? Any expert suggestions.

*Secondly I want to store the db records for ever as this will feed into my machine
learning predictions in the future. Timestream deletes records after a while or is it possible to never delete it

*I will be creating a custom web page to show this telemetries per tenant - any help with how I can do this. Should I directly query the timestream db over api or should i back it up in another db like dynamic etc ?

Your help will be greatly appreciated. Thank you.

A:
For now I am experimenting with Timestream and wanted to know is this the right choice? Any expert suggestions.

I would not call myself an expert but Timestream DB looks like a sound solution for telemetry data. I think ElasticSearch would be overkill if each of your telemetry data is some numeric value. If your telemetry data is more complex (e.g. JSON objects with many keys) or you would benefit from full-text search, ElasticSearch would be the better choice. Timestream DB is probably also easier and cheaper to manage.

Secondly I want to store the db records for ever as this will feed into my machine learning predictions in the future. Timestream deletes records after a while or is it possible to never delete it

It looks like the retention is limited to 4 weeks 200 Years per default. You probably can increase that by contacting AWS support. But I doubt that they will allow infinite retention.
We use Amazon Kinesis Data Firehose with AWS Glue to store our sensor data on AWS S3. When we need to access the data for analysis, we use AWS Athena to query the data on S3.

I will be creating a custom web page to show this telemetries per tenant - any help with how I can do this. Should I directly query the timestream db over api or should i back it up in another db like dynamic etc ?

It depends on how dynamic and complex the queries are you want to display. I would start with querying Timestream directly and introduce DynamoDB where it makes sense to optimize cost.

A: Based on your approach " simple sensor which sends out 5 telemetry data to AWS IoT Core" Timestream is the way to go, fairly simple and cheaper solution for simple telemetry data.
The Magnetic storage is above what you will ever need (200years)


text:
Q: Exception while reading XML, DataSet.ReadXML, Object reference not set to an instance of an object It occurs when multiple calls to read xml files using dataSet.ReadXML.
Object reference not set to an instance of an object.
 at System.Data.DataTable.NewRow(Int32 record)
   at System.Data.DataRowCollection.AddWithColumnEvents(Object[] values)
   at System.Data.XmlDataLoader.LoadTable(DataTable table, Boolean isNested)
   at System.Data.XmlDataLoader.LoadData(XmlReader reader)
   at System.Data.DataSet.ReadXml(XmlReader reader, XmlReadMode mode, Boolean denyResolving)
   at System.Data.DataSet.ReadXml(String fileName, XmlReadMode mode)


text:
Q: ACE code editor - automatic height for multiple editors I'm trying to do all of the following things, at the same HTML page:

*

*Put more than one ACE editor in the same page

*There will be no need to define each editor its own ID tags

*There will be no need to define each editor its own HEIGHT

*The height of each editor will automatically initialized according to its default text

*The height of each editor will automatically grow when adding it text and reduced automatically when deleting from it text

I used this code: https://stackoverflow.com/a/27114508/5354360 for 1. and 2.
I used this code: https://stackoverflow.com/a/13579233/5354360 for 3. 4. 5.
Each of the codes works great by itself, but when I try to combine them and create more than one editor in the same page, the height set according to the last editor.
How should I fix the code?
Thanks!
my code:

#include < iostream >
usimg namespcse std;

int main ()
{
 for (int i = 0; i < 10; i++)
  printf ("%d", i);

 return 0;
}

for (int i = 0; i < 10; i++)
 printf ("%d", i);
}

A: You are using global editor variable, so heightUpdateFunction always works on the last editor.
But it is better to use built in method for resizing
editor.setAutoScrollEditorIntoView(true);
editor.setOption("maxLines", 30);

https://github.com/ajaxorg/ace/blob/v1.2.6/demo/autoresize.html#L40-L41

A: Ok, I found my mistake.
Just replaced:
$('.editor').height(newHeight.toString() + "px");
with:
editor.setOptions({ maxLines: Infinity });
and all fixed out.


text:
Q: Is there a way to use plot () using layers in pine-script with tradingview? Code:
plot(lower1, color=#FFFF00, transp=0, linewidth=2, style=plot.style_circles)
plot(lower2, color=#000000, transp=0, linewidth=2, style=plot.style_area)**
I want to draw an area and a few points above it.
The problem I have is that the points are drawn and then the area is drawn on top of the points and covers the points, and I can't see the points.
I have changed the lines, that is, the area is drawn first and then the points, but it throws me a code error, with another error.
I need this code to draw the points and then the area.
Is there a way to use plot () using layers in pine-script with tradingview?
Help me please, thanks.


text:
Q: Does sequence converge if its differences become strictly monotonously greater? Consider the following sequence:
$(x_n) = x_1, x_2, ...$
Now, let's say this particular sequence has this property: $x_{n + 1} - x_n > 0, \forall n \in \mathbb{N}.$  Then we say that this sequence grows. It' certanily possible that this sequence converges (take, for example, sequence $x_1, x_1 + 0.1, x_1 + 0.01, ...$, we see that $n$-th term is obviously $x_1 + 111...1$ which is obviously some real number).
But add another property of this sequence; let' also say that differences $x_2 - x_1, x_3 - x_2, ...$ make another strictly growing sequence, in other words $x_{n + 1} - x_n > x_{m + 1} - x_m$ for every $n$ such that $n > m$ (it's like positive 2nd derivative in a way).
My intuition tells me that then $(x_n)$ cannot converge. If true, how to prove this? Thanks.

A: The proof is simple. $x_n$ converges if and only if for every $\epsilon > 0$ there exists an index $N > 0$ such that $|x_p-x_q| < \epsilon$ for every $p, q > N$. In particular setting $p = q+1$ yields the necessary condition $|x_{q+1}-x_q| < \epsilon$ for every $q > N$.
(You really don't need Cauchy sequences here. Just notice that if a sequence $x_n$ has to converge, then obviously $x_{n+1}-x_n \to 0$).
You are requiring $x_{n+1}-x_n > x_{m+1}-x_m > 0$ for some $m$ and all $n > m$. Now if you set $\epsilon = x_{m+1}-x_m > 0$, the necessary condition is not satisfied, no matter how you choose $N$ large.


text:
Q: CORS with WebAPI sometimes works, sometimes doesn't I've used the following:
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
As suggested here:
Enabling CORS with WebAPI PUT / POST requests?
to enable cross-origin AJAX requests in my project.  Everything (POST / PUT / DELETE / GET) was working yesterday.  Then I decided to add a new endpoint to my webAPI project, and this one is failing with:
> XMLHttpRequest cannot load http://localhost:24144/api/card. Origin
> http://localhost:11089 is not allowed by Access-Control-Allow-Origin.

In my WebApiConfig I've done this:
        var cors = new EnableCorsAttribute("http://localhost:11089", "*", "*");
        config.EnableCors(cors);

And my AJAX request, identical to others that are working, looks like this:
 var updateCard = function (data) {
        var options = {
            url: apiEndpoint + 'card',
            type: 'PUT',
            async: true,
            dataType: 'json',
            data: data,
            xhrFields: {
                withCredentials: true
            }
        };

        return $.ajax(options)
            .done(function (response) {
                toastr.success("Card Updated", "Success");
            })
            .fail(function (msg) {
                toastr.error("Could not update card.", "Error");
            });
    }
};

Even if use the attribute directly on the method or controller that's failing, I get the same error:
 [EnableCors(origins: "http://localhost:11089", headers: "*", methods: "*")]

Why would this be happening?  I noticed that if I kill my webAPI solution while debugging, I get the same error in the client, but it usually only happens once and expected behavior resumes with the WebAPI project.  This isn't a problem but maybe it's relevant.
If there's anything else you think I should provide here, let me know.
Update:  Stack:
     iisexpress.exe Information: 0 : Request, Method=OPTIONS, Url=http://localhost:24144/api/card, Message='http://localhost:24144/api/card'
iisexpress.exe Information: 0 : Message='Card', Operation=DefaultHttpControllerSelector.SelectController
iisexpress.exe Information: 0 : Message='Selected action 'UpdateCard(CardDto card)'', Operation=ApiControllerActionSelector.SelectAction
iisexpress.exe Information: 0 : Message='CorsPolicyProvider selected: 'System.Web.Http.Cors.EnableCorsAttribute'', Operation=AttributeBasedPolicyProviderFactory.GetCorsPolicyProvider
iisexpress.exe Information: 0 : Message='CorsPolicy selected: 'AllowAnyHeader: True, AllowAnyMethod: True, AllowAnyOrigin: False, PreflightMaxAge: null, SupportsCredentials: False, Origins: {http://localhost:11089}, Methods: {}, Headers: {}, ExposedHeaders: {}'', Operation=EnableCorsAttribute.GetCorsPolicyAsync
iisexpress.exe Information: 0 : Message='CorsResult returned: 'IsValid: True, AllowCredentials: False, PreflightMaxAge: null, AllowOrigin: http://localhost:11089, AllowExposedHeaders: {}, AllowHeaders: {accept,origin,content-type}, AllowMethods: {PUT}, ErrorMessages: {}'', Operation=CorsEngine.EvaluatePolicy
iisexpress.exe Information: 0 : Operation=CorsMessageHandler.SendAsync, Status=200 (OK)
iisexpress.exe Information: 0 : Response, Status=200 (OK), Method=OPTIONS, Url=http://localhost:24144/api/card, Message='Content-type='none', content-length=unknown'
iisexpress.exe Information: 0 : Request, Method=PUT, Url=http://localhost:24144/api/card, Message='http://localhost:24144/api/card'
iisexpress.exe Information: 0 : Message='Card', Operation=DefaultHttpControllerSelector.SelectController
iisexpress.exe Information: 0 : Message='App.Service.Controllers.CardController', Operation=DefaultHttpControllerActivator.Create
iisexpress.exe Information: 0 : Message='App.Service.Controllers.CardController', Operation=HttpControllerDescriptor.CreateController
iisexpress.exe Information: 0 : Message='Selected action 'UpdateCard(CardDto card)'', Operation=ApiControllerActionSelector.SelectAction
iisexpress.exe Information: 0 : Operation=AuthorizeAttribute.OnAuthorization
iisexpress.exe Information: 0 : Message='Value read='App.Repository.Models.Dtos.CardDto'', Operation=JQueryMvcFormUrlEncodedFormatter.ReadFromStreamAsync
iisexpress.exe Information: 0 : Message='Parameter 'card' bound to the value 'App.Repository.Models.Dtos.CardDto'', Operation=FormatterParameterBinding.ExecuteBindingAsync
iisexpress.exe Information: 0 : Message='Model state is valid. Values: card=App.Repository.Models.Dtos.CardDto', Operation=HttpActionBinding.ExecuteBindingAsync
A first chance exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll
iisexpress.exe Information: 0 : Message='Will use same 'JsonMediaTypeFormatter' formatter', Operation=JsonMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message='Selected formatter='JsonMediaTypeFormatter', content-type='application/json; charset=utf-8'', Operation=DefaultContentNegotiator.Negotiate
iisexpress.exe Information: 0 : Message='Action returned 'StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.ObjectContent`1[[System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Headers:
{
  Content-Type: application/json; charset=utf-8
}'', Operation=ReflectedHttpActionDescriptor.ExecuteAsync
iisexpress.exe Information: 0 : Operation=ApiControllerActionInvoker.InvokeActionAsync, Status=500 (InternalServerError)
iisexpress.exe Information: 0 : Operation=CardController.ExecuteAsync, Status=500 (InternalServerError)
iisexpress.exe Information: 0 : Message='CorsPolicyProvider selected: 'System.Web.Http.Cors.EnableCorsAttribute'', Operation=AttributeBasedPolicyProviderFactory.GetCorsPolicyProvider
iisexpress.exe Information: 0 : Message='CorsPolicy selected: 'AllowAnyHeader: True, AllowAnyMethod: True, AllowAnyOrigin: False, PreflightMaxAge: null, SupportsCredentials: False, Origins: {http://localhost:11089}, Methods: {}, Headers: {}, ExposedHeaders: {}'', Operation=EnableCorsAttribute.GetCorsPolicyAsync
iisexpress.exe Information: 0 : Message='CorsResult returned: 'IsValid: True, AllowCredentials: False, PreflightMaxAge: null, AllowOrigin: http://localhost:11089, AllowExposedHeaders: {}, AllowHeaders: {}, AllowMethods: {}, ErrorMessages: {}'', Operation=CorsEngine.EvaluatePolicy
iisexpress.exe Information: 0 : Operation=CorsMessageHandler.SendAsync, Status=500 (InternalServerError)
iisexpress.exe Information: 0 : Response, Status=500 (InternalServerError), Method=PUT, Url=http://localhost:24144/api/card, Message='Content-type='application/json; charset=utf-8', content-length=unknown'
iisexpress.exe Error: 0 : Operation=JsonMediaTypeFormatter.WriteToStreamAsync, Exception=Newtonsoft.Json.JsonSerializationException: Error getting value from 'Stage' on 'System.Data.Entity.DynamicProxies.Side_F7B85DBC8AA69F5AAA5ACCA92A66F2763E57D4D2046F02AC7EE6064A3409DE42'. ---> System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
   at System.Data.Objects.ObjectContext.EnsureConnection()
   at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   at System.Data.Objects.ObjectQuery`1.Execute(MergeOption mergeOption)
   at System.Data.Objects.DataClasses.EntityReference`1.Load(MergeOption mergeOption)
   at System.Data.Objects.DataClasses.RelatedEnd.Load()
   at System.Data.Objects.DataClasses.RelatedEnd.DeferredLoad()
   at System.Data.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)
   at System.Data.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass7`2.<GetInterceptorDelegate>b__2(TProxy proxy, TItem item)
   at System.Data.Entity.DynamicProxies.Side_F7B85DBC8AA69F5AAA5ACCA92A66F2763E57D4D2046F02AC7EE6064A3409DE42.get_Stage()
   at GetStage(Object )
   at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)
   --- End of inner exception stack trace ---
   at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value)
   at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value)
   at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value)
   at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)
   at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__33.MoveNext()
iisexpress.exe Information: 0 : Message='Will use same 'JsonMediaTypeFormatter' formatter', Operation=JsonMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message='Selected formatter='JsonMediaTypeFormatter', content-type='application/json; charset=utf-8'', Operation=DefaultContentNegotiator.Negotiate
iisexpress.exe Information: 0 : Operation=JsonMediaTypeFormatter.WriteToStreamAsync
iisexpress.exe Information: 0 : Operation=CardController.Dispose

A: In case anyone else runs into this and happens to be using Unit Of Work and CORS from WebAPI2 with EF (ha) -
I had a lazily-loaded property that was not available when the Update method was executing.  I don't know why the error thrown was inaccurate, but the stack trace pointed me in the right direction:

Error getting value from 'Stage' on
  'System.Data.Entity.DynamicProxies.Side_F7B85DBC8AA69F5AAA5ACCA92A66F2763E57D4D2046F02AC7EE6064A3409DE42'.
  ---> System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a
  connection.

A: If you are using IIS 7.5 or below use this config
<system.webServer>
    <handlers>
     <remove name="OPTIONSVerbHandler"/>
  </handlers>
 </system.webServer>

Or if you are using IIS 8 or above
<system.webServer>
    <handlers>
        <remove name="OPTIONS"/>
     </handlers>
</system.webServer>

Hope this help