How to get total sum from one table with inner join in mysql

Question: I have two tables one is orders and second is order_product in which I have to find out orders count, product count, totalamount in corresponding to
customer using buyers id from which I have successfully find out the orders count and product count but my totalamount is not coming correct.
orders:
.......................................
 order_id   or_buyer_id   or_total_amt
.......................................
    1           21           10
    2           22           10
    3           21           10

order_product
.................................
op_id  op_order_id  op_buyer_id
.................................
  1       1          21
  2       1          21
  3       2          22
  4       3          21

I want below output but my totalamount value is coming wrong it is coming
30,but the correct value is 20 which i have mentioned in the right output below.
output which i want:
............................................
or_buyer_id  orders  product   totalmount
...........................................
   21         2       3          20
   22         1       1          10

I have tried the below query which is giving 30 value of totalamount which is wrong.
SELECT o.or_buyer_id
     , count(DISTINCT o.order_id) as orders
     , count(op.op_id) as product
     , SUM(o.or_total_amt) as totalamount
  FROM orders as o
  JOIN order_product as op
    on op.op_order_id = o.order_id
   and o.or_buyer_id = op.op_buyer_id
 group
    by o.or_buyer_id

Comment: Please show some queries to return some relevant data. Please read & act on [ask] & [mcve] & hits googling 'stackexchange homework'.
Answer: One approach is to remove the duplicate rows from the order_product table in a subquery.  Then, join that to orders as you were already doing.  One slight trick here is that we maintain the number of original records in the order_product table when removing duplicates in the subquery.  This is because the product column reflects the true original record count.  But the totalamount does not reflect duplicates, hence we sum this quantity with duplicates removed.
SELECT
    t1.op_buyer_id,
    COUNT(DISTINCT t1.op_order_id) AS orders,
    SUM(t1.cnt) AS product,
    SUM(t2.or_total_amt) AS totalamount
FROM
(
    SELECT op_order_id, op_buyer_id, COUNT(*) AS cnt
    FROM order_product
    GROUP BY op_order_id, op_buyer_id
) t1
INNER JOIN orders t2
    ON t1.op_order_id = t2.order_id AND
       t1.op_buyer_id = t2.or_buyer_id
GROUP BY
    t1.op_buyer_id
ORDER BY
    t1.op_buyer_id;

Demo
Answer: You should use a subquery in the inner join instead of referring directly to order_product table:
Try to substitute order_product with
(SELECT DISTINCT op_order_id, op_buyer_id
 FROM order_product) AS op

This will remove duplicates that are giving you the wrong sum.
I also introduced a subquery to get the correct product value:
SELECT count(op_order_id) FROM order_product WHERE order_id = o.order_id AND op_buyer_id = o.or_buyer_id) as product

The final SQL is:
SELECT o.`or_buyer_id`,
       count(DISTINCT o.`order_id`) as orders,
       (SELECT count(op_order_id) FROM order_product WHERE order_id = o.order_id AND op_buyer_id = o.or_buyer_id) as product,
       SUM(o.`or_total_amt`) as totalamount
FROM `orders` as o
INNER JOIN (SELECT DISTINCT op_order_id,
                            op_buyer_id
            FROM order_product) AS op
ON op.op_order_id=o.order_id AND o.or_buyer_id = op.op_buyer_id
GROUP BY o.`or_buyer_id`

Comment: Hi Kiko, this query does not appear to give the correct results ([Demo](http://rextester.com/YFR46727)).
Comment: @TimBiegeleisen I introduced a new subquery to get the correct product field, thanks
Answer: You should use this subquery
SELECT tbl.op_buyer_id, COUNT(DISTINCT tbl.op_order_id) AS orders, SUM(tbl.cont) AS product, SUM(tbl2.or_total_amt) AS totalamount FROM ( SELECT op_order_id, op_buyer_id, COUNT(*) AS cont FROM order_product GROUP BY op_order_id, op_buyer_id ) tbl INNER JOIN orders tbl2 ON tbl.op_order_id = tbl2.order_id AND tbl.op_buyer_id = tbl2.or_buyer_id GROUP BY tbl.op_buyer_id ORDER BY tbl.op_buyer_id


regular expression to get contents after match till end of line

Question: Example: if it's like
some text Match: here is the content I want

Match: here is the content I want
I am trying to get whatever information after Match: till end the end of line.
Regular expression which I  am using now is ?=Match:(. *)?=\n
Issue1: Match: is not getting eliminated.
Issue2: there are some html tags which randomly occur. So I have to eliminate them if they occur.
So in any case I just need "here is the content I want".
Can someone tell me modification that I need to do for my regular expression?
Comment: Please reformat your question and make sure you share the exact pattern you are using, and describe the issue with the regex.
Comment: @WiktorStribiżew: Changes done and i have mentioned the issue which i am facing as well
Comment: I strongly doubt you provided the exact regex. It is [invalid](https://regex101.com/r/mO9pK6/1).
Comment: In case you havent found any help online regarding formatting posts - [see this](http://meta.stackoverflow.com/questions/251361/how-do-i-format-my-code-blocks).
Comment: It is not only formatting, we can access the question source and see the raw text. The thing is that the pattern is not a real regex pattern that can be used in VBScript. The question is unclear without that.
Answer: There are two ways you can approach this:

Remove everything before/after the submatch:
s = "..."

Set re = New RegExp
re.Pattern = "^[\s\S]*?Match: (.*)[\s\S]*"

WScript.Echo re.Replace(s, "$1")

^[\s\S]*? matches any character (including newlines) up to the first occurrence of the term "Match:". (.*) then matches all characters up to the next newline. Your expression must cover everything before and after the submatch, because the replacement won't touch unmatched parts of the string.
Extract the submatch:
s = "..."

Set re = New RegExp
re.Pattern = "Match: (.*)"

For Each m In re.Execute(s)
  WScript.Echo m.Submatches(0)
Next

With this approach the regular expression is simpler, because it only needs to cover what you actually want to match (instead of having to cover the parts you want to remove as well). On the other hand, the handling of the submatch takes a little more work.


Canvas radial gradient with rgba doesn't work on Safari & IE

Question: Here is my code for a moving radial gradient on canvas. It works on Chrome and Firefox, but not on Firefox. I also want a fallback option for IE - actually can't test it easily on a Mac, but I'm assuming it's not if it's an old IE. For IE, seeing through the image without the alpha channel gradient will do. Any idea?
  var cirRadius = 300;

  var posX = 100;
  var posY = 100;
  var RGB = [11,11,11] ;
  var alphas = [0,0,0.1,0.5,1];

  var update = function(){
      if(ctx){
          if(image.complete){
              ctx.drawImage(image,0,0,canvas.width,canvas.height)
          }else{
              ctx.clearRect(0,0,canvas.width,canvas.height);
          }
          var grad = ctx.createRadialGradient(posX,posY,0,posX,posY,cirRadius);
          var len = alphas.length-1;
          alphas.forEach((a,i) => {
               grad.addColorStop(i/len,`rgba(${RGB[0]},${RGB[1]},${RGB[2]},${a})`);
          });
          ctx.fillStyle = grad;
          ctx.fillRect(0,0,canvas.width,canvas.height);
      }
      requestAnimationFrame(update);
  }

Answer: It turns out that Safari doesn't recognize the shortcut in the forEach loop, so I just have to change this:
alphas.forEach((a,i) => {
    grad.addColorStop(i/len,`rgba(${RGB[0]},${RGB[1]},${RGB[2]},${a})`);
});

to this:
alphas.forEach(function (a,i) {
    grad.addColorStop(i/len,`rgba( ${RGB[0]}, ${RGB[1]}, ${RGB[2]}, ${a})`);
});

It works with the latest IE, but I guess I can do a different style for hte older versions of the IE.
Comment: Indeed, arrow functions are not supported by Safari and IE yet.
Comment: Debugging hint: The javascript console would have let you find this problem early on.  It should also be the first step of debugging.


k8s.Exceptions.KubeConfigException: kubeconfig file not found at /root/.kube/config

Question: I have a .net core project that calls the command var config = KubernetesClientConfiguration.BuildConfigFromConfigFile() but it throws an error saying  kubeconfig file not found at /root/.kube/config. Im using docker-desktop with kubernetes on my Windows 10 machine. Any ideas how to point it to the correct config path?
Comment: The default location for the config file is the current user's (home folder's) `.kube/config`. Your container is running as `root`, hence the location. You can change it by changing the container's user and|or setting the `KUBECONFIG` environment variable. You can also mount a config from the host into the container.
Comment: @FariyaRahmat yes your answered helped me figure out I was missing the config file. I had to copy the config file into my /app directory in the container since thats where it was looking for the my config file.
Answer: As @DazWilkin mentioned, The default location for the config file is the current user's (home folder's) .kube/config. Your container is running as root, hence the location.
The error message indicates that the Kubernetes configuration file kubeconfig is missing from the expected location /root/.kube/config. This file is crucial for establishing a connection to a Kubernetes cluster and performing various operations.
As per the official kubernetes documentation on Organizing Cluster Access Using kubeconfig Files :

By default, kubectl looks for a file named config in the $HOME/.kube directory. You can specify other kubeconfig files by setting the KUBECONFIG environment variable or by setting the --kubeconfig flag.

For step-by-step instructions on how to create and specify kubeconfig files, see Configure Access to Multiple Clusters for more information.
Note: To choose the current context use kubectl config use-context command. Also ensure that you have the correct permissions to access the kubeconfig file.


Notation Abstract Algebra

Question: On page 236 of Falko Lorenz's "Algebra Volume 1: Fields and Galois Theory", exercise 4.2(c), the author asks
$\\$
Let $R$ be a unique factorization domain.
If $P$ is a directory of primes of $R$ and $K =$ Frac $R$, the multiplicative group of K satisfies $K^x \cong R^x \times\mathbb{Z}^{(P)}$.
What is $\mathbb{Z}^{(P)}$?
Answer: It looks like its suggesting the direct sum of copies of $\mathbb{Z}$ indexed by the directory of primes.
Construct the map this way. Let $k$ be nonzero in $K$. Write $k$ as $a/b$ with $gcd(a,b)=1$. Uniquely factorize $a$ and $b$ and retrieve the natural numbers that are the powers of the primes in their factorizations. You may need to use units on both $a$ and $b$ to complete the factorization.
Combine the units into $u$. For each prime $p$ that appears in the prime factorization of $a$ and $b$, you get a net result of the power that appears in the position. The thing you map $k$ to is $u$ followed by the integer powers of primes in its expression.
So for example, suppose $a=vp^2q$ and $b=wpq^3$. Then $\frac{a}{b}=\frac{vp^2q}{wpq^3}=up^1q^{-2}$.
where $\frac{v}{w}=u$. Supposing that $p$ and $q$ were the first two primes in the directory, in that order, you would map $a/b$ to $(u,1,-2,0,0,\dots)$.
With a little patience you can show this is multiplicative and preserves inverses, and is bijective, hence you have a group isomorphism.
Comment: Does this give you the idea? Let me know and I can clarify.
Comment: Yup I got it, thank you : )
Answer: $\mathbb Z^{(P)}$ denotes the set of maps $f\colon P\to\mathbb Z$ such that $f(p)=0$ for almost all $p\in P$ (i.e. $f(p)\ne 0$ for at most finitely many $p$).
This is a strict subset if $\mathbb Z^P$, the set of all maps $P\to\mathbb Z$.

Notation Abstract Algebra


Create diff between two files based on specific column

Question: I have the following problem.
Say I have 2 files:
A.txt
1    A1
2    A2

B.txt
1    B1
2    B2
3    B3

I want to make diff which is based only on values of first column, so the result should be
3     B3

How this problem can be solved with bash in linux?
Answer: [ awk ] is your friend
awk 'NR==FNR{f[$1];next}{if($1 in f){next}else{print}}' A.txt B.txt

or more simply
awk 'NR==FNR{f[$1];next}!($1 in f){print}' A.txt B.txt

or even more simply
awk 'NR==FNR{f[$1];next}!($1 in f)' A.txt B.txt

A bit of explanation will certainly help

NR & FNR are awk built-in variables which stand for total number of records - including current - processed so far and total number of records - including current - processed so far in the current file respectively and they will be equal only for the first file processed.
f[$1] creates the array f at first and then adds $1 as a key if the same key doesn't yet exist. If no value is assigned, then f[$1] is auto-initialized to zero, but this aspect doesn't find a use in your case
next goes to the next record with out processing rest of the awk script.
Note that {if($1 in f){next}else{print}} part will be processed only for the second (and subsequent if any) file/s.
$1 in f checks if the the key $1 exists in the array f
The if-else-print part is self explanatory.
Note in the third version, the {print} is omitted coz the default action for awk is printing !!
Comment: Or more simply `awk 'NR==FNR{f[$1];next}!($1 in f)'`
Comment: @123 : I bet you're good in this.. :) Thankyou will add it to solution
Answer: awk 'NR==FNR{array[$1];next} !($1 in array)' a.txt b.txt
3    B3

Answer: Like this in bash but only if you are really not interested in the second column at all:
diff <(cut -f1 -d" " A.txt) <(cut -f1 -d" " B.txt)


Complex looping through groups of variables

Question: I've got an SPSS dataframe looking like this:
K_161   K_161_A K_161_B K_161_B K_161_C K_161_D K_213
0   0   0   0   0   1   0
1   0   0   0   1   1   1
0   0   0   0   0   0   0
0   0   0   0   0   0   0
0   1   0   0   0   0   0
1   1   1   1   1   1   1
0   0   0   1   1   1   1
0   0   0   0   1   1   1
0   1   1   1   1   1   1
1   0   0   0   0   1   0
0   0   0   0   0   0   0
1   1   0   1   1   1   1
0   1   0   0   0   0   0
1   0   0   0   0   0   0
0   0   0   0   1   0   0
1   1   0   1   0   1   1
0   1   0   0   0   1   0
0   1   0   0   0   0   0
0   1   0   1   1   0   0

Basically I want to loop through the variables (columns) and return values for the reliability measure Cronbach's alpha.
Something that would work along the lines of the following pseudocode in Python:
BEGIN PROGRAM.
import spss

unique_ids = open("E:/company_id.txt", "r")

for i in unique_ids:
  i = "K_" + str(i)
  spss.Submit(r'''
  RELIABILITY
  /VARIABLES= + i
  /SCALE('ALL VARIABLES') ALL
  /MODEL=ALPHA.
  ''')

END PROGRAM.

I've got about 9000 columns. The variables used in each loop can be grouped based on their unique number: e.g. for 161 the loop would include K_161 K_161_A K_161_B K_161_B K161_C K_161_D and so on. I've got a list of these unique numbers (textfile) looking like this:
161
213
263
284
295
297
306
347

The SPSS syntax returns a measure for Cronbach's alpha as well as the number of cases. I want to return a dataframe which looks like this:
id  cronbach    cases
161 0.651   5
213 0.856   3
263 0.752   6
284 0.927   22
295 0.884   24
297 0.934   31
306 0.902   9
347     1
398 0.405   4
457 0.884   12
491 0.137   2
507 0.909   28
571     1
590 0.738   9

I kind of lack the creativity to find the right solution here. Really looking for some ideas how you would approach the problem. Thank you very much!
Answer: First I'm creating two datasets to simulate your two files - one with your IDs and one with the actual data for analysis:
data list free/id (f3).
begin data
161  444 213
end data.
dataset name numlist.

data list free/K_161 K_161_A K_161_B K_213_B K_161_C K_161_D K_213 K_213_A K_444 K_444_F K_444_K (11f3).
begin data
3 3 3  4 4 4 5 5 1 2 3 4 5 6 7 8 9 0 9 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7
end data.
dataset name main.

Now the Idea is to use the ID list to write a new syntax file.
For each item in the list, the new syntax will:
1. define a macro that finds all the corresponding variable names in the main file
2. run a reliability analysis on them.
The OMS command will capture the cronbach data from the output into another dataset:
DATASET DECLARE  MyAlphas.
OMS/SELECT TABLES/IF COMMANDS=['Reliability'] SUBTYPES=['Reliability Statistics']
   /DESTINATION FORMAT=SAV NUMBERED=TableNumber_ OUTFILE='MyAlphas' .
dataset activate numlist.
write out="path\temp macro run.sps"
   /'SPSSINC SELECT VARIABLES MACRONAME = "!a', id, '" /PROPERTIES PATTERN=".*', id, '*".'
   /'RELIABILITY /VARIABLES= !a', id, '  /SCALE("ALL VARIABLES") ALL  /MODEL=ALPHA.'.
dataset activate main.
insert file="path\temp macro run.sps".
omsend.

At this point you have a dataset called MyAlphas which has the cronbach values for each reliability test that was run. It doesn't yet have the IDs in it, but it's easy enough to match files this dataset with the IDs list -
you can add an index number to the list and match it with TableNumber_ in MyAlphas.


Is Interface as labels a bad practice in java OO?

Question: During the parsing of certain xml files, I come across a situation that I have to use interface as labels to identify that certain tags belong to certain category, for example, I created a Tag interface to identify that these classes are used to represent xml tags, and ContainableTag to point out that certain tags can be one of the children tags of some tags.
Then I stumble into this page: http://xahlee.org/java-a-day/interface.html (Please look for the "Interface as Labels" session.). It says:

The gist of the problem is that it is
a piece of mathematical irrelevance in
the language. As a labeling mechanism
in a language, for the possible
benefit from the software engineering
perspective, then it should not be
designed as part of the Class
Interface, since the concept of
labeling, and concept of programing
interface, are semantically disparate.

So is interface as labels necessarily a bad practice? As a java programmer, do we have some other alternatives?
Comment: You should point out the existing queries on this topic at SO. They also contain a lot of references. Interesting article you dug out, though.
Answer: Interfaces as markers have largely been replaces by the annotation mechanism in Java 5 or later.  They allow you to add arbitrary meta-data.  If your interfaces are empty and are only serving to act as class markers, then you should be using annotations instead.
Comment: http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html

The biggest gotcha in using annotations is that you need to annotate your annotations with a retention of 'runtime' if you want to use them at runtime.  By default they're discarded by the compiler.
Comment: Another gotcha with annotations is that they are not inherited by default by the subclasses. You need to specify @Inherited (http://www.j2ee.me/j2se/1.5.0/docs/api/java/lang/annotation/Inherited.html) on the annotation to achieve that
Comment: I never look into the usages of annotations, although I use it in certain frameworks. Thank you. I will google for tutorials.

Could you also pass me some links of annotation tutorial if you happen to have some at hand?
Answer: While annotations may provide an alternative for what marker interfaces accomplish, they are only available in Java, and do not integrate well with IDEs: I also use marker interfaces to tag related concepts in my project, and I can then use the type hierarchy browser to find all members (I guess this will be eventually supported by major IDEs for annotations soon).
As for the article you mention, I do not see the point in arguing that if a class syntactically/structurally "fulfills" an interface, that interface may/should be applied automatically to the class ("Any class can declare it [RandomAccess] as a interface..."). That's backwards thinking, in my opinion.
I would argue that the places, where such a marker interface is used in an `instanceof' statement, use inverted logic, but as long as you are stuck within a language without multiple inheritance, aspects and annotations, I see no better way to accomplish this without stepping out of the base language.
Also note that this dead-beat argument about an empty interface always being applicable could also be applied to annotations.
Answer: Annotations are not necessarily what you want. Tagging interfaces are a way of working a property of a type into the type itself. For example, if you're about to start writing code looking like this:
@interface ContainableTag{}

@ContainableTag public class Foo {}

// ... elsewhere...

/**
 * Adds obj as a child element.
 * @throws IllegalArgumentException if obj is not tagged with
 *         the ContainableTag annotation.
 */
public void addElement(Object obj){
    if (!obj.getClass().isAnnotationPresent(ContainableTag.class))
        throw new IllegalArgumentException("obj is not a ContainableTag");
    // add the containable tag as an element
}

Then consider if you really don't think this looks better:
interface ContainableTag {}

public class Foo implements ContainableTag {}

// ... elsewhere...

public void addElement(ContainableTag ct){
    // add the containable tag as an element
}

Sure, the tagging interface does not provide any information about what behavior the type itself provides, but it does allow other types to enforce this non-behavioral property. I certainly would have been spared a lot of annoying bugs if ObjectOutputStream had a writeObject(Serializable) method rather than writeObject(Object).
Edit: I have not insignificant support here.
Comment: Haha.. my "effective java" is too old to have this article. Thank you.


ARIMA - What is the proper ARIMA model for these data?

Question: I am doing my project on forecasting and due to I have limited knowledge in ARIMA, I would like to ask what is the appropriate ARIMA model for these two data. Both data are monthly.
Figure 1

The first data is shown above, i differenced the data once due to stationary problems (as it cuts off slowly, CMIIW), thus the result of differencing is shown below
Figure 2

I have found that the data is under 0.05 on lag 1 and 2. Does it mean that there are 4 available ARIMA model for this data [(1,1,0), (0,1,1), (2,1,0) and (0,1,2)]? I also tried to use ARIMA(1,1,1) but failed since the solution do not converge.

Another one is another data below without differencing (different training data), i found that both ACF and PACF cuts off at lag 3 (with 95% confidence level). Thus are ARIMA(2,0,0) and ARIMA (0,0,2) applicable for this or do i need to do differencing first? The reason i am putting MA(2) and/or AR (2) is that some resources found that the sum of p & q should not exceed 2 to prevent overfitting the model.
Figure 3

Thank you very much for your help :D
Answer: The first series could be a (0,0,0)(1,0,0)3 or (0,0,0(0,0,1)3 OR a hybrid deterministic model with with three seasonal pulses reflecting a quarterly effect and possible short term arima structure. Only your data knows for sure as the acf and pacf can be heavily influenced/clouded by pulses , level shifts ,local time trends and other "infections" or "opportunities" . If you wish you can post your data and I will try and help further.
EDITED AFTER RECEIPT OF DATA:
Neither series requires differncing : see the acf of KL1  kl2  . Unnecessary differencing can inject structure much like rolling in the mud and then washing your shirt.
I took your two data sets into AUTOBOX which sorts out the best approach/model to your data .. the model for series kl1 is and series kl2 here
The Actual/Fit and Forecast graph for kl1 is here  and for kl2 is here
Both series had trend , additive seasonal factors while kl1 had an arima component (1,0,0) and kl2 had three pulses and an evidented error variance change suggesting that weighted least squares be employed ( see http://docplayer.net/12080848-Outliers-level-shifts-and-variance-changes-in-time-series.html ) for a discussion of both Intervention DEtection and Error Variance Deterministic Changes.
SARIMA approaches though usually useful when integrated with deterministic structure is often the preferred route but you had too few observations(24) to pursue this approach.
When following other writers , make sure that they were employing best practices .. which unfortunately is not always the case due to either lack of subject knowledge or lack of software or both.
Comment: Hi, I believe that the model above is SARIMA, right? The first series has been differenced once, so should the d value be 1? FYI, I'm pursuing a master thesis which focusing on several forecasting method including moving average, exponential smoothing, seasonal and holt-winter's, and ARIMA for several fast-moving inventory items. For now i may not touch SARIMA since i have established limitations, maybe if i pursue deeper study on this i'll touch on that. With all due respect, is it possible to adapt those data to ARIMA? I'd like to post the data here but i don't know how. Thank you very much.
Comment: Sorry for another comment here due to the maximum characters per comment. Another question from me is that how to correctly determine the p and q value based on lags? For the first series, is it ARIMA(1,1,0) and ARIMA(0,1,1) since it cuts off AT the second lag (AFTER the first lag) or ARIMA(1,1,0) and ARIMA(0,1,1) since it cuts off AT the first lag (AFTER lag 0)? If the earlier is correct, thus there is no ARIMA(2,1,0) and ARIMA (0,1,2) due to no cut off AT third lag (AFTER second lag)? I consider using confidence level of 95% for this forecast. Thank you once again
Comment: you can use dropbox or email them to me
Comment: If you are happy with my answer ...accept it and close the question.


difference in syntax when doing kuberentes deployments related operations

Question: What is the difference between the following syntax usage:
kubectl get deployments
kubectl get deployment.apps
kubectl get deployment.v1.apps
There are references to deployment.v1.apps and deployment.apps in the documentation specially when talking about rollouts and upgrades.
For example:
To see the Deployment rollout status, run kubectl rollout status deployment.v1.apps/nginx-deployment
For example:
Let's update the nginx Pods to use the nginx:1.16.1 image instead of the nginx:1.14.2 image.
kubectl --record deployment.apps/nginx-deployment set image deployment.v1.apps/nginx-deployment nginx=nginx:1.16.1
Answer: There is no difference. They show you in examples different ways to access the resource.
This is the reference to app/v1 api that you can see in example nginx deployment:
apiVersion: apps/v1
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

You can use shorten way like kubectl get deployments either longer ones you provided in the question.
However, its obvious, you cant use  e.g app/v2
kubectl get deployment.v2.apps/nginx-deployment
error: the server doesn't have a resource type "deployment"


If $μ(\limsup_{n\geq1}A_n)=1,μ(\liminf_{n\geq1}B_n)=1 $ prove that $μ(\limsup_{n\geq1}(A_n\cap B_n))=1 $

Question: If $(X, \mathcal{A},μ)$ is probability space, $(Α_n)_n, (B_n)_n$ sequences of sets in $\mathcal{A}$ such that $μ(\limsup_{n\geq1}A_n)=1,μ(\liminf_{n\geq1}B_n)=1 $
prove that $μ(\limsup_{n\geq1}(A_n\cap B_n))=1 $
That's what I tried: it suffices to prove that $μ(\liminf_{n\geq1}(A^c_{n}\cup B^c_{n}))=0$
$$\liminf_{n\geq1}(A^c_{n}\cup B^c_{n})=\cup_{{n\geq1}} \cap_{{k\geq n}} (A^c_{n}\cup B^c_{n})\subseteq \cup_{{n\geq1}}(A^c_{n}\cup B^c_{n})=\{\cup_{{n\geq1}}(A^c_{n})\}\cup\{\cup_{{n\geq1}}B^c_{n})\}$$ and wanted to prove that their measure is zero. Then I said that $μ(\liminf_{n\geq1}A^c_n)=\lim_{n\rightarrow \infty}μ(\cap_{n\geq 1} A^c_n)=0 $ And tried simirarly for $\limsup B^c_n$.
Well, I ended up believing that I can't prove what I wanted with the above.
Can someone help?
Answer: Since
$$
\limsup_{n\ge 1} (A_n\cap B_n)\supseteq \limsup_{n\ge 1} A_n \cap \liminf_{n\ge 1} B_n,
$$
$$
\mu\!\left(\limsup_{n\ge 1} (A_n\cap B_n)\right)\ge \mu\!\left(\limsup_{n\ge 1} A_n \cap \liminf_{n\ge 1} B_n\right)=1.
$$


Text Capture from Image - SwiftUI

Question: The new iOS 15 feature "Capture Text from Image" option comes only after second tap. So The Apple Team provided
let textFromCamera  = UIAction.captureTextFromCamera(responder: self.notes, identifier: nil)

When I tried to use same with SwiftUI, responser object should confirm to UIResponder/UIKeyInpunt.
How to use same with SwiftUI or Is there any alternate option in SwiftUI ?
Answer: Because I haven't found an answer for this anywhere, I had to figure it out myself. Doing that is actually possible in two ways.
SwiftUI
To create a button for this purpose, you need a class that adopts the protocols UIResponder and UIKeyInput. The required variable hasText and method deleteBackward are not used so you can just ignore them.
class ScanTextResponder: UIResponder, UIKeyInput {
    init(title: Binding<String>) {
        _title = title
    }

    @Binding var title: String

    var canCaptureTextFromCamera: Bool {
        canPerformAction(#selector(captureTextFromCamera(_:)), withSender: self)
    }

    var hasText = false

    func insertText(_ text: String) {
        title = text
    }

    func deleteBackward() {}
}

Because the feature does not work on older devices, you should add a condition like canCaptureTextFromCamera, to not show the button on these devices. Then you just need to use the responder class in a view like this:
struct ScanTextButton: View {
    init(title: Binding<String>) {
        self.responder = ScanTextResponder(title: title)
    }

    private let responder: ScanTextResponder

    var body: some View {
        if responder.canCaptureTextFromCamera {
            Button {
                responder.captureTextFromCamera(nil)

                // Allows dismissal of the camera after multiple presses
                let backup = responder.title
                responder.title = ""
                responder.title = backup
            } label: {
                Label("Scan Text", systemImage: "text.viewfinder")
            }
        }
    }
}

The last three lines in the button action are not necessary, but I have found that otherwise you can't dismiss the camera view after pressing the button multiple times while the camera is already visible. I haven't found a better way to do that.
UIViewRepresentable
Alternatively, there is also the possibility to integrate a UIViewRepresentable. The advantage of that is, that the button label and icon are preconfigured which includes localisation. The disadvantage is that you have to use UIKit if you want to style the button.
struct UIScanTextButton: UIViewRepresentable {
    let coordinator: ScanTextResponder

    func makeCoordinator() -> ScanTextResponder {
        coordinator
    }

    func makeUIView(context: Context) -> UIButton {
        UIButton(primaryAction: .captureTextFromCamera(responder: context.coordinator, identifier: nil))
    }

    func updateUIView(_ uiView: UIViewType, context: Context) {}
}

You can use that in your SwiftUI view like this:
UIScanTextButton(coordinator: responder)
            .fixedSize()

The fixedSize() modifier ensures that the view does not cover the whole screen.
Let me know if you have any questions.
Comment: Thanks a lot saved the day!!
I've tried to modify the ui of the button with no luck
   label: {
                HStack{
               Text("Scan It")
                Image(systemName: "text.viewfinder")
                }
            }
Comment: @Muhammad Since this is a normal Button, changing the label should work, assuming you are using the SwiftUI method. You could also just change the parameters of the Label I used. Without a full code sample, I can't help you further.
Answer: I don't have an iPhone with iOS 15/neural engine to test it right now but this should work. I can get it to work up to clicking the menu.
The WWDC video states that it available in iPhone with neural engine which I think is the iPhone X and above. There is little documentation on this right now
import SwiftUI

@available(iOS 15.0, *)
struct ActionMenuView: View {
    @State var text: String = ""
    var body: some View {
        HStack{
            Text(text)
            ActionMenuView_UI(text: $text)
        }
    }
}
@available(iOS 15.0, *)
struct ActionMenuView_UI: UIViewRepresentable {
    @Binding var text: String

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    func makeUIView(context: Context) -> some UIView {

        //let choosePhotoOrVideo = UIAction(…)
        //let takePhotoOrVideo = UIAction(…)
        //let scanDocuments = UIAction(…)

        // A UIButton can hold the menu, it is a long press to get it to come up
        let button = UIButton()
        let textFromCamera = UIAction.captureTextFromCamera(responder: context.coordinator, identifier: nil)
        let cameraMenu = UIMenu(children: [
            //choosePhotoOrVideo, takePhotoOrVideo, scanDocuments,
            textFromCamera])
        button.setImage(UIImage(systemName: "camera.badge.ellipsis"), for: .normal)
        button.menu = cameraMenu
        return button
    }
    func updateUIView(_ uiView: UIViewType, context: Context) {

    }
    //Making the Coordinator a UIResponder as! UIKeyInput gives access to the text
    class Coordinator: UIResponder, UIKeyInput{
        var hasText: Bool{
            !parent.text.isEmpty
        }

        let parent: ActionMenuView_UI

        init(_ parent: ActionMenuView_UI){
            self.parent = parent
        }
        func insertText(_ text: String) {
            //Update the @Binding
            parent.text = text
        }

        func deleteBackward() { }
    }
}
@available(iOS 15.0, *)
struct ActionMenuView_Previews: PreviewProvider {
    static var previews: some View {
        ActionMenuView()
    }
}

Text Capture from Image - SwiftUI


change user within bash script

Question: I have a simple bash script which runs great as a regular user.  When launched from postfix, it runs as nobody:nobody which prevents many commands from working.
Is it possible for the script to change to another user account while running, to allow these other programs to run?
Thanks
Comment: http://stackoverflow.com/questions/6905697/how-to-run-script-as-another-user-without-password
Answer: You will need to configure sudo so that you can run a specific command as nobody which will run as another user.
Typically, something like (in your sudoers file):
nobody ALL=(userTheScriptShouldRunAs) NOPASSWD: /home/userTheScriptShouldRunAs/test.sh

Then, get your script to execute:
sudo -u userTheScriptShouldRunAs /home/userTheScriptShouldRunAs/test.sh

Comment: I think this is the only way...I don't like to sudo a script callable from a mail message but no option.  Thanks
Answer: You can set a program's permissions with the setuid bit:

chown usertorunas filename
chmod ug+s filename

That will make it run as the user who owns the file.
However, as @Jay reminded me, it doesn't work for scripts.  To run a script as a different user you need to make a small program as explained here which CAN be setuid, and calls your script.
Comment: You can't set setuid bits on scripts, too much of a security risk.

change user within bash script


Dymanimcally add links in main menu (e.g. last 4 nodes)

Question: I have main navigation menu with root menu items. A request is that one of those have links to latest 4 nodes of a certain content type. So for example if I have a structure similar to this:
-Parent item:

child item 4
child item 3
child item 2
child item 1

(All child items are all of the same content type, for example Article)
When a user adds a new node of the content type Article, the structure should be the following:
-Parent item:

child item 5
child item 4
child item 3
child item 2

All I can think of is to use Views to make a list of linked titles in a block and then to attach the block to the menu (i'm using TB Mega Menu which allows this).
The solely problem with this approach is that I then don't have trail of active menu items in menu.
Any ideas?
Thanks.
Answer: Make the URLs static; have the content of those URLs change
You were on the right track with views. But don't use it to create a block with the links, use it to create a page that displays the full rendered entity of the last node of your content type. You can give it a URL like /latest-article.
You could get fancy and use contextual arguments to display the 2nd, 3rd, ... offsets (e.g. /latest-article/%) or you could just add four more displays to the view, each with the offset bumped up by one.
Answer: First, in the you can choose what menu and what parent should those links go . That way, all the new links should appear where you wish.

Then, using Rules and Menu Rules you can make disappear the oldest menu link when you add a new one.


Alternativas para o (anti-)padrão Entity-Attribute-Value

Question: Estou trabalhando em dois sistemas que possuem uma característica comum: entidades cujos atributos são dinâmicos (i.e. não podem ser "engessados" - hardcoded), precisam se consultados em operações de busca (filtro de resultados), mas de outra forma estão desacoplados do restante do sistema (i.e. não há nada fazendo referência a eles, nem eles são usados em nenhum cálculo específico). Estou com dificuldade de encontrar uma forma apropriada para representá-los.
Até o momento, tenho usado o (anti-)padrão EAV. Há uma tabela Entity que identifica a entidade, uma tabela Tag (NxN com Entity) que diz o "tipo" - ou "classe" - da entidade, uma tabela Attribute (Nx1 com Tag) que identifica a propriedade, seu tipo, e se pode ou não estar ausente, e por fim várias tabelas XValue (TextValue, IntValue, DateValue etc) que dizem "a entidade E possui para o atributo A o valor V".

Contextualizando, uma entidade poderia ser um produto à venda, sua tag o tipo de produto (ex.: "carro"), os atributos sendo as características de um carro (ex.: "marca", "modelo", "quilômetros rodados") e os valores a aplicação daquelas características ao produto à venda (ex.: "Fiat", "Palio", "20000"). Tipos de produtos podem ser criados, alterados e excluídos (dinâmicos), pode-se consultar um tipo de produto pelas seus características (ex.: filtrar carros pela marca "Fiat"), mas não há qualquer chave estrangeira para um atributo específico, e jamais haverá qualquer cálculo "não genérico" envolvendo características de produtos.
E, como falei, atualmente implemento isso na forma de modelos EAV - num banco de dados PostgreSQL, cross-platform a princípio porém mais voltado pra Linux.

Normalmente o uso de EAV é um "alerta de WTF em potencial", mas creio que esse seria um dos seus usos legítimos (as estruturas dos dados modeladas dessa forma são realmente dados, e não meta-dados). A grande maioria do banco está formalizada, apenas umas poucas entidades foram modeladas dessa forma (e tomei medidas pra garantir que seria possível formalizar qualquer modelo que porventura venha a ser acoplado ao restante do sistema).
Entretanto, estou procurando por alternativas a esse modelo - já que ele é trabalhoso de se lidar e cheio de pitfalls. Pensei em representar cada entidade por um simples XML, mas há o requisito da busca filtrada - o que não sei como fazer [de forma eficiente]. Não tenho experiência com SGBDs não relacionais ("NoSQL"), por isso não sei se suas características de performance seriam aceitáveis (estou prevendo um número elevado de leituras - buscas filtradas - simultâneas, bem como escritas simultâneas - ainda que não na mesma entidade). Outras ideias me vieram à cabeça, mas me parecem "malucas" demais pra se usar na prática (ex.: alterar dinamicamente o esquema do BD sempre que um "tipo" é modificado).
Peço que as respostas se baseiem em experiência prévia envolvendo sistemas com requisitos semelhantes, não somente opinião e/ou base teórica, se possível. Sugestões de tecnologias específicas são bem vindas, mas o que eu busco é mais uma estratégia de solução, e não uma recomendação de software.

Atualização: Para quem não está familiarizado com o "Entity-Attribute-Value" (infelizmente não encontrei material algum em português sobre o assunto), aqui está um exemplo concreto:
Numa modelagem tradicional (formalizada), uma entidade "Carro" poderia ser representada assim:
Carros
ID      Marca     Modelo     Km
----------------------------------
1       Fiat      Palio      20000
2       Honda     Fit        10000

Numa modelagem EAV, isso é feito assim:
Entidades         Atributos            Valores
ID   Tipo         ID    Nome           Entidade Atributo Valor
----------        -------------        -----------------------
1    Carro        1     Marca          1        1        Fiat
2    Carro        2     Modelo         1        2        Palio
                  3     Km             1        3        20000
                                       2        1        Honda
                                       2        2        Fit
                                       2        3        10000

A vantagem dessa representação é que o tipo "Carro" não está engessado (hardcoded): se eu quiser adicionar um atributo "Cor", eu não preciso mexer na estrutura da tabela, criar queries novas pra lidar com esse atributo, etc - basta criar uma linha a mais na tabela Atributos e para cada carro uma linha a mais na tabela Valores. Se além de carros eu quiser representar outra coisa (ex.: imóveis), é só criar linhas na tabela Entidades com esse novo tipo, e dar-lhe atributos da mesma forma que a "Carros".
As desvantagens são... bem, todas as possíveis e imagináveis! De um modo geral, esse é um padrão a ser evitado a todo custo (i.e. um "anti-padrão"). Entretanto, mesmo os maiores críticos admitem que - em certos casos - ele é inevitável. Minha pergunta é: 1) isso se aplica ao meu caso? ou há uma maneira formalizada de atender aos meus requisitos? 2) se é inevitável, se existem boas alternativas que possuam performance aceitável.
Comment: @HarryPotter Qual parte? Se algo não está claro na pergunta, me indique o que é e eu acrescento mais detalhes.
Comment: @HarryPotter Coloquei um exemplo, espero que fique mais claro. De todo modo, nesses dias em que não tive uma resposta venho pesquisando por alternativas. Se até eu chegar numa solução ninguém postar nenhuma resposta, eu documento aqui o que descobri...
Comment: Será que você não está procurando pelo em ovo? Pela descrição o modelo EAV funciona perfeitamente para o seu caso. Não precisa ter tanto medo dele assim. Eu tenho experiência com um sistema que usa uma derivação desse modelo levada ao extremo, e apesar dos WTFs (que no seu caso parecem bem sob controle) ainda vejo vários pontos positivos.
Comment: Eu não consegui entender, ... ?
Comment: Eu to tentando entender o fio da meada, em relação a tal configuração que é dinâmica, eu já li algumas vezes e cada vez que eu leio fico mais confuso, gostei muito da questão em si, mas, se puder coloque um exemplo que venha na sua cuca quero tentar ajudar, porque, é a parte da programação que mais gosto !!! Não sei se vou conseguir mas, quem sabe!
Comment: @mgibsonbr, vou dar uma analisada, achei muito interessante!
Answer: Esse é um caso de uso típico para ferramentas NoSQL, em especial para ferramentas da família de bancos de dados orientados à documentos (como o MongoDB). Outras alternativas possíveis / complementares são ferramentas de enterprise search (como o Elasticsearch).
A palavra chave aqui é schema-less, uma característica com vantagens e desvantagens (veja essa apresentação do Martin Fowler sobre o assunto).
Tive boas experiência com grandes sistemas de:

E-commerce ⇒ Geralmente possuem modelos relacionais complicadíssimos para representar atributos / grupos de atributos / hierarquia de categorias / atributos de categorias. etc.
Vagas e Currículos ⇒ Geralmente lidam com Informação textual pouco estruturada. Algoritmos para determinar relevância são extremamente importantes.
Telco ⇒ Armazenam configurações diversas e difíceis de estruturar em modelo relacional.

Na verdade, a partir de um determinado volume de dados, bem como para determinadas características de leitura e escrita, enterprise search, NoSQL ou ambas as coisas são praticamente necessárias para manter o sistema responsivo.
Como funciona
Em ambos os casos é possível criar documentos com atributos diversos (e.g., em formato JSON), inclusive atributos complexos (arrays, tipos aninhados, etc). Documentos com atributos diferentes podem ser agrupados na mesma categoria (ou seja, o tipo de um documento não define seus atributos).
Quando você busca por determinado documento (por exemplo, por id), recebe toda a informação que persistiu sobre aquele documento (i.e., todos os atributos).
Quando você faz uma consulta usando determinado atributo as engines fazem uma busca apenas nos documentos que contém aquele atributo.
Na prática sua aplicação acaba conhecendo e definindo as regras para os atributos (e.g., um carro sempre vai ter id, modelo e ano, mas apenas carros importados possuem o atributo país de origem) e você faz consultas "sãs" em cima dessas regras. É o que o Martin Fowlwer chama de schemas implícitos.
Características
Performance: O uso correto dessas soluções é bem mais eficiente do que o padrão EVA em bancos de dados relacionais. Essas soluções são feitas para escalar e retornar rapidamente resultados de consultas em data sets gigantes.
Consultas: Buscas por tipos, ranges, buscas lógicas, ordenação, scoring, full text search, enfim, todo tipo de coisa pode ser feita. É claro que as ferramentas possuem suas próprias características. Leva um tempo até você entender como estruturar as informações de forma eficiente, bem como perder o vício em funções agregadas, cláusulas having e coisas do gênero (ainda que mesmo esse tipo de consulta possa ser feita com soluções de MapReduce).
ACID / BASE: Assim como em bancos de dados relacionais, ferramentas NoSQL geralmente podem ser configuradas para suportar diferentes características de consistência / disponibilidade / tolerância à falha (veja Teorema de CAP). Cada ferramenta também possui seus mecanismos de transação e serialização* .
Praticidade: Persista seus documentos e faça todo tipo de consulta (bem como updates, deletes, updates parciais, etc). Tudo é bem simples (a curva de aprendizagem de SGBDs Relacionais, ao meu ver, é bem mais acentuada).
* Específico para as ferramentas mencionadas: Você não terá nenhum problema com leituras ou escritas concorrentes. Apenas recomendo que mantenha ao menos dois nós no ar o tempo todo (especialmente para o MongoDB). O intuído aqui não é (apenas) garantir alta disponibilidade, e sim extrair o máximo das ferramentas. Recomendo fazer isso mesmo para o ambiente de desenvolvimento... Essa tarefa é bem mais simples do que aparenta (eu fiz configurações locais com VMs no meu laptop, não perdi mais do que uma hora configurando o MongoDB e o Elasticsearch).


How can I find the original un-changed configuration file to compare with the *.rpmnew file?

Question: While upgrading from CentOS 5.7 to 5.8 I've received the following warnings:
<code>warning: /etc/sysconfig/iptables-config created as /etc/sysconfig/iptables-config.rpmnew
warning: /etc/ssh/sshd_config created as /etc/ssh/sshd_config.rpmnew
warning: /etc/odbcinst.ini created as /etc/odbcinst.ini.rpmnew
</code>
(To know the reason for such files, and what one can do with them read - Why do I have .rpmnew file after an update? )
I want to know what exactly has been change in the default config file by comparing the old default file (the original un-changed configuration file) with the new default file (*.rpmnew). Then, I can apply the changes to my modified file (aka diff merge).
The problem is I don't know where can I find the original un-changed configuration file...
Updated:
So my question is actually:

How to find out what was the previous version of the package?
How to get the file of that version?
Comment: Ah.  Look for the final versions of the 5.7 packages from http://vault.centos.org/, specifically http://vault.centos.org/5.7/os/i386/CentOS/ and then use the rpm2cpio tool to extract the ones you want to look at, as per johnshen64's answer.  Also look in http://vault.centos.org/5.7/updates/ for updates to any packages in the 5.7 base.
Comment: It actually says exactly where the original and where the rpmnew files are, right in the warning message: "warning: /etc/ssh/sshd_config created as /etc/ssh/sshd_config.rpmnew"
Comment: @cjc I'm not that fool :) please see updated question
Answer: the original files should be one without .rpmnew
so for instance, you should have a
/etc/ssh/sshd_config
diff /etc/ssh/sshd_config /etc/ssh/sshd_config.rpmnew
will show you the diff. rpm does this to prevent overriding your settings.
if you are looking for the previously installed rpm, you need to find that rpm, and then extract it with rpm2cpio and then cpio to unpack the files.
then you should be able to find the default configuration files in the unpacked files.
Comment: I could be wrong but as far as I understand, the OP has modified the original configuration files, so the files on his system (e.g. sshd_config) is modified. The OP is asking how to find the original unmodified ones
Comment: Ah, you are talking about unmodified configuration file of the previously installed rpm? In that case, we have to find the original rpm and extract. This would depend which exact version was installed before the new rpm version was installed. rpms are just archives that can unpacked to find the individual files. rpm2cpio  is the usual tool for that.
Comment: Yeah dvb is right, that what I'm talking about, I would be grateful if you could edit your answer to explain how to find out what was the previous version and how to get the file of that version


Select data and pass it in to CLR function/sproc?

Question: I can find lots of examples where people pass single parameters in to CLR code like this:
public static void Example(SqlDateTime param1, SqlInt32 param2) {
}

I've also seen lots of code where people pass in parameters which are then used to select data from SQL within code (using an SQLCommand.) Isn't it possible to pass the equivalent to a DataTable object in to the CLR code and manipulate that?
Thanks,
Joe
Answer: You can always pass an equivalent Object in CLI depending on type (Managed/Native) of object.
public class NativeObject
{
private:
    int id;
    string msg;
    SomeClass obj;
    .......
public:
    string getMessage(){return msg;}
    int getID(){return id;}
    ...
}

It's Managed equivalent will be
public ref class ManagedObject
{
private:
    NativeObject* native;
public:
    ManagedObject(NativeObject* obj){
        native = obj;
    }
    String^ getMessage(){
        convertNativeToCLI(native->getMessage()); //you can use marshaling to implement convertNativeToCLI method.
    }
    int getID(){
        return native->getID();
    }
    ...
}

and you will need a Binder or Interface class to convert one object from one form to another. Generally we use this approach when we have complex objects. If we have only few simple data object then this approach will unnecessary put extra overhead.


ERRO: static declaration of follows non-static declaration

Question: Meu código está com o seguinte erro e não estou enxergando e nem entendendo do que se trata.

80:6: error: static declaration of 'print_menu' follows non-static
  declaration  void print_menu(){
14:6: note: previous declaration of 'print_menu' was here  void
  print_menu();

Código:
/* <-- BIBLIOTECAS --> */
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#include "game_pvp.h"
/* <-- BIBLIOTECAS --> */

/* <-- DEFINES --> */
#define TAM 3
/* <-- DEFINES --> */

/* <-- DECLARAÇÃO DE PROCEDIMENTOS --> */
void print_menu();
void print_new_game();
void print_game_level();
void print_pvp_menu();
/* <-- DECLARAÇÃO DE PROCEDIMENTOS --> */

/* <-- MAIN --> */
int main(){
    char menu_choice;
    char game_shape[TAM][TAM];
    int start_player;

    srand(time(NULL));

    print_menu();
    menu_choice = getch();
    while(menu_choice < 49 || menu_choice > 51) {
        printf("\n Please enter a valid option");
        menu_choice = getch();
    }
    if(menu_choice == 49){
        system("cls");
        print_new_game();
        menu_choice = getch();
        while(menu_choice < 49 || menu_choice > 50) {
            printf("\n Please enter a valid option");
            menu_choice = getch();
        }
        if(menu_choice == 49){
            system("cls");
            print_game_level();
            menu_choice = getch();
            while(menu_choice < 49 || menu_choice > 51) {
                printf("\n Please enter a valid option ");
                menu_choice = getch();
            }
            system("cls");
            // CHAMA JOGADOR vs IA Passando o nivel
        }
        else{
            system("cls");
            print_pvp_menu();
            start_player = (rand() % 2) + 1;
            if(start_player == 1){
                printf("\n  O Player 1 comeca (press any key)");
            }
            else{
                printf("\n  O Player 2 comeca (press any key)");
            }
            getch();
            system("cls");
            // CHAMA JOGADOR vs JOGADOR Passando a vez

            game_pvp(game_shape, start_player);
        }

    }
    // Aqui entra game save e EXIT

    system("pause");
}

/* <-- MAIN --> */

/* <-- PROCEDIMENTOS --> */
void print_menu(){
    printf("\n -=- JOGO DA VELHA -=- \n");
    printf("\n 1 - New Game");
    printf("\n 2 - Saved game");
    printf("\n 3 - EXIT");
    printf("\n Enter your choice ");
}

void print_new_game(){
    printf("\n -=- JOGO DA VELHA -=- \n");
    printf("\n 1 - One player");
    printf("\n 2 - Two players");
    printf("\n Enter your choice ");
}

void print_game_level(){
    printf("\n -=- GAME LEVEL -=- \n");
    printf("\n 1 - Easy");
    printf("\n 2 - Medium");
    printf("\n 3 - Hard");
    printf("\n Enter your choice ");
}

void print_pvp_menu(){
    printf("\n -=- PLAYER vs PLAYER -=- \n");
    printf("\n X - Player 1");
    printf("\n O - Player 2");
    printf("\n\n Sorteando quem vai comecar ...");
}
/* <-- PROCEDIMENTOS --> */

compiling_error:
C:\Users\Gabriel\Desktop\jogo da velha\main.c:80:6: error: static declaration of 'print_menu' follows non-static declaration
 void print_menu(){
      ^~~~~~~~~~
C:\Users\Gabriel\Desktop\jogo da velha\main.c:14:6: note: previous declaration of 'print_menu' was here
 void print_menu();
      ^~~~~~~~~~
C:\Users\Gabriel\Desktop\jogo da velha\main.c:88:6: error: static declaration of 'print_new_game' follows non-static declaration
 void print_new_game(){
      ^~~~~~~~~~~~~~
C:\Users\Gabriel\Desktop\jogo da velha\main.c:15:6: note: previous declaration of 'print_new_game' was here
 void print_new_game();
      ^~~~~~~~~~~~~~
C:\Users\Gabriel\Desktop\jogo da velha\main.c:95:6: error: static declaration of 'print_game_level' follows non-static declaration
 void print_game_level(){
      ^~~~~~~~~~~~~~~~
C:\Users\Gabriel\Desktop\jogo da velha\main.c:16:6: note: previous declaration of 'print_game_level' was here
 void print_game_level();
      ^~~~~~~~~~~~~~~~
C:\Users\Gabriel\Desktop\jogo da velha\main.c:103:6: error: static declaration of 'print_pvp_menu' follows non-static declaration
 void print_pvp_menu(){
      ^~~~~~~~~~~~~~
C:\Users\Gabriel\Desktop\jogo da velha\main.c:17:6: note: previous declaration of 'print_pvp_menu' was here
 void print_pvp_menu();
      ^~~~~~~~~~~~~~
C:\Users\Gabriel\Desktop\jogo da velha\main.c:108:1: error: expected declaration or statement at end of input
 }
 ^

game_pvp.h:
#include "game_pvp.c"

game_pvp.c:
int game_pvp(char game_shape[3][3], int turn){
    char x, y;

    if(turn == 1){
        print_shape(turn);
        printf("\n Enter a value for X: ");
        x = getch();
        printf("%c",x);
        while(x < 49 || x > 51 ){
            printf("\n Please enter a valid option");
            x = getch();
        }
        printf("\n Enter a value for Y: ");
        y = getch();
        printf("%c",y);
        while(y < 49 || y > 51 ){
            printf("\n Please enter a valid option");
            y = getch();
        }
    }
    else{
        print_shape(turn);
        printf("\n Enter a value for X: ");
        x = getch();
        printf("%c",x);
        while(x < 49 || x > 51 ){
            printf("\n Please enter a valid option");
            x = getch();
        }
        printf("\n Enter a value for Y: ");
        y = getch();
        printf("%c",y);
        while(y < 49 || y > 51 ){
            printf("\n Please enter a valid option");
            y = getch();
    }

}

void print_shape(int turn){

        printf("\n -=- PLAYER %i TURN -=- \n", turn);
        printf("\n");
        printf("      1   2   3   Y\n");
        printf("\n");
        printf(" 1    X | X | X \n");
        printf("     ---|---|--- \n ");
        printf("2    X | X | X \n");
        printf("     ---|---|--- \n ");
        printf("3    X | X | X \n");
        printf("\n X\n");

}

Comment: Tenta mudar para static void print_game()... na sua função
Comment: Deve ter um `print_menu()` em outro lugar. Alias um dos motivos que odeio declaração separado da definição.
Comment: Coloquei static na frente e não adiantou.
Comment: Tbm mudei o print_menu() para print_menu2() e continuou com o erro mas agora no print_menu2()
Comment: Qual o conteúdo do `.h`?
Comment: E qual o compilador? Se possível, quais flags de compilação?
Comment: Opa, Jefferson. Comentei a parte .h é voltou a funcionar, já vou colocar o conteúdo dele.
Comment: @GabrielDantas o problema está no `.h`, que você inclui o `.c`
Comment: Qual o problema do .h Jefferson ?
Comment: @GabrielDantas o `.h` não deve ter código, apenas declaração. Por isso, não inclua arquivos `.c`, o comportamento que o compilador vai executar não vai ser o que você espera, o ciclo de compilar um fonte C de modo separado é distinto daquele que você imagina; mais detalhes nessa resposta: https://pt.stackoverflow.com/a/213804/64969
Comment: Na resposta, eu boto o comportamento do `#include"hello.c"` em um projeto e mostrou qual a inconsistência gerada
Answer: O seu problema é que existe um descasamento de {} no arquivo game_pvp.c. Você esqueceu de fechar um } na função int game_pvp(char game_shape[][3], int turn)
Agora o grande problema mesmo é que vc está usando o arquivo .h de modo errado. Ele não tem a finalidade de incluir um arquivo .c, como vc fez, mas de ser um cabeçalho onde vc coloca as declarações das funções e estruturas que o seu programa irá usar.
Sendo assim, a forma correta de criar o game_pvp.h, seria algo do tipo:
#ifndef __GAME_PVP_H__
#define __GAME_PVP_H__

int game_pvp(char game_shape[][3], int turn);
void print_shape(int turn);

#endif /* __GAME_PVP_H__ */

Comment: Faz total sentido. Pensei que tinha sido erro de digitação do AP
Comment: Obrigado amigo, vou dar uma estudada sobre esse .h


passing strucure pointer of dynamic array through functions in C

Question: I am trying to implement three functions for a program:

The first one counts the number of lines in a file,
The second one creates a dynamic array and fills it with the content of the file - one row for each row of the table, and returns a structure with two fields: the first one stores a pointer to the created dynamic array, and the second one stores the size of that array.
The third function prints this array.

I need help with the code I've written so far:
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

struct vehicle {
    char brand[40];
    char model[40];
    int production_year;
    float engine_capacity;
};

struct array {
    char*** ptr;
    int size;
};

int count_lines(FILE* file) {
    int temp;
    char temp1[50];
    char temp2[50];
    int temp3;
    int line_count = 0;
    while (!feof(file)) {
        fscanf(file, "%s", &temp1);
        fscanf(file, "%s", &temp2);
        fscanf(file, "%d", &temp);
        fscanf(file, "%d", &temp3);
        line_count++;
    }
    rewind(file);
    return line_count;
}

struct array read_array(FILE* file) {
    struct array arr;
    int n;
    n = count_lines(file);
    char** t1 = malloc(n * sizeof(char*));
    for (int i = 0; i < n; i++)
        t1[i] = malloc(50 * sizeof(char));

    int i = 0;
    while (i < n) {
        fgets(t1[i], 50, file);
        i++;
    }

    arr.ptr = &t1;
    arr.size = n;

    return arr;
}

void print_array(struct array arr) {
    printf("Array t1:\n");
    for (int i = 0; i < arr.size; i++) {
        printf("%s", t1[1]);
    }
}

int main() {
    FILE* stream_read;
    struct vehicle cars;
    struct array my_array;
    if ((stream_read = fopen("dane.txt", "r")) == NULL)
        printf("File 'data' could not be opened\n");
    else
        printf("File 'data' has been opened\n");
    int line_count;

    line_count = count_lines(stream_read);

    my_array = read_array(stream_read);

    print_array(my_array);

    if (fclose(stream_read)) {
        printf("File 'data' was not closed\n");
    }

    getchar();
    return 0;
}

I'm having trouble with printing the array, as I'm doing something wrong when passing the array from the function to main and printing it. Could you please help me fix and understand it
I'm sure that the text is properly being stored in the array, but I have no idea how to pass it to other functions so that it doesn't produce random symbols.
Comment: Do you really need 3 stars?
Comment: `while (!feof (fp))` seems wrong. See https://stackoverflow.com/q/5431941/20017547
Comment: If you want to count lines, use `fgets()` to read each line. You don't need to parse the lines.
Comment: @Haris They won't, but the error message will explain the segmentation fault :)
Comment: You are returning (in the structure) a pointer to an object whose lifetime has ended.
Comment: `arr.ptr = &t1` in read_array() is a local that goes away when the fcn exits. The return value is thus invalid. Undefined behavior.
Comment: "for each row of the table" - what table? You only mentioned a file. "Prints this array" - prints it how? One element per line would reproduce the original file.
Comment: And not a single comment documenting the code...
Comment: How are subsequent operations supposed to read from the file if `fopen()` failed?
Comment: @ScottHunter: Come on, that's not fair, OP is in the middle of writing their code, and they're a newbie. Please rephrase your comment as a positive suggestion.
Comment: The calls to `fscanf()` invoke undefined behaviour because the `%s` format specifier expects a `char *`, not a `char (*)[]`.
Answer: You have implemented this part of the requirements incorrectly:

two fields: the first one stores a pointer to the created dynamic array [...]

The dynamic array is the allocated space, not the (local to function read_array) variable in which you initially store a pointer to that space.  The local variable exists only while the function is executing.  After it returns, any pointers to its local variables, such as the one you return inside your structure, become indeterminate.
You want this:
struct array {
    char **ptr;
    int size;
};

and this:
    arr.ptr = t1;  // assign the value of t1, not a pointer to t1
    arr.size = n;

    return arr;

And in function print_array(), you need to use the pointer received in the structure to access the lines.  There is no t1 in that function, but after the above changes, arr.ptr should work fine in its stead.


Configure WildFly to use SSL

Question: I am using WildFly25, and have it running with default settings.
Server console
WildFly Full 25.0.0.Final (WildFly Core 17.0.1.Final) started in 3938ms - Started 308 of 547 services (338 services are lazy, passive or on-demand)
Http management interface listening on http://127.0.0.1:9990/management
Admin console listening on http://127.0.0.1:9990

I want to update the config, so it runs using SSL/TLS on https.
So I follow the WildFly documentation to configure it using the WildFly CLI (advise is to use the CLI and not to edit the XML manually because there is less chance for errors).
Configuration
Connect via the CLI:
/home/jboss/wildfly/wildfly-25.0.0.Final/bin ./jboss-cli.sh
connect

I have a keystore (mykeystore.jks). So then I add the keystore to the WildFly config:
/subsystem=elytron/key-store=httpsKS:add(path=/home/jboss/wildfly/wildfly-25.0.0.Final/standalone/configuration/mykeystore.jks,credential-reference={clear-text=password},type=JKS)

/subsystem=elytron/key-manager=httpsKM:add(key-store=httpsKS,credential-reference={clear-text=password})
/subsystem=elytron/server-ssl-context=httpsSSC:add(key-manager=httpsKM,protocols=["TLSv1.2"])

When I check the security-realm:
/subsystem=undertow/server=default-server/https-listener=https:read-attribute(name=security-realm)
{
    "outcome" => "success",
    "result" => undefined
}

This is visible in standalone.xml:
        <tls>
            <key-stores>
                <key-store name="applicationKS">
                    <credential-reference clear-text="password"/>
                    <implementation type="JKS"/>
                    <file path="application.keystore" relative-to="jboss.server.config.dir"/>
                </key-store>
                <key-store name="httpsKS">
                    <credential-reference clear-text="password"/>
                    <implementation type="JKS"/>
                    <file path="/home/jboss/wildfly/wildfly-25.0.0.Final/standalone/configuration/mykeystore.jks"/>
                </key-store>
            </key-stores>
            <key-managers>
                <key-manager name="applicationKM" key-store="applicationKS" generate-self-signed-certificate-host="localhost">
                    <credential-reference clear-text="password"/>
                </key-manager>
                <key-manager name="httpsKM" key-store="httpsKS">
                    <credential-reference clear-text="password"/>
                </key-manager>
            </key-managers>
            <server-ssl-contexts>
                <server-ssl-context name="applicationSSC" key-manager="applicationKM"/>
                <server-ssl-context name="httpsSSC" protocols="TLSv1.2" key-manager="httpsKM"/>
            </server-ssl-contexts>
        </tls>

But I don't see any <security-realm> in the xml:
        <security-realms>
            <identity-realm name="local" identity="$local"/>
            <properties-realm name="ApplicationRealm">
                <users-properties path="application-users.properties" relative-to="jboss.server.config.dir" digest-realm-name="ApplicationRealm"/>
                <groups-properties path="application-roles.properties" relative-to="jboss.server.config.dir"/>
            </properties-realm>
            <properties-realm name="ManagementRealm">
                <users-properties path="mgmt-users.properties" relative-to="jboss.server.config.dir" digest-realm-name="ManagementRealm"/>
                <groups-properties path="mgmt-groups.properties" relative-to="jboss.server.config.dir"/>
            </properties-realm>
        </security-realms>

As the security-realm is undefined (before and after any changes), I run the following (from the WildFly documentation), but it has no affect. (this looks like it sets the security-realm to undefined so it should not have any affect to an already undefined security-realm).
batch
/subsystem=undertow/server=default-server/https-listener=https:undefine-attribute(name=security-realm)
/subsystem=undertow/server=default-server/https-listener=https:write-attribute(name=ssl-context,value=httpsSSC)
run-batch

reload

Question
What am I missing?  After following the WildFly documentation, I would expect to have the following (i.e. the server listening for the management console on https and port 9993):
Server console
WildFly Full 25.0.0.Final (WildFly Core 17.0.1.Final) started in 3938ms - Started 308 of 547 services (338 services are lazy, passive or on-demand)
Http management interface listening on https://127.0.0.1:9993/management
Admin console listening on https://127.0.0.1:9993

More info
[standalone@localhost:9990 /] /core-service=management/management-interface=http-interface:write-attribute(name=secure-socket-binding, value=management-https)
{
    "outcome" => "failed",
    "failure-description" => "WFLYSRV0259: If attribute secure-socket-binding is defined ssl-context must also be defined",
    "rolled-back" => true
}

Answer: When I ran this it started to work:
/core-service=management/management-interface=http-interface:write-attribute(name=ssl-context,value=httpsSSC)
reload
/core-service=management/management-interface=http-interface:write-attribute(name=secure-socket-binding, value=management-https)
reload

console output:
09:25:59,234 INFO [org.jboss.as] (Controller Boot Thread) WFLYSRV0062: Http management interface listening on http://127.0.0.1:9990/management and https://127.0.0.1:9993/management
09:25:59,234 INFO [org.jboss.as] (Controller Boot Thread) WFLYSRV0053: Admin console listening on http://127.0.0.1:9990 and https://127.0.0.1:9993

Configure WildFly to use SSL


PHP Replace all characters other than [a-zA-Z0-9\-]

Question: I would like to replace all characters in a string other than [a-zA-Z0-9\-] with a space.
I've found this post and no matter how many times I tweak the REGEX, I can't get it to "don't match [a-zA-Z0-9-], only match and replace other characters".
At the moment, I have the following:
$original_name = trim(' How to get file creation & modification date/times in Python?  ');

$replace_strange_characters = preg_replace("/^((?!([a-zA-Z0-9\-]+)*))$/", " ", $original_name);

// Returns: How to get file creation & modification date/times in Python?
echo $replace_strange_characters;

I wish for it to replace all of the strange characters with a space ' ', thus returning:
How to get file creation   modification date times in Python?

I'm really struggling with these "don't match" scenarios.
Here's my code so far: http://tehplayground.com/#2NFzGbG7B
Comment: I wish to retain dashes, using `\w` as suggested in the answers for that question would not have the desired effect. :(
Answer: You may try this (You mentioned you want to keep dash)
$original_name = trim(' How to get file creation & modification date/times in Python?  ');
$replace_strange_characters = preg_replace('/[^\da-z-]/i', ' ', $original_name);
echo $replace_strange_characters;

DEMO.
Comment: I think that link rot has set in...
Answer: Wouldn't this regex do it?
[^a-zA-Z0-9\-]

Oh, and why are you doing this btw?
Comment: Thanks for trying, but your example doesn't say "no not match" anything?
Comment: @Coulton Eh? It says matching anything but a-zA-Z0-9\- (with other words, not a-zA-Z0-9\-, but everything else).
Answer: Try this
$replace_strange_characters = preg_replace("([^a-zA-Z0-9\-\?])", " ", $original_name);

The previous answer strip out the ?


How to merge a list of dataframes by a single column?

Question: I have a list of dataframes, each of which has a "Name" column and a "Sample" column.
df1:

Name Sample1
A 23
B 445
C 456

df2:

Name Sample2
A 45
B 984
C 374

How can I merge all the dataframes in my list so they end up like so:
merged:

Name Sample1 Sample2
A 23 45
B 445 984
C 456 374

I have tried answers from similar questions on SO but none of them have produced the desired result. E.g. merged.data.frame = Reduce(function(...) merge(..., all=T), list.of.data.frames)
Edit:
My original script is listed below
# List all files in current working directory
fs <- list.files()

# Load the data from each file into a list of data frames
dfs <- lapply(fs, read.table, header=TRUE, sep="\t")

# Select only the Name and Concentration columns from the list of data frames
dfs <- lapply(dfs, subset, select=c(Name, Concentration))

# Sort each dataframe alphabetically by the Name column
dfs <- lapply(dfs, function(df){df[order(df$Name),]})

# Rename each Concentration heading with the basename of the filename where the data originates
for (i in 1:length(dfs)){colnames(dfs[[i]])[2] <- substr(fs[i], 1, nchar(fs[i]) - 4)}

# Merge all the dataframes together by the Name column

# Write merged dataframe out to a tab-delimited file
write.table(dfs, ".", sep="\t")

Comment: Try `join_all` from `library(plyr)`.  Also, `Reduce(function(...) merge(..., all=TRUE, by="Name"), list(df1, df2))` gave the expected output you showed based on the 2 datasets.
Answer: It should work (as follows):
dats <- list(df1=data.frame(Name=c("A", "B", "C"), Sample1=c(23, 445, 456), stringsAsFactors=FALSE),
             df2=data.frame(Name=c("A", "B", "C"), Sample2=c(45, 984, 374), stringsAsFactors=FALSE),
             df3=data.frame(Name=c("A", "B", "C"), Sample3=c(66, 111, 2), stringsAsFactors=FALSE))

dats

## $df1
##   Name Sample1
## 1    A      23
## 2    B     445
## 3    C     456
##
## $df2
##   Name Sample2
## 1    A      45
## 2    B     984
## 3    C     374
##
## $df3
##   Name Sample3
## 1    A      66
## 2    B     111
## 3    C       2

# with by="Name"
merged.data.frame <- Reduce(function(...) merge(..., by="Name", all=TRUE), dats)

merged.data.frame

##   Name Sample1 Sample2 Sample3
## 1    A      23      45      66
## 2    B     445     984     111
## 3    C     456     374       2

# without by="Name" (same result)
merged.data.frame <- Reduce(function(...) merge(..., all=TRUE), dats)

##   Name Sample1 Sample2 Sample3
## 1    A      23      45      66
## 2    B     445     984     111
## 3    C     456     374       2

Comment: I just tried your command and it does join them together but there are thousands of repeated rows in the data frame. I have attached my full script to my original question, incase it is a type error I'm coming across?
Answer: It works for me. Is this an accurate reproduction of the problem you are trying to solve?
> X <- replicate(20, data.frame(name=letters, r=runif(26)), simplify=FALSE)
> for(i in 1:20) names(X[[i]])[2] <- paste0("Sample", i)
> M <- Reduce(function(x,y)merge(x,y,by="name"), X)
> str(M)
'data.frame':   26 obs. of  21 variables:
 $ name    : Factor w/ 26 levels "a","b","c","d",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ Sample1 : num  0.17 0.957 0.443 0.181 0.113 ...
 $ Sample2 : num  0.8983 0.1802 0.7817 0.0818 0.7741 ...
 $ Sample3 : num  0.7473 0.6888 0.0195 0.9815 0.9674 ...
 $ Sample4 : num  0.557 0.331 0.902 0.177 0.504 ...
 $ Sample5 : num  0.0784 0.1561 0.5524 0.2631 0.2082 ...
 $ Sample6 : num  0.7455 0.5604 0.7232 0.5651 0.0727 ...
 $ Sample7 : num  0.721 0.807 0.902 0.965 0.41 ...
 $ Sample8 : num  0.209 0.17 0.207 0.303 0.258 ...
 $ Sample9 : num  0.736 0.566 0.125 0.417 0.521 ...
 $ Sample10: num  0.639 0.778 0.499 0.57 0.934 ...
 $ Sample11: num  0.0104 0.1629 0.4513 0.4821 0.383 ...
 $ Sample12: num  0.20123 0.95563 0.39992 0.00256 0.69283 ...
 $ Sample13: num  0.466 0.735 0.857 0.695 0.673 ...
 $ Sample14: num  0.562 0.873 0.269 0.151 0.628 ...
 $ Sample15: num  0.809 0.75 0.414 0.644 0.953 ...
 $ Sample16: num  0.7729 0.0129 0.5654 0.5705 0.7514 ...
 $ Sample17: num  0.239 0.454 0.538 0.596 0.743 ...
 $ Sample18: num  0.29 0.1 0.806 0.66 0.668 ...
 $ Sample19: num  0.461 0.739 0.474 0.64 0.418 ...
 $ Sample20: num  0.631 0.369 0.913 0.655 0.641 ...

Comment: One thing to look out for is if the `Name` column is set up as a factor correctly; try `stringsAsFactors=FALSE` for your `read.table`; also if the sets of names are different among files, you might need `all=TRUE` for the `merge`, otherwise you will only get the row that appears in *all of them*.
Comment: Your example works perfectly, so it must be something wrong with the pre-processing of my data. Which is strange because right up until the step where I need to merge the dataframes, it looks just like the dummy data you created.


Singing seated on the floor: Best position?

Question: I use to sing a lot in large groups of people who are seated on the floor (just on some soft pad or similar). I always find myself not being able to sing well because of the position in which I sit, with my legs crossed. This causes that I can't sing as high and as loud as when I stand, for instance.
Is there a better (and comfortable) position in which I can sit to be able to better sing?
Answer: You could rest on your knees with your pad below it (imagine someone on their knees in prayer, but with a pillow to cushion their knees). This would allow you to keep your diaphragm, neck and head straight but also keep your knees comfortable with the floor.
Sitting with your legs crossed is definitely going to make it more difficult for you to push project your voice.
Comment: Yep, there is. It's a meditative church services (Taizé-kind). I know it's not ideal, but I want to get the best out of it. Thanks for the answer!
Comment: How do you arrange your feet so that the ankles don't start hurting after half an hour? I don't manage to put them straight below me, my ankle is not flexible enough for that :( Maybe I'll need a bit thicker pad...
Comment: I would arrange my ankles so that each was turned inward, with the left foot cupping the right. Something like this: http://cf.ltkcdn.net/yoga/images/std/121896-283x425-Hero_pose2.jpg
Comment: Again, sitting on the ground is not ideal for singing. Is there a reason why people aren't sitting in chairs?
Comment: Fascinating - I should have guessed that! No problem. I would definitely recommend some seated yoga for you and the rest of congregation. Google the "Hero Pose" (or Virasana) or the "Easy Pose" (or Sukhasana). Good starters.


Delete all .bak files from folder with CMD

Question: I want automate the delete files with .bak extension in my backup folder
I have a little CMD who ZIP all my  BD .back and after this i want delete this bak but not ZIP file
I use this but dont work, the bak files are in F:\bckup
del /s /q /f "F:\bckup*.bak"

enter image description here
Answer: You're missing a backslash in the path.
Try del /s /q /f "F:\bckup\*.bak"
Comment: I really can't understand how it's possible to not only make typo (it happens), not notice it (it happens too), not notice it when troubleshooting (even this happens)... but to even *post a question here including the typo and not noticing it again*. Do people ever re-read what they write?
Comment: well it could be that he use native paths, however `forfiles` can be also a choice if you're planning to make a delay on the deletion


Git ignore directory without making changes to remote

Question: I need to ignore changes, both local and remote, to a directory. For example I have remote git set with:

templates/T1
templates/T2
templates/Tn

And I want to set local git so that it track only T2 for example, and ignore others.
What I tried was this:
    git rm -r --cached templates/T1
    git rm -r --cached templates/Tn

And then added this to the .gitignore inside of templates dir
    /*
    !/T2

But after doing this I got bunch of files marked as deleted that want to be pushed to remote, I do not want this. I need remote to keep having all templates, but on this single local machine I need only one template tracked.
Comment: Related: http://stackoverflow.com/questions/2673232/how-do-you-tell-git-to-permanently-ignore-changes-in-a-file
Comment: Do you only need **one template tracked** or do you only need **one template checked out**?
Comment: one checked out is probably a better way of saying it
Comment: In that case, take a look at [my answer](http://stackoverflow.com/a/28675672/2274224).
Answer: To ignore some files in git they should be removed from remote server and added to .gitignore. So this approach doesn't work for you.
To keep files on a remote server but not to track them you can with git update-index --assume-unchanged files. This will keep some initial version of T1, Tn files on a remote and will not track them on your local repo. So git status will not list changed T1, Tn.
Answer: You cannot ignore an already tracked file even if you add it to .gitignore or exclude.
What you can do is write a pre-commit hook that reverts any changes in the directories you don't want to track. However you will have them in your repository! You cannot delete them without bothering git.
Hope it helps!
Answer: Since you said in the comments that you only need one template checked out, I would like to suggest you make use of gits sparse-checkout.
You can take a look at this answer, which explains it in greater detail, but I will provide a specific example for your case.

Activate sparse-checkout with git config core.sparsecheckout true
Create a sparse-checkout file in .git/info; you need to specifiy patterns for the files you want to checkout

In your case this file could look like this:
*               # Add everything for checkout
!templates/     # Don't checkout the content of templates
templates/T2    # Checkout T2 in templates

Update your working tree git read-tree -m -u HEAD

The last command should be executed in the root of your repository, with a clean working tree (no changed files etc.).
This should leave your working trees templates directory empty except for the T2 file.


Is this $\delta-\varepsilon$ proof correct?

Question: Let $\Omega$ be an intervall and let $\gamma\in\Omega$. $\lim_{x\rightarrow \gamma}f(x)=L$ is equivalent to the statement bellow.
$$\forall \varepsilon>0\exists \delta:\forall x \in \Omega: 0<\mid x-\gamma\mid<\delta \Rightarrow \mid f(x)-L \mid < \varepsilon$$
I'm working on an assignment where I have to use the above definition of a $\lim_{x\rightarrow \gamma}f(x)=L$ to show that a particular function converges. I've come up with two proofs thus far but I am not certain that the second one is correct since I have allowed  $\Omega$ to depend on $\varepsilon$. Is this allowed?
I will give you an example of what I did. At a certain point in the proof I find that $\mid f(x)-L \mid = C\mid x-\gamma\mid ^2$, $C>0$. So if $0<\mid x-\gamma\mid<\sqrt{\frac{\varepsilon}{C}}$ we have that $\mid f(x)-L \mid = C\mid x-\gamma\mid ^2 < C\left(\sqrt{\frac{\varepsilon}{C}}\right)^2=\varepsilon$. If I let $\Omega = \left(\gamma - \sqrt{\frac{\varepsilon}{C}}, \gamma + \sqrt{\frac{\varepsilon}{C}}\right)$ then I can let $\delta = \sqrt{\frac{\varepsilon}{C}}$ correct? Am I allowed to do this or did I mess up?
Answer: No you cannot change $\Omega$; but there is no need to anyway. You've already solved it. You can choose  $\delta = \sqrt{\frac{\varepsilon}{C}}$ regardless of what $\Omega$ is. It doesn't matter if your $\Omega$ is contained in $(\gamma - \delta, \gamma + \delta)$ or if $(\gamma - \delta, \gamma + \delta)$ is contained in $\Omega$, or neither. To prove the limit is $L$ you must prove that for every $x$ which is in $\Omega$ and in $(\gamma - \delta, \gamma + \delta)$, we have $|f(x)-L|< \epsilon$. It doesn't matter if some points are in $\Omega$ but not in $(\gamma - \delta, \gamma + \delta)$ or vice versa.
Let me know if you have any questions.


React useState assíncrono

Question: sou novo no React e estou com dificuldade para fazer um filtro em dados que serão exibidos em uma tabela. Tenho os inputs dos filtros (são 5 no total) e um botão filtrar que chama uma função, nessa função tenho o setState que alimenta o state que contém as informações. O lance é que, por ser assíncrono, o useState só filtra os dados quando eu clico pela segunda vez no botão 'filtrar', como poderia fazer para esse filtro ser executado imediatamente? Abaixo um trecho do código:
 const [data, setData] = useState([]);
 const [data_filter, setDataFilter] = useState([]);

 setData(data);
 setDataFilter(data);

**Variavel 'data' contem todos os dados do db retornados pelo axios (get)
 function handleFiltro() {
     if (numero) {
       const p_filter = data_filter.filter(id => {
         return id.id == numero;
       });
       setDataFilter(p_filter);
     }
     const data1 = data_filter.map(data => ({
       ...data,
       emissao: format(parseISO(data.createdAt), "d 'de' MMMM 'de' yyyy", {
         locale: pt,
       }),
       expiracao: format(parseISO(data.expire_at), "d 'de' MMMM 'de' yyyy", {
         locale: pt,
       }),
     }));

     setData(data1);
  }

  <button type="button" onClick={() => handleFiltro()}>
     Filtrar
  </button>

Comment: Dentro de sua função "handleFiltro", tente fazer o setData desta forma: setData([...data1]);
Comment: Fiz o teste e continua da mesma forma, só funciona com 2 clicks no botão filtrar...
Answer: A melhor forma de resolver esse problema é com o hook useEffect, fazendo com que ele assista o estado data_filter e apenas dispare o setData após a atualização ter sido concluída. Ficaria assim:
function handleFiltro() {
  if (numero) {
    const p_filter = data_filter.filter(id => {
      return id.id == numero;
    });

    setDataFilter(p_filter);
  }
}

useEffect(() => {
  const data1 = data_filter.map(data => ({
    ...data,
    emissao: format(parseISO(data.createdAt), "d 'de' MMMM 'de' yyyy", {
    locale: pt,
    }),
    expiracao: format(parseISO(data.expire_at), "d 'de' MMMM 'de' yyyy", {
    locale: pt,
    }),
  }));

  setData(data1);
}, [data_filter]);

React useState assíncrono


Can I get a function info(return/parameter type) in another function with C++?

Question: See my demo code below:
string foo(double a, double b) {
  //...
}

void goo(foo) {
  // ... do something base on string/double/double of foo
}

I want do something in goo base on the return/parameter type of foo, how can I make with C++?
One possible way is to bind foo and goo in a template class object.
In my real case, foo and goo are not determined at the same time which means you can't bind them together.
Comment: The return type must be `string` because of the typedef `func`. Am I misunderstanding your question?
Comment: @JosephMansfield foo can be any return/parameter type, but only 2 input parameters
Comment: *"In my real case, foo and goo are not determined at the same time"*, does that mean `foo` could change after you have complied `goo`? There is `decltype`, but it would require `foo`'s definition to be visible when `goo` gets complied.
Comment: Do you want that `goo` can take any function pointer that take exactly 2 parameters ?
Answer: Assuming you pass foo by pointer, you can use templates:
template<typename R>
void bar(R (*func)(double, double))
{
    // Do something with func
    // example:
    R variable = func(3.14, 42);
    std::cout << variable;
}

Use:
bar(foo);
// or
bar(&foo);

It is also possible to do some meta-programming based on R. Note that you can also use templates for the function parameters:
template<typename R, typename P1, typename P2>
void bar(R (*func)(P1, P2))
{
    // ...
}


What's the deal with using unreliable green energy in datacenters?

Question: The news say that Google now uses 48 MW of electricity produced by wind turbines to power one of its datacenters.
I've always heard that "green" energy is great, but it is unreliable - wind doesn't blow constantly, sometimes there's no wind and so no energy.
How can a datacenter be powered by energy sources that don't supply constant power?
Comment: If you had a datacenter that used wind power and just wind power, as you say, you'd have a lot of downtime.
Comment: @tombull89  Not necessarily, since a datacenter will always feed power into batteries anyway.  They very well could have a datacenter that's powered solely by green power, if their datacenter UPS system has enough capacity.
Comment: @voretaq7 Yeah, but imagine the cooling required.
Comment: @tombull89 Not if it's located in DC - plenty of wind in that town :)
Comment: ISS (space station) is using green power (solar). Seems not to be a problem.
Answer: Because they are also connected to reliable power generation, such as batteries, diesel generators, or grid power.
Answer: They feed the power generated by green sources into massive and expensive banks of batteries as part of datacenter-grade uninterruptable power systems.
They'd also have backup generators in case the banks of batteries ran down, and as longneck said in his answer, almost certainly have a secondary power feed coming in from "the grid," powered by conventional energy sources.
EDIT:  Looks like I should source my answer, given that a number of people seem to think it's all handled with conventional energy at some point.
For a source on how this can be done, here's a little article on one of Apple's new 100% renewable energy datacenters.

The company had already announced plans to build a 20 MW solar array installation and a 5 MW fuel cell installation at the NC data center, which will be the largest private solar array and the largest non-utility fuel cell project in the country. Those projects are expected to provide 60 percent of the data center's electricity needs. The big news is that Apple is now doubling the on-site solar power capacity by building a second 20 MW array with the total solar power generation to now hit 84 million kWh per year.
The remaining energy needs of the data center not met by the on-site sources will be met through purchasing renewable power from local and regional sources.

So basically, between batteries, fuel cells, and purchasing "green power" from non-local sources, it's easily possible to power a data center with 100% "green" energy, and not rely on conventional "dirty" power at any point, possibly excepting a backup/emergency power feed based off the normal power grid.
And, just because this is who I am, I'll pose the question I always do regarding "green" [whatever]... how environmentally friendly do you think it is to manufacture all this green energy generation and storage equipment?
It's a rhetorical question, and the answer is it's very much not environmentally friendly.)


$\text{rank}(AB) = \text{rank}(BA)$ if product of $A$ and $B$ is defined?

Question: How can I prove this statement is true/false? I have found a counterexample which proves it is not, but I don't understand why it doesn't work, neither why it does work in some cases.
Comment: Here's a simple counterexample. If $u$ and $v$ are orthogonal vectors, then $uv^T$ has rank $1$, whereas $v^Tu$ equals zero and therefore has rank zero.
Comment: What is your counterexample?
Comment: As soon as you have a counterexample, you've proven that the statement isn't true in general. Your prompt "why it does work in some cases", though a legitimate question, is a bit vague. I don't think there's really anything nice one can say in general.
Comment: Sorry, you're totally correct, my mistake.
Comment: @Nick Alger, that's not really a counter-example, because you've transposed, rather than commuted the matrices.
Comment: @AlexanderHeyes No, it is indeed a real counterexample. They are commuted and not transposed. Perhaps it will be easier to see this if you temporarily define $A:=u$, $B:=v^T$. Then the two expressions are $AB$ vs. $BA$.
Answer: If you have found a counter-example, then that's enough to conclude this identity is not true. However, you might be looking at some specific matrices $A, B$, then it might hold for them; however, that would be a total coincidence.
The reason why it doesn't hold in generally is pretty intuitive. I presume you know that $\text{rank}:M\rightarrow \mathbb{F}$ is a function that tells you what the dimension of the range of a particular matrix is. So $\text{rank}(I_2)=2$, because its range is the whole space of $\mathbb{R}^2$. Compare this to $\begin{bmatrix}1&0\\0&0\end{bmatrix}$, which maps all of $\mathbb{R}^2$ into the horizontal axis - it collapses the plane down, losing information.
Now think about some matrices that would collapse the space in different ways. Say $A$ maps $\mathbb{R}^3$ into the $x$-$y$ plane, but that whole plane is the kernel of $B$; then $\text{rank}(BA)=0$, because the product matrix $BA$ maps everything to the origin. Now suppose $B$ maps the $z$ axis back to itself, and $A$ then maps this line into the plane. Then $\text{rank}(AB)=1$, because this product matrix maps $\mathbb{R}^3$ into a line, a one-dimensional subspace.
Explicitly, this becomes:
$$AB=\begin{bmatrix}
1&0&1\\
0&1&0\\
0&0&0
\end{bmatrix}
\begin{bmatrix}
0&0&0\\
0&0&0\\
0&0&1
\end{bmatrix}
=
\begin{bmatrix}
0&0&1\\
0&0&0\\
0&0&0
\end{bmatrix}
\qquad \text{rank}(AB)=1$$
Compare with
$$BA=\begin{bmatrix}
0&0&0\\
0&0&0\\
0&0&1
\end{bmatrix}
\begin{bmatrix}
1&0&1\\
0&1&0\\
0&0&0
\end{bmatrix}
=
\begin{bmatrix}
0&0&0\\
0&0&0\\
0&0&0
\end{bmatrix}
\qquad \text{rank}(BA)=0$$
In other words, the rank is different because applying matrices in different orders changes which vectors end up where. And really, this is just another way of saying matrices don't commute! Which you probably already knew. :)
Comment: Thank you for the answer, this was very helpful, you made it way more understandable for me :)


SQL DB2 - conditional logic in WHERE clause

Question: I need to pull back records based on a location ID, but I've got two fields that MAY contain the incoming criteria....
something like this
SELECT * FROM tbl
WHERE myVar = locationID
    IF LocationID = 0
      myVar = location2ID

this is a 'logical' example...
I think I can do
WHERE myVar = CASE WHEN locationID = 0 THEN location2ID ELSE locationID END

although I've read that CASE in a WHERE clause should be avoided...? why? or is this OK?
- either way it FAILS
WHERE CASE WHEN locationID=0 THEN location2ID=myVAr ELSE locationID=myVar END

also FAILS
thx
Sorry for the confusion lads - didn't mean to be "ambiguous" - looks like #2 will do what I want - but for the clarification requested here is the issue...
the table stores TWO locations, let's call then CURRENT_LOC and ORIGINAL_LOC... in most cases these will BOTH have data, but in some cases the 'thing' hasn't moved... so the CURRENT_LOC is '0'. MY issue is I'll be passing in a LOCATION ID, I want the records where CURRENT_LOC matches OR if the the CURRENT_LOC=0 then I ALSO want the ORIGINAL_LOC... where that matches...
does that help the discussion? I hope.
Comment: You've been given two answers, which have slightly different outlook on the problem.  Please disambiguate your question (by indicating what happens to `location2ID` when `locationID` is not 0), and accept the relevant answer.
Answer: WHERE myVar = COALESCE(NULLIF(locationID, 0), location2ID)
Alternatively,
WHERE (
       (locationID <> 0 AND myVar = locationID)
       OR
       (locationID = 0 AND myVar = location2ID)
      )


GPP Registry Item Level Targeting in PowerShell

Question: Is there any way to add item level targeting to an existing GPP Registry item via powershell?
I'm in the process of streamlining my build process and I have come up empty for anything item level targeting related.
Edit: To clarify I will be creating active directory groups then appending a registry key to an existing GPP using that group as the item level targeting. This whole process needs to be automated to avoid transcription and logic errors.
Comment: Could you clarify your requirements? I'm not sure why you can't just build the GPO with item level targeting using the standard tools.
Comment: Unfoetunately the built in tools aren't well suited for bulk or frequent changes. I'm looking for a powershell method that I can pass multiple groups to and always get a uniform build.
Answer: I automated all the steps other than setting up the item level targeting via PowerShell and created a custom MMC snapin that opens straight to the group policy and registry keys in question at the end of my script.
While not ideal it was the best possible option until MS provides a ready way to script item level targeting.
Answer: You might find this interesting:
http://www.sdmsoftware.com/products/group-policy-automation-engine/
A norwegian guy use this module for handling prefernce-printers adding his own cmdlet on top of the SDM-objects:
http://blog.powershell.no/2010/01/18/automate-group-policy-preferences-printer-management-using-windows-powershell-2/


override views-view-fields.tpl.php in custom module

Question: Hi i want to Override views-view-fields.tpl.php in our custom module. kindly help me by example.
Answer: You need to define a theme hook for the field-template in your module and place a template in custom_module/theme/your-custom-template.tpl:
/**
* Implementation of hook_theme().
*/
function custom_module_theme($existing) {
  return array(
    'views_view_field__view_name__field_name' => array(
    'arguments' => array('view' => NULL, 'field' => NULL, 'row' => NULL),
    'template' => 'your-custom-template',
    'original hook' => 'views_view_field',
    'path' => drupal_get_path('module', 'custom_module') . '/theme',
   ),
  );
}

To narrow down which field-templates you want to replace you can name your return key to:

views_view_field__view_name: Override all field templates of the view named "view_name"
views_view_field__view_name__field_name: Override only this specific field

This example is taken from grayside.org
Comment: great, then please mark the answer which helped you most as "accepted" to close this issue
Comment: For Drupal 8 this worked but instead of `arguments` you need `variables`. Also this question should specify for which version of Drupal this is.
Answer: The view object is available in the tpl file, so by having an if-else statement it is possible to filter the views that need to the override by inspecting the name/display of the view.
A sample piece of code might help say for example using hook_field_attach_view_alter():
function MYMODULE_field_attach_view_alter(&$output, $context) {

  $field_name = 'test';
  $to_display = array('a');

  if (isset($output[$field_name]['#field_name'])) {
    if ($field_name == $output[$field_name]['#field_name']) {
      foreach ($output[$field_name]['#items'] as $delta => $item) {
        if (in_array($item['value'], $to_display)) {
          unset($output[$field_name][$delta]);
        }
      }
    }
  }
}