text:
Q: Spring MVC : HTTP Status 404 - /SimpleMVC/WEB_INF/HelloPage.jsp I am trying to develop a simple Spring MVC web app.
    I am getting  HTTP Status 404 - /SimpleMVC/WEB_INF/HelloPage.jsp
    The requested resource is not available.
I am new to Spring MVC .
This is my web.xml
 <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
      <display-name>SimpleMVC</display-name>
      <servlet>
      <servlet-name>front-controller</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      </servlet>

      <servlet-mapping>
      <servlet-name>front-controller</servlet-name>
      <url-pattern>/</url-pattern>
      </servlet-mapping>
    </web-app>

This is my front-controller.

    <bean name="/welcome.html" class="controller.HelloController"></bean>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix"> <value>/WEB_INF/</value>
    </property>
    <property name="suffix"> <value>.jsp</value></property>
    </bean>

     This is my Controller :
 package controller;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.AbstractController;

    public class HelloController extends AbstractController {

        @Override
        protected ModelAndView handleRequestInternal(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
            ModelAndView giveBackMessage = new ModelAndView("HelloPage");
            giveBackMessage.addObject("welcomeMessage","This is the response got from Controller");
            return giveBackMessage;
        }

    }
This is my Response JSP:

$(welcomeMessage)

I dont know where i am missing. Please help me where i am going wrong

A: You have mentioned wrong prefix in viewResolver.
<property name="prefix"> <value>/WEB_INF/</value>
Correct one should be
<property name="prefix"> <value>/WEB-INF/</value>
Also

$(welcomeMessage)

should be

${welcomeMessage}


text:
Q: mysql query takes 3 hours to run and process I have a query that is ran on a cron job late at night. This query is then processed through a generator as it has to populate another database and I make some additional processes and checks before it is sent to the other DB.
I am wondering is there anyway for me to speed up this query and hopefully keep it as a single query. Or will I be forced to create other queries and join the data within PHP? This queries the main mautic database.
SELECT  c.id as "campaign_id",
        c.created_by_user,
        c.name,
        c.date_added,
        c.date_modified,
        (SELECT DISTINCT COUNT(cl.lead_id)) as number_of_leads,
        GROUP_CONCAT(lt.tag) as tags,
        cat.title as category_name,
        GROUP_CONCAT(ll.name) as segment_name,
        GROUP_CONCAT(emails.name) as email_name,
        CASE WHEN c.is_published = 1 THEN "Yes" ELSE "No" END AS "published",
        CASE WHEN c.publish_down > now() THEN "Yes"
             WHEN c.publish_down > now() AND c.is_published = 0 THEN "Yes"
             ELSE "No" END AS "expired"
FROM campaigns c
    LEFT JOIN campaign_leads cl ON cl.campaign_id = c.id
    LEFT JOIN lead_tags_xref ltx on cl.lead_id = ltx.lead_id
    LEFT JOIN lead_tags lt on ltx.tag_id = lt.id
    LEFT JOIN categories cat on c.category_id = cat.id
    LEFT JOIN lead_lists_leads llist on cl.lead_id = llist.lead_id
    LEFT JOIN lead_lists ll on llist.leadlist_id = ll.id
    LEFT JOIN email_list_xref el on ll.id = el.leadlist_id
    LEFT JOIN emails on el.email_id = emails.id
GROUP BY c.id;

Here is a image of the explain
https://prnt.sc/qQtUaLK3FIpQ
Definitions
Campaign Table:
https://prnt.sc/6JXRGyMsWpcd
Campaign_leads table
https://prnt.sc/pOq0_SxW2spe
lead_tags_xref table
https://prnt.sc/oKYn92O82gHL
lead_tags table
https://prnt.sc/ImH81ECF6Ly1
categories table
https://prnt.sc/azQj_Xwq3dw9
lead_lists_lead table
https://prnt.sc/x5C5fiBFP2N7
lead_lists table
https://prnt.sc/bltkM0f3XeaH
email_list_xref table
https://prnt.sc/kXABVJSYWEUI
emails table
https://prnt.sc/7fZcBir1a6QT
I am only expected 871 rows to be completed, I have identified that the joins can be very large, in the tens of thousands.

A: Seems you have an useless select DISTINCT  .. could you are looking for a count(distinct  .. )
In this way you can avoid nested  select for each rows in main select  ..
SELECT  c.id as "campaign_id",
        c.created_by_user,
        c.name,
        c.date_added,
        c.date_modified,
        COUNT(DISTINCT cl.lead_id) as number_of_leads,
        GROUP_CONCAT(lt.tag) as tags,
        cat.title as category_name,
        GROUP_CONCAT(ll.name) as segment_name,
        GROUP_CONCAT(emails.name) as email_name,
        CASE WHEN c.is_published = 1 THEN "Yes" ELSE "No" END AS "published",
        CASE WHEN c.publish_down > now() THEN "Yes"
             WHEN c.publish_down > now() AND c.is_published = 0 THEN "Yes"
             ELSE "No" END AS "expired"
FROM campaigns c
    LEFT JOIN campaign_leads cl ON cl.campaign_id = c.id
    LEFT JOIN lead_tags_xref ltx on cl.lead_id = ltx.lead_id
    LEFT JOIN lead_tags lt on ltx.tag_id = lt.id
    LEFT JOIN categories cat on c.category_id = cat.id
    LEFT JOIN lead_lists_leads llist on cl.lead_id = llist.lead_id
    LEFT JOIN lead_lists ll on llist.leadlist_id = ll.id
    LEFT JOIN email_list_xref el on ll.id = el.leadlist_id
    LEFT JOIN emails on el.email_id = emails.id
GROUP BY c.id;

anyway be sure you have a proper composite index on
table campaign_leads columns campaign_id, lead_id
table lead_tags_xref columns lead_id, tag_id
table lead_lists_leads columns lead_id, leadlist_id
table email_list_xref columns leadlist_id, email_id

redpajama_set_name: RedPajamaStackExchange


text:
Q: Importing timestamps into Excel I have a text file of a transcription that I am looking to bring into Excel to modify.
The format of the text file is something like this
00:01 Speaker  This is a test of the transcription

00:02 Speaker  Thank you for listening

The time stamp is in the format mm:ss.
I can import easily through cut and paste, but when I try to manipulate column A with the time, Excel assumes the format is hh:mm. Even if I format the column before import as mm:ss, it imports as
01:00 Speaker  This is a test of the transcription

02:00 Speaker  Thank you for listening

Hope this makes sense - is there a correct way of importing this text file so the timestamp matches in Excel?


text:
Q: Count all possible pairs per group I couldn't find a relevant post for this, but apologies if something similar has been asked and answered. If I have the following data:
Market  Product Test
A       1       1
A       2       1
A       3       0
A       4       1
B       1       0
B       2       0
B       3       1
B       4       1
C       1       1
C       2       1
C       3       0
C       4       0

If Test = 1, then a product exists in a market. If I want to count the number of markets where two products co-exist for all product-market combinations, how do I do that? For example, 1&2 = 2; 1&3 = 0; 1&4 = 1.
I already calculated the sum of markets for each product using dplyr:
Answer <- Data %>%
            group_by(Market) %>%
            summarise(ProductCount = sum(Test))

A: Looks like a job for table within rows that have Test == 1:
 (combMkt <- with(  Data[ Data$Test==1, ], table(Market, Product)) )
#-- the starting point of all Test=1 rows:
      Product
Market 1 2 3 4
     A 1 1 0 1
     B 0 0 1 1
     C 1 1 0 0

# Choose the ones with 2 or more Markets
 combMkt[ , which( apply( combMkt, 2, sum) >=2 )]
      Product
Market 1 2 4
     A 1 1 1
     B 0 0 1
     C 1 1 0

A: Here is an idea using only base R. We aggregate on Market and get all possible combinations when Test == 1. We then use table to count the pairs and arrange them in a data.frame
d1 <- aggregate(Product ~ Market, df[df$Test == 1,], FUN = function(i)combn(i, 2, FUN = toString))
d2 <- as.data.frame(table(unlist(d1$Product)), stringsAsFactors = FALSE)

d2
#  Var1 Freq
#1 1, 2    2
#2 1, 4    1
#3 2, 4    1
#4 3, 4    1

However, If you want to include all pairs non-appearing, then,
n <- setdiff(combn(unique(df$Product), 2, toString), d2$Var1)
rbind(d2, data.frame(Var1 = n, Freq = 0, stringsAsFactors = FALSE))

#  Var1 Freq
#1 1, 2    2
#2 1, 4    1
#3 2, 4    1
#4 3, 4    1
#5 1, 3    0
#6 2, 3    0

A: The n.markets function below gives a matrix of the counts you want. The first two rows give the product pair, e.g. the first column shows the pair 1&2, and the third row gives the market count.
dat <- data.frame(Market = c(rep('A',4),rep('B',4),rep('C',4)), Product = rep(1:4,3), Test = c(1,1,0,1,0,0,1,1,1,1,0,0))

n.markets <- function(dat){
    combs  <- combn(unique(dat$Product),2)
    mkts   <- unique(as.vector(dat$Market))
    counts <- rep(0,ncol(combs))
    for(j in 1:ncol(combs)){
        for(i in seq_along(mkts)){
            counts[j] <- counts[j] + (sum(dat[dat$Market==mkts[i] & dat$Product %in% combs[,j], 'Test'])==2)
        }
    }
    rbind(combs,counts)
}

n.markets(dat)

##        [,1] [,2] [,3] [,4] [,5] [,6]
##           1    1    1    2    2    3
##           2    3    4    3    4    4
## counts    2    0    1    0    1    1

Edit: The answer in user20650's comment is much faster
tab = crossprod(table(d[d$Test==1, -3]))
tab[lower.tri(tab, diag=TRUE)] <- NA
reshape2::melt(tab, na.rm=TRUE)


text:
Q: How to use numbers from a js file in the css sheet? I want to use the numbers claculated in js in the css sheet.
I have this js:

The has the alert where viewportwidth shows the width of the browser and viewportheight shows the height of the browser window. I want to use those number is the style sheet like so:

Is is possible to do this?
I found this: Parse Javascript variable to CSS variables
but I'm having trouble getting it to work

A: You can modify a specific element's styling using JavaScript:
document.getElementById('map_canvas').style.width = "800px";

A: You can't change the CSS stylesheet with JS. However, you can override the stylesheet by applying inline style to elements or by appending a new


text:
Q: Node.js promise chain not running synchronously Maybe I'm misunderstanding promises (again) but my promise chain isn't waiting for the previous promise to resolve before moving onto the next.
Here is my code:
function getLocations(){
  return new Promise((resolve, reject) => {
    request('https://api.sportradar.us/ncaamb/trial/v4/en/polls/ap/2017/rankings.json?api_key=MY_KEY', function (error, response, body) {
      resolve(body);
    });
  })
}

function convertLocations(body){
  return new Promise((resolve, reject) => {
    for(var i=0; i<15; i++){
      myLocation = JSON.parse(body).rankings[i].market

      var geocodeParams = {
        "address": myLocation
      }

      gmAPI.geocode(geocodeParams, function(err, result){
        areaLat = result.results[0].geometry.location.lat.toFixed(2);
        areaLong = result.results[0].geometry.location.lng.toFixed(2);
        console.log(areaLat + "  " + areaLong);
        locationString += areaLat + "  " + areaLong + "|";
      });

      params["markers"].push({location: myLocation})
    }

    resolve(locationString);
  })
}

getLocations()
.then((body) => convertLocations(body))
.then((locationString) => {
  console.log("HERE ---> " + locationString);
})

So the last thing that i want to be output in the console.log("HERE ---> " + locationString); but it gets output before anything else instead.. why is the last function in the promise chain not waiting for the other promises to resolve?

A: Try this:
function getLocations() {
  return new Promise((resolve, reject) => {
    request('https://api.sportradar.us/ncaamb/trial/v4/en/polls/ap/2017/rankings.json?api_key=MY_KEY', function (error, response, body) {
      resolve(body);
    });
  })
}

function convertLocation(location) {
  return new Promise((resolve, reject) => {
    // do whatever you need to convert, i'm not sure if i was careful enough when I copy-paste you code

    var geocodeParams = {
      "address": myLocation
    }
    gmAPI.geocode(geocodeParams, function (err, result) {
      areaLat = result.results[0].geometry.location.lat.toFixed(2);
      areaLong = result.results[0].geometry.location.lng.toFixed(2);
      console.log(areaLat + "  " + areaLong);
      resolve(areaLat + "  " + areaLong + "|"); // <---- reosolve promise !!!
    });

  })
}

function convertLocations(body) {

  var promises = [];
  var data = JSON.parse(body);

  for (var i = 0; i < 15; i++) {
    promises.push(convertLocation(data.rankings[i].market));
  }

  return Promise.all(promises).then(arrayOfResulst => {
    return arrayOfResulst.join('')
  })
}

getLocations()
  .then((body) => convertLocations(body))
  .then((locationString) => {
    console.log("HERE ---> " + locationString);
  })

I'm not pretty sure I copied all correctly, and code could be written better (e.g. use reduce instead of for-loop), but i hope it will show you main idea.


text:
Q: sorting a nested hash error "can't convert Symbol into Integer" I can't figure out why this fails?
1.9.3p0 :022 > hash = Hash.new
 => {}
1.9.3p0 :023 > hash["jon"] = [:name=>"jon",:age=>22]
 => [{:name=>"jon", :age=>22}]
1.9.3p0 :024 > hash["bob"] = [:name=>"bob",:age=>19]
 => [{:name=>"bob", :age=>19}]
1.9.3p0 :025 > hash["sid"] = [:name=>"sid",:age=>25]
 => [{:name=>"sid", :age=>25}]
1.9.3p0 :026 > hash
 => {"jon"=>[{:name=>"jon", :age=>22}], "bob"=>[{:name=>"bob", :age=>19}], "sid"=>[{:name=>"sid", :age=>25}]}
1.9.3p0 :027 > hash.sort_by { |k, v| v[:age] }
TypeError: can't convert Symbol into Integer
    from (irb):27:in `[]'
    from (irb):27:in `block in irb_binding'
    from (irb):27:in `each'
    from (irb):27:in `sort_by'
    from (irb):27
    from /usr/share/ruby-rvm/rubies/ruby-1.9.3-p0/bin/irb:16:in `<main>'
1.9.3p0 :028 > hash.sort_by { |k, v| v[:age].to_i }
TypeError: can't convert Symbol into Integer
    from (irb):28:in `[]'
    from (irb):28:in `block in irb_binding'
    from (irb):28:in `each'
    from (irb):28:in `sort_by'
    from (irb):28
    from /usr/share/ruby-rvm/rubies/ruby-1.9.3-p0/bin/irb:16:in `<main>'
1.9.3p0 :029 >

This article suggests it should work: http://www.rubyinside.com/how-to/ruby-sort-hash

A: Your syntax is off.
hash["jon"] = [:name=>"jon",:age=>22]

means
hash["jon"] = [{:name=>"jon",:age=>22}]

So change your code to:
hash = Hash.new
hash["jon"] = {:name=>"jon",:age=>22}
hash["bob"] = {:name=>"bob",:age=>19}
hash.sort_by { |k, v| v[:age] }


text:
Q: Proving $\sum_{n=-\infty}^\infty e^{-\pi n^2} = \frac{\sqrt[4] \pi}{\Gamma\left(\frac 3 4\right)}$ Wikipedia informs me that
$$S = \vartheta(0;i)=\sum_{n=-\infty}^\infty e^{-\pi n^2} = \frac{\sqrt[4] \pi}{\Gamma\left(\frac 3 4\right)}$$
I tried considering $f(x,n) = e^{-x n^2}$ so that its Mellin transform becomes $\mathcal{M}_x(f)=n^{-2z} \Gamma(z)$ so inverting and summing
$$\frac{1}{2}(S-1)=\sum_{n=1}^\infty f(\pi,n)=\sum_{n=1}^\infty \frac{1}{2\pi i}\int_{c-i\infty}^{c+i\infty}n^{-2z} \Gamma(z)\pi^{-z}\,dz = \frac{1}{2\pi i}\int_{c-i\infty}^{c+i\infty}\zeta(2z) \Gamma(z) \pi^{-z}\,dz$$
However, this last integral (whose integrand has poles at $z=0,\frac{1}{2}$ with respective residues of $-\frac 1 2$ and $\frac 1 2$) is hard to evaluate due to the behavior of the function as $\Re(z)\to \pm\infty$ which makes a classic infinite contour over the entire left/right plane impossible.
How does one go about evaluating this sum?

A: This one is a direct evaluation of elliptic integrals. Jacobi's theta function $\vartheta_{3}(q)$ is defined via the equation $$\vartheta_{3}(q) = \sum_{n = -\infty}^{\infty}q^{n^{2}}\tag{1}$$ Let $0 < k < 1$ and $k' = \sqrt{1 - k^{2}}$ and we define elliptic integrals $K, K'$ via $$K(k) = \int_{0}^{\pi/2}\frac{dx}{\sqrt{1 - k^{2}\sin^{2}x}}, K = K(k), K' = K(k')\tag{2}$$ Then it is almost a miracle that we can get $k$ in terms of $K, K'$ via the variable $q = e^{-\pi K'/K}$ using equations $$k = \frac{\vartheta_{2}^{2}(q)}{\vartheta_{3}^{2}(q)}\tag{3}$$ where $\vartheta_{2}(q)$ is another theta function of Jacobi defined by $$\vartheta_{2}(q) = \sum_{n = -\infty}^{\infty}q^{(n + (1/2))^{2}}\tag{4}$$ Also the function $\vartheta_{3}(q)$ is directly related to $K$ via $$\vartheta_{3}(q) = \sqrt{\frac{2K}{\pi}}\tag{5}$$ The proofs of $(3)$ and $(5)$ are given in the linked post on my blog.

The sum in the question is $\vartheta_{3}(e^{-\pi})$ so that we have $q = e^{-\pi}$. This implies that $K'/K = 1$ so that $k = k'$ and from $k^{2} + k'^{2} = 1$ we get $k^{2} = 1/2$. And then $$\vartheta_{3}(q) = \sqrt{\frac{2K}{\pi}} = \sqrt{\frac{2}{\pi}\cdot\frac{\Gamma^{2}(1/4)}{4\sqrt{\pi}}} = \frac{\Gamma(1/4)}{\pi^{3/4}\sqrt{2}}$$ Now using $\Gamma(1/4)\Gamma(3/4) = \pi/\sin(\pi/4) = \pi\sqrt{2}$ we get $$\sum_{n = -\infty}^{\infty}e^{-\pi n^{2}} = \vartheta_{3}(e^{-\pi}) = \frac{\sqrt[4]{\pi}}{\Gamma(3/4)}$$ The value of $K = K(1/\sqrt{2})$ in terms of $\Gamma(1/4)$ is evaluated in this answer.

A: see: Ramanujan's Notebooks Volume 3, Chapter 17, Example(i). pp 103.
see also: Ramanujan's Notebook Volume 5 chapter 35. Values of Theta-Functions P. 325.
(seems like many of the previous comments mention what I have.)

A: I am not sure if it will ever help, but the following identity can be proved:
$$ S^2 = 1 + 4 \sum_{n=0}^{\infty} \frac{(-1)^n}{\mathrm{e}^{(2n+1)\pi} - 1}. $$

A: Maybe you can use this relationship:
If $$\vartheta(x)=\sum_{n\in \mathbb{Z}}e^{-\pi n^2 x},$$
then:
$$\pi^{-s/2}\Gamma(s/2)\zeta(s)=\int_{0}^{\infty}x^{s/2-1}\frac{\vartheta(x)-1}{2}dx.$$


text:
Q: Can anybody explain "Lose money for my firm..." for me, please? I don't quite understand the whole sentence of Buffett:
"Lose money for my firm and I will be understanding; lose a shred of reputation for the firm, and I will be ruthless"

A: Warren Buffett is saying that the reputation of his firm is extremely important to him and that he will not tolerate behaviour (by employees) that damages its reputation.
He will however be sympathetic if some of their business dealings are not profitable (because of the inevitable risks involved in commerce).


text:
Q: sending a command to heroku console What's the correct way of sending a command to heroku console on Cedar?
heroku console 2+2 works on older stacks - it warns me to use heroku run console on cedar.
When I run
heroku run console 2+2
it loads the unwanted "2+2" environment and opens up a console.
Loading 2+2 environment (Rails 3.2.3)
irb(main):001:0>

So what's the proper way of sending a command to heroku console on Cedar?

A: It's not the prettiest solution, but piping the command in did work.
echo "2 + 2" | heroku run console

Looking at the code, it appears there is no (current) built in way to do it.


text:
Q: Signals and slots in Qt console app I'm new to this but am wanting to write a Qt console app which uses Qt's features including signals and slots and therefore want an application event loop. Following this question How do I create a simple Qt console application in C++? I seem to be heading in the right direction but why does anything get executed after emitting finished in the following code:
// main.cpp
#include <QtCore>
#include <QDebug>

class Task : public QObject
{
    Q_OBJECT
public:
    Task(QObject *parent = 0) : QObject(parent) {}

public slots:
    void run()
    {
        // Do processing here
        qDebug() << "Hello World";
        emit finished();
        qDebug() << "I thought I'd finished!";
    }

signals:
    void finished();
};

#include "main.moc"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // Task parented to the application so that it
    // will be deleted by the application.
    Task *task = new Task(&a);

    // This will cause the application to exit when
    // the task signals finished.
    QObject::connect(task, SIGNAL(finished()), &a, SLOT(quit()));

    // This will run the task from the application event loop.
    QTimer::singleShot(0, task, SLOT(run()));

    return a.exec();
}

A: Try to subclass the QCoreApplication and reimplement the quit() signal with inserting a debug print in.
You will see that the quit function is called immediately before your second print in the "run" slot, provided you are using DirectConnection.
Also, worth nothing that quit() is slightly different to the GNU C exit() as per documentation:

Note that unlike the C library function of the same name, this function does return to the caller -- it is event processing that stops.

This means quit() dos not mean that application quits right away without terminating gracefully in the middle of your method execution.


text:
Q: New automaton that runs two others step by step? If I have two automatons for two languages ($M_1, M_2, L_1,L_2$ respectively), what would be the procedure to mix them by defining a new automaton such that the new automaton would accept the words $\theta_1\sigma_1\theta_2\sigma_2...\theta_n\sigma_n $ where $\theta_1 ... \theta_n \in L_1 , \sigma_1 ... \sigma_n \in L_2 $? By making it run from $M_1$ to $M_2$ to $M_1$ again to $M_2$ again and finally to an accepting state of $M_1$?

A: Assuming $M_1$ and $M_2$ are deterministic finite state machines, form a non-deterministic finite automaton with ε moves as shown below and then apply the powerset construction to get a deterministic one.

A: You did not define what kind of automaton you want. I will use finite state automatons. Let $M_1$ have state set $Q_1$, symbol set $S_1$, initial state $i_1 \in Q_1$, transition function $t_1: Q_1×S_1 \mapsto Q_1$ and accepting states $A_1 \subseteq Q_1$. Similarly define the components of $M_2$.
We can construct the machine you want with:

*

*states $Q_1×Q_2 + Q_2×Q_1$,

*symbols $S_1 + S_2$,

*initial state $(i_1, i_2)$,

*transition function left as exercise, :-)

*accepting states $A_1×A_2$.

I hope you can finish it from here.


text:
Q: Is it possible to approach diagonally divided table cell in HTML/CSS? I need to achieve something like this with HTML table:

I have tried but if there is another/better solution please share:
https://jsfiddle.net/mso268dr/113/
It just adds 4 empty cells and ::before blocks in two of them.
It uses transform rotate of 45 deg. of one border side of ::before.

table {
  border: 2px solid red;
  border-collapse: collapse;
  box-sizing: border-box;
}
table th, table td {
  background-color: #eff;
  border: 1px solid gray;
  padding: 0.2em 0.5em;
}

table th {
  background-color: #a85;
  color: #eee;
  border: 1px solid #5f5;
}

.t {
  position: relative;
  border-bottom: none;
  border-right: none;
}

.t + * {
  border-left: none;
  border-right: none;
}

.bs {
  border-top: none;
  border-right: none;
}

.bs + * {
  border-left: none;
  border-right: none;
}

.t::before, .b::before {
  content: "";
  height: 100%;
  background-color: none;
  border-left: 1px solid #5f5;
  transform: rotate(-45deg);
  transform-origin: bottom;
  position: absolute;
  left: 100%;
  top: 0;
}

.b::before {
  transform-origin: top;
  left: -1px;
}

.b {
  position: relative;
  border-left: none;
  border-top: none;
}

.te {
  border-left: 0;
  border-bottom: 0;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>table test</title>

    TOP - Right label

    some label

    BOTTOM label

    some text
    some text

if it could be done without additional empty cells only by ::before statements it would be a good improvement.
Thanks in advance!


text:
Q: WHAT DOES (file_t)(-1),0, IN THE STRUCTURE MEAN? I am making changes in a atheros SDK for my need and wish to understand why and for what purpose (file_t)(-1), 0, is used in the structure:
  struct channel channel =
{
        (file_t)(-1),
        0,
        CHANNEL_ETHNUMBER,
        CHANNEL_ETHDEVICE,
        {
                0x00,
                0xB0,
                0x52,
                0x00,
                0x00,
                0x01
        },
        {
                0x00,
                0x00,
                0x00,
                0x00,
                0x00,
                0x00
        },
        0x0000,

#if defined (__linux__)

#elif defined (__APPLE__) || defined (__OpenBSD__)

        0,
        0,
        0,
        0,

#elif defined (WINPCAP) || defined (LIBPCAP)
        (pcap_t *)(0),
        {
                0
        },

#else
#error "Unknown Environment"
#endif

        CHANNEL_TIMEOUT,
        CHANNEL_OPTIONS
};

I am not exploring the SDK and would help if anyone suggest to start off.
Thanking you.

A: You have presented the declaration of variable channel as a struct of type struct channel.  The code you asked about is in this variable's initializer:
    (file_t)(-1),
    0,

These are the values with which to initialize the first two members of channel.  The first is -1, cast to type file_t (which must have been defined earlier), and the second is itself.
The meaning of those members depends on the details of struct channel and the way it is used, which you have not provided.


text:
Q: Custom config file cannot be found in JAR (Jooby application) I am trying to build an executeable JAR with a custom config file.
In Eclpise all is working fine but in the jar file the config file is missing.
I tried it in different ways. I put the application.conf in directory "Conf" and in "Resources". In addition to that I tried with following Statements in the code-section.
Does anyone have an Idea?
PS. The application.conf of Jooby is based on this:
https://github.com/lightbend/config
PS2:
I let the config write out to the console. How expected, in Eclipse all custom settings are set. In my Jar File the Configuration only contains things like port and name of application and tons of system settings (Java version, Path xyz, ...). So it does not merge my custom config settings to the system-settings :(
//Config conf = ConfigFactory.parseResources("application.conf");
Config conf = require(Config.class);
//Config conf = ConfigFactory.load();
//Config conf = App.class.getResourceAsStream("application.conf");


text:
Q: how to use react-slick slider for multiple images in reactjs I dont want like that output how to do that. I am developing but it is not adjusted
const settings = {
      infinite: true,
      slidesToShow: 3,
      slidesToScroll: 3,
    };

              <Slider {...settings} >

A: Have you had a look at the Multiple Items Example (visual here)?
If you want to have 3 images displayed at one time, you change the settings to:
slidesToShow: 3,
slidesToScroll: 3


text:
Q: vue.runtime.esm.js?TypeError: Cannot read properties of undefined I create this component from the vuetify documentation.
https://github.com/vuetifyjs/vuetify/blob/master/packages/docs/src/examples/v-card/prop-outlined.vue
<template>
    <v-card class="mx-auto" max-width="344" outlined>
        <v-list-item three-line>
            <v-list-item-content>

OVERLINE

                <v-list-item-title class="text-h5 mb-1"> {{ person.name }} </v-list-item-title>
                <v-list-item-subtitle> {{ person.role }} </v-list-item-subtitle>
            </v-list-item-content>

            <v-list-item-avatar tile size="80" color="grey"></v-list-item-avatar>
        </v-list-item>

        <v-card-actions>
            <v-btn outlined rounded text> Message </v-btn>
        </v-card-actions>
    </v-card>
</template>

I import them like so... was intended to use it in a loop 5 times.
<template>

Teams

        <v-container class="my-5">
            <v-card class="mx-12 my-12">
                <v-row>
                    <v-flex xs12 sm6 md4 lg3 v-for="person in team" :key="person.name">
                        <Person :name="person" :role="person" />
                    </v-flex>
                </v-row>
                <v-divider></v-divider>
            </v-card>
        </v-container>

</template>

However, it is not compiling... I kept getting

vue.runtime.esm.js?2b0e:1897 TypeError: Cannot read properties of undefined (reading 'name')

What did I forget to do ??
If I comment out the
 <Person :name="person" :role="person" />

Result

{{ person.name }} seems accessible...

A: I think it has something to do with the data being rendered after the html. You can probably solve this by:

*

*Adding v-if on the  component; only render the component if data exists. You can also add it on v-flex component but as far as I know it's a bad practice because it may disturb the flow.

<v-flex xs12 sm6 md4 lg3 v-if="person" v-for="person in team" :key="person.name">
       <Person />
</v-flex>

or alternatively:
<Person v-if="person" />

*Add a default value on Person component props

    // Object with a default value
        person: {
          type: Object,
          default: function () {
            return { name: '' }
          }
        }

More about props: https://v2.vuejs.org/v2/guide/components-props.html


text:
Q: How to use promises correctly with multiple piped writestreams var promisePipe = require("promisepipe");
var fs = require("fs");
var crypt = require("crypto");
var // ....

files = ['/mnt/Storage/test.txt', '/mnt/Storage/test2.txt', '/mnt/Storage/test3.txt']

var promises = files.map(function(file_enc) {
  return new Promise(function(resolve, reject) {
    var file_out = file_enc + '.locked';
    promisePipe(
      fs.createReadStream(file_enc),
      crypt.createCipheriv(alg, genhashsub, iv),
      fs.createWriteStream(file_out),
    ).then(function(streams){
      console.log('File written: ' + file_out);
      // Promise.resolve(file_out); // tried but doesnt seem to do anything
    }, function(err) {
      if(err.message.substring(0, 7) === 'EACCES:') {
        console.log('Error (file ' + file_out + '): Insufficient rights on file or folder');
      } else {
        console.log('Error (file ' + file_out + '): ' + err);
      }
      // Promise.reject(new Error(err)); // tried but doesnt seem to do anything

    });
  })
});

Promise.all(promises).then(final_function(argument));

I'm trying to encrypt files contained in an array named files.
For the sake of simplicity I added them manually in this example.
What I want to happen:

*

*Create promises array to call with promises.all on completion

*Iterate through the array

*

*Create promise for this IO operation

*Read file    \

*Encrypt file  -- all done using streams, due to large files (+3GB)

*Write file   /

*On finish write, resolve promise for this IO operation

*Run finishing script once all promises have resolved (or rejected)

What happens:

*

*Encryption of first file starts

*.then(final_function(argument)) is called

*Encryption of first file ends

The files all get encrypted correctly and they can be decrypted afterwards.
Also, errors are displayed, as well as the write confirmations.
I've searched both Stack as well as Google and I have found some similar questions (with answers). But they don't help because many are outdated. They work, until I rewrite them into promises, and then I'm back to where I started.
I could also place 8 different ways to achieve this job, using npm modules or vanilla code, but all of them are also failing in one way or another.

A: an analog of short , file-based process wrapped in a promise all . You could do your encrypt in the  'encrypt' which is wrapped in file handler.  encrypt() returns a promise.
segments passes your array of files needing work.
  var filHndlr = function(segment){
    var uri = segment.uri;
    var path = '/tmp/' + uri;
    return that.getFile(path)
      .then (datatss => {
        return that.encrypt(uri, datatss);
      });
  }
...

        Promise.all(segments.map(filHndlr))
        .then(resp => { ... });

A: If you already have a promise at your disposal (and promisepipe appears to create a promise), then you generally should not use new Promise(). It looks like your main problem is that you are creating promises that you never resolve.
The other problem is that you are calling final_function in the last line instead of passing a function that will call final_function.
I suggest giving this a try:
var promises = files.map(function(file_enc) {
  var file_out = file_enc + '.locked';

  return promisePipe(
      fs.createReadStream(file_enc),
      crypt.createCipheriv(alg, genhashsub, iv),
      fs.createWriteStream(file_out),
  ).then(function(streams){
     console.log('File written: ' + file_out);

     return file_out;
  }, function(err) {
    if(err.message.substring(0, 7) === 'EACCES:') {
      console.log('Error (file ' + file_out + '): Insufficient rights on file or folder');
    } else {
      console.log('Error (file ' + file_out + '): ' + err);
    }

    throw new Error(err);
  });
});

Promise.all(promises).then(() => final_function(argument));


text:
Q: Recommend a content delivery network (CDN) for a specific purpose could you please recommend a CDN for the following use:
1) Ability to update files on the edge servers automatically through API, so it should take no more than 5-10 minutes to make a new version of a file available to all customers worldwide. I need an API command to instant refresh edge file copies. No other udate mechanisms are needed (TTL etc.)
2) Pay-as-you-go
What I've found:
1) Amazon cloudFront is not suitable because they only have TTL that is 24 hours minimum.
2) Rackspace Cloud Hosting is not suitable either, because its TTL is 8 hours min.
3) Cachefly.com. User connects to their ftp (or scp), updates files on the origin and disconnets. Once he disconnected cachefly will instantly update all changed to edge files. There is no limit on connections/disconnections frequency and amout. So cachefly is suitable, but it is not cheap. The transfer price per GB vary from $0.49/GB to $0.25/GB depending on your traffic.
4) SimpleCDN.com. Its support claims that the instant update can be done through admin interface and will be available in API in near future. But I didn't manage to find the ui feature and simplecdn support does not clarify what "near future" means. Moreover, I don't trust simplecdn much, because I didn't manage to find information about the amount and geography of its edge servers and the specifications about its service. But compared to Cachefly.com they are TEN times cheaper: from $0.039 downto $0.019 per GB (it is very strange)
5) Edgecast.com. I've contacted its support and they claimed to have the feature and promised me to send their basic pricing, but I didn't receive anything and AFAIK they are not cheap and not pay-as-you-go.
Community, could you please recommend me some CDN to fulfill my requirments.
Thanks and kind regards,
Alex

A: Thanks to Jauder Ho. I've carefully reviewed the list and finally found CloudLayer CDN, which I am going to stick with. It has a purge cache API call and affordable prices.

A: Is there any reason you couldn't simply use unique file names, perhaps with a redirector under your control?


text:
Q: Junit test error with Ant, no message, no reason given I'm trying to use Junit test with ant.
Since I don't really know how to write Junit test without eclipse, I'll just start with something completely trivial I found online. This should always pass.
Test1.java
import junit.framework.*;
public class Test1 extends TestCase {
  @Test
  public void testOne()
  {
    System.out.println("Heyy there I'm a test!");
    assertTrue( "TestExample", true );
  }
}

I add to my build.xml these...
49   <target name="junit" depends="jar">
50     <junit printsummary="withOutAndErr" fork="yes" showoutput="yes">
51       <classpath refid="application"/>
52       <test name="test.Test1"/>
53     </junit>
54   </target>

So now when I run "ant junit" I'm getting
junit:
    [junit] Running test.Test1
    [junit] Tests run: 1, Failures: 0, Errors: 1, Time elapsed: 0 sec

So... that doesn't tell me anything... what was wrong? how to fix it? nothing.
Anyone knows what's up?

A: I can reproduce it. I was expecting junit to give some more verbose message, like Class test.Test1 not found. But no, it just fails. It means the class is not in the classpath. Open your jar file (with archivizer like 7zip to confirm that).
And no surprise, as your class does not compile :) Add the following:
package test;
import org.junit.Test;

and your first test should pass.

A: @jarekczek helped me huge by letting me know that Junit is not some external thing to be compiled separately to execute but it needs to be compiled into the jar with your other source files.
The problem was that I put my test/ directory outside of my src/ directory, and when ant compiles the java files in src/ it did not compile the file Test1.java into Test1.class
I moved the test/ folder into the src/ folder, and now I got more informative error messages from the javac compiler, and was able to fix it. Thanks so much!


text:
Q: Proof of standard limit $\lim_{x \to 0}(1 - \cos x)/x^{2}$ $$\lim_{x\to 0} \frac{1-\cos(x)}{x^2}=\frac{1}{2}$$
Proof:
$$\lim_{x\to 0} \frac{1-\cos (x)}{x^2} \times \frac{1+\cos (x)}{1+\cos(x)}$$
$$\lim_{x\to 0} \frac{1-\cos^2(x)}{x^2(1+\cos (x))}$$
$$\lim_{x\to 0} \frac{\sin^2(x)}{x^2(1+\cos (x))}$$
$$=\frac{1}{2}$$
Hence we prove it.
But I try to use $\varepsilon$  & $\delta$ method but I was not able to complete the proof. Some one help me to prove it using $\varepsilon$ and $\delta$ method.
Thanks in advance.

A: Proving any and every limit via $\epsilon-\delta$ definition is not a good idea and it does not help at all in understanding the $\epsilon-\delta$ definition of limit. Still many textbooks and teachers give problems to prove a limit by $\epsilon-\delta$. And students most of the time struggle to find an expression for $\delta$ in terms of $\epsilon$. This kind of approach merely treats calculus/analysis as a fancy extension of algebra where you have to do all sorts of algebraic symbol shunting in order to get $\delta$ in terms of $\epsilon$. This is so wrong an approach. An understanding of calculus can not be had by treating it in terms of algebraic manipulation. You have to transcend the algebraic thought process and really start having an appreciation for the concept of real numbers and order relations ($<, >$) on real numbers.
Further the right way to understand the $\epsilon-\delta$ definition of limit is to use it to verify simple limits like $\lim_{x \to 2}x^{2} = 4$ and more importantly to see the use of this definition in proving limit theorems. Moreover the emphasis should not be on finding a $\delta$ as an explicit expression in $\epsilon$ but rather one should be convinced that for any $\epsilon$ a corresponding $\delta$ exists without ever writing $\delta$ explicitly in terms of $\epsilon$.

But still you insist to have an $\epsilon-\delta$ proof for the limit $$\lim_{x \to 0}\frac{1 - \cos x}{x^{2}} = \frac{1}{2}\tag{1}$$ then the only way out is to use the standard limits $$\lim_{x \to 0}\cos x = \lim_{x \to 0}\frac{\sin x}{x} = 1\tag{2}$$ and to use the algebraic identity $$\frac{1 - \cos x}{x^{2}} = \dfrac{\dfrac{\sin x}{x}\cdot\dfrac{\sin  x}{x}}{1 + \cos x}\tag{3}$$ which you have already established in your question.
In case you have studied the proof of limit theorems concerning algebra of limits then you can see that via equation $(3)$ the desired limit $(1)$ can be evaluated by knowing the limits in $(2)$ and using limit theorems. You have one addition ($1 + \cos x$) followed by a division ($/(1 + \cos x)$) and a multiplication. In each step you can start with an $\epsilon$ and find a corresponding $\delta$ (like in the proof of corresponding limit theorem) and thereby finally obtain a $\delta$ for a given $\epsilon$ which is sufficient to prove $(1)$.
Note: You can simplify the above process if you use following equation instead of $(3)$: $$\frac{1 - \cos x}{x^{2}} = \frac{1}{2}\cdot\frac{\sin (x/2)}{x/2}\cdot\frac{\sin (x/2)}{x/2}\tag{4}$$

But doing this does not help much except for being a cumbersome exercise. It will be best to study and understand the proofs of limit theorems and then apply them in evaluating limits.

A: We need to find a δ so that if $$|x| < \delta$$
$$|\frac{1 - cos(x)}{x ^ 2} - \frac{1}{2}| < \varepsilon$$
Note that
$$|\frac{1 - cos(x)}{x ^ 2}| = |\frac{1 - cos ^ 2(x)}{x ^ 2(1 + cos(x)) }| = |\frac{sin^2(x)}{x ^ 2(1 + cos(x))}| = |\frac{sin(x)}{x}|^2|\frac{1}{1 + cos(x)}|$$
But $$\big|\hspace{1mm}|\frac{sin(x)}{x}|^2|\frac{1}{1 + cos(x)}| - \frac{1}{2}\big|$$ is an expression of the form $xy - x_0y_0$ where $$x = |\frac{sin(x)}{x}|^2\\ y = |\frac{1}{1 + cos(x)}|\\ x_0 = 1\\ y_0 = \frac{1}{2} $$
Since $$|xy - x_0y_0| = |(x - x_0)(y - y_0) + x(y - y_0) + y(x - x_0)| \\ \hspace{2.5cm}\leqslant |(x - x_0)(y - y_0)| + |x(y - y_0)| + |y(x - x_0)|$$
We need to find a $\delta$ such that all the three terms in the last expression are less that $\frac{\varepsilon}{3}$
Since $lim_{x\to0} y_0 = y$ and $lim_{x\to0} x_0 = x$, minimize each term separately and pick the smallest $\delta$ of the three you get. The result follows.
P.S. - This is my first time typing an answer out in latex. If I've made any errors formatting this answer, I'm sorry.


text:
Q: Fix All Commit Messages in Git I am in process of migrating a subversion repository to git.  We enforce a commit message format like so:
[#<Issue Number Here>] The commit message.
During the migration, I noticed that some people put a new line into the commit message like this:
[#<Issue Number Here>]
The commit message.

I'll be adding a pre-commit hook to enforce our message format once the migration is complete, but how can I fix existing all commit messages after I've used git svn to clone the source repository?

A: Using filter-branch
git filter-branch --msg-filter fix-imported-msg.sh HEAD

(you need to write your own fix-imported-msg.sh script to take the original message on stdin, and write the corrected version to stdout).
This will be slightly more complicated if you have multiple branches, if you've already pushed the imported repo, etc.


text:
Q: javascript array.Join continious srings values into new array i have this array = ["john", "mike", "george", 55, "hello", 344, "goodmorning"]
and i want to take this:["johnmikegeorge",55,"hello",344,"goodmorning"].I want where there are continuous strings to unite them into one.
  var s = ""
    var new_data = []
    var pin = ["john", "mike", "george", 55, "hello", 344, "goodmorning"]
    for (let i = 0; i < pin.length; i++) {
      if (typeof pin[i] === "string") {
        s = s + pin[i]
        new_data.push(s)
      } else {
        s = ""
        new_data.push(pin[i])
      }
    }
    console.log(new_data)

In previous code i take this ["john", "johnmike", "johnmikegeorge", 55, "hello", 344, "goodmorning"]

A: You could check the value and last item of the result set, if they are strings and add the actual string as well.
Otherwise push the item. This is either a starting string of a series or a number.

var array = ["john", "mike", "george", 55, "hello", 344, "goodmorning"],
    result = array.reduce((r, v) => {
        if (typeof v === 'string' && typeof r[r.length - 1] === 'string') {
            r[r.length - 1] += v;
        } else {
            r.push(v);
        }
        return r;
    }, []);

console.log(result);

A: I've modified what you already have to make it work. whenever you get a number, you push the concatenated string that you found before that number and then push the number. the if condition after the for loop is to check if you have more strings after the last number is pushed.
var s = "";
var new_data = []
var pin = ["john", "mike", "george", 55, "hello", 344, "goodmorning"]

for (let i = 0; i < pin.length; i++) {
  if (typeof pin[i] === "string") {
    s = s + pin[i]
  } else {
    if (s !== "") {
      new_data.push(s);
      s = "";
    }
    new_data.push(pin[i])
  }
}
if (s !== "") {
  new_data.push(s);
}

console.log(new_data)


text:
Q: How to use clang and distcc to compile on a slave of a different architecture (e.g. Mac/Linux) I want to use distcc to compile code from my Mac to a bunch of Linux hosts, but I can't figure out how to make everything "line up". I've successfully used distcc from Mac to Mac, so I have a general idea of how to set things up.
I'm using Clang 4.0 and have it installed and working on both Mac and Linux. The following command compiles fine without the distcc at the beginning, but after adding distcc, I get the following issues:
distcc /Users/xaxxon/Downloads/clang+llvm-4.0.0-x86_64-apple-darwin/bin/clang++   -I/usr/local/include -I/Users/xaxxon/v8toolkit/./include -I/Users/xaxxon/v8/include  -stdlib=libc++ -g -Werror=return-type -g   -std=gnu++1z -o CMakeFiles/v8toolkit_static.dir/src/v8toolkit.cpp.o -c /Users/xaxxon/v8toolkit/src/v8toolkit.cpp

I'm not sure what compiler is being picked up on Linux, nor do I know how to find out. It's possible it's picking up GCC instead of Clang.
My first concern is this:
clang: warning: argument unused during compilation: '-stdlib=libc++'

My first error is:
In file included from /Users/xaxxon/v8toolkit/src/v8toolkit.cpp:5:
In file included from /usr/include/assert.h:44:
In file included from /Users/xaxxon/Downloads/clang+llvm-4.0.0-x86_64-apple-darwin/bin/../include/c++/v1/stdlib.h:94:
/usr/include/stdlib.h:250:20: error: blocks support disabled - compile with -fblocks or pick a deployment target that supports them
int atexit_b(void (^)(void)) __attribute__((availability(macosx,introduced=10.6)));

The next error I get (which becomes the first error if I manually add -fblocks to the compilation command (which isn't needed on a native Mac build) is:
/Users/xaxxon/Downloads/clang+llvm-4.0.0-x86_64-apple-darwin/bin/../include/c++/v1/__tuple:289:13: error: unknown type name '__type_pack_element'
    typedef __type_pack_element<_Ip, _Types...> type;
            ^
/Users/xaxxon/Downloads/clang+llvm-4.0.0-x86_64-apple-darwin/bin/../include/c++/v1/__tuple:289:32: error: expected member name or ';' after declaration specifiers
    typedef __type_pack_element<_Ip, _Types...> type;
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~^
/Users/xaxxon/Downloads/clang+llvm-4.0.0-x86_64-apple-darwin/bin/../include/c++/v1/__tuple:356:43: error: use of undeclared identifier '__type_pack_element'
      typename _ApplyFn::template __apply<__type_pack_element<_Idx, _Types...>>...
                                          ^
/Users/xaxxon/Downloads/clang+llvm-4.0.0-x86_64-apple-darwin/bin/../include/c++/v1/__tuple:357:6: error: expected a type
    >;

I don't understand if I'm doing something fundamentally wrong or if there's something small I'm missing which is making the Linux compiler act differently.
I just made sure to have Clang on Linux in the same named directory and now am only getting the -fblocks and unused during compilation -stdlib=libc++ issues.
I can get everything to compile (albeit with warnings), but when it links, I get:
ld: warning: ignoring file CMakeFiles/v8toolkit_shared.dir/src/debugger.cpp.o, file was built for
unsupported file format ( 0x7F 0x45 0x4C 0x46 0x02 0x01 0x01 0x00 0x00 0x00
0x00 0x00 0x00 0x00 0x00 0x00 ) which is not the architecture being linked
(x86_64): CMakeFiles/v8toolkit_shared.dir/src/debugger.cpp.o

A: As long as you specify the -target flag, you can even cross-compile, because Clang is a native cross compiler.
Cross-compilation using Clang

A: Adding the -target flag fixes everything! In my case, for Mac OS X v10.11 (El Capitan), the target triple is:
-target x86_64-apple-darwin15.6.0

for a build command of:
distcc /Users/xaxxon/Downloads/clang+llvm-4.0.0-x86_64-apple-darwin/bin/clang++  -Dv8toolkit_shared_EXPORTS -I/usr/local/include -I/Users/xaxxon/v8toolkit/./include -isystem /Users/xaxxon/v8/include  -stdlib=libc++ -g -Werror=return-type -target x86_64-apple-darwin15.6.0 -g -fPIC   -std=gnu++1z -o CMakeFiles/v8toolkit_shared.dir/src/v8toolkit.cpp.o -c /Users/xaxxon/v8toolkit/src/v8toolkit.cpp

You can get the current host's target by typing clang -v:
$ clang -v
clang version 4.0.0 (tags/RELEASE_400/final)
Target: x86_64-apple-darwin15.6.0 <<==== THIS LINE HERE
Thread model: posix
InstalledDir: /Users/xaxxon/Downloads/clang+llvm-4.0.0-x86_64-apple-darwin/bin

The following CMake lines will grab (and print) the triple for the current machine:
# Get the target triple for the current host by calling clang -v and then stripping out the Target: value from its output.  CMake regex syntax is quite limited.
execute_process(COMMAND ${CMAKE_CXX_COMPILER} -v ERROR_VARIABLE CLANG_VERSION_INFO)
string(REGEX REPLACE ".*Target:[\r\n\t ]*([^\r\n\t]*).*Thread model.*" "\\1" TARGET_TRIPLE ${CLANG_VERSION_INFO})
message(STATUS "TARGET TRIPLE: '${TARGET_TRIPLE}' END")

Much thanks to @duskwuff and oftc.net #llvm for help figuring this out!


text:
Q: .htaccess RewriteRule not working after switching providers I want to have a short link for images hosted on my website. An example:
http://example.com/sharex/user/UUd.png

The short link:
i.example.com/nUUd

The subdomain "i" redirects to http://example.com/sharex, and the "n" character indicates the directory the file is stored in. The expected behaviour is to visit the short link, and view the image file hosted at the long link (without the URL changing in the browser).
Here's the .htaccess file I have in the /sharex/ directory:
RewriteEngine On
RewriteBase /
RewriteRule ^n(.*)$ /user/$1.png [P,L]

This issue presented itself after switching hosting providers, even though the exact same thing worked on my previous host.

A: This is assuming your have mod_proxy correctly setup on new host.
Fix your RewriteBase and use a relative URI in target:
RewriteEngine On
RewriteBase /sharex/

RewriteRule ^n(.*)$ quartzic/$1.png [P,NC,L]


text:
Q: Conditionally convert a decimal value to integer create table #Temp
(
    id int,
    Volume decimal(18,3)
)

insert into #Temp(id,Volume)values(1,10)
insert into #Temp(id,Volume)values(2,10.2)

id  Volume
-----------------
1   10.000
2   10.200

Declare @Type as int
set @Type=1

 select Id,Convert(varchar(10),CASE WHEN @Type=1 THEN CAST(Volume AS INT)
 ELSE Volume  END) AS Quantity from #Temp

It is showing a result like this
id  Volume
-----------------
1   10.000
2   10.000

But I want result like this when type is 1 then result should be in integer format:
id  Volume
-----------------
1   10
2   10

on else condition (@Type rather than 1) I want result like this
    id  Volume
    -----------------
    1   10.000
    2   10.200

I have tried this query
select Id,Convert(varchar(10),CASE WHEN @Type=1 THEN CAST(Volume AS INT)
ELSE Volume  END) AS Quantity from #Temp

A: This will work for you.
 select Id, (CASE WHEN @Type=1 THEN convert(varchar(10),convert(int,volume))
 ELSE convert(varchar(10),Volume)  END) AS Quantity from #Temp

When @type is 1, the result will be 10 for both values. Otherwise it will be exact value in the table.


text:
Q: Keeping the time stamp when syncing with Ubuntu One? I would like to keep the original time stamp of a file when synchronizing with Ubuntu One.  Now Ubuntu One is messing with my time stamps, and I no longer know when I last worked on the file.  Ubuntu One also seem to mess up time stamps on the original source host.
This really is a show stopper, and we are just about to implement Ubuntu One across the many users in the organization.

A: According to FAQ of Ubuntu One, you can't, because Ubuntu One does not sync metadata about files.


text:
Q: SQL Error "You were not connected because a duplicate name exists on the network" I got a C# program installed in 5 different machines, pointing to the same database, running at the same time. The database is running on Machine A. 3 machines are running Windows Server 2016 (including A) and others are running Windows 10. None of them are virtual.
I am using 3 different connection strings:

*

*connectionString="Data Source=SERVERNAME\INSTANCENAME;Initial Catalog=myDataBase;Persist Security Info=True;User ID=myUsername;Password=myPassword - used on machine A (Windows Server 2016)

*connectionString="Data Source=IP\INSTANCENAME;Initial Catalog=myDataBase;Persist Security Info=True;User ID=myUsername;Password=myPassword - used on 1 Windows Server 2016 machine

*connectionString="Data Source=IP\PORT;Initial Catalog=myDataBase;Persist Security Info=True;User ID=myUsername;Password=myPassword - used on all other machines

Sometimes this error shows up while trying to insert data into the database.
The "Maximum number of concurrent connections" on SQL Server Management Studio is set to unlimited and all machines have different names.


text:
Q: InfluxDB - Kapacitor udf timeout I am trying to get data from InfluxDB inside a kapcitor udf written in Python using InfluxDBClient. I am able to get data in case the size is very small like 2000 records, but as soon as the size of data goes beyond that it starts failing with below error message:
_ts=2018-10-22T11:19:32.535Z lvl=error msg="encountered error" service=kapacitor task_master=main task=batch_task1 node=func2 err="keepalive timedout, last keepalive received was: 2018-10-22 11:17:52.535771714 +0000 UTC_
_ts=2018-10-22T11:19:32.536Z lvl=error msg="failed to snapshot task" service=kapacitor task_master=main task=batch_task1 err="keepalive timedout, last keepalive received was:  2018-10-22 11:17:52.535771714 +0000 UTC_
I have tried changing timeouts in kapacitor.conf for udffunctions but didn't get any success. I even tried raising the timeout to large value more than 1 hour but still it gives the same error.
Any help would be appreciated.
Thanks in advance


text:
Q: String is in wrong format c# I'm trying to figure out why when I run my program and press the submit button I get an error saying that my list is in the wrong format. A little background on the program: It's for my visual programming class. The program is for a bank account. I tried to comment on what each section is to make it kinda easier to read
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    //Tab 1 Create and close account
    private void Submitbtn_Click(object sender, EventArgs e)
    {
        double x;

        if (OpenRdo.Checked == true && Nametxtbx.TextLength > 0)
        {
            double.TryParse(Nametxtbx.Text, out x);

            // after clicking the button there is
            // no number; it says system.random
            Random acct = new Random();
            int AccountNumber = acct.Next(5, 1000);
            outputlbl.Text = acct.ToString();
        }

        // list for accounts
        // This is where it says I have the error
        // that my list is in the wrong format
        var accounts = new List<Account>
        {
            new  Account(Nametxtbx.Text, double.Parse(outputlbl.Text), 0)
        };

        // Write these records to a file
        WriteFile(accounts);

        // message box when you create account
        if (ValidateChildren(ValidationConstraints.Enabled))
        {
            MessageBox.Show("Account Created", "Message",
                MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }

    //writing to the file
    static void WriteFile(List<Account> accts)
    {
        StreamWriter outputFile = File.CreateText("accounts.txt");
        string record;

        foreach (var acct in accts)
        {
            record = $"{acct.Name},{acct.Balance}";
            Console.WriteLine($"Writing record: {record}");
            outputFile.WriteLine(record);
        }

        outputFile.Close();
    }
}

A: As far as I can tell (this is rather a lot of code), the issues are those lines:
Random acct = new Random();
int AccountNumber = acct.Next(5, 1000);
outputlbl.Text = acct.ToString();

You set the label to "System.Random" (because you call ToString() on the wrong thing). And that can not be sensibly casted into a integer later.
Ideally you should not even retrieve the data from the UI. If you got a integer in code behind, keep it there. Use it. But with the seperation between Events that might not be always possible.

A: I would recommend, do not just parse a text if you not know whats in the textbox.
Rather do something like this
if(double.TryParse (outputlbl.Text, out double outputNumber))
{
     new  Account(Nametxtbx.Text, outputNumber, 0);
}

Also, have a look at the formatprovider


text:
Q: Symfony , Autoloader class was not in it I'm getting this error and I'm getting crazy because of that as well.
I'm using Symfony 3.2.2 framework and Autoloader claims that The file was found but the class was not in it, the class name or namespace probably has a typo.
Stack Trace
throw new \RuntimeException(sprintf('Trying to autoload a class with an invalid name "%s". Be careful that the namespace separator is "\" in PHP, not "/".', $class));
            }
            throw new \RuntimeException(sprintf('The autoloader expected class "%s" to be defined in file "%s". The file was found but the class was not in it, the class name or namespace probably has a typo.', $class, $file));
        }
        if (self::$caseCheck) {
            $real = explode('\\', $class.strrchr($file, '.'));

Thats my BookType.php;
    <?php

namespace Bookkeeeper\ManagerBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class BookType extends AbstractType{

    public function buildForm(FormBuilderInterface $builder, array $options){
        $builder->add('title')->add('description')->add('pages');

    }
    public function setDefaultOptions(OptionsResolverInterface $resolver){
        $resolver->setDefault(array('data_class'=>'Bookkeeeper\ManagerBundle\Entity\Book'));

    }
    public function getName(){
        return 'bookkeeeper_managerbundle_book';
    }

}

**That's my BookController.php file
**
<?php

namespace Bookkeeper\ManagerBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Bookkeeper\ManagerBundle\Entity\Book;
use Bookkeeper\ManagerBundle\Form\BookType;

class BookController extends Controller
{

    public function indexAction(){
        return $this->render('BookkeeperManagerBundle:Book:index.html.twig');
    }
    public function showAction($id){
        return $this->render('BookkeeperManagerBundle:Book:show.html.twig');
    }
    public function newAction(){
        $book = new Book();

        $form = $this->createForm(new BookType(), $book, array (
            'action' =>$this->generateUrl('book_create'),
            'method'=> 'POST'
        ));
        $form->add('submit' , 'submit' , array('label' => 'Create Book'));

        return $this->render('BookkeeperManagerBundle:Book:new.html.twig', array(
            'form'=>$form->createView()
        ));

    }
    public function createAction(Request $request){

    }
    public function editAction($id){
        return $this->render('BookkeeperManagerBundle:Book:edit.html.twig');
    }
    public function updateAction(Request $request, $id){

    }
    public function deleteAction(Request $request, $id){

    }
}

A: You wrote namespace Bookkeeeper\ManagerBundle\Form; instead of namespace Bookkeeper\ManagerBundle\Form; (note the extra e in what you wrote)
<?php

namespace Bookkeeper\ManagerBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class BookType extends AbstractType{

    public function buildForm(FormBuilderInterface $builder, array $options){
        $builder->add('title')->add('description')->add('pages');

    }
    public function setDefaultOptions(OptionsResolverInterface $resolver){
        $resolver->setDefault(array('data_class'=>'Bookkeeeper\ManagerBundle\Entity\Book'));

    }
    public function getName(){
        return 'bookkeeeper_managerbundle_book';
    }

}


text:
Q: FeatureLayer selectFeatures hides the feature only on one layer I am using arcgis 3.23. I have defined the following SimpleLineSymbol to use to highlight selected features in different FeatureLayers.
              app.selectionLineSymbol = new SimpleLineSymbol();
              app.selectionLineSymbol.setWidth(15);
              app.selectionLineSymbol.setColor(new Color([255, 255, 255, 0.60]));

The layers in question are defined as follows
      var blazeColorsTa = new FeatureLayer(app.blazeColorsTaUrl, {
          id: "blazeColorsTa",
          outFields: ["*"]
      });
      blazeColorsTa.hide();
      layers.push(blazeColorsTa);

      var longTrails = new FeatureLayer(app.longTrailsUrl, {
          id: "longTrails",
          outFields: ["*"]
      });
      layers.push(longTrails);

I use the following code to highlight selected features from the blazeColorsTa layer and the selected features show through the selection symbol as desired.
                var blazeColorLayer = app.map.getLayer("blazeColorsTa");
                blazeColorLayer.show();
                blazeColorLayer.setSelectionSymbol(app.selectionLineSymbol);
                blazeColorLayer.selectFeatures(queryParams,FeatureLayer.SELECTION_NEW);

However, when I use identical code to highlight selected features from the longTrails layer the selected features are hidden by the selection symbol.
                var longTrailLayer = app.map.getLayer("longTrails");
                longTrailLayer.show();
                longTrailLayer.setSelectionSymbol(app.selectionLineSymbol);
                longTrailLayer.selectFeatures(queryParams,FeatureLayer.SELECTION_NEW);

I assume the problem has to do with a difference in how the layers are created in the GIS service but the only difference I can see is the longTrails layer is has both the Min Scale and Max Scale set to 0.  Where should I look to see what is causing the issue?
EDIT:
Here is what the trail looks like before selection:

Here is what it should look like after selection.  I changed the color to light green so you could see it better.  The selection symbol works when it is called by the popup.  It also looks like this when I use my selection code on the blazeColorsTa layer.

Here is what it looks like when I call it with the code I listed above on the longTrails layer where the feature is hidden by the selection symbol.

Just in case it is helpful, here is the code which defines the popup mentioned earlier.
            popup = new Popup({
                  lineSymbol: app.selectionLineSymbol,
                  visibleWhenEmpty: false,
                  hideDelay: 0,
                  zoomFactor: 1,
                  keepHighlightOnHide: true
              }, domConstruct.create("div"));

I had to make a custom zoom for the popup and I use the selection code to highlight the feature I have zoomed to.


text:
Q: how interrupt id and ISR is mapped? I am studying the lab 4 from CS.USFCA which generates a simulated interrupt to the virtual NIC.
class page:
http://cs.usfca.edu/~cruse/cs686s08/
The program will create a emulated NIC interface and user can manually issue a interrupt to the NIC by cat the proc.
Steps:

*

*cat /proc/interrupt to select a proper IRQ, and I select IRQ #18

*then I print the content of IOAPIC. the entry#18 bit0-7 is 55, so I set IntID as 55.

*Next, I install the module, and use ifconfig to bring up eth3. The IRQ is 18 which is correct.

*while tring to simulate the interrupt by cat /proc/netframe, the kernel log shows that
[18828.842375] do_IRQ: 1.85 No irq handler for vector (irq -1)
I know Linux manage 0-255 interrupt vectors by itself, and the 24 entries in IOAPIC decides how Interrupt from IO device is delivered to CPU(Intel).
in my case, it seems I triggers a wrong interrupt. So CPU cannot find the correct irq handler.
But how the interrupt is mapped to the corresponding IRQ in my case?

my code
#include <linux/module.h>   // for init_module()
#include <linux/etherdevice.h>  // for alloc_etherdev()
#include <linux/proc_fs.h>  // for create_proc_info_entry()
#include <linux/interrupt.h>    // for request_irq(), free_irq()
#include <linux/wait.h>     // for init_wait_queue_head()
#include <linux/seq_file.h>

#define irqID       0x12    // temporary -- an unused IRQ
#define intID       0x55    // temporary -- IOAPIC mapped

typedef struct  {
    struct tasklet_struct   my_rxtasklet;
    wait_queue_head_t   my_waitqueue;
    spinlock_t      my_lock;
} MY_DRIVERDATA;

int my_open( struct net_device * );
int my_stop( struct net_device * );
int my_hard_start_xmit( struct sk_buff *, struct net_device * );
irqreturn_t my_isr( int, void * );
void my_rx_handler( unsigned long );
int my_get_info( char *, char **, off_t, int );

char modname[] = "netframe";

static const struct net_device_ops mynetdev_ops={
    .ndo_open=my_open,
    .ndo_stop       = my_stop,
    .ndo_start_xmit = my_hard_start_xmit,
};

struct net_device  *netdev;

int my_get_info( char *buf, char **start, off_t off, int count )
{
    int len = 0;
    int i;
    *start = buf;
    if ( off == 0 )
    {
        len += sprintf( buf+len, "simulating an interrupt " );
        len += sprintf( buf+len, "by \'%s\' \n", netdev->name  );
        off += len;
    }
    else
    {
        asm(" int %0 " : : "i" (intID) );
    }

    return  len;
}

static int my_seq_open(struct inode *inode,struct file *file){
    printk(KERN_ALERT "DEBUG: Enter %s\n",__FUNCTION__);
    return single_open(file, &seq_proc_show,NULL);
}

struct file_operations fops = {
    .read=my_get_info,
};

static int __init my_init( void )
{
    printk( "<1>\nInstalling \'%s\' module\n", modname );

    if(!proc_create(modname,0666,NULL,&fops)){
        printk(KERN_INFO "ERROR! proc_create\n");
        remove_proc_entry(modname,NULL);
        return -1;
    }
    netdev = alloc_etherdev( sizeof( MY_DRIVERDATA ) );
    if ( !netdev ) return -ENOMEM;
    netdev->irq     = irqID;
    netdev->netdev_ops=&mynetdev_ops;

    return  register_netdev( netdev );
}

static void __exit my_exit(void )
{
    unregister_netdev( netdev );
    free_netdev( netdev );
    remove_proc_entry( modname, NULL );
    printk( "<1>Removing \'%s\' module\n", modname );
}

int my_open( struct net_device *dev )
{
    MY_DRIVERDATA   *priv = netdev_priv(dev);
    unsigned long   devaddr = (unsigned long)dev;

    printk( "opening the \'%s\' interface \n", dev->name );

    spin_lock_init( &priv->my_lock );
    init_waitqueue_head( &priv->my_waitqueue );
    tasklet_init( &priv->my_rxtasklet, my_rx_handler, devaddr );

    if ( request_irq( dev->irq, my_isr, IRQF_SHARED, dev->name, dev ) < 0) return -EBUSY;

    netif_start_queue( dev );
    return 0;
}

int my_stop( struct net_device *dev )
{
    MY_DRIVERDATA   *priv = netdev_priv(dev);

    printk( "stopping the \'%s\' interface \n", dev->name );

    free_irq( dev->irq, dev );

    tasklet_kill( &priv->my_rxtasklet );
    netif_stop_queue( dev );
    return 0;
}

int my_hard_start_xmit( struct sk_buff *skb, struct net_device *dev )
{
    MY_DRIVERDATA   *priv = netdev_priv(dev);

    printk( "starting transmit on the \'%s\' interface \n", dev->name );

    dev->trans_start = jiffies;
    dev->stats.tx_packets += 1;
    dev->stats.tx_bytes += skb->len;

    wait_event_interruptible( priv->my_waitqueue, 1 );

    dev_kfree_skb( skb );
    return 0;
}

irqreturn_t my_isr( int irq, void *data )
{
    struct net_device   *dev = (struct net_device*)data;
    MY_DRIVERDATA   *priv = netdev_priv(dev);
    tasklet_schedule( &priv->my_rxtasklet );
    wake_up_interruptible( &priv->my_waitqueue );
    return  IRQ_HANDLED;
}

void my_rx_handler( unsigned long data )
{
    struct net_device   *dev = (struct net_device *)data;
    struct sk_buff      *skb;
    int         rxbytes = 60;

    skb = dev_alloc_skb( rxbytes + 2 );
    skb->dev = dev;
    skb->protocol = eth_type_trans( skb, dev );
    skb->ip_summed = CHECKSUM_NONE;
    dev->stats.rx_packets += 1;
    dev->stats.rx_bytes += rxbytes;
    netif_rx( skb );
}

module_init( my_init );
module_exit( my_exit );
MODULE_LICENSE("GPL");


text:
Q: Address of allocated memory not the same when running under valgrind I am testing valgrind and have this small C program that leaks 4 bytes:
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int* x = malloc(sizeof(int));
    printf( "Address: %p\n", x);
    return 0;
}

I compile it with: gcc -g -o leak leak.c, and run it:
$ leak
Address: 0x55a72e303260
$ leak
Address: 0x55f370273260

So it shows two different addresses for two separate runs. However if I run it under valgrind it always shows the same address: 0x4a66040:
$ valgrind --leak-check=full --show-leak-kinds=all  leak
==8186== Memcheck, a memory error detector
==8186== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==8186== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==8186== Command: leak
==8186==
Address: 0x4a66040
==8186==
==8186== HEAP SUMMARY:
==8186==     in use at exit: 4 bytes in 1 blocks
==8186==   total heap usage: 2 allocs, 1 frees, 1,028 bytes allocated
==8186==
==8186== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1
==8186==    at 0x483874F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==8186==    by 0x109156: main (leak.c:6)
==8186==
==8186== LEAK SUMMARY:
==8186==    definitely lost: 4 bytes in 1 blocks
==8186==    indirectly lost: 0 bytes in 0 blocks
==8186==      possibly lost: 0 bytes in 0 blocks
==8186==    still reachable: 0 bytes in 0 blocks
==8186==         suppressed: 0 bytes in 0 blocks
==8186==
==8186== For counts of detected and suppressed errors, rerun with: -v
==8186== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

Why is this so? And is it possible for valgrind to show the real address of the memory?

A: It is the "real" address of the allocated memory.
Valgrind replaces your malloc() implementation with its own version, so that it can do what it does, see the line:
==8186==    at 0x483874F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)

So it is the underlying call to obtain memory that differs between your "normal" libc implementation of malloc() and that of valgrind's implementation. Likely libc uses brk() and valgrind uses mmap().
brk() follows the rules of Address Space Layout Randomization while mmap() allows for explicitly selecting the virtual memory address where to map the newly allocated memory.
Edit: strace of both versions, shows:
libc:
brk(NULL)                               = 0x5611e25ec000
brk(0x5611e260d000)                     = 0x5611e260d000
fstat(1, {st_dev=makedev(0, 22), st_ino=67, st_mode=S_IFCHR|0620, st_nlink=1, st_uid=1000, st_gid=5, st_blksize=1024, st_blocks=0, st_rdev=makedev(136, 64), st_atime=1566292432 /* 2019-08-20T11:13:52.993864629+0200 */, st_atime_nsec=993864629, st_mtime=1566292432 /* 2019-08-20T11:13:52.993864629+0200 */, st_mtime_nsec=993864629, st_ctime=1564479628 /* 2019-07-30T11:40:28.009864433+0200 */, st_ctime_nsec=9864433}) = 0
write(1, "Address: 0x5611e25ec260\n", 24) = 24

valgrind:
mmap(0x4c2c000, 2158912, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0) = 0x4c2c000
...
write(1027, "==18842==    at 0x4C2FB0F: mallo"..., 91) = 91

So in fact Valgrind explicitly chooses where to map its memory pool.


text:
Q: How to bold a whole row of data in JTable? I am doing a message function , and i want to bold a road where "read=No" and after i click it , it will become read=yes, and unbold ... i done the database part already , but i seriously don't know how to do table rendering .... cauze i am still very fresh in java ... so , anyone can help ? appreciates a lot !

A: you can make it using HTML
String str = "this is bold this is normal ";

A:
i want to bold a road where "read=No" and after i click it , it will become read=yes, and unbold ...

Use the Table Row Rendering approach to render a row based on data in the row. Modifying the code from the examples given you would use the following when required:
c.setFont(  c.getFont().deriveFont(Font.BOLD) );

A: Sorry for reviving an old post, but I was looking for something very similar to this and came up with my own solution (though it kind of plays off of Jigar's answer).  In my case, I have a table of scripts/programs that displays both the current version (in the 4th column) and the latest version of the script/program (in the 3rd column).  I wanted to make it easier to spot the ones that were not up-to-date.  All the solutions I saw elsewhere seemed to give a method that involved changing the DefaultCellRenderer, but didn't mention how to activate it on an already populated table (or really at all, that I could see).  As a result, I went about figuring out my own method through the "Keep It Simple Stupid" (KISS for short) way of thinking, and came up with the below code... hopefully someone else finds it useful.
        for(int r=0;r<table.getRowCount();r++) {
            if(!table.getValueAt(r, 2).equals(table.getValueAt(r, 3))) {
                for(int c=0;c<table.getColumnCount();c++) {
                    table.setValueAt("" + table.getValueAt(r, c) + "", r, c);
                }
            }
        }

I'm sure there are other, more efficient methods out there... but this was what I was able to come up with with my (still limited) knowledge of Java that actually worked in my situation.  Again, sorry for reviving an old post, but I do hope this helps some others in similar situations to my own.


text:
Q: How to print out the value in a function from a user input in Go package main

import (
    "bufio"
    "fmt"
    "os"
)

func Option1() {
     fmt.Println("Option1")
}
func main() {
     for true {
         fmt.Println("Pleae enter text: ")
         reader := bufio.NewReader(os.Stdin)
         text, _ := reader.ReadString('\n')
         if text == "1" {
                Option1()
         }

      }
 }

So my code will eventually have multi functions example: option1 option2 and etc.. I'm trying to execute a function every time a user types 1, 2, 3 and etc, but my code doesn't print out whatever is in Option1.
Your help will be appreciated.

A: Ground rule is ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter. So I used text = strings.TrimSpace(text) to trim it before comparing .See the modified program.
package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

func Option1() {
    fmt.Println("Option1")
}
func main() {

    for true {
        fmt.Println("Pleae enter text: ")
        reader := bufio.NewReader(os.Stdin)
        text, _ := reader.ReadString('\n')
        fmt.Println("Length of text,before trimming:", len(text))
        text = strings.TrimSpace(text)
        fmt.Println("Length of text,after trimming:", len(text))
        if text == "1" {
            Option1()
        }

    }
}

Oputput is
VScode> go run sofstringcompare.go
Pleae enter text:
1
Length of text,before trimming: 3
Length of text,after trimming: 1
Option1


text:
Q: Win2d blur doesn't always work in c++ I'm trying my hand at writing WP apps in c++ and have a strange problem with blurring .png image. It sometimes works and sometimes doesn't. When it doesn't work it appears as if image was invisible. Just to be sure I implemented same thing in C# and it works perfectly. This is my C# code
private async void blurDefaultAvatar() {
    try {
        var storageFile = await Package.Current.InstalledLocation.GetFileAsync("Assets\\menu_user.png");
        using(var imgStream = await storageFile.OpenReadAsync()) {
            using(var stream = await getBlurredImageStreamWithStream(imgStream, CanvasBitmapFileFormat.Png)) {
                var bitmap = new BitmapImage();
                bitmap.SetSource(stream);
                blurredAvatar.Source = bitmap;
            }
        }
    } catch(Exception e) {
        System.Diagnostics.Debug.WriteLine("Avatar load fail: {0}", e.Message);
    }
}

private async Task<IRandomAccessStream> getBlurredImageStreamWithStream(IRandomAccessStream stream, CanvasBitmapFileFormat format) {
    try {
        var device = new CanvasDevice();
        var bitmap = await CanvasBitmap.LoadAsync(device, stream);
        var renderer = new CanvasRenderTarget(device, bitmap.SizeInPixels.Width, bitmap.SizeInPixels.Height, bitmap.Dpi);

        using(var ds = renderer.CreateDrawingSession()) {
            var blur = new GaussianBlurEffect();
            blur.BlurAmount = 30.0f;
            blur.Source = bitmap;
            ds.DrawImage(blur);
        }

        var imgStream = new InMemoryRandomAccessStream();
        await renderer.SaveAsync(imgStream, format);

        return imgStream;
    } catch(Exception e) {
        System.Diagnostics.Debug.WriteLine("Avatar blur fail: {0}", e.Message);
        return null;
    }
}

and more or less (I hope) equivalent in c++
void MainPage::blurDefaultAvatar(){
  concurrency::create_task(Package::Current->InstalledLocation->GetFileAsync(L"Assets\\menu_user.png")).then([](concurrency::task<StorageFile^> t){
      try{
          auto storageFile = t.get();
          return concurrency::create_task(storageFile->OpenReadAsync());
      } catch(Exception^ e){
          std::wstringstream wss;
          wss<<"\nAvatar not found: '"<<e->Message->Data()<<"'\n";
          OutputDebugString(wss.str().c_str());
          return concurrency::create_task(concurrency::create_async([]()->IRandomAccessStreamWithContentType^{ return nullptr; }));
      }
  }, concurrency::task_continuation_context::use_current()).then([this](concurrency::task<IRandomAccessStreamWithContentType^> t){
      try{
          auto imgStream = t.get();
          concurrency::create_task(getBlurredImageStreamWithStream(imgStream, CanvasBitmapFileFormat::Png)).then([this](IRandomAccessStream^ stream){
              if(stream!=nullptr && stream->Size>0){
                  auto bitmap = ref new BitmapImage();
                  bitmap->SetSource(stream);
                  blurredAvatar->Source = bitmap;
              }
          });
       } catch(Exception^ e){
           std::wstringstream wss;
           wss<<"\nAvatar failed to read: '"<<e->Message->Data()<<"'\n";
           OutputDebugString(wss.str().c_str());
       }
   });
}

IAsyncOperation<IRandomAccessStream^>^ MainPage::getBlurredImageStreamWithStream(IRandomAccessStream^ stream, CanvasBitmapFileFormat format){
    return concurrency::create_async([stream, format]() -> IRandomAccessStream^{
        auto imgStream = ref new InMemoryRandomAccessStream();
        auto device = ref new CanvasDevice();
        return concurrency::create_task(CanvasBitmap::LoadAsync(device, stream)).then([stream, device, format, imgStream](concurrency::task<CanvasBitmap^> t){
            try {
                auto bitmap = t.get();
                auto renderer = ref new CanvasRenderTarget(device, bitmap->SizeInPixels.Width, bitmap->SizeInPixels.Height, bitmap->Dpi);
                auto ds = renderer->CreateDrawingSession();
                auto blur = ref new GaussianBlurEffect();
                blur->BlurAmount = 30.0f;
                blur->Source = bitmap;
                ds->DrawImage(blur);
                return concurrency::create_task(renderer->SaveAsync(imgStream, format));
            } catch(Exception^ e){
                std::wstringstream wss;
                wss<<"\nBitmap load fail: '"<<e->Message->Data()<<"'\n";
                OutputDebugString(wss.str().c_str());
                return concurrency::create_task(concurrency::create_async([]()->void{}));
            }
        }, concurrency::task_continuation_context::use_current()).then([imgStream](concurrency::task<void> t){
            try{
                t.get();
                return imgStream;
            } catch(Exception^ e){
                std::wstringstream wss;
                wss<<"\nStream save fail: '"<<e->Message->Data()<<"'\n";
                OutputDebugString(wss.str().c_str());
                return (InMemoryRandomAccessStream^)nullptr;
            }
        }).get();
    });
}

Methods are called with a press of a button. Any idea what might be wrong?

A: You need to Close()/Dispose() the drawing session.  So in the C# version you have:
using(var ds = renderer.CreateDrawingSession()) {
    ...
    ds.DrawImage(blur);
}

Going out of the using's scope calls Close() on the drawing session.  In C++/CX  you call Close() with "delete ds".  So:
auto ds = renderer->CreateDrawingSession();
auto blur = ref new GaussianBlurEffect();
blur->BlurAmount = 30.0f;
blur->Source = bitmap;
ds->DrawImage(blur);
delete ds; // <<<<<---- add this
return concurrency::create_task(renderer->SaveAsync(imgStream, format));

This page has some more information about 'delete' and IDisposable.
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh699870.aspx
The reason that you're seeing this sometimes work and sometimes not work is because when the ds goes out of scope it is also closed.  Sometimes this happens before the SaveAsync call has grabbed the D2D lock, and sometimes it happens after.  The net result here is that SaveAsync either saves the contents of the rendertarget before the blur has been drawn to it or it saves the contents after the blur has been drawn.


text:
Q: How to make inline matplotlib graphics in ipython3 notebook I tried following methods, but I always got error.
I tried:
1. Use ipython3 notebook --matplotlib inline in Mac console to launch iPython notebook.
Or/And
2. Use %matplotlib inline in the first cell of iPython notebook.
I got this error:

/usr/local/Cellar/python3/3.3.3/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/IPython/core/formatters.py:239:
  FormatterWarning: Exception in image/png formatter: Could not create
  write struct
        FormatterWarning,

I followed the solution @cel showed me (uninstall XQuartz), but I got the same error:

/usr/local/Cellar/python3/3.3.3/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/IPython/core/formatters.py:239:
  FormatterWarning: Exception in image/png formatter: Could not create
  write struct   FormatterWarning,

And if I execute both 1 (ipython3 notebook --matplotlib inline) and 2 (%matplotlib inline), I only got this message:
<matplotlib.figure.Figure at 0x1089fab50>

Additional info:
1. OS X (10.9.5), Python 3.3.3
2. If I use ipython3 notebook --matplotlib=osx to launch ipython notebook, the figure pops up in a different window (not inline).


text:
Q: Sending PKPass via email using nodejs I'm generating the pkpass successfully server-side and now I'm trying to send the pkpass via email. I'm using nodemailer to try and do this but when I try to open the pass after downloading it from the sent email I get this error The pass "Event.pkpass" could not be opened. The pass can be opened via my app and works fine. What am I doing wrong?
Pass Url: shoebox://card/Q03UycwVF9DPkMG6ytNw+DviZ6A=
Generating the PKPass:
try {
  const examplePass = await createPass({
      model: "./models/Event.pass",
      certificates: {
          wwdr: "./models/certs/wwdrc.pem",
          signerCert: "./models/certs/signerCert.pem",
          signerKey: {
              keyFile: "./models/certs/signerKey.pem",
              passphrase: "54321"
          }
      },
      overrides: {
          // keys to be added or overridden
          serialNumber: serialNumber
      }
  });

  examplePass.barcode("36478105430"); // Random value

  examplePass.headerFields.push({
    label : "EVENT",
    key : "title",
    value : title
  });

  examplePass.primaryFields.push({
    key : "date",
    label : "DATE",
    value : date
  });

  examplePass.secondaryFields.push({
    key : "location",
    label : "LOCATION",
    value : location
  });

// Generate the stream, which gets returned through a Promise
const stream = examplePass.generate();

res.set({
  "Content-Type": "application/vnd.apple.pkpass",
  "Content-disposition": `attachment; filename=${passName}.pkpass`
});

stream.pipe(res);

Sending the email:
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false,
requireTLS: true,
auth: {
    user: 'email@gmail.com',
    pass: 'password'
}
});

let mailOptions = {
from: 'email@gmail.com',
to: userEmail,
subject: "You're on your way to ",
html: '
Testing email
',
attachments: [
  {
    filename: 'Event.pkpass',
    contentType: 'application/vnd.apple.pkpass',
    content: stream
  }
]
};

transporter.sendMail(mailOptions, (error, info) => {
   if (error) {
      return console.log(error.message);
   }
   console.log('success');
});


text:
Q: How to get server IP from given url Can anyone tell me how to get the IP of a server, for example:

https://capi-eval.signnow.com/api/document/

I need it for curl call, which might be slow because of dns.
I can't get ip with ping or  any other tool I can think of.
What am I missing here? Also how to do this?

A: From command prompt:
nslookup capi-eval.signnow.com
dig capi-eval.signnow.com
Which returns:
Server:  resolver1.dyndnsinternetguide.com
Address:  216.146.35.35

Non-authoritative answer:
Name:    ec2-54-147-193-212.compute-1.amazonaws.com
Address:  54.147.193.212
Aliases:  capi-eval.signnow.com

Ping reply often is shut off now to prevent useless DDOS attacks simply by flood pinging a server with requested maximum reply packet size among other things.
Note that if this is an AWS server you control, you can turn on ping reply through the security firewall. Otherwise you have to get the IP by other means. The assigned IP for this server is probably pretty static, so a single DNS query probably is sufficient to establsh the IP address.

A: did you tried this ? CMD --> ping www.signnow.com


text:
Q: Can Asterisk play rtsp streams? How can I configure asterisk to play an RTSP url? there is an official application app_rtsp which is buggy. I could not make it work. Is there any official way or any other alternative?

A: You can try the Dialogic open source project DiaStar


text:
Q: akka - How to get results from master after all workers report back? I'm following the akka tutorial. Basically, there is a listener, a master, and some workers.
class Listener extends Actor {
  def receive = {
    case Report => // message from Master, print result, shutdown system
  }
}

class Master extends Actor {
  def receive = {
    case Calculate => // ask Workers to calculate
    case Result => // message from Workers, aggregate results.
                   // if all Workers have reported back, stop self and children,
                   // and send Report message to Listener
}

class Worker extends Actor {
  def receive = {
    case Calculate => // work, send result back to Master
  }
}

My question is how can I get results in Listener from outside world? Assume Report message is case class Report(results: Int).

A: I have figured it out. Just call the outside setters in Listener when it receives Report message.
object DataHolder {

  private var _data: Int = _

  def data = _data // getter
  def data_= (i: Int): Unit = _data = i // setter
}

class Listener extends Actor {
  def receive = {
    case Report(results) = {
      DataHolder.data = results // call external setter here
    }
  }
}

A: import scala.concurrent.Await
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.duration._

implicit val timeout = Timeout(5 seconds)
val future = actor ? msg // enabled by the "ask" import
val result = Await.result(future, timeout.duration).asInstanceOf[String]


text:
Q: Lean4: Proving that `(xs = ys) = (reverse xs = reverse ys)` Intuitively stating that xs is equal to ys is the same as saying that the respective reverse lists are equal to each other.
I'm currently learning Lean 4 and so I set myself the following exercise. I want to prove the following theorem in Lean 4:
theorem rev_eq (xs ys : List α) : (xs = ys) = (reverse xs = reverse ys)

However, I am not sure, whether this theorem can actually be proven in Lean 4. If not, why can it not be proven?
The closest I could get so far is proving the claim under the assumption that xs = ys:
theorem rev_eq' (xs ys : List α) :
  xs = ys -> (xs = ys) = (reverse xs = reverse ys) := by
  intros h
  rw [h]
  simp

Maybe, if one could prove that the claim also holds if one assumes that xs is not equal to ys, then the original theorem would follow. I got stuck on that route as well though.
Any ideas?

A: In Lean, it is usually idiomatic to state the equality of propositions using Iff, which is equivalent under the axiom propext. From there, iff is an inductive type with two sides, one direction that you have proved, and the other direction that follows from induction. (This theorem is still provable without this axiom, fwiw)
But I'd recommend you to do induction xs and induction ys and then look at the goals. Two should be impossible and Lean should show you they are contradictions (or indeed you'll get a that can be simplified to false = false) and two trivially true goals. Make sure to expand the definition of reverse.

A: This property is typically proved by induction. I never used lean but once induction on the list is done then it should be easy. You may need a lemma saying that (xs = ys) -> xs@l = xs@l (also by induction I guess, @ stands for list concatenation).


text:
Q: Converting Azure Cosmos DB graph database to python graph object I need to run some link prediction models on a graph database using the networkx package in python.  The graph database is currently stored in Azure Cosmos DB.  I have been able to connect to the database using gremlin-python package, but I cannot extract the data in any form that can be converted to a graph object for networkx.  I need the vertices and all of their attributes as well as the edges connecting them.
Here's what I have so far, which just returns an empty dataframe.  The vertex information will appear in the terminal, but I cannot save it as an object.
How can I extract the data from Cosmos DB into a format that can be converted to a graph object in python?  Thanks.
Code:
from gremlin_python.driver import client, serializer,protocol
import pandas as pd

def get_vertices(client, vertices):
   callback = client.submitAsync(vertices)
   for result in callback.result():
       print("\t{0}".format(result))

   return(pd.DataFrame(callback.result()))

   if __name__ == "__main__":

       client = client.Client('<endpoint>','g',
       username=="<username>"
       password="<password>"

       message_serializer=serializer.GraphSONSerializersV2d0())

   vertices = "g.V().valueMap().by(unfold()).toList()"

   Vdata = get_vertices(client, vertices)
   print(Vdata.head())

A: I think the specific issue in your above code is how you are accessing the result. You are using callback.result() where you might need to be doing something like callback.result().all().result(). callback is a future and you are correctly getting the result of the future (.result()) but that returns a ResultSet so you need the additional all().result() to access what you need.
Azure has some samples and you can see how they access the return results here: https://github.com/Azure-Samples/azure-cosmos-db-graph-python-getting-started/blob/master/connect.py

I did this a while back as I wanted to visualise data quickly in Python from CosmosDB. I didn't use Pandas, I directly put the data in a NetworkX graph. I am not sure if this is the most efficient way of going about it but it worked:

*

*Create your NetworkX graph G = nx.DiGraph()

*Execute query to get vertices you want from your graph client.submit(<YOUR GREMLIN VERTEX QUERY e.g. g.V()>)

*Iterate over returned result, for each vertex add a node into the NetworkX graph G.add_node()
    vertices_response = client.submit(<YOUR GREMLIN VERTEX QUERY e.g. g.V()>)
    vertices = vertices_response.all().result()
    for vertex in vertices:
        G.add_node(< Up to you how you transform your data to be represented here. You could explicitly state what fields you need e.g. vertex["id"] >)

*Repeat for edges:

    edges_response = client.submit(<YOUR GREMLIN VERTEX QUERY e.g. g.E()>)
    edges = edges_response.all().result()

    for edge in edges:
        logging.debug(edge)
        G.add_edge(edge["inV"], edge["outV"])

Note: Mine is slightly different using submit instead of AsyncSubmit but you should be able to get the rough idea


text:
Q: How to retrieve count from date ranges that overlap? I want to get the count of records that are within a x day interval. The intervals are overlapping though. Example: For a given time frame (lets say 30 days) I want to get the count for the first 5 days ( day 1  - day 5 inclusive), then count for day 2 - day 6, then day 3 - day 7, then day 4 - day 8, etc etc until I reach day 26 - day 30.
Whats the best way to go about this?
Is it possible to retrieve all the data for 30 days then group by?
Get queries for each sub interval then union them together?
Another method?
What would the query look like?
Example output, range is not necessarily but helpful.
count, range
   30, 2016-01-01 - 2016-01-05
   32, 2016-01-02 - 2016-01-06
   34, 2016-01-03 - 2016-01-07
   33, 2016-01-04 - 2016-01-08

Hopefully its understandable, if not please let me know and i'll clarify.
Thanks!

A: You need to join with a table that contains each date range. You can create this on the fly with a bunch of UNIONs.
SELECT t1.start, t1.end, COUNT(t2.date) AS count
FROM (SELECT '2016-01-01' AS start, '2016-01-05' AS end
      UNION
      SELECT '2016-01-02', '2016-01-06'
      UNION
      SELECT '2016-01-03', '2016-01-07'
      UNION
      SELECT '2016-01-04', '2016-01-08'
      ...) AS t1
LEFT JOIN yourTable AS t2 ON t2.date BETWEEN t1.start AND t1.end
GROUP BY t1.start

The LEFT JOIN ensures that you see the 0 counts for any date ranges with no records.


text:
Q: Response body of a Post Request can't be displayed I wonder if anyone can help. I am trying to send a post request to create an item and I get the correct  the status code back, but not the response body. I am fairly new to APIs',so, bit confused by this. Googling hasn't helped either. Here's my code:-
public void createGoods() {
    RequestSpecification httpRequest = RestAssured.given();
    RestAssured.baseURI = "http://192.168.0.31:8081/transit-api/clothes?_dc=159053130885&productId=1";
    JSONObject requestParams = new JSONObject();
    requestParams.put("productId", "1");
    requestParams.put("productDeploymentId", "1");
    requestParams.put("displayableId", goodsDisplayable);
    requestParams.put("createdUserName", "null");
    requestParams.put("product", "null");
    requestParams.put("productDescription", "");
    requestParams.put("createdDate", "null");
    requestParams.put("lastEventDate", "null");
    requestParams.put("progressDescription", "");
    requestParams.put("progressDate", "null");
    requestParams.put("active", true);
    requestParams.put("treatmentMilestones", "null");
    requestParams.put("status", "null");
    requestParams.put("stopComment", "");
    requestParams.put("primaryIdentifierString", "");
    requestParams.put("isPrimaryIdentifierAvailable", false);
    httpRequest
            .header("Accept", "application/json")
            .header("Accept-Language", "en-US,en;q=0.9")
            .header("Connection", "keep-alive")
            .header("Accept-Encoding", "gzip, deflate, br")
            .contentType(ContentType.JSON)
            .header("X-Requested-With", "XMLHttpRequest")
            .sessionId(sessionId);

    httpRequest.body(requestParams.toJSONString());
    Response response = httpRequest.request(Method.POST);

    System.out.println("RESPONSE body is--->>>>" + response.getBody().asString());
    System.out.println("Status code is----------------->>>" + response.getStatusCode());

}

}
The response I get is below:-
>>>>

RESPONSE body is---createTreatment----------->>>>*io.restassured.internal.RestAssuredResponseImpl@55259aa7*

Status code is ----------------->>>200

Step failed
java.lang.IllegalStateException: Cannot invoke the path method because no content-type was present in the response and no default parser has been set.
You can specify a default parser using e.g.:
RestAssured.defaultParser = Parser.JSON;

    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:83)
    at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrapNoCoerce.callConstructor(ConstructorSite.java:105)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:60)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:235)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:247)
    at io.restassured.internal.RestAssuredResponseOptionsGroovyImpl$_path_closure5.doCall(RestAssuredResponseOptionsGroovyImpl.groovy:392)

A: parsing is a way to read data from your response. Set the below as your default parser.
RestAssured.defaultParser = Parser.JSON;

result read!

A: Try setting a default parser for REST Assured:
RestAssured.defaultParser = Parser.JSON;

See an example here: https://github.com/rest-assured/rest-assured/blob/rest-assured-4.3.0/examples/rest-assured-itest-java/src/test/java/io/restassured/itest/java/DefaultParserITest.java#L44-L52
Alternatively, make sure that the service you're testing returns a valid Content-Type HTTP response header.