Doubles of NetworkRequestMetric in Logcat for each network query

Question: I am using Firebase Performance in my Android application and see the doubles of each network query in Logcat. Here is an example:
2019-04-09 19:19:18.206 25147-28713/com.example.app D/OkHttp: --> GET https://my-host.net/getStatistic?
19:19:18.273 25147-28713/com.example.app D/OkHttp: <-- 200 https://my-host.net/getStatistic? (66ms)
2019-04-09 19:19:18.282 25147-25252/com.example.app D/FirebasePerformance: Logging NetworkRequestMetric - https://my-host.net/getStatistic 0b 76ms,
2019-04-09 19:19:18.284 25147-25252/com.example.app I/FirebasePerformance: Rate Limited NetworkRequestMetric - https://my-host.net/getStatistic
2019-04-09 19:19:18.285 25147-25252/com.example.app D/FirebasePerformance: Logging NetworkRequestMetric - https://my-host.net/getStatistic 0b 111ms,
2019-04-09 19:19:18.286 25147-25252/com.example.app I/FirebasePerformance: Rate Limited NetworkRequestMetric - https://my-host.net/getStatistic
2019-04-09 19:19:24.770 25147-25147/com.example.app I/InfoManager.lambda$getStatisticsDisposable$0,208: StatisticData :

OkHttp interceptor is showing only one request in logcat. But there are two lines of "Logging NetworkRequestMetric" of FirebasePerformance with different time metrics. I also have Stetho incorporated in the app, and Stetho also shows only one request is made to the server.
So, why is the FirebasePerformance showing that the request is made twice?
Answer: Looking at the log - it seems the two network requests were made are captured. One important thing to note here is that the logs do not show the complete URL, the queryParams are stripped before logging. So the domain and query path might be the same, but the params might be different.
2019-04-09 19:19:18.282 25147-25252/com.example.app D/FirebasePerformance: Logging NetworkRequestMetric - https://my-host.net/getStatistic 0b 76ms,
2019-04-09 19:19:18.284 25147-25252/com.example.app I/FirebasePerformance: Rate Limited NetworkRequestMetric - https://my-host.net/getStatistic
2019-04-09 19:19:18.285 25147-25252/com.example.app D/FirebasePerformance: Logging NetworkRequestMetric - https://my-host.net/getStatistic 0b 111ms,
2019-04-09 19:19:18.286 25147-25252/com.example.app I/FirebasePerformance: Rate Limited NetworkRequestMetric - https://my-host.net/getStatistic


returned NULL without setting an error

Question:     def image_descriptors(file):
      img = cv2.imread(file,0)
      img = cv2.resize(img, (256, 256))
      _ , descriptors = cv2.SIFT().detectAndCompute(img, None)
   return descriptors
   def folder_descriptors(folder):
     cv_img=[]
     for img in glob.glob("*.jpg"):
         n=cv2.imread(img)
         cv_img.append(n)
   print("Calculating descriptos. Number of images is", len(cv_img))
   return np.concatenate([image_descriptors(file) for file in cv_img])

I am getting the following in output screen:
Calculating descriptos. Number of images is 274
SystemError:  returned NULL without setting an error
Answer: Path.glob return list of Path object (WindowsPath in windows or PosixPath in linux). and cv2.imread expect string.
you can get string of path from Path object using str class (str(path_object)) or build in magic method from Path object (path_object.__str__())
def image_descriptors(file):
  img = cv2.imread(file,0)
  img = cv2.resize(img, (256, 256))
  _ , descriptors = cv2.SIFT().detectAndCompute(img, None)
  return descriptors
def folder_descriptors(folder):
  cv_img=[]
  for img in glob.glob("*.jpg"):
     # convert `Path` object to string
     n=cv2.imread(str(img))
     cv_img.append(n)
  print("Calculating descriptos. Number of images is", len(cv_img))
  return np.concatenate([image_descriptors(file) for file in cv_img])

returned NULL without setting an error


How can I get integer output from a sql execution using F#

Question: I am new in F#. So that I face some problem in my project.
let getTotalNoOfSmsPerDay (Db cStr) =
    use cmd = new SqlCommandProvider<"select COUNT(id) as NoOfSMS
                                      from transport.SmsNotification
                                      where CONVERT(date, CreatedOn) = CONVERT(date, GETDATE())
                                     ",ConnectionString, SingleRow = true>(cStr)
    async {
         let! result = cmd.AsyncExecute()
         return result
     }

This is my Code . I just want a integer number NoOfSMS . But It gives me <Option<int>>
How can I solve this?
Thanks in advance
Answer: Option represents that nothing may be returned. This is the point where most other languages would return null.
There are a few ways to use the value inside Option. Explore the functions available.
Often what you will do though is to match on the 2 cases ie. Some value was returned or None.
match result with
| Some v -> v
| None -> 0

Here are some links to tutorials I have written on the topics.
Control flow
Pattern matching
Handling no data
Comment: If I want to apply control flow statement in this result it doesn't work. like `let! noOfSMSPerday = connection.GetTotalNoOfSmsPerDay
        if noOfSMSPerday <= 400 then  ` It gives error **Type mismatch :  'Async' but given a  'Async'**
Comment: If you do not have an else, the return type is unit. Once you have got the int you might want to return from the async CE and just use the value. let n = async { return or return! } depending on what you working with.
Comment: You are right,As I don't write else it gives me unit . Thank you Solved it


Regression plot and function for: heavy-tailed probability distribution

Question: I've got data points from a simulation as coordinates in a text-files like so:
<code>23 0.000022842
24 0.000022842
25 0.000091368
26 0.000251262
27 0.000182736
28 0.000411156
29 0.000890838
30 0.00143905
31 0.00246694
32 0.00317504
33 0.0042943
34 0.00719523
35 0.00922817
36 0.0134083
37 0.0150072
38 0.019233
39 0.0228877
40 0.0281642
41 0.0320702
42 0.0350168
43 0.038306
44 0.0418694
45 0.0433541
46 0.0468946
47 0.0458896
48 0.0487905
49 0.0500925
50 0.045113
51 0.0458667
52 0.0423034
53 0.0418009
54 0.0369355
55 0.0349254
56 0.0311565
57 0.0294205
58 0.026314
59 0.0237557
60 0.0213344
61 0.017931
62 0.0151899
63 0.0135453
64 0.0115352
65 0.00918248
66 0.00778912
67 0.00669271
68 0.00532219
69 0.00479682
70 0.00395167
71 0.00322072
72 0.00262683
73 0.00187304
74 0.00121063
75 0.0011421
76 0.00111926
77 0.000708102
78 0.000708102
79 0.000479682
80 0.000319788
81 0.000205578
82 0.000251262
83 0.000137052
84 0.000091368
85 0.000091368
86 0.00011421
87 0.000045684
88 0.000045684
92 0.000045684
94 0.000045684
</code>
with 1st column being my x-data and 2nd column being probability values, accordingly.
The probability density function of this data first looked like a binomial distribution to me so I plotted an approximated binomial pdf that in the end didn't really match the simulated data.
The plot has got a relatively slight right heavy tail, so I'm wondering which distribution description would return the best regression curve in python.
I've already tried a polynomial fit but then there's the problem with the oscillating edges - Note: I will use the regression function in order to sum up values from k to infinity, so what I actually need is a smooth fit for the edges and a tool that returns the function I need.
I'd appreciate approaches with python and bash!
Comment: Could you explain what you mean by "edges" and "sum up values ... to infinity", given your data stop at $x=94$, which seems just a little short of $\infty$?  Are your "probability values" actually *relative frequencies*? (They look like counts divided by $43779$.) If so, they are best analyzed in terms of the counts themselves. Please note that this is not a regression problem: it's a distribution estimation problem. Using regression techniques is likely to go awry.
Comment: @whuber: Thanks for your response! 1) By edges I mean values close to 23 and 94 - I think this is called the RUNGE PROBLEM; 2) Yes, my probability values are actually relative frequencies.; 3) And by sum up, I'm referring to a currently unknown function that fits my data and that I can use for calculations such as a summation from a value k=26 to ∞.; Thanks for the valuable hint of 'distribution estimation'! - What do you mean by _'... analyzed in terms of the counts themselves'_, would you please explain? - I'm really desperate ...
Comment: ... since I'm not very familiar with tools I could use to proceed with my calculations and for calculations I need an estimated function :/
Comment: Your data will exhibit "oscillating edges" because the relative uncertainty is greater for any low count than for a higher count.  An accurate fitting procedure will take this into account. That's routine. Your special problem concerns a gross extrapolation beyond what you have actually observed: the summation to infinity. There's nothing in these data that give any direct information about that sum. To make progress, you have to adopt an assumption--either explicitly or implicitly--about the distribution of the frequencies for higher values of $x$.
Comment: My assumption was a binomial distribution but it doesn't really 'represent' my data. Would you kindly give me a hint for an appropriate assumption?
Comment: The best possible hints would be based on a consideration of what this simulation is doing. As I pointed out, there is *no* information in the data themselves that tell us about what happens for $x$ between $94$ and $\infty$. All we know is that such values are relatively rare, because you haven't yet observed anything greater than $94$.
Comment: Between x and ∞ the relative frequency is asymptotically getting close to 0 but unfortunately I'm not able to let the simulation run in order to get large samples.
Comment: Could you briefly describe what you're simulating (and how)?
Answer: I would suggest that you go back to the original data and use methods like those posted here to find the best fitting distribution.
My apologies for not writing Python code. I do not use Python as a development tool. I rescaled the data to be the counting numbers from which it was apparently obtained and wrote the following Mathematica code
(begin code)
x = {23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
   39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
    56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
   72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
    92, 94};
y = {1, 1, 4, 11, 8, 18, 39, 63, 108, 139, 188, 315, 404, 587, 657,
  842, 1002, 1233, 1404, 1533, 1677, 1833, 1898, 2053, 2009, 2136,
  2193, 1975, 2008, 1852, 1830, 1617, 1529, 1364, 1288, 1152, 1040,
  934, 785, 665, 593, 505, 402, 341, 293, 233, 210, 173, 141, 115, 82,
   53, 50, 49, 31, 31, 21, 14, 9, 11, 6, 4, 4, 5, 2, 2, 2,
  2};
s =.; m =.;
model = s m^x Exp[-m]/x!;
H = NMinimize[{Norm[y - model]}, {{s, 20000, 100000}, {m, 40, 60}}]
s = H[[2, 1, 2]];
m = H[[2, 2, 2]];
Show[ListPlot[Transpose[{x, y}], PlotStyle -> {Blue}],
 ListPlot[Table[{t, s m^t Exp[-m]/t!}, {t, 23, 94, 1}],
  PlotStyle -> {Red}]]
y - model
(end code)
The results are not quite Poisson.
{1050.39, {s -> 39747.1, m -> 49.1786}}

Blue for data, red for Poisson
Hope that helps.


Mapa do Google Maps desapareceu

Question: Olá, estou usando a API JS V3 do Google Maps. Fui estilizar a página e o mapa desapareceu.
jQuery, CSS e HTML:

$(function() {
  $('.nav-toggle').click(function() {
    if ($(".nav").hasClass("side-fechado")) {
      $('.nav').animate({
        left: "0px",
      }, 100, function() {
        $(".nav").removeClass("side-fechado");
      });

      $('#map-canvas').animate({
        left: "170px",
      }, 100);
    } else {
      $('.nav').animate({
        left: "-170px",
      }, 100, function() {
        $(".nav").addClass("side-fechado");
      });

      $('#map-canvas').animate({
        left: "0px",
      }, 100);
    }
  });
});
* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
html {
  height: 100%
}
body {
  height: 100%;
  margin: 0;
  padding: 0
}
.container {
  height: 100%;
}
#map-canvas {
  width: 100%;
  height: 100%;
  position: relative;
  float: none;
}
.nav {
  background: #5F9EA0;
  min-height: 100%;
  font-size: 1em;
  position: absolute;
  top: 0;
  left: 0;
  width: 170px;
}
.nav ul {
  padding: 10%;
}
li {
  display: block;
  width: 100%;
  margin: 5%;
}
.nav-toggle {
  position: absolute;
  top: 0;
  right: -43px;
  color: #FFF;
  cursor: pointer;
  width: 44px;
  height: 24px;
  z-index: 1000;
  display: block;
  background: #444;
  padding: 12px 6px 6px 6px;
}

Seu código: 123

Nome: Leonardo

Onde trabalha: Oi

Editar perfil

Deslogar

Alguma ideia do que pode ser?
Answer: O problema é que você adicionou um
 com a classe drop e ele está sem altura definida.
Você vai conseguir ver o mapa ao adicionar a seguinte regra no arquivo CSS:
.drop {
  height: 100%;
}

Só que você vai perceber que o mapa ficou por cima de tudo. Para corrigir esse problema adicione uma margem à esquerda no #map-canvas do tamanho da sua barra lateral, a sua regra tem que ficar assim:
#map-canvas {
  width: 100%;
  height: 100%;
  position: relative;
  float: none;
  margin-left: 170px;
}

Comment: Obrigado! Porém, tirei o margin-left: 170px do #map-canvas, pois ficava uma margem grande quando o menu estava escondido, daí coloquei um z-index: 1 no .nav

Mapa do Google Maps desapareceu


Probability of reaching node A from node B in exactly X steps

Question: I have a three-node matrix with two edges (A-B and A-C). I would like to determine what the probability is starting from B and ending at C in exactly 100 steps.
I have only written out probabilities:
<code>P(A|B) = 1
P(B|A) = 0.5
P(A|C) = 1
P(C|A) = 0.5
</code>
But there are so many combinations of ways to get from B to C in exactly 100 steps using these probabilities. Any suggestions on how to continue this problem?
Comment: Thanks you! I get a transition matrix of ([0,.5,.5],[1,0,0],[1,0,0]) where the first block [] is the top row. The rows and columns are labeled A, B, C. When I multiply the initial vector times (transition matrix)^100, I get [0, 0,5, 0.5], which means it has 1/2 chance of being at B and half chance of being at C. This makes sense because it will be at either B or C after an even number of moves, and A after an odd number of moves.
Comment: I'm so sorry. I somehow "edited" your comment, when I meant to just "comment"!!
Answer: After an odd number of steps you must be at A and after an even number of steps you will be in either B or C, each with probability 0.5, therefore after 100 steps the probability of being in C is 0.5
Edit
More formally we can define a Markov chain with transition matrix:
$$ T = \left(\array{0&\tfrac{1}{2}&\tfrac{1}{2}\\1&0&0\\1&0&0}\right) $$
Now we can compute $T^2$ and $T^3$ to show that for $n\ge 1$, $T^{2n-1}=T$:
$$ T^2 = \left(\array{1&0&0\\0&\tfrac{1}{2}&\tfrac{1}{2}\\0&\tfrac{1}{2}&\tfrac{1}{2}}\right) $$
$$ T^3 = \left(\array{0&\tfrac{1}{2}&\tfrac{1}{2}\\1&0&0\\1&0&0}\right) = T $$
Therefore we calculate that $T^{100}=T^2$ and that $x_0 T^{100} = x_0 T^2$
$$ x_0 T^2 = \left(\array{0&1&0}\right) \left(\array{1&0&0\\0&\tfrac{1}{2}&\tfrac{1}{2}\\0&\tfrac{1}{2}&\tfrac{1}{2}}\right) = \left(\array{0&\tfrac{1}{2}&\tfrac{1}{2}}\right) $$


Vue router Auth-guard function doesn't check Vuex store state

Question: I am trying to set-up an auth-guard for a profile page. I am using Vue (2.0) with vue-router and Vuex for state. My backend is firebase, but I don't think that's imporant here? My auth-guard function seems unable to properly fetch the requiresAuth state.
This is my auth-guard function:
  {
path: "/profile",
name: "Profile",
component: Profile,
meta: {
  requiresAuth: true
}

}
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes
});

router.beforeEach((to, from, next) => {
  console.log('-----------ROUTE GUARD PROPS--------');
  console.log(store.state.user.isAuthorized);
  console.log(store.state.user);
  console.log('----------- END ROUTE GUARD PROPS--------');
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (store.state.user.isAuthorized) {
      next()
    } else {
      next("/Login")
    }
  } else {
      next()
  }
})

And the result in the browser console when changing pages is the following:

The issue here, to be clear, is why the console.log contradicts the isAuthorized in the print-out of the user module's state. For reference, my store has a user and shared module. The user module has a state with two members: user and isAuthorized. Hence the browser output.
Any ideas why these two conflict?
Comment: So you're asking why `console.log(store.state.user.isAuthorized)` and `console.log(store.state.user)` shows two different things in the console?
Comment: Well, why `console.log(store.state.user.isAuthorized)` appears to be `false` but the `isAuthorized` within the `store.state.user` is `true`. I feel like these should be the same thing?
Answer: This is happening because when you expand an object in the console, it will evaluate the object and its values based on the time of expanding, and not based on the time of logging it. It should tell you when the value was evaluated, if you hover the small blue square with an ! in it.

Meaning that, when you log the object. isAuthorized is indeed false, as you can see when you log the property directly, but when you go and expand the object in the console it's true. Because at some point after logging it, some part of your program has changed ´isAuthorized´ to true.
The display also varies a little whether your console is open at the time of logging the value of not.
The below screenshots are based on the snippet at the end of this post, so you can try it yourself.
The first image is how it looks if the console is closed at the time of logging. Here it simply shows Object, and when you expand it, it shows state is true.

In the second picture, the console was open when logging, and here it shows state: false, and when you expand it, it shows state: true, because it's fetching the current state of the object.

const object = {
  state: false
}

console.log('State:', object.state)
console.log('Object:', object)

object.state = true
Open up your browsers console to see the output.
Comment: I appreciate this answer - especially since I was unaware of the promote aspec (I'm new at this). This is indeed the answer to the question, though I really don't understand why the `state` could be false. But, that appears to be a different question than what I asked.
Comment: @Paco My guess would be, that what ever code that authenticates the user, is run after entering the route in question. Good luck :)


Index of permutation with sorted constraint

Question: I'm trying to find a bijective mapping between a permutation and an index. The permutation refers to a 4-tuple of integers.
Tuples consist of $(a,b,c,d)$ such that $a,b,c,d \in [1;15]$ with $a \leq b \leq c \leq d$. For instance, these are possible:

0,0,0,0
0,2,7,8
8,9,15,15

And these, for instance, are not possible:

1,0,0,0
0,1,2,1

I would like to map these tuples to an index and back. As an example:

0,0,0,0 $\leftrightarrow 0$
0,0,0,1 $\leftrightarrow 1$
...
0,0,0,15 $\leftrightarrow 15$
0,0,1,0 $\leftrightarrow 16$
...
6,15,15,15 $\leftrightarrow k$
7,7,7,7 $\leftrightarrow k+1$
...
15,15,15,15 $\leftrightarrow 3876$ (19 choose 4)

The order given above is not the only one, I am perfectly fine with any bijective mapping as long as it is not too computationally expensive. Can you help me find a formula?
Some background: I'm using this idea to compress sorted lists of integers. Right now I use a loopup table for translation, but it is rather large, so I am hoping to find a way with only rather elementary calculations. (But just out of curiousity, I would also love to see how this can be generalized to different numbers of elements and larger value ranges.)
The number 3876 (total number of valid combinations) is from this question, I also confirmed it experimentally.
Answer: $$f(a,b,c,d)=\binom{d+3}{4}+\binom{c+2}{3}+\binom{b+1}{2}+a$$
Or, if your binomial function doesn't like $\binom{3}{4}=0$, use this:
$$f(a,b,c,d)=\frac{d}{4}\binom{d+3}{3}+\frac{c}{3}\binom{c+2}{2}+\frac{b(b+1)}{2}+a$$
Either way, the values are mapped like this:

0,0,0,0 $\leftrightarrow 0$
0,0,0,1 $\leftrightarrow 1$
0,0,1,1 $\leftrightarrow 2$
0,1,1,1 $\leftrightarrow 3$
1,1,1,1 $\leftrightarrow 4$
0,0,0,2 $\leftrightarrow 5$
0,0,1,2 $\leftrightarrow 6$
...
2,2,2,2 $\leftrightarrow 14$
0,0,0,3 $\leftrightarrow 15$
...
14,15,15,15 $\leftrightarrow 3874$
15,15,15,15 $\leftrightarrow 3875$ (This is $\binom{19}{4}-1$ because the first index is $0$)

Notice that this mapping is expandable. You can increase the max value without affecting the mapping of lesser values: 0,0,0,16 $\leftrightarrow 3976$
The reverse, finding a tuple given its index, involves quartic and cubic equations and is probably easiest with look-up tables. The tables are small, just $16$ elements for each of $b,c,d$, and can also be used in place of the above function as they contain the pre-calculated values of the binomials.
$L_d(0\text{ to }15)$ holds the values $L_d(d)=\binom{d+3}{4}$
$L_c(0\text{ to }15)$ holds the values $L_c(c)=\binom{c+2}{3}$
$L_b(0\text{ to }15)$ holds the values $L_b(b)=\binom{b+1}{2}$
Given index $x$, find the greatest value $d$ for which $L_d(d)\le x$
Then let $x=x-L_d(d)$ and find the greatest value $c$ for which $L_c(c)\le x$
Then let $x=x-L_c(c)$ and find the greatest value $b$ for which $L_b(b)\le x$
Finally, let $a=x-L_b(b)$
Using the tables to find the index:$$f(a,b,c,d)=L_d(d)+L_c(c)+L_b(b)+a$$
Comment: @mafu Years ago, I needed to map number pairs $(a,b)$ to unique indices. As I wrote the list in this particular order, I noticed the relation of $b$ to the triangular numbers. This yielded $f(a,b)=\binom{b+1}{2}+a$. Some time later, I attempted to modify the formula to work for $3$ variables and found that $f(a,b,c)=\binom{c+2}{3}+f(a,b)$, and this pattern continues for any number of variables. $f(a,b,c,d,e)=\binom{e+4}{5}+f(a,b,c,d)$ and so on
Comment: Excellent and very helpful answer. I tested and confirmed it works fine. Can you briefly explain how you arrived at the first line?


how to make query that can generate the equivalent date range and sum the count in mongodb

Question: I am using MONGODB in Ruby on Rails language and I have the following table:
 { "_id" : ObjectId("53d23cb06b69720326e80300"), "starttime" : ISODate("2014-07-24T10:14:04.809Z"), "endtime" : ISODate("2014-07-24T10:02:03.411Z"), "visitor_detail_id" : ObjectId("53cf8b686b697275230f0000"), "stayedtime" : 721.398 }
 { "_id" : ObjectId("53d23cb06b69720326f20300"), "starttime" : ISODate("2014-07-24T09:48:04.595Z"), "endtime" : ISODate("2014-07-24T09:43:04.353Z"), "visitor_detail_id" : ObjectId("53cf8b686b697275230c0000"), "stayedtime" : 300.242 }
 { "_id" : ObjectId("53d23cb06b69720326f30300"), "starttime" : ISODate("2014-07-24T09:48:04.595Z"), "endtime" : ISODate("2014-07-24T09:43:04.353Z"), "visitor_detail_id" : ObjectId("53cf8b686b697275230c0000"), "stayedtime" : 300.242 }
 { "_id" : ObjectId("53d23cb06b69720326ed0300"), "starttime" : ISODate("2014-07-24T09:45:04.368Z"), "endtime" : ISODate("2014-07-24T09:33:04.281Z"), "visitor_detail_id" : ObjectId("53cf8b686b697275230c0000"), "stayedtime" : 720.087 }

here i will give starttime and endtime , then i need to count sum of stayedtime as weekly wise like(Week 1,Week 2,Week 3,Week 4 etc)
I want to be able to generate like this:
   |   period    | stayedtime |
   |  1/7 - 7/5  |  2000  |
   | 25/6 - 31/7 |  ....  |
   | 18/6 - 24/6 |  ....  |
   | 12/6 - 18/6 |  ....  |

Comment: It looks like your `starttime` happens after the `endtime`?
Answer: The MongoDB aggregation framework has various date aggregation operators that can extract information from dates. You can use the aggregation framework from mongoid via the .collection() accessor on the class model you are using:
result = Model.collection.aggregate([

  # Query to match documents
  { "$match" =>  {
    "starttime" => {
      "$gte" => starttime, "$lte" => endtime
    }
  }},

  # Group by intervals
  { "$group" => {
    "_id" => {
      "year" => { "$year" => "$endtime" },
      "week" => { "$week" => "$endtime" }
    },
    "stayedtime" => { "$sum" => "$stayedtime" }
  }}

]);

Or if you prefer to work with timestamp values ( milliseconds since epoch ) in your response you could take this date math approach instead to get the date value at the start of the week:
result = Model.collection.aggregate([

  # Query to match documents
  { "$match" =>  {
    "starttime" => {
      "$gte" => starttime, "$lte" => endtime
    }
  }},

  # Group by intervals
  { "$group" => {
    "_id" => {
      "$subtract" => [
        { "$subtract" => [
          { "$subtract" => [ "$endtime", Time.gm(1970,1,1) ] },
          { "$cond" => [
            { "$eq" => [ { "$dayOfWeek" => "$endtime" }, 1 ] },
            0,
            { "$multiply" => [
              1000 * 60 * 60 * 24,
              { "$subtract" =>  [ { "$dayOfWeek" => "$endtime" }, 1 ] }
            ]}

          ]}
        ]},
        { "$mod" => [
          { "$subtract" => [
            { "$subtract" => [ "$endtime", Time.gm(1970,1,1) ] },
            { "$cond" => [
              { "$eq" => [ { "$dayOfWeek" => "$endtime" }, 1 ] },
              0,
              { "$multiply" => [
                1000 * 60 * 60 * 24,
                { "$subtract": [ { "$dayOfWeek" => "$endtime" }, 1 ] }
              ]}
            ]}
          ]}
        ]}
      ]
    },
    "stayedtime" => { "$sum" => "$stayedtime" }
  }}

])

In either case, the "start of the week" is generally considered to be "Sunday", so if you intend to work from a different day as the "start" then you would need to adjust your math.
This moves the "aggregation" to the server where your only other option would be to process query results in your client code. Generally speaking the server is going to do this much faster and avoid transferring all the matching documents from the collection "over the wire" in order to be processed.
Also see the general aggregation pipeline operators in the official MongoDB documentation for a detailed explanation of each operator used.


Modifying VO bind variables

Question: So, I am trying to modify some VO bind variables inside my application. Currently, I am using executeQueryForCollection() to intercept and modify my variables. Also, I could do the same thing by using VariableValueManager().
I found an article on this website http://www.awasthiashish.com/2015/01/setting-view-object-bind-variable-override-bindparametersforcollection-preparerowsetforquery-executequeryforcollection.html that provides a brief explanation, but it does not say anything about using VariableValueManager().
I was wondering does anyone know what is the best way to intercept and modify bind variables before the query is executed? Thank you in advance!
Comment: Do you mean the View Object bind variables ? Or Jsf Binding variable?
Comment: View Object bind variables
Answer: If you want to do it programmatically in your controller before sending the request to your model using the VariableValueManager, as you mentionned, is the right way to go.
You can use an utilitary function like the following :
<code>public static void setBindVariableValueToViewObjectBindVariable(ViewObject vo, String bindVarName, Object bindVarValue) {
    if (vo != null && bindVarName != null && bindVarValue != null) {
        VariableValueManager vm = vo.ensureVariableManager();
        vm.setVariableValue(bindVarName, bindVarValue);
    }
}
</code>

Modifying VO bind variables


dropdown com javascript puro

Question: Fala galera, bom dia, to precisando de uma ajuda com um dropdown.
a cada doação no banco de dados eu tenho um botão que se clico aparece os itens que foram doados.
estou com a seguinte linha de código:
user-donation.js
const dropdownBtns = document.querySelectorAll('.arrow img');
for (dropdownBtn of dropdownBtns){
    dropdownBtn.onclick = dropDown;
}
function dropDown(){
    const contents = document.querySelectorAll('.dropdown-content');
    for (let content of contents){
        content.classList.toggle("show");
    }
}

user-donations.js

            {% for item in donation.items %}

{{item.material.name}} x{{item.quantity}}

            {% endfor %}

Porém quando eu clico em qualquer um dos dropdownBtn eu mostro os itens de todas as doações e não só a que eu quero.
Alguém será q consegue me ajudar ?
Answer: Coloque um parâmetro na função dropDown() de onde você consegue saber a origem do clique.
function dropDown(e){...
                  ↑

Para saber qual elemento foi clicado e que chamou a função, você usa:
e.target

Com isso você consegue chegar ao elemento .dropdown-content próximo relacionado. Esse elemento é irmão do pai do botão clicado. Você chega nele com:
e.target.parentNode.nextElementSibling;
              ↑             ↑
             pai   irmão adjacente do pai

Exemplo:

const dropdownBtns = document.querySelectorAll('.arrow_img');
for (dropdownBtn of dropdownBtns){
    dropdownBtn.onclick = dropDown;
}
function dropDown(e){
   let alvo = e.target.parentNode.nextElementSibling;
   alvo.classList.toggle('show');
}
.dropdown-content{
   display: none;
}
.show{
   display: block;
}

            {% for item in donation.items %}

{{item.material.name}} x{{item.quantity}}

            {% endfor %}

            {% for item in donation.items %}

{{item.material.name}} x{{item.quantity}}

            {% endfor %}

Nota: nas imagens dos botões você está usando id="arrow". Imagino que esses botões serão repetidos, logo irão repetir o mesmo
  id, o que é incorreto. Um id deve ser único na página. Troque o
  id="arrow" por class="arrow_img".

Se quiser ocultar o que está aberto quando mostra outro, altere o código do for adicionando um if para remover a classe .show do que está aberto:

const dropdownBtns = document.querySelectorAll('.arrow_img');
for (dropdownBtn of dropdownBtns){
    dropdownBtn.onclick = dropDown;
}
function dropDown(e){

   let alvo = e.target.parentNode.nextElementSibling;

   const contents = document.querySelectorAll('.dropdown-content');
   for (let content of contents){
      if(alvo != content) content.classList.remove('show');
   }

   alvo.classList.toggle('show');

}
.dropdown-content{
   display: none;
}
.show{
   display: block;
}

            {% for item in donation.items %}

{{item.material.name}} x{{item.quantity}}

            {% endfor %}

            {% for item in donation.items %}

{{item.material.name}} x{{item.quantity}}

            {% endfor %}

Comment: o `id="arrow"` era pq eu estava tentando algo, mas depois percebi a incoerência, mas valeu por ter notado kkkkk, cara sua explicação foi simplesmente sensacional, consegui resolver o meu problema, muito obrigado.

dropdown com javascript puro


Omitting part of a mongo array when it has a specific value

Question: I have a json array structured like this:
{
    "properties": [{
            "name": "ok",
            "value": 1
        },
        {
            "name": "ok_aswell",
            "value": 1
        },
        {
            "name": "ok_aswell",
            "value": 2
        },
        {
            "name": "get_rid",
            "value": 2
        }
    ]
}
I want my query to return everything except the "get_rid" record:
{
    "properties": [{
            "name": "ok",
            "value": 1
        },
        {
            "name": "ok_aswell",
            "value": 1
        },
        {
            "name": "ok_aswell",
            "value": 2
        }
    ]
}
I tried the suggestions from here: Conditionally include a field (_id or other) in mongodb project aggregation? , however they didn't seem to work.
Answer: Try $filter in projection aggregate
{$project:{
  properties:{
      $filter: {
                 input: "$properties",
                 as: "item",
                 cond: {$ne: ["$$item.name","get_rid"]}
               }
  }
}}


How to launch a windows web service only when an HTTP request is made to its port?

Question: I am running TeamCity on my Windows server. It is a Java-based build service running TomCat and uses a hefty 300MB. I only use it occasionally so it doesn't really merit running all the time, using up memory when other services (websites) could make use of it.
Currently I have a simple protected webpage to start and stop the service when I need to use it.
I have also implemented a script to see when the service hasn't done any builds for a while and shuts the service down automatically.
So when the service is down, going to the TeamCity port (9090) results in no response. I would prefer to be able to visit the port, then something automatically fires up the service and then I can access it again.
Is it possible to have a 'middle man' application/proxy/packet sniffer to listen on port 9090, and if the service is not running, start the service and forward all requests to that service?
I would prefer to implement this as an http packet sniffer to avoid any performance issues proxying all the requests from A to B.
If someone could point me in the right direction that would be great, I plan to implement something in C# if I need to.
Comment: If the server doesn't do anything it will be swapped out to the page file and therefore the RAM it consumes will be again free for other programs. If you use it it will be automatically swapped in. Isn't that what you want?
Comment: I think you've missed the point of TeamCity...
Comment: Peter, I haven't missed the point of TeamCity, I wanted a one click build engine to run occasionally but don't have the resources to run it 24/7. I was interested to see if this solution was possible, if there was something clever I could do.
Answer: I think your own idea is pretty close to a good-enough solution: have a 'middle man' application listen on port 9090 whenever you shut the service down, and on incoming activity it should start the service and exit, freeing 9090 for the TeamCity...
Answer: Just thought I would mention how I solved this problem in the end.
I created a subdomain which runs some code to check if the TeamCity service is running. If it hasn't started then it starts the service and then redirects to the TeamCity site port. If it has already started it simply redirects. When no builds have been started for a period of time, then the service shuts down automatically, freeing memory.


Is this way of exceptions handling good practice?

Question: Would you change anything in this code?
class LocalPort {
public:
    LocalPort(int portNumber) {
      innerPort = new ACMEPort(portNumber);
   }

    void Open() {
      try {
          innerPort->Open();
      }
      catch (DeviceResponseException& e) {
          throw PortDeviceFailure(e);
      }
      catch (ATM1212UnlockedException& e) {
         throw PortDeviceFailure(e);
      }
      catch (GMXError& e) {
         throw PortDeviceFailure(e);
      }
   }
private:
    ACMEPort* innerPort;
};

/////////

try {
    LocalPort* port = new LocalPort(12);
    port->Open();
}
catch (bad_alloc& e) {
    ReportError(e);
    logger.Log("Wyjątek alokacji pamięci", e);
    delete port;
}
catch (PortDeviceFailure& e) {
    ReportError(e);
    logger.Log(e.getMessage(), e);
    delete port;
}

What I tried to above do was to make code below look and act better.
try {
    ACMEPort* port = new ACMEPort(12);
    port->Open();
}
catch (bad_alloc& e) {
    ReportPortError(e);
    logger.Log("Wyjątek alokacji pamięci", e);
    delete port;
}
catch (DeviceReponseException& e) {
    ReportPortError(e);
    logger.Log("Wyjątek odpowiedzi urządzenia", e);
    delete port;
}
catch (ATM1212UnlockedException& e) {
    ReportPortError(e);
    logger.Log("Wyjątek odblokowania", e);
    delete port;
}
catch (GMXError& e) {
    ReportPortError(e);
    logger.Log("Wyjątek odpowiedzi urządzenia");
    delete port;
}
catch (...) {
    ReportPortError(0);
    logger.Log("Wyjątek nieznanego pochodzenia");
    delete port;
}

Did I succeed? Is the first better than the second? What do you think?
Comment: @Space_C0wb0y: Agreed. We should have an auto-migrate for codereview, ideally.
Comment: any advices how to make it "better" are strongly welcome :)
Comment: @dantuch: Well you never `delete port` in the only scope that `port` exists. You have attempted to do it in the `catch` handlers (but not for the case where no exception was thrown; presumably that's done later in your code, which you didn't include in your thus-inaccurate example), but as far as I can tell that won't compile (or, you have another variable named `port` further up the scope hierarchy that you're accidentally `delete`ing instead, probably invoking UB). Summary: either a double-free for something else, or a compile error.
Comment: @closers: why would this be off-topic?
Comment: @JohnSaunders Because it contains working code, for which he is asking for a **code review**. As such, it is too localized for SE, but a perfect fit for said other site. If it was reworked to ask a specific question rather than "What would you change in this code?" it could fit here.
Comment: @Kazark: so, if he reduced the code to just a sample of the technique he's using, would you be ok with the question? I would. Granted, it might be better to break it down into smaller questions, but still, taking his code as a sample of a pattern, rather than as a block of code to review, I think it's ok (IMHO).
Comment: @JohnSaunders Mmm, good point. Yes. At that point the question becomes a general question and not a specific request for a code review (though it might still be good to do some rephrasing in light of the trimmed-down code since his phrasing makes it look like a request for review).
Answer: It seems like you have badly designed exception classes. Why don't you simply add a member-function getMessage to your exception-hierarchy (preferably in the base-class all your exceptions derive from - std::exception provides the method what that returns an error message). This way, you could simply catch all exceptions in one statement, and handle them all in the same way.
class DeviceResponseException : public std::runtime_error {
public:
    DeviceResponseException() : std::runtime_error("Some error message") {}
};

class ATM1212UnlockedException : public std::runtime_error {
public:
    ATM1212UnlockedException() : std::runtime_error("Some other error message") {}
};

Then in your code, you can do this:
try {
    std::auto_ptr<ACMEPort> port(new ACMEPort(12));
    port->Open();
}
catch( std::runtime_error & e) {
    ReportPortError(e);
    logger.Log(e.what(), e);
}

Since your exception-classes all derive from std::runtime_error, this catch-clause catches them all. This is OK, since the handling is the same for all cases. If you have specific exceptions that require special handling, you add additional catch-clauses.
Also, instead of calling delete port in the exception handler, you should use an std::auto_ptr or boost::scoped_ptr or something of the kind. Read about RAII.
Comment: RAII would take away all those `delete`s and `bad_alloc` but rest will remain the same?
Comment: so I can simply make a new exception class, that all those small exception classes will inherit from? I want to group exceptions that are similar to each other, caused by the same component
Comment: @dantuch: You can group exceptions by deriving from the same class. You exception hierarchy can have more than two levels.
Comment: One problem. According to the standard std::Exception does not take any parameters in its constructor. So it is usually better to derive from one of the exceptions that have been derived from std::exception. Personally I always use std::runtime_error. This works exactly like you want std::exception to work above.
Answer: Yes, I would:

have one single exception class and thus:
not translate exceptions from one type to another
catch the exceptions much higher up in the code and thus:
not end up writing more exception handling code than real code
and I would not create objects using new, and if I did I'd use smart pointers

Basically, I think you have completely misunderstood how exceptions should be used.
The best single change you could make to your code is to replace:
ACMEPort* port = new ACMEPort(12);
port->Open();

with:
ACMEPort port(12);
port.Open();

and similarly elsewhere - the need for catching exceptions then goes away.
Comment: You should not just have one single exception class. You should however have one singe base-class for all exception classes.
Comment: Can you provide some (really) quick changes that can improve my code? Don't mind my quiestion if it would take some time.
Comment: @Space Matter of opinion. I have got on very well for many years with a single exception class.
Comment: @Space_Cowb0y: I usually have zero/one exception class per library. Unless there is some very specific type of exception that can be caught and handled separately for correction purposes. So though the concept of building an exception hierarchy is nice in practice it is rare (and we have std::exception for the common base).
Answer: I'd move the exception handlers into the class and let the class handle errors instead of forcing all callers to handle it. This way you can do clean up of the pointer (if you really have to have a pointer for some reason) by checking the result value of Open():
class LocalPort {
public:
    LocalPort(int portNumber) {
      innerPort = new ACMEPort(portNumber);
   }

    bool Open() {
      try {
          innerPort->Open();
          return true;
      }
      catch (DeviceResponseException& e) {
          throw PortDeviceFailure(e);
      }
      catch (ATM1212UnlockedException& e) {
         throw PortDeviceFailure(e);
      }
      catch (GMXError& e) {
         throw PortDeviceFailure(e);
      }
      catch (bad_alloc& e) {
         ReportError(e);
         logger.Log("Wyjątek alokacji pamięci", e);
      }
      catch (PortDeviceFailure& e) {
         ReportError(e);
         logger.Log(e.getMessage(), e);
      }
      return false;
   }
private:
    ACMEPort* innerPort;
};

LocalPort* port = new LocalPort(12);
if (!port->Open()) {
  delete port;
}


How do I resolve a unresolved dependency error after using Composer to install modules?

Question: I'm going to pull my hair out if I stare at this problem any longer. I've seen the similar questions and tried everything but I can't fix this issue with module dependency versions.
I'm using Composer require drupal/<module_name> and I've tried including specific versions too but that hasn't worked. I see that the current version number isn't being displayed at the end of the error message which makes me wonder whether the system knows what version is even installed?
I also don't understand how so many modules can be asking for different versions of the same dependency. How can you possibly resolve that :|
I should also add that I was in the process of converting manually installed modules into Composer controlled dependencies. I'm not sure if that would make a difference.
It really seems to me that Drupal doesn't know what versions of Modifiers and Paragraphs are installed but I don't see how.
Comment: I'd always start with `rm composer.lock && rm -rf vendor/ && composer install -n` on a local copy of the site, followed by `drush cr && drush -y updb`.
Comment: Also check that composer (the tool) itself is up to date!
Comment: Thanks for the suggestions. I tried the above but even after using `composer clear-cache` it still shows "cloning XXX from cache" which is odd. The update still shows the "unresolved dependency" messages and the update looks like this:

`>  [notice] Update started: paragraphs_library_update_8004
>  [error]  Cannot add field paragraphs_library_item_revision_field_data.label: field already exists.
>  [error]  Update failed: paragraphs_library_update_8004
[error]  Update aborted by: paragraphs_library_update_8004
[error]  Finished performing updates.`
Comment: I've just edited the question above with updated details
Answer: So, the system couldn't decide what version of the modules were installed. Here is a fix:
https://www.drupal.org/project/modifiers/issues/3052416
Basically, install Git Deploy module to add versioning details to modules .info files.


Novell access manager VMC proc 200% cpu then restarts

Question: First off we have an SR opened with Novell but I figure I'd ask here anyway.
The quick scenario is this.
When the load average on one of the access gateways (LAG) spiked above 2.0 I saw some CPU wait time and the ics_dyn proc was over 50% and the java proc was over 112%.- It lasted only about 1 second. The load average dipped back down right away and the offending processes were dropped to under 10% CPU.
I went to the web console and saw the LAG was not responding. I refreshed and it went green right away.
It looks like the processes are spiking, the cpu goes over 100% and other process are now waiting for CPU time ics_dyn restarts and everything goes back to normal but the cycle starts all over again.
<code>    grep RESTARTED ics_dyn.log
Mar 29 09:34:58 <SERVERNAME> vmcontroller: AM#404514000: AMDEVICEID#: AMAUTHID#0: AMEVENTID#0: VM-0 DOWN, being RESTARTED (Tue Mar 29 09:34:57 2011 ). restarted 60 times. fastRestartMode.
Mar 29 09:38:33 <SERVERNAME> vmcontroller: AM#404514000: AMDEVICEID#: AMAUTHID#0: AMEVENTID#0: VM-0 DOWN, being RESTARTED (Tue Mar 29 09:38:32 2011 ). restarted 61 times. fastRestartMode.
Mar 29 09:51:17 <SERVERNAME> vmcontroller: AM#404514000: AMDEVICEID#: AMAUTHID#0: AMEVENTID#0: VM-0 DOWN, being RESTARTED (Tue Mar 29 09:51:16 2011 ). restarted 62 times. fastRestartMode.
</code>
Lots of these in dmesg.
<code>ics_dyn[11708]: segfault at 1c ip b5caf868 sp b22561d0 error 4 in libproxy.so.1[b5b8b000+1e2000]
</code>
I know there is going to be requests for more info and I'm prepared to provide it. The problem is kinda strange and I think it is a bug in the access manger software.
Version  2.7.3  (20100428_184640)
  Copyright (c) 1999-2009 Novell, Inc.
  All rights reserved.
Field Patches:
  Field Patch 3 -- 20100425
Answer: After coredump and log analysis the fix was provided by Novell. It's a bug in their code and they supplied a recompiled libproxy.


Trouble simplifying conditional

Question: I'm having trouble simplifying a conditional statement. It looks like this:
There is an array of arrays like this, dice = [ [a, b], [c, d] ].
a, b, c, and d representing random numbers on a dice 1 > 6.
Every array in the array represents a roll of two dice where the last roll is [c, d] = [2, 5] for example, and the second-last roll is [a, b] = [3, 6] for example.
Now if you roll 2 x 1 in a row or 2 x 6 in a row something happens.
so,  a + c || a + d and b + c  || b + d may not be 2 or 12.
The conditional below works but I think if you open the door to hell it looks prettier.
dice = last roll = [c, d]
prev = second last roll = [a, b]
if (dice[0] + prev[0] === 2 || dice[1] + prev[1] === 2 || dice[1] + prev[0] === 2 || dice[0] +
prev[1] === 2 &&
dice[0] + prev[0] === 12 || dice[1] + prev[1] === 12 || dice[1] + prev[0] === 12 || dice[0] +
prev[1] === 12){
//something happens here
}

Comment: Is your question's code missing parentheses around each of the set of ORs? i.e. should it be `if ((dice[0] + prev[0] === 2 || dice[1] + prev[1] === 2 || dice[1] + prev[0] === 2 || dice[0] +
prev[1] === 2) &&
(dice[0] + prev[0] === 12 || dice[1] + prev[1] === 12 || dice[1] + prev[0] === 12 || dice[0] +
prev[1] === 12)) {`
Comment: You are right @BenStephens, they are present in the app itself.
Comment: I've managed to reduce the condition to 23 characters.
Answer: I would do something like this:
var combinations = dice.reduce(function(acc, curr) {
    return acc.concat(prev.map(function(curr2) {
        return curr + curr2;
    }));
}, []);

if (combinations.indexOf(2) !== -1 && combinations.indexOf(12) !== -1) {
    //something happens here
}

In ES6 it is a little bit shorter:
const combinations = dice.reduce((acc, curr) => acc.concat(prev.map(curr2 => curr + curr2)), []);

if (combinations.indexOf(2) !== -1 && combinations.indexOf(12) !== -1) {
    //something happens here
}

What this actually does is calculate all combinations (additions) and then check whether one is 2 and one is 12.
Comment: Very nice. The ES6 version could use `includes` instead of `indexOf`
Comment: Agreed. `indexOf` is just an oldschooled habit of me. :-D
Answer: I came out with a simpler solution more fitted to your need

const throws1 = [[1, 2], [3, 4]]
const throws2 = [[1, 2], [3, 1]]
const throws3 = [[1, 6], [6, 1]]

const checkCondition = (prev, dice) => [1, 6].every(res => prev.includes(res) && dice.includes(res))

console.log(checkCondition(...throws1))
console.log(checkCondition(...throws2))
console.log(checkCondition(...throws3))
Comment: Please may you also explain the code?
Comment: @Noud I simplify my answer take a look
Comment: Unfortunately however this does not answer OP's question. All the possible throws that get inside OP's `if` statement are  `[[1,6],[1,6]]` or `[[6,1],[6,1]]`.
Comment: @Nuod tell if you need more explanation and if that make sense
Comment: @R4ncid it's not for me, but for the OP (or any other user) who may not understand how your code works.
Comment: @R4ncid, thanks for the effort. And yes I need a deeper analysis of the code you provided.
Comment: My understanding of the question makes me think that `some` should be replaced by `every` in this answer.
Comment: @BenStephens you're absolutely right. I updated the comment
Comment: @albjerto because I deleted my previous comment it now looks like you're agreeing with a comment of mine that you weren't, sorry about that.
Answer: The condition can only happens when both dice and prev contain 1 or 6. So, we can just check that.

let throws = [[5,3],[1,6]];
let prev = throws[0];
let dice = throws[1];

if ((prev.includes(1) && dice.includes(1)) || (prev.includes(6) && dice.includes(6))){
  console.log("2 or 12 occurs")
}
else {
  console.log("2 and 12 do not occur")
}
Answer: What about something like the following?:

const one_and_six_found = (roll) => roll.includes(1) && roll.includes(6);
const two_rolls_have_one_and_six = (roll1, roll2) =>
  one_and_six_found(roll1) && one_and_six_found(roll2);

console.log(two_rolls_have_one_and_six( [1, 6], [1, 6] ));
console.log(two_rolls_have_one_and_six( [6, 1], [1, 6] ));
console.log(two_rolls_have_one_and_six( [5, 1], [1, 6] ));
Comment: I believe I managed to reduce the condition to 23 characters :)
Answer: Here's the conditional simplified:
2*(a + b + c + d) == a*b + c*d + 16

Comment: What if b is 2 and d is 5?
Comment: `let a = 1, b = 2, c = 6, d = 5;` :: `a % 5 + c % 5 == 2` #true :: `a + b + c + d == 14` #true :: `((a + c === 2 || b + d === 2 || b + c === 2 || a + d === 2) && (a + c === 12 || b + d === 12 || b + c === 12 || a + d === 12))` #false
Comment: Thanks! I amended the answer to address your comments. (I'm confused by what seems like someone having removed a similar comment to this that I posted here yesterday.)
Answer: I wasn't 100% sure about a couple of these answers so I thought I'd test them:

const orig = ([a, b], [c, d]) =>
  ((a + c === 2 || b + d === 2 || b + c === 2 || a + d === 2) && (a + c === 12 || b + d === 12 || b + c === 12 || a + d === 12));

const A = ([a, b], [c, d]) => 2*(a + b + c + d) == a*b + c*d + 16;
const B = (prev, dice) => [1, 6].every(res => prev.includes(res) && dice.includes(res));
const one_and_six_found = (roll) => roll.includes(1) && roll.includes(6);
const C = (roll1, roll2) => one_and_six_found(roll1) && one_and_six_found(roll2);
const D = (prev, dice) => (prev.includes(1) && dice.includes(1)) || (prev.includes(6) && dice.includes(6));
const E = (prev, dice) => {
  const combinations = dice.reduce((acc, curr) => acc.concat(prev.map(curr2 => curr + curr2)), []);

  return (combinations.indexOf(2) !== -1 && combinations.indexOf(12) !== -1);
};

const test = (fn) => {
  for(let i = 1; i <= 6; i++)
    for(let j = 1; j <= 6; j++)
      for(let k = 1; k <= 6; k++)
        for(let l = 1; l <= 6; l++)
          if(fn([i, j], [k, l]) !== orig([i, j], [k, l])) {
            console.log('failed on ' + [i, j, k, l].join(', '));
            return false;
          }

  return true;
};

console.log('A', test(A) ? 'success' : 'failed');
console.log('B', test(B) ? 'success' : 'failed');
console.log('C', test(C) ? 'success' : 'failed');
console.log('D', test(D) ? 'success' : 'failed');
console.log('E', test(E) ? 'success' : 'failed');
Comment: D returns true if dice and prev have 1 in them; it will also return true if dice and prev have 6 in them; it doesn't require that both of these things are true. If the `||` in D was changed to `&&` it would basically do the same as B and C.
Comment: Ben Stephens, is test(D) failing because of the possibiltity of 4 x 1 or 4 x 6 in a row. Which is not included in the conditional.
Comment: Hi @Noud I'm not sure if this is a question or a statement (and, therefore, I've not understood the original question).

Trouble simplifying conditional


Multivariate analysis for a data with different metric units

Question: I have some weird data that I don't know how to treat them!
I have a data of metabolite measurements in different groups of samples with 5 replicate in each group:
Groups      treatment   diet
Group1:     yes         A
Group2:     NO          A
Group3:     yes         B
Group4:     No          B

Each sample has been measured for 500 different metabolites. but the measurement values are so weird since:

The measured values are the signals and not the concentration, which means the metric units are different (i.e. value 2 means totally different in metabolite 1 comparing to metabolite 2).
There are some missing values, which means that it wasn't possible to detect those metabolites in that specific sample but it doesn't mean it is zero! E.x. as below.
samples         metabolite1
Group1          12374
Group1          NA
Group1          NA
Group1          NA
Group1          46091
Group2          128025
Group2          90689
Group2          129950
Group2          76813
Group2          66439

What I want to do:

First, I would like to do a principle component analysis to see if there is any clear separation between the groups.
And then I would like to study if any of the factors: treatment or diet or the interaction has any effect on each metabolite.

What do you suggest me to do with this data?
P.S. I analyze my data in R!
Comment: Regarding your "missing data", these are *censored* because the values are below the limit of detection. You might find this thread helpful: [How small a quantity should be added to x to avoid taking the log of zero?](http://stats.stackexchange.com/q/30728/7290) More generally, what are you trying to find out from these data? What model do you want to fit?
Answer: Missing values
As @gung says, a first step would be to go and find out why there are NAs:

concentrations are below LOD/LOQ/signal below critical value: ask for the uncensored values. At the very least make sure that in future data is not censored and instead you are provided with the critical values/LOD/LOQ in addition to the data.
Btw: known LOD and LOQ implies that a calibration is available.
Obviously, if NAs are not due to censoring but mean that for some reason measurement was not possible, you'll have to go on with missing values.
Whether the NAs come from (left) censoring or other reasons is important for dealing with them.
Ivana Stanimirova from Katowice has done a lot of work about data analysis with missing values both completely at random (CAR) and/or due to censoring.
I. Stanimirova: Practical approaches to principal component analysis for simultaneously dealing with missing and censored elements in chemical data, Analytica Chimica Acta, 796 (2013) 27–37.
DOI: 10.1016/j.aca.2013.08.026
may be a good starting point.

Signals instead of concentrations and scaling

are not very problematic:
different metabolites come at vastly varying concentrations as well, so you'd anyways need to think about scaling
if all signals are physically the same unit and don't vary in their order of magnitude, you may keep them as they are
see also: Variables are often adjusted (e.g. standardised) before making a model - when is this a good idea, and when is it a bad one?
Sometimes it is possible to set up scaling according to some control group.

Study factors
ASCA (ANOVA Simultaneous Component Analysis), PCA-ANOVA and rMANOVA (regularized MANOVA) could be starting points.


Can't understand parallel progression. Can explain with example?

Question: I'm sorry, I'm very noob at music theory.
I know major scales, minor scales (natural, harmonic and melodic) and them chords.
Since yesterday (so funny) I believed that to compose a track (I love trance music) you have to choose a scale and play all its grades (or a pentatonic) and play chords (obviously not simple as described), some are consonant and some dissonant and need to be resolved, choose modes etc.
Online learning (https://learningmusic.ableton.com/advanced-topics/mommy-whats-a-record.html), I saw strange progression: in example in a same track/song the chord progressione can be:
Cm (C, Eflat, G, B flat) -> G minor (G, B flat, D, F) -> A minor7 (A, C, E, G).
So I think the scale of this track change every time, so it has no a defined scale as most of Western music.
And what about a melody? Should melody use anyway notes of choosen scale?
Sorry, this could be a stupid answer and I feel so stupid asking this, but I'm a lot confused.
Thanks in advance
Comment: Welcome to the community, Alessio! I'm not 100% sure I understand your question and don't want to give you an unhelpful answer. Are you asking how to determine the key of a chordal progression? Or are you asking how the key of a piece changes so that one piece moves through multiple keys?
Answer: Cm and Gm chords can come from a shared scale although that scale could be either C minor or G minor. If you are familiar with roman numerals for chords, you would have i and v in C minor or iv and i in G minor. For the moment let's not worry about choosing between the two, and let's move on to the Am chord.
Am is not in C minor or G minor. Typically the use of that chord in either scale would be labelled as a borrowed chord. Borrowed chords being chords from the parallel key. The parallel key of C minor is C major, G minor's parallel key is G major. So Am is borrowed "vi" in C minor, and borrowed "ii" in G minor.
That give us the theory background regarding scales, key, and how to label the chords. Now on to what I think your actual question is.

So I think the scale of this track change every time...

I think you mean "the scale will change with each chord, because there is not one scale for all the chords."
I'll assume a simple tonal style where the chords and melody come from the same scale.
There is a shared scale for Cm and Gm so you do not need to change the scale between those two chords. It is not necessary to use the shared scale, but let's just be aware we can use a shared scale.
What happens in the melody over the Am chord - and how that may be perceived as a scale change - will depend on which notes are used. The important thing is to match up the Am chord tones to a given scale. Let's consider a single melody note over the Am chord, like this:

If the melody is "A" over the Am in G minor, then "A" is the 2nd
scale degree in G minor. Melody/scale-wise you don't leave the scale.
But we get the flavor of a borrowed chord.
If the melody is "C" over the Am in either G minor or C minor, then
the "A" is either the 4th degree or G minor of the tonic of C minor.
Again, we get the flavor of a borrowed chord, but the scale used for
the melody hasn't changed.
If the melody is "E natural" over the Am in either key, then the "E"
actual is from outside the minor scale. This would be a change to
the scale.

The rhythm is important in this regard. The three examples above would probably be long values (perhaps a vocal part.) If we use just one note, we can isolate that note to a common note between the borrowed chord and the scale in use.
If you were playing a faster rhythm - like a fast guitar solo - we can't really isolate the melody to just the common tones. To get the melody matching the chord it will change the scale. So again rhythm is important.
Of course you can play anything you want over those chords. You can pick scales that don't "match" the chords. My answer assumes a typical approach where melodies and scales match chords.
If you do not want a clear change in scale, use common tones between the chord and scale.
Otherwise, change the scale and listen to the contrast or expressive effect it provides.
These are choices you can make.


Create script that will build sub-domain (linux/whm/cpanel) based on the values from webform

Question: I don't know whether this can be done. I need to create sub-domain in a server using puppet based on the values from a web form.
Answer: if you save your form data on disk, you can work with external node classifiers.
more info here: https://puppet.com/docs/puppet/6.3/nodes_external.html


Given probability x, how likely is it that probability y is due to chance?

Question: I wrote a Python script searching text for words and separating unique and non unique words.  Running the pages I have through my program, I find 1041 unique words out of 3742 total, so roughly 27% of all the words are unique.  Yet when I look at the first word of each page, 33 of the 44 words starting each page are unique, for a 75% ratio.
How do I measure how likely this 75% result is due to chance, given the 'normal' 27% unique word probability? I have some experience in R if that helps at all in explaining things to me.
Comment: You condition on events rather than probabilities. In this case the *event* you condition on is an observed proportion, not a probability.
Comment: You could try modelling this process with a Bernoulli Distrbution  http://en.wikipedia.org/wiki/Bernoulli_distribution  having a success probability of 0.27.
Comment: This Q&A is fairly similar:  http://stats.stackexchange.com/questions/920/test-if-probabilities-are-statistically-different
Answer: I think that the term 'by chance' is not clearly defined as long as you do not have a specific hypothesis you want to test.
You could regard the full text as your population. The complete 'census' of all words resulted in the 'true' parameter $\theta=.27$, say.
Now you describe that you took a 'sample' of words, whose characteristic is page position (first word on each page) and you want to test the hypothesis, whether page position affects the probability of a word being unique.
Hence you want to test: $$H_0:\theta=.27$$ which is equivalent to asking whether the sample of words comes from the population of all words (your full text) or forms an own (sub-) population.
If we regard the 44 pages (words) as independent draws from a Bernoulli distribution, the number of positive outcomes $X$ is Binomial. Now we need
$$P(X \ge 33|H_0) \approx 4.68*10^{-11}$$
As you can verify using R pbinom(32,44,.27,lower.tail=FALSE). This probability is very small, so you can say with very low probability of error that observing 33 unique of 44 words was not caused by chance, because if the null hypothesis was true the pobability of this event happening by chane alone would be very small. Hence, $\theta$ of the sub-population of words at the top of all pages seems to be different from your population $\theta$ of .27.
Put differently, position seems to have an impact on the probability of uniqueness. Only in a very small proportion of cases you would make an error when claiming this.
Comment: awesome, thank you! I will start looking at the pbinom function right away.  The word list I'm looking at is the Voynich manuscript, btw  ...
Comment: (+1) In rounding $1041/3742$ to $0.27$ you destroy all but the most significant digit in your probability(!), which should equal $1.116\times 10^{-10}$. It may also be worth noting that we should interpret your "If we regard" as an *approximation* to the true probability indicated by your model, which is of sampling *without* replacement. The sample consists of the 44 initial words out of the population of 3742 words. This lowers the answer to $8.41\times 10^{-11}$ as computed by `phyper(32, 1041, 3742-1041, 44, lower.tail=FALSE)`.
Comment: That is correct: changing a p-value that is already less than $10^{-10}$ by an order of magnitude will not change any conclusions.  I was motivated to add that comment because it might help readers who are addressing the same problem but with different numbers; in some cases the distinctions I made will be important.
Comment: I actually thought a bit about why this might happen and with what sorts of texts. Independent from the info you gave I thought that it might be a typesetting issue, in the sense that short words like 'a', 'the' (= not unique) etc often end up at the lower page and new pages are started with a longer word, which often are nouns etc, but more often unique. When writing the manuscript by hand Voynich might have done so willingly or intuitively.
Comment: @whuber +1 Thanks, adds a lot! Though the p-value is changed, the conclusion would perhaps not change  (p<.0001 in all cases).
Comment: @whuber I thought about it a bit more: isn't the issue here that I assumed (and approximated) a finite population by assuming sampling from an infinite population, whereas one would need to use hypergeometric if the population is small enough to be regarded as finite? That is, as the population size (words of the full text) grows, one could use my 'approximation' with less 'error', but hypergeometric would be more exact.
Comment: Thanks, my memories on significant digits aren't as good as they need to be, hehe.  I agree with the typesetting idea as an explanation, at the least it needs to be investigated, I'd need to look at the original manuscript, I'm just using ascii transliterations right now.
Comment: If interested, I've now done the first 78 pages and the stats are holding.  23.2% of all words are unique, but 73% of the first words of each page (57/78) are unique. Interestingly, the second word of each page is only unique 24% of the time, right at the average.
Comment: @RobBerkes If you could identify this pattern in other texts written by hand at that time, it would point to the fact that the language Voynich used is actual a 'real' one and not just fantasy.


How are the conditions supposed to be for $\frac{d}{dx}{a^{x}=a^{x}\ln(a)}$ & $\int{a^{x}dx=\frac{1}{\ln(a)}a^{x}}$?

Question: $$\frac{d}{dx}{a^{x}=a^{x}\ln(a)}\tag{1}$$
$$\int{a^{x}dx=\frac{1}{\ln(a)}a^{x}},a>0,a\neq1\tag{2}$$
This is what I found written in my book. I was wondering if they wrote it wrongly:
$$\frac{d}{dx}{a^{x}=a^{x}\ln|a|}\tag{1'}$$
$$\int{a^{x}dx=\frac{1}{\ln|a|}a^{x}},|a|\neq1\tag{2'}$$
Can $(1)$ & $(2)$ be written as $(1')$ and $(2')$. Are $(1')$ and $(2')$ mathematically correct? This (see 'Addendum') might help you in answering the question.
PS: Notice that in (1') and (2'), I did not put absolute value signs around $a$, like $|a|^{x}$, in LHS.
Answer: The function $f(x) = a^x$ is only continuously defined on the entire set of real numbers for positive values of $a$; if $a$ is not positive, the function is not differentiable at all.  So any formula for $\frac{d}{dx}a^x$ implicitly assumes $a > 0$ as a condition, which means that the absolute value symbols are unnecessary.
Comment: Maybe include some parts where $f$ uses another function $g$, not the constant $a$ for the absolute value to be explained?
Comment: Sir, did you notice that in (1') and (2'), I did not put absolute value signs around $a$ in LHS?
Comment: Yes, my point is that the expression $\frac{d}{dx} a^x$ is **only meaningful** if we assume $a>0$, in which case there is no difference between writing $\ln |a|$ and $\ln a$.
Comment: @mweiss What I mean is that, maybe you can explain what happens when $f$ is an exponential function of the form $(g(x))^x$? Something like that to explain the absolute value?
Comment: @soupless I'm not sure I understand what you mean.
Comment: @tryingtobeastoic Notice that $\displaystyle(-7)^\frac5m$ is undefined whenever $m$ is even.
Comment: @soupless That would not justify using absolute values. Once again, you are missing the point of the answer. If $g(x)\lt0,$ then the expression $g(x)^x$ is meaningless to begin with,
Answer: Before answering your question, I first need to establish what the notation $a^x$ even means: otherwise, you are likely to just stay confused. The notation $a^x$ is an abbreviation for the somewhat more tedious expression $\exp[\ln(a)x],$ where $\exp$ is a function $\mathbb{R}\rightarrow(0,\infty)$ defined by the functional equation $\exp(x+y)=\exp(x)\exp(y)$ with $\exp(0)=1$ and $\exp(1)=\lim_{n\to\infty}\left(1+\frac1{n}\right)^n=:e,$ and $\ln$ is the inverse function. Typically, we use the notation $\exp(x)=e^x$ when doing calculus, but the definition for $a^x$ stays the same.
Keeping this in mind, you can use the chain rule to conclude that $$\frac{\mathrm{d}}{\mathrm{d}t}a^t=\frac{\mathrm{d}}{\mathrm{d}t}e^{\ln(a)t}=\ln(a)e^{\ln(a)t}=\ln(a)a^t.$$ However, in order to be able to make this conclusion, $\ln(a)$ must be a well-defined expression to begin with, and this is only true if $a\gt0.$ The expression $a^x$ is meaningless when $a\lt0,$ unless you confine $x$ to the set of integers, which is clearly not what we are doing.
I understand this is confusing, which is why I am a strong advocate for stopping the use of such bad notation and making it obsolete. I think we should stick to using the notation $\exp[\ln(a)t],$ even if it takes slightly more symbols to write. Distinguishing this notation from the power notation $x^n,$ where $n\in\mathbb{Z},$ is what I consider a healthy mathematical habit that eliminates confusion and is much less error-prone. \
Anyhow, the fact is that $$\frac{\mathrm{d}}{\mathrm{d}t}a^t=\ln(a)a^t$$ implies that $$\frac{\mathrm{d}}{\mathrm{d}t}\frac1{\ln(a)}a^t=\frac1{\ln(a)}\ln(a)a^t,$$ but it only implies that if $$\frac1{\ln(a)}$$ is a meaningful expression, and such an expression is only meaningful when $a\gt0,\,a\neq1.$ For $a=1,$ we have that $1^t=1,$ so  $$\frac{\mathrm{d}}{\mathrm{d}t}1^t=0=0\cdot1^t,$$ and $$\frac1{\ln(0)}\neq0,$$ and furthermore, $$\lim_{a\to1}\frac1{\ln(a)}\neq0.$$ This is why $a\neq1$ is a necessary restriction.


rails config mailer default url options not taking effect (development environment)

Question: I'm working on adjusting the url appearing in a mailer created with,
<%= controller_url %>

but when I change the default with the following command
config.action_mailer.default_url_options = { :host => "example.com", :protocol => 'https', :subdomain => "www"}

the url remains unchanged as
http://localhost:8000/controller
What are some possible causes for this not working? I looked pretty thoroughly through my project folder for places where the host or subdomain might be defined, but found nothing.
EDIT:
It seems I needed to restart my server after making the changes.
Comment: I believe the default url is being implemented on production, which is the cause for the need to change. (splitting the :host and :subdomain)
Answer: I don't know how you trying but I can show my files to compare with yours.
So my development file is /config/environments/development.rb
config.consider_all_requests_local = true
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

and my production file is /config/environments/production.rb
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_url_options = { :host => "https://example.com" } #=> Or https://www.example.com
config.action_mailer.perform_deliveries = true

ActionMailer::Base.smtp_settings = {
    :user_name => ENV['USERNAME'],
    :password => ENV['PASSWORD'],
    :domain => 'example.com',
    :address => 'smtp.example.net',
    :port => 321,
    :authentication => :plain,
    :enable_starttls_auto => true
}
config.action_mailer.delivery_method = :smtp

and it's working perfectly.
Remember these:

Development file is working only when a project is a development mode
Production file is working only when a project is a production mode
And make sure you restarted the server after change anything on related to configuration

You can check the logs while sending mail what's happening and for production run follow this command rails server -e production
Comment: Ahh, it was the restarting the server! I had assumed it was updating as I read that the development config file was reloaded at every request.
Comment: Thanks. If you change the host: 'localhost' part in development, does it change your generated urls? From reading the rails guides, I would assume that it should, but it's not changing for me. It'd be helpful to have this information to determine if there is a setting someone else made in the project that is overriding this, or if it is the normal behavior.
Comment: @SamuelFrost Yes! it's changing I'm sure for over sure I just checked again and my logs showing `Click here to login`, here I just change host `example` and restarted the server. make sure restart the server after change anything on the configuration
Comment: Thanks, that helps narrow things down a bit! But I'm still puzzled as to why it's not working. I can only imagine there's either a gem doing something behind the scenes or something going on at an OS level.
Comment: Great to hear it


c++ fff mock temporary disable fake function

Question: I have the following code :
#include "gtest/gtest.h"
#include "fff.h"
#include <sys/mman.h>
DEFINE_FFF_GLOBALS;

FAKE_VALUE_FUNC(void *, mmap, void*, size_t, int, int, int, __off_t);

TEST(my_test, ok) {
  FILE * pFileMmap;
  pFileMmap = tmpfile();
  int pFileMmap_fd = fileno(pFileMmap);

  void* r = mmap(nullptr,
      255,
      PROT_READ | PROT_WRITE,
      MAP_SHARED,
      pFileMmap_fd,
      getpagesize());

  mmap_fake.return_val = r;

  void* ptr = my_function_calling_mmap();

  EXPECT_TRUE(ptr == r);
}

I want to mock the mmap function with a real variable returned by the real mmap.
The problem is that void* r = mmap(... actually call my fake mmap function...
Is there a way to disable the fake mmap the time to init my variable r and re-enbale it just after ?
Answer: I workaround the problem by using function dlsym from dlfcn.h :
#include "gtest/gtest.h"
#include "fff.h"
#include <sys/mman.h>
#include <dlfcn.h>
DEFINE_FFF_GLOBALS;

FAKE_VALUE_FUNC(void *, mmap, void*, size_t, int, int, int, __off_t);

TEST(my_test, ok) {
  FILE * pFileMmap;
  pFileMmap = tmpfile();
  int pFileMmap_fd = fileno(pFileMmap);

  // save mmap address inside fmmap to be able to use the real mmap function
  void* (*fmmap) (void*, size_t, int, int, int, __off_t) = (void* (*)(void*, size_t, int, int, int, __off_t)) dlsym(RTLD_NEXT, "mmap");
  void* r = fmmap(nullptr,
      255,
      PROT_READ | PROT_WRITE,
      MAP_SHARED,
      pFileMmap_fd,
      getpagesize());

  mmap_fake.return_val = r;

  void* ptr = my_function_calling_mmap();

  EXPECT_TRUE(ptr == r);
}

I don't know if this is the cleanest way to that but it works.


The exception of CSMA/CD in 802.3

Question: It is stated that CSMA/CD is generally used in 802.3. I understand that there is an exceptional case that does not fit into the generalization.
I searched about it but I couldn't find that case. Is there such a case? What would that case be? I suppose it is about the length of the data or the distance between the stations but I am not sure.
Thanks in advance.
Comment: Collision detection is *rarely* used, because most network connections are full duplex.
Answer: Hi if your connection from Switch to host is full duplex you can switch CSMA/CD off as it is no longer required

The exception of CSMA/CD in 802.3


Custom messages for user_pass_reset

Question: I would like to customize the messages for one time login links (i.e. password reset links). In some cases, I redirect the user to the login page. In these cases, it does not make sense to have "Please request a new one using the form below."
Is there a hook or module I can use to add some logic to that message? (I can do a global override with String Overrides, but am looking for more conditional messages.)
I am using Drupal 7.
Comment: Drupal version?
Comment: Whoops, Drupal 7. Edited.
Answer: If you mean the email message for a password reset. You can use hook_mail_alter to change the email contents before it's sent out to the user.
If you mean the form the user sees on the webpage, then you can use hook_form_alter to change the verbiage shown on the screen.
Edit
override the displayed form with the reset button to goto your own form_submit action. In your custom module action, simply copy and paste user_pass_reset function body into your own function and tweak it as needed to change the messages (careful).
Comment: I actually mean the messages that are shown when a link is clicked. Specifically, `drupal_set_message(t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.'), 'error');` in `user_pass_reset`.
Comment: see my edit to my answer.
Comment: Then he should alter the reset link menu, not the form. The ```user_pass_reset``` is a menu callback.
Comment: Ops, sorry, you are right, it's form. I always use the link with the /login at the end and forgot is managed by a form not a direct link.
Comment: Would something like this work? https://www.ignoredbydinosaurs.com/posts/40-altering-drupal-password-reset-process
Answer: Those messages are pretty harcoded in user module in the file user.pages.inc, user_pass_reset function.
There's no hook to alter drupal set messages, but if you want to suppress certain messages you have luck with the module Disable Messages:

Gives a site owner options to disable specific messages shown to end
  users.

Features:

Filter out messages that match a full text string exactly.
Filter out messages that match a regular expression.
Permissions to specifically hide all messages of a given type from any role.
Disable all filtering for specific users.
Disable all filtering for specific paths.
Apply filtering only for specific paths.
Debug system to get messages in the HTML without showing it to the end users.

About using rules
There is an issue about this: Is it possible to unset or override system messages with Rules?
Comment: If I disable them, is there a way (either programatically or via Rules) to set a new message? I was looking for a Rule event for "One time login link was clicked" or something, but did not find any. (Other modules offer Rules integration but do not play well with Password Reset Landing Page, which I also use.)
Comment: Not possible with rules at the moment, answer updated.

Custom messages for user_pass_reset


Can we deliver an updated text file (any non versioned file) in an MSP

Question: Step 1: I have an updated msi which has a new text file : env.info
an msp generated out of it places this text file in the folder.
Step 2: I have updated this text file and generated an msp again, now this msp doesn't replace the new file.
Any idea how to handle non versioned files in an msp?
Comment: precisely, what can i do to have this file replaced in the installed folder (using an msp) every time it changes
Comment: Have a look at the REINSTALLMODE property covered in the following page: https://msdn.microsoft.com/en-us/library/windows/desktop/aa371182(v=vs.85).aspx
Answer: The issue is most likely that the overwrite rules prohibit replacing non-versioned files that have been updated since the install:
https://msdn.microsoft.com/en-us/library/windows/desktop/aa370531(v=vs.85).aspx
and you can verify this if you produce an MSI log of the patch install.
The safest solution, as here:
https://blogs.msdn.microsoft.com/astebner/2013/05/23/updating-the-last-modified-time-to-prevent-windows-installer-from-updating-an-unversioned-file/
is to change the times on the file to let it be replaced. That's because the other solution is to set the REINSTALLMODE to overwrite all files - this may not always be the write thing to do if you end up replacing a higher versioned file with a lower version.
A better design for this issue is to have the keypath of the data file be set to a versioned binary, companion files.
Comment: can we add MsiFileHash to the unversioned file and generate an msi? will this work?
Comment: ignore my previous question. but i have another question- Pointing to my original question, my msp1 places this file in istallation folder, an msp2 with the updated env.info file doesn't replace the older file. I checked that the msihash is different for both the files. Is this not sufficient for the msp2 to replace the file?
Comment: i would want the usage of companion file. I researched on support sites but couldn't find any
Comment: i would want the usage of companion file. I researched on support sites but couldn't find any


Como abrir uma imagem aleatoria

Question: estou com uma nova duvida e este tem sido o melhor lugar para encontrar respostas, desde ja agradeco.
Meu problema e o seguinte, estou fazendo um questionario escolar para meu filho.
E uma coisa simples, ao menos deveria ser. Uma questao com 3 respostas, uma certa e duas erradas. Ao clicar na resposta certa uma imagem comemorativa aparece.
Gostaria que esta imagem fosse aleatoria para nao se tornar cansativa.
Estou usando o seguinte
function SIM() {
    var oImg = document.createElement("img");
    oImg.setAttribute('src', 'img/certo.jpg');
    oImg.setAttribute('alt', 'na');
    oImg.setAttribute('height', '200px');
    oImg.setAttribute('width', '200px');
    document.body.appendChild(oImg);
}

E no body
<button id="SIM" onclick="SIM();">6</button>

Gostaria de ter 10 imagens de comemoracao e estava pensando em algo do tipo
function SIM() {
    var oImg = document.createElement("img");
    oImg.setAttribute('src', '**NUMERO DE 1~10 ALEATORIO**.jpg');
    oImg.setAttribute('alt', 'na');
    oImg.setAttribute('height', '200px');
    oImg.setAttribute('width', '200px');
    document.body.appendChild(oImg);
}

Existe alguma maneira de conseguir isso???
Muito obrigado
Answer: Para criares um numero aleatorio podes fazer Math.round(Math.random() * 10).
function SIM() {
    var oImg = document.createElement("img");
    var nr = Math.round(Math.random() * 10);
    oImg.setAttribute('src', nr + '.jpg');
    oImg.setAttribute('alt', 'na');
    oImg.setAttribute('height', '200px');
    oImg.setAttribute('width', '200px');
    document.body.appendChild(oImg);
}

Comment: Salvou Meu Dia, Muito Obrigado!!!  Nao sabia como chamar o resultado de uma var para dentro do atributo.

Como abrir uma imagem aleatoria


Get Vector between unit vectors at certain angle in 3d

Question: If I have two 3d unit vectors, how can I get a third 3d unit vector, that is on the same plane as the other two, at an angle of $x$ degrees from the first Vector?
For 2 dimensions, this is simple, because the requirement, that all three vectors have to be on a plane is always satisfied, but I can't figure it out for 3d.
Comment: Do you know about the Gram–Schmidt process? Starting with two vectors $\mathbf{v}_1$ and $\mathbf{v}_2$, assuming that they're not parallel so that they actually span a plane, G–S yields a new pair of orthogonal unit vectors, say $\mathbf{e}_1$ and $\mathbf{e}_1$. Then your new vector is
$$
\mathbf{w} = (\cos x) \mathbf{e}_1 + (\sin x) \mathbf{e}_2,
$$
or replace $x \mapsto -x$ if you want it at angle $x$ in the other direction. This just amounts to switching the sign on the second term.
Answer: Let consider $\vec v_1$ and $\vec v_2$, firstly we need to othogonalize $\vec v_2$ with respect to $\vec v_1$ that is
$$\vec u_2 = \frac{\vec v_2- (\vec v_2\cdot \vec v_1)\vec v_1}{|\vec v_2- (\vec v_2\cdot \vec v_1)\vec v_1|}$$
then we have
$$\vec v_3=(\cos x) \vec v_1+(\sin x) \vec u_2 $$
such that $\vec v_3 \cdot \vec v_1 =\cos x$.
Answer: As the new vector is on the same plane as the two vectors, we can take it as some $v = \frac{v_1 + \lambda v_2}{\Vert v_1 + \lambda v_2\Vert}$, then we need to solve this equation for lambda using dot product $v\cdot v_1 = cos (x)$. Substituting this value in value of $v$ would yield the vector


Adding persistence to a REST application error

Question: How can I user persistency in my REST application?
I want to use @Inject and @PersistenceUnit annotation to instantiate my needed PersistencyManager object,
by when I call the persistency functionality by REST service I get an error:
<code>[2014-03-15 05:05:45,472] Artifact CubieboardGPIO:war: Error during artifact deployment. See server log for details.
[2014-03-15 05:05:45,473] Artifact CubieboardGPIO:war: javax.ejb.EJBException: The bean encountered a non-application exception; nested exception is:
org.apache.openejb.OpenEJBRuntimeException: java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/]]
</code>
This is my Rest:
<code>@Inject
private PersistenceManager persistenceManager;

@GET
@Path("/activate")
public String activate(@QueryParam("pin") int pin) {
    persistenceManager = new PersistenceManager();
    // URI : /cubieboard/gpio/activate?pin=67
    String[] messages = _activate(pin);
    StringBuilder sb = new StringBuilder();
    sb.append(ConfigurationManager.getConfiguration("ACTIVATE_MESSAGE")+"\n");
    sb.append("Persistence:\t");        sb.append(messages[0]);     sb.append("\n");
    sb.append("Terminal Response:\t");  sb.append(messages[1]);     sb.append("\n");
    return sb.toString();
}
</code>
This is PersisteneManager:
<code>    @Stateless
public class PersistenceManager {

    @PersistenceUnit(name = "cubieDB")
    private static EntityManagerFactory factory;
    private EntityManager em;

    public PersistenceManager(){
     //   factory = Persistence.createEntityManagerFactory(ConfigurationManager.getConfiguration("PERSISTENCE_UNIT_NAME"));
//        factory = Persistence.createEntityManagerFactory("cubieDB");
        em = factory.createEntityManager();
    }

    public List<Operation> getAllOperations() {
        Query q = em.createQuery("SELECT op FROM Operation op");
        List<Operation> ops = q.getResultList();
        return ops;
    }

    public void persist(Operation operation) {
        em.getTransaction().begin();
        em.persist(operation);
        em.getTransaction().commit();
    }

    public void deleteAll(){
        em.getTransaction().begin();
        Query q = em.createNativeQuery("DELETE FROM Operation");
        q.executeUpdate();
        em.getTransaction().commit();
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        em.close();
    }
}
</code>
And this is my persistence.xml:
<code>    <?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">

    <persistence-unit name="cubieDB" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>com.sakhoshdel.cubieboard.gpio.persistence.Operation</class>
        <properties>
            <!--<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>-->
            <property name="eclipselink.ddl-generation" value="create-tables"/>
            <!--<property name="javax.persistence.schema-generation-action" value="drop-and-create"/>-->
            <!--<property name="javax.persistence.schema-generation-target" value="database-and-scripts"/>-->
            <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:derby:cubieDB;create=true" />
        </properties>
    </persistence-unit>

</persistence>
</code>
Also when I call the persistence functionality from a normal class it runs. but when I want to deploy it I get error. I am using TomEE for application server.
Thank you
Answer: Well ejb constructor shouldnt be used (shouldnt even be called in last versions). Injection of static field is not recommanded neither.
Finally maybe just use a jta persistence unit and remove the em.getTransaction calls.
Side note: tomee comes with openjpa so you need to provide eclipselink if you want it


Is there strong research that demonstrates the effect of emotion on performance in different types of sports?

Question: Many people discuss the physical toughness and attributes of athletes, while there is also plenty of anecdotal evidence about how 'mental toughness' can impact on the performance, especially under pressure or at times when people perform beyond their apparent physical capacity.
Just wondering if there is much literature on this area of sports medicine/research, and what the results indicate for different types of sports or sport person.
Answer: I don't know what you consider to be "strong research". But, there are several sports psychology papers that take up the concept of "mental toughness". In the Journal Of Applied Sport Psychology (2002), Jones, Hanton and Connaughton from the University of Wales studied ten international elite athletes to determine what mental toughness is, and, what the attributes are of someone who is mentally tough. Although it's a relatively small study, it does define mental toughness:

Mental toughness is having the natural or developed psychological edge
  that enables you to:

Generally, cope better than your opponents with the many demands    (competition, training, lifestyle) that sport places on a performer.
Specifically, be more consistent and better than your opponents in    remaining determined, focused, confident, and in control under pressure.

The definition came about after a three stage study that consisted of focus groups, individual interviews, and an "individual rating of the definition and ranking of mental toughness attributes". They identified 12 attributes of mental toughness and applied an "importance ranking". The researchers claim the results of the study have helped teams and individual performers in archery, field hockey, athletics, gymnastics, ice skating, weightlifting, squash, swimming, speed skating, cycling, association football, judo, rowing, and modern pentathlon. They did not differentiate outcomes based on different sports or athletes.


Two random variables X and Y follow the same distribution. Then

Question: Two random variables $X$ and $Y$ follow the same distribution.
Then

The distribution of $X − Y$ must be symmetric about $0$.
The median of $X − Y$ must be zero.
The median of $X + Y$ is twice of the median of $X$.
The mean of $X − Y$ , if finite, must be $0$.
None of the above is correct.

It is a very short question, and I think the answer is Number $5$, isn't it?
Comment: Could you provide your reason?
Comment: Can more than one answers be correct?
Comment: Only can choose 1 answer
Comment: Are you sure that the last one is "none of the above" and not the opposite "all of the above are correct"? Because $X-Y$ and $-(X-Y)=Y-X$ have the same distribution, so 1. is correct. But also $E[X]=E[Y]$ so $E[X-Y]E[X]-E[Y]=0$ so 4. is also correct. Similarly 2. is also correct and I did not check 3.
Comment: @Jimmy $X$ and $Y$ could be dependent, hence $4$ is the answer.
Answer: If $X=Y$ then 1,2,3,4 would be correct.  In particular $X-Y=0$ with probability $1$
If $X$ and $Y$ are independent then 1,2,4 are correct but 3 might not be.  For example, suppose $X$ takes the value $1$ with probability $0.4$ and the value $0$ with probability $0.6$
But if $X$ and $Y$ have a more complicated relationship then there is little you can say about distributions and medians.  For example if $(X,Y) = (0,1)$, $(1,4)$ or $(4,0)$ each with probability $\frac13$. You are left with linearity of expectation and assertion 4.


nginx modify and proxy URL

Question: Ngnix newbie here.
Please I need some help to figure out how to correctly make nginx modify and redirect (proxy?) incoming requests.
The redirection seems to work ok, but the URL is not rewritten at the destination.
My configuration is:
        server {

       listen 91 default_server ssl;

       ssl_prefer_server_ciphers on;
       ssl_certificate /etc/nginx/ssl/domain.crt;
       ssl_certificate_key /etc/nginx/ssl/domain.key;

        location /dest {

        rewrite ^a_service_prod&id_number=((1234701|1234708|1234802|1234808|1234812|1234902)\d+)&(.*?)$ /dest?service=a_service_prod.sub_service&operation=sub_service&id_number=$1&$2 break;
            proxy_pass http://192.168.1.1:1440;
            proxy_redirect off;
            proxy_set_header Host $host;
        }
    }

Im trying to get requests such as /dest?service=a_service_prod&id_number=12347016734696&slime=somethig
to be rewritten and the request sent to another server as http://192.168.1.1:1440/dest?service=a_service_prod.sub_service&operation=sub_service&id_number=12347016734696&slime=somethig
But instead at the destination, what is received is http://192.168.1.1:1440/dest?service=a_service_prod&id_number=12347016734696&slime=somethig
Please what am I doing wrong, and how can I fix it?
Answer: You current method does not work because you are attempting to capture the query string in the regular expression of a rewrite directive. nginx uses a normalized URI for evaluating rewrite and location directives, which does not include the ? and anything that follows it.
You can find the query string in the $request_uri variable, the $args variable - or split up amongst the $arg_xxx variables. See this document for details.
You can apply a regular expression to one of those variables by using an if statement or a map directive.
The example below uses a map directive (see this document for details) with a regular expression and two named captures to reconstruct your required argument list. The upstream URI is appended to the proxy_pass directive (see this document for details).
map $args $newargs {
    default $args;
    ~*^(?<prefix>service=a_service_prod)&(?<suffix>id_number=(?:1234701|1234708|1234802|1234808|1234812|1234902)\d+&.*)$  $prefix.sub_service&operation=sub_service&$suffix;
}
server {
    ...
    location /dest {
        proxy_pass http://192.168.1.1:1440$uri?$newargs;
        ...
    }
}

Comment: Thank you very much, this is very valuable information. I ended up using if statements, because I had multiple groupings of `id_number=([:digits:])` that needed to go to different rewrites, and also because I am still trying to understand map.

nginx modify and proxy URL