Dynamo DB + In put Item Request how to pass null value?

Question: I have one field which i have declared as string in the model as show below:
App.Student= DS.Model.extend({
name: DS.attr('string'),
address1: DS.attr('string'),
address2: DS.attr('string'),
city: DS.attr('string'),
state: DS.attr('string'),
postal: DS.attr('string'),
country: DS.attr('string'),
});

Here in the Edit mode when i update Adderess 2 field as null then below error comes:
"Failed to edit property: One or more parameter values were invalid: An AttributeValue may not contain an empty string"
I know this Error is generated because i am updating address 2 field as null and that what i want Address 2 field is not mandatory(One can pass data or can also left that column as blank")
Answer: If you are using DynamoDB (not DocumentClient) you can specify nulls like this
const putItem: PutItemInput = {
  TableName: `${process.env.PRIMARY_TABLE}`,
  Item: {
    key: { S: ${userId}` },
    someField: { NULL: true }
  }
}

Answer: Finally i got this right, The way might be some what different but it work for me !!!
Here is the code for the same.
AttributeUpdates: {
                     Address2:
                     {
                        Action: "DELETE"
                     },
                  }

And then i am adding the value on the condition.
if (propertyObj.address2) {
        params.AttributeUpdates.address2 = {
            Value: {
                S: propertyObj.address2
            },
            Action: "PUT"
        }
    }

Thank you to all from bottom of my heart :)who tried to help me, Cheers !!!
Comment: FYI, DynamoDb now supports empty string values for non-key attributes: https://aws.amazon.com/about-aws/whats-new/2020/05/amazon-dynamodb-now-supports-empty-values-for-non-key-string-and-binary-attributes-in-dynamodb-tables/
Comment: Also FYI you [*don't need to map the attribute itself at all*](https://stackoverflow.com/a/62723116/1357094), in order to represent "no value".
Answer: I just pass nulls. Here's my NodeJS script for loading data from file into DynamoDB, I just use ternaries to avoid empty strings.
var AWS = require("aws-sdk");
var fs = require('fs');

// Make sure we got a filename on the command line.
if (process.argv.length < 3) {
  console.log('Usage: node ' + process.argv[1] + ' FILENAME');
  process.exit(1);
}

var filename = process.argv[2];

AWS.config.update({
    region: "us-west-2",
    //endpoint: "http://localhost:8000"
});

var docClient = new AWS.DynamoDB.DocumentClient();

console.log("Importing Addresses into DynamoDB. Please wait.");

var allObjs = JSON.parse(fs.readFileSync(filename, 'utf8'));
allObjs.forEach(function(obj) {
    var params = {
        TableName: "Address",
        Item: {
            "address_detail_pid":  obj.address_detail_pid,
            "flat_type":  obj.flat_type == '' ? null : obj.flat_type,
            "flat_number":  obj.flat_number == '' ? null : obj.flat_number,
            "level_type":  obj.level_type == '' ? null : obj.level_type,
            "level_number":  obj.level_number == '' ? null : obj.level_number,
            "number_first":  obj.number_first == '' ? null : obj.number_first,
            "street_name":  obj.street_name == '' ? null : obj.street_name,
            "street_type_code":  obj.street_type_code == '' ? null : obj.street_type_code,
            "locality_name":  obj.locality_name == '' ? null : obj.locality_name,
            "state_abbreviation":  obj.state_abbreviation == '' ? null : obj.state_abbreviation,
            "postcode":  obj.postcode == '' ? null : obj.postcode,
            "longitude":  obj.longitude == '' ? null : obj.longitude,
            "latitude":  obj.latitude == '' ? null : obj.latitude
        }
    };

    docClient.put(params, function(err, data) {
       if (err) {
           console.error("Unable to add obj", obj.address_detail_pid, ". Error JSON:", JSON.stringify(err, null, 2));
       } else {
           console.log("PutItem succeeded:", obj.address_detail_pid);
       }
    });
});

Comment: Your answer should be the de facto solution for handling empty strings/values. My understanding, however, is that this is permissible for `DocumentClient.put` and not `PutItem`. For others, see http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html
Comment: One caveat, I wasn't able to query against a GSI that includes the field set to null as a range value.
Answer: I think the best way is to check if the value of the field is blank and not save the value in the database.
When the field is blank, we should not include it in the attribute value map.
Here is the code snippet I have used in GO language
myAttributeValues := map[string]*dynamodb.AttributeValue{
        "field1": {
            S: aws.String(value1),
        },
        "field2": {
            S: aws.String(value2),
        },
        "field3": {
            S: aws.String(value3),
        },
    }

    if field4  != "" {
        field4Attribute := dynamodb.AttributeValue{
            S: aws.String(value4),
        }
        myAttributeValues["field4"] = &field4Attribute
    }

    if field5 != "" {
        field5Attribute := dynamodb.AttributeValue{
            S: aws.String(value5),
        }
        myAttributeValues["field5"] = &field5Attribute
    }

    input := &dynamodb.PutItemInput{

        TableName: aws.String(mytableName),
        Item:      myAttributeValues,
    }

Answer: You can use AttributeValue null type as a placeholder. If you cannot change the type, then, choose a sentinel value, like "ZZZZZ" or similar and make that represent the empty string. Alternatively, your model could just have one address field, and then, you could encode both address lines in address1, if the second address line is null/empty.
Comment: It is already declares as a string and i also can not make it to "Attributes value Null" is there any other way to do the same where datatype remains the same as "String" and i can do the operation ?
Answer: AWS finally resolved this issue.
DynamoDb now supports empty string values for non-key attributes: https://aws.amazon.com/about-aws/whats-new/2020/05/amazon-dynamodb-now-supports-empty-values-for-non-key-string-and-binary-attributes-in-dynamodb-tables/
Answer: Since DynamoDB is NoSQL, you can look at this in an entirely different way:
Instead of trying to add a "null"/empty value into DynamoDB, just plan on not attempting to add the attribute itself with the "null" value in the first place...
"null"-check in code, instead by checking if the attribute itself is present [by attribute name]:

If not present, interpret that as "null" for the state of that variable/attribute in code
If present, then it has a non-null value
If trying to set an existing attribute from non-"null" to "null", just remove the attribute
If trying to set what is ("conceptually" at the moment) a "null" value to non-"null", add the attribute [with its non-"null" value]

Note my use of quotes on "null" above - I did that on purpose to emphasize that if you use this thinking of representing null by not mapping its attribute itself, then there is no attribute that actually exists as "null" (no attribute that actually holds an actual "null" value).
*Besides the benefit of capturing "null"-checking in this way being possible in itself, this strategy has an additional benefit of saving [at least some] DynamoDB storage space, & read/write capacity units (i.e: on-demand pricing limits 1 write unit to 1kb & 1 read unit to 4kb):  No attribute stored to represent "null" means no storage otherwise spent!  I don't for a fact, but I am guessing Amazon intentionally makes AWS architecture design choices to force decisions/tradeoffs like this:  Operate under constraint of things like {no null values, no empty sets}, and save resources that would otherwise be spent on them.
Once again, this is all possible because of DynamoDB's NoSQL implementation - unlike a SQL database, NoSQL data can be unstructured; and in particular, the unstructured-ness can be leveraged in this case to include an attribute in some documents in a given DynamoDB table and not other documents (in the same table).  It is impossible to do the analogous same thing in a SQL database as each db row there must have all columns - that's what forces having to set a SQL variable/column to null for records where "no value" is desired (note my different formatting of null in this sentence ;), and not being able to just "not include the column/variable" on that row.  NoSQL's version to "not include a column on some rows" is possible by just not including an attribute (which it can do because NoSQL is unstructured :)
*This strategy can still be used for benefits despite the fact that Amazon DynamoDB now supports empty values for non-key String and Binary attributes - this strategy would still at least have the exceeding benefit of saving space.
*Note this strategy can also be used to represent an "empty set" (since in DynamoDB sets must have at least 1 value) - just don't map the set attribute until it is desired to be non-empty ;)
[This strategy can be read in a similar discussion for MongoDB]
Comment: Further to the storage benefits, if you have a GSI that's keyed on that attribute, you can save a huge amount if you omit the attribute. This is because the index will be much smaller. E.g. if your main DDB table has 1 million rows, and you have a GSI on `address2`, which is only filled in for 10,000 rows, then your entire GSI will only have 10,000 rows, as opposed to 1 million if you set it to `"null"`.


Piano finger apparatus in history or film

Question: Can anyone recall the movie where a piano player was using an apparatus to strengthen (or stretch) their ring finger. I keep picturing AMADEUS but i can't find references. If not, does any one know of a piano player who was documented as having used such tools.The tool had a string and pulley.
Comment: I believe this should be over at Movies SE
Answer: Robert Schumann supposedly injured his hand with a device designed to strengthen the fourth finger.
http://ericsams.org/index.php/on-music/essays/on-schumann/116-schumann-s-hand-injury-some-further-evidence
His hand was injured but the actual injury has now acquired the patina of legend.


Term for improvisation (or Melody) based on specific intervals, not notes?

Question: Is there a term for melodic improvisation where only specific intervals are taken into consideration?
As an example, Beginning on C, the player then has the option of moving either up or down, (Or repeating the same note) but only in the intervals of:
Min 2nd (C#/Db), Min 3rd (D#/Eb), Aug 4th/Dim 5th (F#/Gb), Min 6th (G#/Ab), Min 7th (A#/Bb), and into the next octave. (Min 2nd + Octave). Once the player decides on an interval, and plays it, he or she then selects the next interval from the same set.
If the second notes were F#/Gb, the available notes would then be: G, A, C, D, and E.
Below is a short passage composed under the stipulations above, as an illustration.

No key was applied, because I don't have the knowledge of which key would clean up the notation most efficiently.
Comment: Did you see this technique described somewhere/by someone? Or maybe there was a related idea that triggered this concept in your mind? I'm not familiar with it but find it interesting. Do you have any examples of a melody/improvisation that's based on this technique?
Comment: No jdjazz, I do not. I have spent the last two years listening almost exclusively to the music of Robert Fripp. His guitar playing from 1994 - 2004 included many harsh, dissonant sounding sections, particularly in his improvisations with King Crimson's Double Duo formation. I don't know what he was thinking, or what method he was drawing on as he improvised, but I thought that the method outlined in this question would make it easier to formulate a general feel (motif) in improvised music: in my case try to mimic his. (Check this example of Fripp's soloing: https://youtu.be/tHAJncjlQHM?t=564 )
Comment: @Erik What you're talking about sounds like what I'm looking for, and I think your answer is correct. I've removed my response to your answer from the posted question.
Comment: @DaleyCodyYakoweshen That's great! To expand on your question the concept of interval inversions might interest you too.
Comment: I just tried to notate something in Musescore using this technique of composing. I can't think of any way of making it look less messy. It contains many accidental's making for difficult reading, at least for me, though my reading is very poor.
Comment: @Daley, could you perhaps move your reply to me? It could help maintaining the consistency of the thread.
Comment: @Erik you've inspired me to write a short Q+A on inverted intervals: https://music.stackexchange.com/questions/70510/is-there-simple-way-to-reference-inverted-intervals-and-relate-them-to-the-15-k/70511#70511
Answer: To me this looks like scale transposition. Every played note becomes the new root note for the scale consisting of the stated intervals.


Hawkes-Process for non binary events

Question: I am currently using a univariate Hawkes-process for modeling the behaviour of agents in a social network. For example, the likelihood that a user will tweet in the next period is defined by the intensity $\lambda$ of a Hawkes-Process such as:

$\lambda_t = \mu + \sum_{t_i < t}\alpha e^{-\beta (t-t_i)}$

For a counting-process defined $(N(t): t>0)$ with the associated filtration $(\mathcal{F}(t): t>0)$  on $[0, T]$ with $t_1 ... t_N$ the realizations of $(N_t)_{t>0}$
My problem is that I would like to apply the same methodology on non-binary variables, let's say retweet counts for example. If the user as been retweeted 180 times at time $t$ I would that to have a higher impact on my intensity than it has been retweeted only 2 times.
To clarify, I am able to have the model for a time-series like this one, for a user that got retweeted at time $t_1$, $t_4$, $t_5$ and $t_7$ on $[0,T]$ for T=8:

$[0, 1, 0, 0, 1, 1, 0, 1, 0]$

I would like to have a model that takes into account the fact that simultaneous events occured at a given discrete time, 3 retweets at time $t_1$, 180 retweets at time $t_4$, 2 retweets at time $t_5$ and 90 retweets at time $t_7$ represented by the below sparse vector:

$[0, 3, 0, 0, 180, 2, 0, 90, 0]$

The problem with the Hawkes-Process framework as I understand it, is that it only takes binary events into consideration and I don't see how to apply it to my problema.
One might actually suggest that 'slicing' my time series of occurring event at a high enough frequency will eventually lead to a binary vector of occurrences. That's true, but since this has to be applied to big data, I can't afford to multiply my data length by 1000 or even more.
I don't really need a solution here, even just a paper dealing with such issue might be of great help.
Thanks.
Answer: One approach to answer your question is to use a multivariate Hawkes process to handle events associated with different volumes (or counts in your case). Instead of considering a one-dimensional Hawkes process for all events, you could group your counts into intervals. For instance, consider

$I_1=[1, 50]$,
$I_2 = [51, 100]$,
$I_3 = [101, 150]$,
$I_4 = [150, 200]$.

You can now model your data with a 4-dimensional Hawkes process $(N^1_t, N^2_t, N^3_t, N^4_t)$, each component of the process $N^j_t$ corresponding a point process that counts events whose number of retweets belong to $I_j$. This article uses that trick to model arrivals of trades with different sizes.
For the inference of such multivariate Hawkes process, I would recommend you to use the open-source library tick developed by smart guys of my team. This example may be helpful.
Comment: Interesting paper. Are you working at X? I planed on contacting Stéphane with this matter, but wanted to sand-down a bit more first. Thanks for your answer.
Comment: Yes, I'm one of his PhD student. I read your question again, and I may have missed some point: do you work with regular or irregular sampled data ? If you work with regular sampled data, AR processes can do the job as well.
Comment: I work with regular sampled data. But the choice of Hawkes-process was due to the strong sparsity and clustering nature of the time-series.
Comment: @L20DA, Is there anybody who installed 'tick' on windows? I installed it on MacOS with no issues, but on Windows, I tried using GCC instead of VS14 as a compiler, even tried to patch distutil, but no solution... Is there a tip for instaling the package on Python? Thanks.
Comment: @ylnor No, nobody installed it on windows. You should prefer MacOs or Linux. If you don't have the choice, one of the main developper advised to use docker to get rid of windows related issues.
Comment: @L20DA , Thanks. I have installed it on MacOS, but if I want to use it at work/lab, I have no choice but using it on a windows environement. docker isn't really helpfull in that case actually. I have created a question on stackoverflow, maybe the devs can take a quick look at it : http://stackoverflow.com/questions/43889093/python-distutils-error-nonetype-object-has-no-attribute-lstrip-when-ins .  Thanks anyways.

Hawkes-Process for non binary events


Why is threadTerminate not called inside a dll

Question: I have a problem that code inside my dll is acting different compared to the same code within a normal application. After some debugging I found that the thread's OnTerminate is never called within the dll.
type
  TTest = class
  private
  public
     procedure threadStart();
     procedure threadEnd(Sender: TObject);
     procedure lines(value: String);
  end;

procedure TTest.threadStart();
var aThread : TThread;
begin
 aThread :=
    TThread.CreateAnonymousThread(
      procedure
      begin
         lines('start')
      end
    );
  aThread.FreeOnTerminate := True;
  aThread.OnTerminate := self.threadEnd;
  aThread.Start;
end;

procedure TTest.threadEnd;
begin
  lines('end')
end;

procedure TTest.lines(value: String);
  var MyText: TStringlist;
begin
  MyText:= TStringlist.create;
  MyText.Add(value);
  MyText.SaveToFile('.\filename.txt');
  MyText.Free
end;

If I run this code from a normal VLC Delphi Application, I get end in the text file.
If I run the same code from a dll (loading it either static or dynamic into a VLC Application), I get start in the text file.
My question: Why? Or better asked, how can I let my dll act the same way as my VLC. Current version I'm using is XE7.
Comment: Correct, because the EXE is not looking for and processing `Synchronize()` requests from the DLL, so they are not signaled, thus `Synchronize()` blocks indefinitely.
Comment: Can duplicate in XE2, execution dies in `TMonitor.Wait(..` of `TThread.Synchronize`.
Answer: The TThread.OnTerminate event is triggered in the context of the main UI thread via a call to TThread.Synchronize(), which stores requests in a queue that the main UI thread checks periodically, executing pending requests when available.
If the DLL and EXE are compiled with Runtime Packages enabled, they share a single copy of the RTL (and thus require you to deploy rtl.bpl with your app). When the EXE checks the RTL's Synchronize() queue, it will see pending requests from both EXE and DLL.
However, if they are not sharing a single RTL, then they will be compiled with separate copies of the RTL that are not linked to each other.  By default, there is nothing in the EXE that checks and processes pending requests from the DLL's Synchronize() queue, only from the EXE's Synchronize() queue.  To address that, you have to export a function from the DLL that calls the CheckSynchronize() function of the DLL's RTL, and then make the EXE call that exported DLL function periodically, such as in a timer.
Otherwise, the other way to get around this problem is to bypass the Synchronize() call that triggers the OnTerminate event, by overriding the thread's virtual DoTerminate() method (which you cannot do with TThread.CreateAnonymousThread()).  You can have DoTerminate() call OnTerminate directly, or just do what you need inside of DoTerminate() itself.  But either way, you have to make sure this code is thread safe, as DoTerminate() runs in the context of the worker thread.
Comment: You can stick with the anonymous thread and just put your termination behaviour at the end of your anonymous method.
Comment: Since I'm only interested when the thread is done, I think I will use a push notification to inform the main program it should call doSynchronize in the dll. This answer helped me as well to figure out a small memory leak since finished threads would never be freed as well. I prefer the simplicity of the anonymousThread over the comfort to be able to override DoTerminate. Thanks for the clear answer.
Comment: @Kanitatlan: just be sure to wrap the method's code in a `try/finally` block so you can perform termination logic regardless of whether an uncaught exception is raised or not. `TThread` has an internal `try/finally` around `Execute()` so `DoTerminate()` is always called.


Calibrating Probabilities worse than Original Model even though better performance on calibration curve? (in R / Caret)

Question: I'm currently working on the exercises of the book 'Applied Predictive Modeling' by Kuhn and Johnson (using R and caret) and am stuck at the issue of 'Calibrating Probabilities'.
Exercise 12.3 shows a problem linked to openly available data on churning:
library(C50)
data(churn)
table(churnTrain$Class

First of all I fit some linear classification models (the chapter is also about linear classification models so I did not go further than that for the exercises).
I found that LDA had the best fit with a sensitivity of 0.24 and specificity of 0.96. All of the five models had a very low sensitivity so this is actually the problem of this task I guess.
But then later I try calibration. By that I try to refit probabilities of Naive Bayes and of another model. When doing the calibration curve it looks like the Naive Bayes recalibration fits very well!
But then I try a confusion matrix between the estimated values through the Naive Bayes correction and the testing sample and see that it became worse: a sensitivity of 0.12.
And this is what I don't understand: it looks on the curve as if Naive Bayes fits very well to the line - but so why is the final prediction worse? Did I maybe do something completely wrong?
I am attaching here a reduced code of what I've done:
Thanks,
Nebi
library(C50)
library(caret)
data(churn)
str(churnTrain)
table(churnTrain$churn)

tr_y<-churnTrain$churn
te_y<-churnTest$churn

data_temp<- predict(dummyVars(~ ., data = churnTrain[,-length(churnTrain)]), newdata = churnTrain[,-length(churnTrain)])
test_temp<- predict(dummyVars(~ ., data = churnTest[,-length(churnTest)]), newdata = churnTest[,-length(churnTest)])

predictorInfo<-nearZeroVar(data_temp, saveMetrics = TRUE)
summary(predictorInfo)
vector<-!predictorInfo$nzv
data_temp<-data_temp[,vector]
test_temp<-test_temp[,vector]

correlations = cor(data_temp)
highCorrpp <- findCorrelation(correlations)

data_temp <- data_temp[, -highCorrpp]
test_temp <- test_temp[, -highCorrpp]

#no missing values
sum(!complete.cases(data_temp))

ctrl<- trainControl(method="cv",number=10,
                    summaryFunction=twoClassSummary,
                    classProbs=TRUE)

tr_x<-data_temp

te_x<-test_temp

#######I CUT OUT HERE THE OTHER MODELS

ldaMod<-train(x=tr_x,y=tr_y,
              method="lda",
              metric="ROC",
              preProcess=c("center","scale","BoxCox"),
              tuneLength = 15,
              trControl=ctrl)
ldaMod

ldaPred<-predict(ldaMod,te_x)
confusionMatrix(ldaPred,te_y)

ldaProb<-predict(ldaMod,te_x, type="prob")

glm.rocCurve = pROC::roc( response=te_y, predictor=ldaProb[,1] )
glm.rocCurve
plot(glm.rocCurve,legacy.axes=TRUE)

comb_te<-as.data.frame(te_x)
comb_te$y<-te_y#sic damit y bei beiden tr_y heisst

comb_te$ldaProb<-ldaProb[,1]
liftCurve<- lift(y~ldaProb,data=comb_te)
liftCurve

xyplot(liftCurve,
       auto.key=list(columns=2,
                     lines=TRUE,
                     points=FALSE))

calCurve <- calibration(y~ldaProb,data=comb_te)
calCurve
xyplot(calCurve,auto.key=list(columns=2))

comb_train<-as.data.frame(tr_x)
comb_train$y<-tr_y
sub_two<-predict(ldaMod,tr_x, type="prob")
comb_train$ldaProb<-sub_two[,1]

sigmoidalCal<-glm(relevel(y,ref="no")~ldaProb,
                  data=comb_train,
                  family=binomial)
coef(summary(sigmoidalCal))

sigmoidProbs<-predict(sigmoidalCal,newdata=comb_te[,"ldaProb",drop=FALSE],
                      type="response")

comb_te$LDAsigmoid<-sigmoidProbs

library(klaR)
BayesCal<-NaiveBayes(y~ldaProb,data=comb_train,usekernel=TRUE)
BayesProb<-predict(BayesCal,newdata=comb_te[,"ldaProb",drop=FALSE])
comb_te$LDABayes<-BayesProb$posterior[,"yes"]
head(comb_te)

#this is the curve that shows that NaiveBayes is performing well!
calCurve2<-calibration(y~ldaProb+LDAsigmoid+LDABayes, data=comb_te)
xyplot(calCurve2,auto.key=list(columns=3))

#and here is the confusion matrix showing that sensitivity is even lower!
confusionMatrix(BayesProb$class,comb_te$y)

Comment: I run your example code. Please note that all models have rather low Cohen's $k$ ($\leq 0.25$). While clearly no particular metric is a panacea, this suggests that none of them really does very good to begin with.
Answer: Sensitivity, specificity, and a confusion matrix are at odds with optimal prediction.  See here for more information.  Calibration and predictive discrimination are all important.  Calibration should be assessed using a flexible continuous calibration curve, accounting for overfitting.  Predictive discrimination should be assessed using proper accuracy scoring rules combined with the semi-proper $c$-index (AUROC).
Comment: Thank you for your answer and insightful article. I understand that the AUROC is for optimal prediction overall more important than sensitivity and specificity. However, I am also in several aspects more confused now than before. I will try to find out more about these issues. For example in such an example, where 'yes' is so badly predicted, I thought that it would be worth to make a trade-off between ROC and sensitivity. Also the differentiation that you mention between the calibration on the one hand and the predictive discrimination makes me think...
Comment: That is exactly not the way to think about it in my humble opinion.  Please read the article carefully at the link above and read also [this](http://www.fharrell.com/2017/01/classification-vs-prediction.html).


SSIS with MySQL and without SQL Server

Question: Our Organization is planning to cut costs on SQL Sever licenses. We use  SSIS for our ETLs. Is it possible to install only SSIS with a MySQL server and  without SQL Server?
Answer: No, you can't run SSIS without also running the SQL Server engine, which means paying a license.
The reason for this is quite simple, SSIS is a SQL Server component/feature. It is integrated in the SQL Server Engine.
And you will at a minimum require a standard SQL Server edition to use the SSIS runtime.
Answer: I think no. There is used MS SQL Server to store SSISDB, so you can't install SSIS without SQL Server. You can split SSIS out from SQL server and use one server for SSIS and the other server for databases. If you do this, you will need to license both servers which will drive up costs.

SSIS with MySQL and without SQL Server


htaccess to add directory to relative root requests

Question: My site is using relative root paths i.e: /_imgs/abc.jpg /_js/stuff.js /product/123/someproduct
As it is on a shared server for testing and I've not assigned a domain to the site as yet the url of the test server is http://server/~testsite/ so a request to http://server/_imgs/abc.jpg  results in a 404.
Is there a rule I can add in htaccess to prepend /~testsite to all url requests?
I've tried using RewriteBase with no success.
Answer: You could try something along these lines: (untested)
RewriteRule ^(.*)$  /~testsite/$1 [R=301,L]

This would result in all your pages 301 redirecting, but for development, it should be fine.
Comment: unfortunately because of the other rules I have in place that doesn't direct properly.
Answer: I always create a new vitualhost and add an entry to my hosts file.
<VirtualHost *:80>
        ServerName example
        DocumentRoot /var/www/example
</VirtualHost>

and
127.0.0.1  example

this way the website acts just like on a normal server.


Change detection algorithm - likelihood ratio

Question:
Consider a sequence of independent random variables $(y_k)_k$ with a
  probability density $p_{\theta}(y)$ depending upon only one scalar
  parameter. Before the unknown change time $t_0$, the parameter
  $\theta$ is equal to $\theta_0$, and after the change it is equal to
  $\theta_1 \neq \theta_0$. The problems are then to detect and estimate
  this change in the parameter.

snip... snip...

The tools for reaching this goal are as follows. First, our
  description of all the algorithms of this chapter is based on a
  concept that is very important in mathematical statistics, namely the
  logarithm of the likelihood ratio, defined by
  $$s(y) = \ln\frac{p_{\theta_1}(y)}{p_{\theta_0}(y)}$$ and referred to as the
  log-likelihood ratio. The key statistical property of this ratio is as
  follows : Let $E_{\theta_0}$ and $E_{\theta_1}$ denote the
  expectations of the random variables under the two distributions
  $p_{\theta_0}$ and $p_{\theta_1}$, respectively. Then,
$$E_{\theta_0}(s) < 0\space \text{and} \space E_{\theta_1}(s) > 0 $$

(This appears to be a quotation from Chand & Xiao, Change-Point Monitoring for Secure In-Network Aggregation in Wireless Sensor Networks, 2007.)
My question is HOW can we get the 2nd formula? What does $E_{\theta_0}(s)$ mean (I know $E$ is the expectation of $y$, but what about $(s)$ )? How can we get the > 0 or < 0?
Answer: Here $E_{\theta_0}(s)$ is the expectation of log likelihood ratio given that $\theta=\theta_0$, and similarly for $E_{\theta_1}(s)$.  Now, if $\theta=\theta_0$ we expect $p_{\theta_0}(y)$ to be greater than $p_{\theta_1}(y)$ so $\frac{p_{\theta_1}(y)}{p_{\theta_0}(y)}<1$, and so $s<0$.


Problemas ao tentar acessar arquivo JSON no Python

Question: Olá, estou tentando ler determinados dados de um arquivo JSON no Python, porém estou com alguns problemas...
Esse é o arquivo JSON:
{
   "linguagem":"Python",
   "dados":"JSON"
}

Implementando o arquivo JSON diretamente dentro do script em Python, funcionou, e o programa em Python ficou assim:
import json
test = '{"linguagem": "Python", "dados": "JSON"}'
arquivo = json.loads(test)
print(arquivo [linguagem])

Porém, gostaria de acessar o arquivo JSON externamente. Tentei o seguinte comando, que não funcionou:
import json
arquivo = json.loads(TesteJSON.json)
print(arquivo [linguagem])

Neste último caso, "TesteJSON.json" é o nome do arquivo JSON que tentei acessar.
Se alguém puder me ajudar, agradeço!
Answer: Para abrir um arquivo no Python você pode usar a função open combinado com a palavra chave with.
Veja:
import json

with open('TesteJSON.json', 'r') as f:
    dados = json.loads(f.read())

print(dados['linguagem'])

Através do método read o Python lê os arquivos para uma string
A variável dados recebe o valor do json.loads, que retorna um dict.
O dict deve ter o índice acessado através de uma string como o nome da propriedade do seu JSON. Da forma que você fez, poderia gerar um erro.
Answer: O nome json.loads possui o S no final justamente para indicar "load String".

json.loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.

O que você precisa é carregar a partir de um arquivo. Para isso existe a função json.load, sem o S.

json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table.

with open('TesteJSON.json') as stream:
    dados = json.load(stream)

print(dados['linguagem'])

Sem o gerenciamento de contexto poderia ser apenas:
dados = json.load(open('TesteJSON.json'))

Comment: @WallaceMaxters Está lá na documentação xD
Comment: Não sabia essa do `.load` +1


ACF of MA(q) cuts off after lag q - but isn't it also AR(∞)?

Question: I struggle with that thought process a bit - intuitively I get why the ACF of an MA(q) would cut off as there's no more dependence for >q.
But if we can express an MA(q) as an AR(∞) - how does that agree with the fact that the ACF of an AR process doesn't cut off?
Furthermore, why does the PACF for an MA(q) not cut off for >q - how are we "bringing back" some of the dependence by excluding extra terms?
Thank you!
Answer: Imagine you have some infinite AR. Then in general an infinite set of AR terms, each with its own geometrically-decreasing but never-cut-off-ing ACF won't cut off (of course).
However, we're not dealing with the general case; the question is ... is it possible to make particular ACF values zero with an infinite AR?
Imagine you're free to choose population parameters to solve a problem: could we keep the first $k$ ACF values as is but set the ACF at lag $k+1$ to be $0$? Indeed, it turns out that we can -- it imposes a specific kind of restriction on the parameters. Could we set the ACF at lags $k+1$ and $k+2$ to be $0$? Well, yes, again, we can do that, but now we have an additional restriction on our set of parameters. If we keep going we can set all the later ones to zero.  We end up with the infinite set of AR parameters that corresponds to an invertible MA.
You might like to consider an AR(1) with parameter $\phi_1$. How does its ACF go?
Now consider we have an AR(2) with that $\phi_1$ parameter; what value of $\phi_2$ in an AR(2) would zero out the ACF at lag 2? Given that resulting ACF, can you zero out the third autocorrelation with an AR(3)? ... Now look at an MA(1) which has the same lag-1 autocorrelation and invert it ... what are the first few AR terms?
Your last question seems to be based on some confusion. The higher-lag autocorrelations are 0 but the remaining autocorrelation after you remove the effect of earlier autocorrelations is not 0; in that particular sense there is dependence there.


IIS 7.5 Restrict IPs on a Subdirectory, with Proxy detection

Question: I have a legacy IIS web server (2008 R2) that is hosting a handful of WordPress sites.  I need to restrict access to the login capability of WordPress (/wp-admin directory) to only a couple known IP addresses.  Complicating this matter is the fact that this web server is behind an F5 load balancer, which overrides the true client IP (although I get the true IP via normal XFF header).
From what I understand there is the IP Address and Domain Restrictions IIS module which can allow blacklist/whitelist of a sub-directory like I need, but it isn't smart enough to handle proxy/Load-Balancer client IP translation.  Then there is the Dynamic IP Restrictions IIS module, which is smart enough to handle proxy/Load-Balancer client IP translation, but it cannot handle creating rules on a subdirectory (only website-level granularity).
Is there a known way to handle this type of restriction in IIS?  I'm sure I could restrict at the firewall or L/B, but I'm trying to get it done within IIS if possible.
Answer: Looks like the URL Rewrite module is a fairly straight-forward approach for this need.  Something like the rule below will accomplish restricting certain URLs under a website (e.g., the pattern used can grab only a certain directory if desired).
<code>        <rule name="wordpress-login-restrictions" enabled="true" stopProcessing="true">
                <match url="(^wp-admin)|(^wp-login.php)" />
                <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                    <add input="{HTTP_X_FORWARDED_FOR}" pattern="(^55\.55\.555\.555$)" negate="true" />
                </conditions>
                <action type="CustomResponse" statusCode="404" subStatusCode="44" statusReason="File or directory not found" statusDescription="The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable." />
        </rule>
</code>


Existence of symmetric matrix for linear operator

Question: Given any linear operator $ T: ℝ^n →ℝ^n$ I'm asked to show that there exists an n x n matrix A such that T(x)= A x for all x in $ℝ^n.$

I don't even know where to start this proof, yet it seems terribly straightforward. Could anyone please give me a hint/ guide me through the proof? Unfortunately I'm behind on my lectures, so any help is appreciated!
Comment: @NooBie20 You won´t find a $\textbf{symmetric}$ matrix for any linear operator
Answer: $\textbf{Hint}$:Consider a basis $\{v_1,...,v_n\}$ of $\mathbb{R}^n$ and use that $Tv_j=\sum_{j=1}^{n}\alpha_{ij}v_j$ where $\alpha_{ij}$,$i=1,...,n$ are unique for $j=1,...,n$.
Answer: The matrix of your transformation is the matrix $M$ whose columns are vectors found by the images of the standard basis $$ { T(1,0,0,...,0), T(0,1,0,...,0),...,T(0,0,0,...,1) }.$$
The first column is $ T(  1,0,0,...,0)$
The second column is $ T( 0,1,0,...,0)$
And so forth.
Comment: So the "proof" could be as simple as showing that the identity matrix satisfies the requirements?
Comment: Not the identity, the matrix whose columns are Transforms of the identity.


ethtool: set/unset autonegation, RX/TX pause

Question: I was looking at the sources of ethtool, particularly at function do_spause() where autonegotiation, rx/tx pause can be enabled/disabled. I noticed that at first it issues ioctl() for ETHTOOL_GPAUSEPARAM command, i.e. it fetches the current settings, and they're the same, it doesn't change anything, otherwise it will issue ioctl() with ETHTOOL_SPAUSEPARAM command and set new parameters.
What is the reason for this? Is this optimization, or way to avoid link disruption?
Answer: ethtool_ops are implemented separately for each device type.  It would be reckless to assume all ioctls are benign when setting an already set value.  Implementation in the kernel is here:
https://elixir.bootlin.com/linux/v3.10.108/source/net/core/ethtool.c#L1003
Comment: thanks for comment. Is this also true for offload features setting? (Read the current offload settings,and if a flag already set, don't try to do this.)
Comment: Changing offload seems as likely to cause disruption as other params.


SSIS package execution stops before finishing

Question: Today I came across a bug that I'd like to share with everyone.
When trying to execute an SSIS package in Visual Studio (2015 and 2017 the following can happen (note this package was executed sucessfully before).

While on the bottom it clearly says the SSIS package is finished, the data flow task is still in progress (and will never finish). What also happens (don't know if consistently) a CMD window pops open with "SQLDUMPER.EXE".
This is not due to the way the steps are configured, since executing them individually might still lead to the proper results.
Note as well that in my case this problem makes Visual Studio incredibly unstable. It is not uncommon that after or during every execution Visual Studio crashes completely and is automatically shut down by Windows.
There are no error messages and I had no idea what the reason is this happened untill... (answer below)
Answer: After a lot of googling i've found a reason whya multitude of people seem to have this problem.

Right click the project and then click on properties
Click "Debugging"
Set "Run64BitRunTime" to "True"

Apparently for most people this fixes the problem.
For me however I had to come up with another solution.

Right click the project and click on properties
Click "General"
Set "TargetServerVersion" to either the target SQL server and run the package again OR set it to any SQL server version, run the package to see if it works, and if it doesn't set it to another version.

These solutions are counter intuitive because this problem seems to arrise at a random moment and the target sql server version might have been the same throughout the entire development.
I have not tried to see what happens when I deploy the bugged project to a server and see if it runs there, so any and all extra information on this problem would be appreciated.
Comment: Thanks! Didn't know that!
Comment: You have to accept this answer, even if it is yours. just click on the accept mark under the voting arrows
Comment: Even though for me it was actually **the opposite** (it was set to True, and after switching it to False, the package runs without any issue), thanks for this answer!
Answer: I spent a good bit of time googling this problem. It looks like it is being reported by many people around the world. It is usually down to either x32/x64 compatibility or some miniscule issue with sorting or data sizes or compiling a custom C# script (or combination thereof).
None of these things worked for me so I rebuilt the entire package from scratch and the issue was gone.
It is far from perfect, especially if your package is large and/or complex but if nothing else works, this is your last resort.
Answer: "Run64BitRunTime" was already set to  "True", but I was getting this error. so I restarted the visual studio and problem resolved.
Answer: None of the proposed solutions worked for me. I had to rebuild both the solution and the project a couple of times and this fixed it. Of course, I opened and closed the VS a couple of times in between. I guess this is a bug and you have to tinker with it to get it to work.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/31518508)


How to sort, group, and aggregate values in a list of nested dictionaries?

Question: given the list of dictionaries below, I want to do the following things:
1: Sort the following data by key (top level)'name'
2: Sort the by the nested key "name" under key "items"
3: Group values under items by aggregation interval for example "1d"
4: Get again the min max and avg result from step number 3\
Atm, I resolve this by iter down to the values and group them with pandas, aggregate again min max and avg from result.
This way feels really tricky, and the performance is not given.
Can someone help me out?
[
    {
        '_id': 2,
        'name': 'b',
        'device': 'b',
        'items': [
            {
                'item_id': 'item_id_2', 'name': 'item_2', 'unit': 'b/s',
                'values': [
                    {'time': datetime.datetime(2022, 9, 5, 15, 0), 'min': 0.0, 'max': 1.0, 'avg': 0.5},
                    {'time': datetime.datetime(2022, 9, 5, 16, 0), 'min': 0.0, 'max': 1.0, 'avg': 0.5},
                    {'time': datetime.datetime(2022, 9, 5, 17, 0), 'min': 0.0, 'max': 1.0, 'avg': 0.5},
                    {'time': datetime.datetime(2022, 9, 5, 18, 0), 'min': 0.0, 'max': 1.0, 'avg': 0.5},
                    {'time': datetime.datetime(2022, 9, 5, 19, 0), 'min': 0.0, 'max': 1.0, 'avg': 0.5},
                    {'time': datetime.datetime(2022, 9, 5, 20, 0), 'min': 0.0, 'max': 1.0, 'avg': 0.5},
                ]
            }
        ]
    },
    {
        '_id': 1,
        'name': 'a',
        'device': 'a',
        'items': [
            {
                'item_id': 'item_id_1', 'name': 'item_1', 'unit': 'b/s',
                'values': [
                    {'time': datetime.datetime(2022, 9, 5, 15, 0), 'min': 0.0, 'max': 1.0, 'avg': 0.5},
                    {'time': datetime.datetime(2022, 9, 5, 16, 0), 'min': 0.0, 'max': 1.0, 'avg': 0.5},
                    {'time': datetime.datetime(2022, 9, 5, 17, 0), 'min': 0.0, 'max': 1.0, 'avg': 0.5},
                    {'time': datetime.datetime(2022, 9, 5, 18, 0), 'min': 0.0, 'max': 1.0, 'avg': 0.5},
                    {'time': datetime.datetime(2022, 9, 5, 19, 0), 'min': 0.0, 'max': 1.0, 'avg': 0.5},
                    {'time': datetime.datetime(2022, 9, 5, 20, 0), 'min': 0.0, 'max': 1.0, 'avg': 0.5},
                ]
            }
        ]
    }
]

As for the result, I would expect something like this:
[
    {
        '_id': 1,
        'name': 'a',
        'device': 'a',
        'items': [
            {
                'item_id': 'item_id_1', 'name': 'item_1', 'unit': 'b/s',
                'values': [
                    {'time': datetime.datetime(2022, 9, 5, 0, 0), 'min': 0.0, 'max': 1.0, 'avg': 0.5},
                ]
            }
        ]
    },
    {
        '_id': 1,
        'name': 'b',
        'device': 'b',
        'items': [
            {
                'item_id': 'item_id_2', 'name': 'item_2', 'unit': 'b/s',
                'values': [
                    {'time': datetime.datetime(2022, 9, 5, 0, 0), 'min': 0.0, 'max': 1.0, 'avg': 0.5},
                ]
            }
        ]
    }
]

Answer: With the initial list of dicts that you provided and that I choose to call data, here is one way to do it:
df = pd.DataFrame(data)

# First, sort values
df = df.assign(temp=df["items"].apply(lambda x: x[0]["name"])).pipe(
    lambda df_: df_.sort_values(by="temp").drop(columns="temp").reset_index(drop=True)
)

# Get aggregated as new column 'temp'
dfs = df["items"].apply(lambda x: pd.DataFrame(x[0].pop("values", None)))
df["temp"] = pd.Series(
    [
        {
            k: v[0]
            for k, v in df.set_index("time")
            .resample("D")
            .mean()
            .reset_index()
            .to_dict(orient="list")
            .items()
        }
        for df in dfs
    ]
)
df["items"] = df["items"].apply(lambda x: x[0])

# Merge intermediate dictionaries
df["items"] = df.apply(lambda x: x["items"] | {"values": [x["temp"]]}, axis=1)
df = df.drop(columns="temp")

And so:
print(df.to_json(orient="records"))
# Output
[
    {
        "_id": 1,
        "name": "a",
        "device": "a",
        "items": {
            "item_id": "item_id_1",
            "name": "item_1",
            "unit": "b\\/s",
            "values": [{"time": 1662336000000, "min": 0.0, "max": 1.0, "avg": 0.5}],
        },
    },
    {
        "_id": 2,
        "name": "b",
        "device": "b",
        "items": {
            "item_id": "item_id_2",
            "name": "item_2",
            "unit": "b\\/s",
            "values": [{"time": 1662336000000, "min": 0.0, "max": 1.0, "avg": 0.5}],
        },
    },
]

Comment: Wow, looks really pretty!
Now i try to use two different objects (Under top level items key).
Thank you!


Como Dividir as Cores?

Question:
Gostaria de introduzir as cores da bandeira da frança no retângulo acima,mas não sei dividir as cores(nem sei se tem como sou noob no assunto rs)alguem poderia me ajudar?
Comment: Sua pergunta não esta clara, coloque o que vc já tem de código, e indique melhor onde eh que vc quer colocar as cores
Comment: olha essa imagem que fiz no paint e veja se me entende agora > https://uploaddeimagens.com.br/imagens/2019-03-30_-2-png
Comment: se quiser posso te passar o link do jogo para voce testar e ver como funciona,é apenas 70mb
Comment: Cara tem 1000 formas de fazer isso, vc precisa dar mais detalhes, comece Editando a sua pergunta e incluindo o que vc já tem de código
Comment: > https://uploaddeimagens.com.br/imagens/2019-03-30_-3-png < codigos que tenho e sei usar (são os unicos que sei, foram esses que usei pra fazer o texto que esta na imagem "TSUBASA 10")
Answer:

.grid-container {
  display: grid;
  grid-template-columns: auto auto auto;
}

.grid-container>div {
    height: 200px;
}
<!DOCTYPE html>

Como Dividir as Cores?


SUM price with nested select

Question: I have this table here:
total_price  date_buy                number_buy
$$ 299.00    18/06/2014 12:59:34 PM  1
$$ 299.00    18/06/2014 12:59:34 PM  1
$$ 76.00     21/06/2014 16:22:12 AM  2

All I'm trying to do is SUM the total_price grouped by date_buy (month) and number_buy, for this I try this code:
select SUM(CAST(substr(total_price, 4) as FLOAT)) as Total, substr(date_buy, 4, 2) as Month FROM myDatabase WHERE substr(date_buy, 7, 4) = '2014' group by substr(date_buy, 4, 2) ORDER BY substr(date_buy, 4, 2)

This code works great and he give me the SUM of this values:
299.00
299.00
76.00
______

1152.00

But as I said earlier , I want to accomplish the sum grouping date_buy (month) and number_buy, so.. The correct Sum are:
299.00
76.00
______

375.00

I believe that I should have a subquery (nested select), in place of the command: SUM(CAST(substr(total_price, 4) as FLOAT)) as Total that will bring me the SUM of total_price grouped by number_buy, and and so I could continue with the rest of the code, Right?
If no, How i can SUM the total_price grouped by date_buy and number_buy? Else how I can create that nested select?
Comment: @andrewdleach, the table have more than this 3 columms, one of the columns are called product that have two different products.
Answer: You can use your both columns in your group by clause to group depend up on the two columns you require. Try the below thing.
select SUM(CAST(substr(total_price, 4) as FLOAT)) as Total, substr(date_buy, 4, 2) as Month FROM myDatabase WHERE substr(date_buy, 7, 4) = '2014' group by substr(date_buy, 4, 2), number_buy ORDER BY substr(date_buy, 4, 2)
You can refer to the below page for detailed explanation about groupby clause.
Using group by on multiple columns

SUM price with nested select


ActionBar no Android Studio 1.4

Question: Eu atualizei meu Android Studio para a versão 1.4 e estou tendo problemas para implementar o ActionBar numa activity.
O aplicativo executa a validação dos dados de um usuário através do MainActivity e depois direciona o usuário para a segunda activity(WelcomeActivity). Estou tentando criar um "up navigation "através do códigogetActionBar().setDisplayHomeAsUpEnabled(true);mas quando eu executo o aplicativo, ele fecha no momento que vai passar de uma activity para outra. Se eu remover a informação da actionbar mencionado acima, o aplicativo funciona normalmente.
Também tentei retirar as informações referentes a toolbar que existe nas activities mas não funcionou.
//        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);

MainActivity.java
package br.com.luizugliano.actionbar;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

}

public void onClickBtBuscar(View view){
    EditText etNome = (EditText) findViewById(R.id.etNome);
    EditText etCPF = (EditText) findViewById(R.id.etCPF);
    String nome = etNome.getText().toString();
    String cpf = etCPF.getText().toString();
    if("luiz".equals(nome) && "123456789".equals(cpf)){
        Intent intent = new Intent(getContext(),WelcomeActivity.class);
        Bundle params = new Bundle();
        params.putString("nome", "Luiz");
        intent.putExtras(params);
        startActivity(intent);
    }else{
        alert("Usuário não encontrado, faça seu cadastro");
    }
}

private Context getContext(){
    return this;
}

private void alert(String s){
    Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
}
}

WelcomeActivity.java
package br.com.luizugliano.actionbar;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.TextView;

public class WelcomeActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    Bundle args = getIntent().getExtras();
    String nome = args.getString("nome");

    //Atualizando o texto do TextView com uma mensagem de boas vindas
    TextView textView = (TextView) findViewById(R.id.textView);
    textView.setText(nome + ", seja bem-vindo.");

    //Adiciona o botão de navegação da action bar
    getActionBar().setDisplayHomeAsUpEnabled(true);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == android.R.id.home) {
        //O método finish encerrará essa activity
        finish();
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="br.com.luizugliano.actionbar" >

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".WelcomeActivity"
        android:label="@string/title_activity_welcome"
        android:theme="@style/AppTheme.NoActionBar"
        android:parentActivityName=".MainActivity">
    </activity>
</application>

content_welcome.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"    android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_welcome"
tools:context="br.com.luizugliano.activity.WelcomeActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Medium Text"
    android:id="@+id/textView" />

activity_welcome.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context="br.com.luizugliano.actionbar.WelcomeActivity">

<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
    android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar android:id="@+id/toolbar"
        android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_welcome" />

</android.support.design.widget.CoordinatorLayout>

styles.xml
<resources>

ActionBar no Android Studio 1.4


Add action event handler to text field java fx

Question: I have a Textfield node as such in my java fx code:
TextField Name= new TextField();

I understand how to fire code if one clicks on a button by adding an event handler like so:
Button getName= new Button("Save");

getName.setOnAction(new EventHandler<ActionEvent>() {
    public void handle(ActionEvent args) {
       System.out.println("You clicked me!"):
    }
});

Could I add the same code to my textField node so when one clicks on the text field, it fires a bunch of code? Or how do you do this?
Comment: Just as an FYI, an [onAction event handler](https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TextField.html#onActionProperty) can be specified for a TextField.  "The action handler is normally called when the user types the ENTER key."  Which does not appear to be what you are actually asking for.
Comment: So you can specify it for a click?
Comment: No, that is not how `onAction` works for a TextField, for a TextField `onAction` is triggered by the ENTER key, not a click.  If you want to capture a click (or touch) event, you will need an event filter, sry I don't have time write now to type up a solution.
Comment: Ok but thanks, good to know
Comment: Read up on [event handling and event filters](http://docs.oracle.com/javase/8/javafx/events-tutorial/events.htm).
Answer: To respond to mouse clicks, use setOnMouseClicked.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class ClickOnTextField extends Application {

    @Override
    public void start(Stage primaryStage) {
        TextField textField = new TextField();
        textField.setOnMouseClicked(e -> {
            System.out.println("Clicked");
        });

        StackPane root = new StackPane(textField);
        Scene scene = new Scene(root, 350, 120);
        primaryStage.setScene(scene);;
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Comment: I thought that the TextField would consume the mouse click event and it wouldn't bubble back up again to the onMouseClicked handler, so you would need a filter . . . but I thought wrong :-)
Comment: There doesn't seem to be much consistency in when controls consume events and when they don't. IIRC text controls consume key pressed events, but it seems they don't consume mouse events.
Answer: Try this:
TextField yourTextField = new TextField();
yourTextField.focusedProperty().addListener(new ChangeListener<Boolean>()
{
    @Override
    public void changed(ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue)
    {
        if (newPropertyValue)
        {
            System.out.println("Textfield on focus");
        }
        else
        {
            System.out.println("Textfield out focus");
        }
    }
});

Comment: That responds to the text field getting focus, not to a mouse click on it. So, for example, your handler would be fired if the user used the tab key to put focus on the text field (but never used the mouse at all). On the other hand, if the text field already had focus, and the user clicked on it, your handler would not be fired.
Comment: How do I add click event to a text field, really looking for it


python flask change sys.executable

Question: im have next file
#!/usr/bin/python3.5
from flask import Flask, render_template, request

import sys
app = Flask(__name__)

@app.route("/")
def hello():
    return sys.executable

if __name__ == "__main__":
    app.run()

this code return /usr/bin/python
How i can change sys.executable to /usr/bin/python3.5
python3.5 is exist
Comment: run >> python3 flask_app.py ,instead of >>python flask_app.py
Comment: why?im not run python flask_app.py
Comment: im create site on VPS, and go to browser
Comment: im use this titirial https://www.digitalocean.com/community/tutorials/how-to-deploy-a-flask-application-on-an-ubuntu-vps
Comment: then make sure that the default python environment chosen for the vps is python 3.5... Or else use virtual environment in your vps to run the flask_app using python 3.5
Comment: I think you will have to set the path something like this in the beginning of the file. `sys.path.insert(0, '/home/username/public_html/cgi-bin/myenv/lib/python3.5/site-packages')`, depending upon the correct path.
But don't forget to import `sys` first.
Answer: I'm shocked to discover this, but it turns out if this file in question (presumable "app.py") is executable, then the app with run using the python defined in your shebang rather than the python of you executing environment. Try this out:
chmod +x app.py

python flask change sys.executable


Rank 1 tensors, how to describe them? (specific case)

Question: I want to undestand a specific case. I consider two $\mathbb{C}$-vectorial spaces, $\mathbb{C}^2$ both. Then, I want to work with $\mathbb{C}^2\otimes \mathbb{C}^2$. Now, I consider basis for each vectorial space  $\langle a,b\rangle=\mathbb{C}^2$ and $ \langle u,v\rangle=\mathbb{C}^2$. In this point, I consider a tensor in $\mathbb{C}^2\otimes \mathbb{C}^2$ expressed in terms of these basis as follows: $$x (a\otimes u)+y(a\otimes v)+w( b\otimes u)+ z( b\otimes v)$$ and I'd like to see when it is a rank 1 tensor, so it has to be like this: $$\lambda_1a+\lambda_2b\otimes \gamma_1u+\gamma_2v$$
From these and making some algebra, I got $$\frac{x}{\gamma_1}=\frac{y}{\gamma_2};\frac{w}{\gamma_1}=\frac{z}{\gamma_2}$$
$$\frac{x}{\lambda_1}=\frac{w}{\lambda_2};\frac{y}{\lambda_1}=\frac{z}{\lambda_2}$$
And it says me if consider this tensor as a matrix, then this matrix has rank 1. But I'd like to get some equations in terms just of $x,y,w$ and $z$, and if it's possible get some characterization of rank 1 tensors in terms of these equations
Comment: Just a note on vocabulary: https://mathworld.wolfram.com/TensorRank.html. See also https://math.stackexchange.com/questions/2245849/is-the-rank-of-a-tensor-different-from-the-rank-of-a-matrix
Answer: If you make the  matrix
$$
\begin{bmatrix} x & w  \\ y & z \end{bmatrix}
$$
the condition for your tensor to be rank-1 is that this matrix must be rank-1, as you said. So the same equations that guarantee you have a rank-1 matrix are necessary and sufficient. That means that one of the eigenvalues is $0$, hence the determinant must equal $0$. But the matrix is not the $0$-matrix. So you could write $xz-wy=0$ because that is the formula for the determinant. But also $|x|^2+|y|^2+|z|^2+|w|^2\neq 0$ because that is equivalent to saying that the matrix is not $0$.
Comment: Tanks!! It's really helpful.
I began to study this topics by myself and I'd like some recommendations about books. If you have any suggestion, it'd be great.
Once again, thanks for your answer


Using a variable in a conditional sentence

Question: I want to save a value in a variable and then use it in a conditional sentence. To clarify this I'll give you a simpler example: Imagine that I have a database with the kind of animal(dogs and cats),their age(1 or 2) and their weight. I want to do the following conditional:
IF( animal=dog & age=1 & weight>= percentile75 ) Wdogs=1.
EXECUTE.
IF( animal=dog & age=1 & weight<percentile75) Wdogs=0.
EXECUTE

I want to calculate percentile75 automatically and save in a variable so I can use the code in any database I have. Also I want to rewrite the variables if I change the database and execute the code. Is there a way to do this?
Thanks a lot
Answer: You can use RANK in order to divide the weights into n groups. The command creates a new rank variable which you can then use in your conditionals.
For the ranking to be done separately in each relevant sub-group, use the BY sub-command.
In your example, each animal/weight subgroup will be ranked separately into weight quartiles, and the subsequent command will use the new variable:
RANK VARIABLES=weight (A) BY animal weight/NTILES(4).
IF(animal=dog & age=1 & Nweight=4) Wdogs=1.
IF(animal=dog & age=1 & Nweight<=3) Wdogs=0.
EXECUTE.

You can save a line of syntax by using (instead of the two if commands):
IF(animal=dog & age=1) Wdogs=(Nweight=4).

Comment: Thank you mate. I forgot to say that I need the percentile of the each subgroup. For example, I need the percentile of the weight for dogs and age=1. Can I do it with your code?
Comment: my code already does that - see the BY sub-command. I added an edit to clarify that.
Comment: Awesome mate. I'll try to do with your code.Thank you very much
Comment: Hello mate. I've tested your code and I have a problem. I need to do that with percentiles 75 , 85 and 90. I've done with percentile 90 and it works well. After that I've done with percentile 85(I've calculated ntiles(100) ) but it doesn't work. It seems that to do the conditional takes the first rank althought it creates the second rank. Do I explain well?Thanks!
Comment: If you've calculated a few ranks based on the same original variable, the rank variables that SPSS creates get different names. make sure your syntax calls the right variable names in the right places. Also I recommend you look up the RANK command, and check what you want to do in the situation of ties (you should have some if you're using ntiles(100).
Comment: I suggest you mark this question as answered and start another question for the new problem (include your syntax with some sample data).
Answer: First thing mate is lose those EXECUTE commands (They are unnecessary and betray you as a noob point and clicker with default options).  From other posts I discern you need to do that with multiple variables.  Simplify your life by boning up on VARSTOCASES, maintain the current RANK with BY and put a f'ing Shrimp (or a PRAWN) on the Barbie Queue.


Oreo (8.0) status bar notification icon all white

Question: I'm currently having problems with Android Oreo showing the notification icon correctly in the status bar and on the notification itself (screenshots provided below).
To create the icons, I am using Android 3.1, right clicking on the res folder and choosing New > Image Asset. Within that, I'm uploading an all white png (as per docs) and selecting a red background as per screenshot:

Within the AndroidManifest.xml, I set the icon like this:
<application
...
    android:icon="@mipmap/ic_launcher"

The actual App looks correct, but the notification icon does not show up correctly.
Notification icon errors:
Comment: create a correct icon just for notification and do not use app icon for notification
Comment: @WIZARD how plz?
Comment: https://developer.android.com/guide/practices/ui_guidelines/icon_design_status_bar.html
Comment: @30secondstosam use above link by Stephen and use your selected icon without any background it should has transparent background
Comment: Thanks @WIZARD - am I supposed to set this icon somewhere though as I do in the manifest for the launcher icon? And if so, where is that?
Comment: Since Android 6 afaik, notification icons are all white and black.
Comment: @30secondstosam add it in `drawable` folders base on dpi of icon and use it like `R.drawable.ic_notify`
Answer: You need to create icon as per this
Also you need to add
<meta-data
    android:name="com.google.firebase.messaging.default_notification_icon"
    android:resource="@drawable/statusbar_notification" />

in AndroidManifest
Comment: This is the correct answer, worked for me, thanks a lot.


Archicad - Create Simple Textbox with Inputs and show saved data

Question: As per a requirement of a job interview, I am tasked with developing add-ons for Archicad with C++. Archicad is totally new to me and I just heard about the software from my interviewer this morning. I visited the ArchiCAD website for their API documentation, but it seems a bit unusual to me. I have never worked with any CAD software like API and Archicad examples are not yet available to me as I've just requested for a Developer ID and it might take 2/3 days to grant me this.
So, I am requesting help with some documentation and proper examples on how to build C++ add-ons for ArchiCAD from scratch.  My task includes :

A windowed add-ons which will have a text box for the name, a drop-down for gender, and a text-box for some descriptions
A save button to save these data
And upon saving these data , it will save somewhere inside the persistence database of ArchiCAD add-ons
The previous saved data will be shown on the windowed add-ons as list box.

This is all I need to show the recruiter within 3-4 days for qualifying for the next round in the process. So, if anyone comes up with the helping docs or example, I will be truly grateful. Honestly, I am badly in need of a job.
Thanks in Advance.
Answer: You can follow this link https://archicadapi.graphisoft.com/getting-started-with-archicad-add-ons. This is a simple tutorial to create an simple Add-ons and add it to the Archicad software.
And again if you installed the API Development Kit for the Archicad. In the installation location you will found a folder called "Examples" where you will get some of the demo project for the add-on. I think that will help you a lot.


How to delete discovered bluetooth devices on ios 7?

Question: I use BeeTee project for discover nearby bluetooth devices. Everything is good, but if it discovered a device its store this somewhere, and i cant find it again. If the device doesnt send bluetooth signal the bluetooth manager write this in log: BTM: lost device "device_name" device_address
How can i delete discovered devices?
Answer: They are stored in a dictionary:
<code>@property (retain, nonatomic) NSMutableDictionary *currentAvailableDevices;
</code>
If you want to delete one of them, you can call the the delegate method
<code>- (void)removeBluetoothDevice:(BluetoothDevice *)bluetoothDevice
{
    [self.currentAvailableDevices removeObjectForKey:bluetoothDevice.address];
    [self.tableView reloadData];
}
</code>
But are you sure that this approach makes sense?
Comment: By the way, I am working on an update for BeeTee. Maybe this is helpful for you.


Address sanitizer and __attribute(section("mysection")) failing

Question: I'm using a library to register some structs at compile time. In this case it's registering a struct representing a JSON-RPC method that I'd like to expose. The library marks the structs with __attribute(section("xautodata_" "somename")) so that it'll be put in a separate section that can later be retrieved. The generated content will look like this:
static const autodata_json_command_ *__attribute__((__used__)) __attribute__((section("xautodata_" "json_command"))) autodata_json_command_151 = (&help_command);;
static const autodata_json_command_ *__attribute__((__used__)) __attribute__((section("xautodata_" "json_command"))) autodata_json_command_173 = (&stop_command);;

The code that later retrieves the commands will get a pointer to the section (and count the number of elements in that section) and iterate over it, like this:
size_t count;
struct json_command **commands = get_json_commands(&count);
for (size_t i=0; i<count; i++) {
  // Access commands[i];
}

This works perfectly fine if we don't compile with -fsanitize=address, but it'll add padding when compiled with -fsanitize=address.
Without the address sanitizer commands are adjacent to each other, i.e., commands[0] and commands[1] are valid pointers to structs. With the sanitizer only every 8th command is a valid pointer (presumably due to padding).
Now for the real question: what's the cleanest way to fix this? Should I try to make the stepsize larger (in which case a preprocessor instruction is needed to distinguish the sanitizer use)? Or is there a way to disable this padding for things in the section?
Answer: GCC Asan deliberately avoids instrumenting variables in custom sections for the reasons you outlined (i.e. to preserve consecutiveness):
/* Don't protect if using user section, often vars placed
   into user section from multiple TUs are then assumed
   to be an array of such vars, putting padding in there
   breaks this assumption.  */
  || (DECL_SECTION_NAME (decl) != NULL
  && !symtab_node::get (decl)->implicit_section
  && !section_sanitized_p (DECL_SECTION_NAME (decl)))

(from gcc/asan.c). A special flag -fsanitize-sections=wildcard1,wildcard2,... can be used to force instrumentation in this case.
Clang Asan on the other hand ignores user section annotations (see AddressSanitizer.cpp).
I suggest to add a PR to Asan tracker to either make Clang behave like GCC or add a special flag to control instrumentation of user sections (in latter case we also need to update Asan Clang/GCC incompatibility wiki).


Model comparison between glm (with Firth correction), random Forest, penalised SVM

Question: I am currently developing three models to classify features of gene sites.
I was using glm (with Firth correction), random Forest and SVM to build the models and I used forward and backward selection for glm (forward and backward functions from logistf), selection using the oob error (with the function varSelRF from the package varSelRF) and the function svm.fs from the package penalizedSVM to select variables for the models.
I used cross-validation to validate the model building of training data. I generated ROC curves of the performance on the test data as I want to use ROC as a goodness-of-fit measure.
Now my question: In terms of the best (i.e. best predictive accuracy) model, is it enough to compare the AUC of each ROC curve and choose the model with the highest AUC as the best model?
Thanks for your answer!
Comment: That depends entirely what *best* means in your context.
Comment: Sure, if I want to have best predictive accuracy...?
Answer: Its a very big & open question on which metrics are best to use to access classifier performance. This paper did a great job comparing them:
Caruana, Rich, and Alexandru Niculescu-Mizil. "Data mining in metric space: an empirical analysis of supervised learning performance criteria." Proceedings of the tenth ACM SIGKDD international conference on Knowledge discovery and data mining. ACM, 2004.
They actually concluded that AUC is one of the best metrics to use - however, its far from foolproof since some methods do better with one metric than another. For example, I'd suspect SVM & RF will do very well with AUC, but GLM might do much better with a probability-based metric such as cross-entropy.
tl;dr: no one will criticize you for using AUC, but know that this metric will still be biased towards some methods over others since there is no 'perfect' metric.
Comment: Thanks! I will vote your answer up, as soon as I have a reputation of 15.
Comment: I don't see any reason to assume that GLMs perform relatively bad in AUROC compared to other metrics.
Comment: @MarcClaesen sorry if my wording was unclear. There is no reason to assume GLMs will do good or bad w/ ROCs - but there is a reason to think that it will be the best method to optimize cross-entropy, since that is what it was designed to do!


Invalid type conversion of non-type template argument

Question: I would expect that x can be used used as converted constant expression of type bool, because of the user-defined conversion-operator constexpr operator bool() const. However, GCC and MSVC reject this code while Clang seems to accept it. Should the code be legal according to the C++20 standard?
template<bool B>
struct s { constexpr operator bool() const { return B; } };
constexpr auto f(auto x) -> s<x> { return {}; }
static_assert(f(s<true>{})); // clang ok, gcc nope, msvc nope

Live example

The error message from GCC:
<source>:3:32: error: template argument 1 is invalid
    3 | constexpr auto f(auto x) -> s<x> { return {}; }
      |                                ^
<source>:3:32: error: template argument 1 is invalid
<source>:3:32: error: template argument 1 is invalid
<source>:3:32: error: template argument 1 is invalid
<source>:3:29: error: invalid template-id
    3 | constexpr auto f(auto x) -> s<x> { return {}; }
      |                             ^
<source>:3:32: error: use of parameter outside function body before '>' token
    3 | constexpr auto f(auto x) -> s<x> { return {}; }
      |                                ^
<source>:3:11: error: deduced class type 's' in function return type
    3 | constexpr auto f(auto x) -> s<x> { return {}; }
      |           ^~~~
<source>:2:8: note: 'template<bool B> struct s' declared here
    2 | struct s { constexpr operator bool() const { return B; } };
      |        ^
<source>:4:15: error: 'f' was not declared in this scope
    4 | static_assert(f(s<true>{}));
      |               ^

The error message from MSVC:
<source>(4): error C2440: 'static_assert': cannot convert from 's<x>' to 'bool'
<source>(4): note: No user-defined-conversion operator available that can perform
this conversion, or the operator cannot be called

Comment: Remove the trailing return type and do `return s{};` inside the function.
Comment: @TedLyngmo That's a workaround that shouldn't be taken lightly, as it comes with a cost that's not always acceptable: https://www.youtube.com/watch?v=Tnl7FnwJ2Uw&t=2583s
Comment: Do you mean the cost of clarity? Well, using deduced return types where it's obvious what the type will be isn't such a high cost for making it work. In this case it's really obvious so there's not much of a loss of clarity. In really complicated functions I sometimes typedef the types of interest. The first line in your function could be `using return_type = s;` to make that clear.
Answer: According to a comment by a GCC maintainer, gcc is motivated to reject by a Note to [basic.scope.param]:

[Note 1: A function parameter cannot be used for its value within the parameter-declaration-clause ([dcl.fct.default]). — end note]

However, you are not using the parameter for its value (the conversion operator does not access the class object) so this Note is irrelevant (as well as, of course, being non-normative). There is no other reason to reject, so per [expr.const]/5 the code should be accepted.
If you change the declaration of f to:
constexpr auto f(auto x) -> decltype([](auto y) { return s<y>(); }(x)) { return {}; }

then gcc and MSVC accept, but clang rejects.
Comment: Which specific text of the standardese allows the use of `[](auto x) -> decltype(+std::get(std::array{0})) { return {}; }(std::bool_constant{});`? The part of interest being where `x`'s member-function `constexpr operator bool() const` is invoked without needing an actual `std::bool_constant` object to operate on.
Comment: @303 expr.const/5: "An expression E is a core constant expression unless [...]" and [Example 5](https://eel.is/c++draft/expr.const#example-5) to expr.const/8.


Is it possible to schedule gitlab pipeline in less than an hour?

Question: I try to set up a scheduled pipeline that runs every 20 mins. I use the customized cron syntax (*/20 * * * *) in the setting, but gitlab doesn't honor this and still runs it every hour.
Is this a gitlab bug or did I miss something?
Answer: Check out GitLab schedules: it does mention:

The pipelines won't be executed precisely, because schedules are handled by Sidekiq, which runs according to its interval.
For example, if you set a schedule to create a pipeline every minute (* * * * *) and the Sidekiq worker runs on 00:00 and 12:00 every day (0 */12 * * *), only 2 pipelines will be created per day.
To change the Sidekiq worker's frequency, you have to edit the pipeline_schedule_worker_cron value in your gitlab.rb and restart GitLab.
Comment: Thanks! That works and my last step is `gitlab-ctl reconfigure` instead of `restart` as I'm using the omnibus version.
Comment: I have the same issue but I am using a hosted free Gitlab version. Is there any workaround for running a pipeline every 15 mins?
Comment: @AnshulTripathi The pipeline schedule page I mention (https://docs.gitlab.com/ce/user/project/pipelines/schedules.html) should be available for a hosted free GitLab version though.
Comment: It says "The pipelines won't be executed exactly on schedule because schedules are handled by Sidekiq, which runs according to its interval." Since mine is a hosted one so I don't have access to the Gitlab server. I want the pipeline to run every 15 mins. If it is not possible, I would have to change the whole logic which is a bummer.
Answer: New way for 12.8.X
To change the Sidekiq worker's frequency:
Edit the gitlab_rails['pipeline_schedule_worker_cron'] value in your instance's gitlab.rb file.
The exact line I have checked from gitlab.rb file is
# gitlab_rails['pipeline_schedule_worker_cron'] = "19 * * * *"

So uncomment the line and for example to run every minute do this.
gitlab_rails['pipeline_schedule_worker_cron'] = "* * * * *"

Reconfigure GitLab for the changes to take effect.
Then go to job and add this in your job schedule, in this example it will run every 5 minutes :
*/5 * * * *

Older version 10.x.x the good way is.
Edit the gitlab_ci['schedule_builds_minute'] = "0" value in your instance's gitlab.rb file.
Please check the the official page, it's changing offen
https://docs.gitlab.com/ce/user/project/pipelines/schedules.html#advanced-configuration
Comment: Strange, considering this particular setting `schedule_builds_minute` was documented in https://github.com/gitlabhq/omnibus-gitlab/commit/bbbb5001dda1713deb24fed717117434737ccbff, in 2014. Do you have a merge request which documents the new method?
Comment: @VonC, my bad, I have installed in my lab the last version **gitlab-ce-12.8.1-ce** and the documentation is correct, But for my current version **gitlab-ce-12.6.4-ce** there is not **gitlab_rails['pipeline_schedule_worker_cron']** in gitlab.rb,
Comment: @VonC I think It's because the gitlab.rb file has not be changed when I have done the update from 10.2.x to 12.6.4. Strange issue.


Is Prop extensionality inconsistent in Coq?

Question: I noticed a discussion on a mailing list about this topic from quite a while ago where they gave an example to show propositional extensionality was inconsistent:
link
However, I was not able to recreate it, as in further discussion it was noted that it was more an issue related to the definition of recursive functions, which seems to have been changed.
Is there a consensus on whether propositional extensionality is consistent or not?
Answer: The consensus is that propositional extensionality is consistent.

Inconsistencies in Coq are generally documented in dev/doc/critical-bugs; this one is documented here:

component: library of extensional sets, guard condition
summary: guard condition was unknown to be inconsistent with propositional extensionality in library Sets
introduced: not a bug per se but an incompatibility discovered late
impacted released versions: technically speaking from V6.1 with the introduction of the Sets library which was then inconsistent from the very beginning without we knew it
impacted coqchk versions: ?
fixed by constraining the guard condition: (9b272a8, ccd7546c 28 Oct 2014, Barras, Dénès)
found by: Schepler, Dénès, Azevedo de Amorim
exploit: ?
GH issue number: none
risk: unlikely to be exploited by chance (?)

So indeed this one has been fixed.
Propositional extensionality is easily shown to be consistent with the intended classical model of Coq (interpret Prop as bool), and Coq is widely believed to support this model (though of course there may be more bugs like the above).
Furthermore, propositional extensionality can be seen as a restricted version of univalence from Homotopy Type Theory, which posits roughly that isomorphic types are equal (more precisely, it defines a particular notion of isomorphism which has the property that, assuming functional extensionality, any two proofs of "f is an isomorphism" are equal, and then posits that the map from equality of types to isomorphism of types is itself an isomorphism). Univalence has been proven consistent (with pen and paper), and is widely held to be consistent with Coq without Prop (Homotopy Type Theory uses a different variant of Prop which is different in subtle ways from the Prop in Coq).  Furthermore, univalence is widely believed to be consistent with a "propositional resizing axiom", which is believed to be adequate to model impredicative Prop when -indices-matter is turned on (which forces equality out of Prop).


Application crash - debug says "objc_msgsend"

Question: I have started a 2d tile based game for iphone , i will jump directly to the class's i have and the issue. i have totally 2 class for now Tile , Table , and Base main class
Tile
`@interface Tile : NSObject {
 CCSprite *sprite;
 CCSprite *outline;
 int row,column;
 BOOL highLight;
}
@property (nonatomic , retain)CCSprite *sprite;
@property (nonatomic , retain)CCSprite *outline;
@property (nonatomic, readonly) int row, column;
@property (nonatomic , readwrite)BOOL highLight;
-(id) initWithSpriteName: (NSString*)argSpriteName Row:(int)argRow Column:(int)argColumn Position:(CGPoint)argPosition;
@end`
Table
`@interface Table : NSObject {
 CCLayer *layer;
 CGSize  size;
 NSArray *icons;
 NSMutableArray *content;
}
@property(nonatomic, retain) NSMutableArray *content;
@property(nonatomic, retain) CCLayer *layer;
@property(nonatomic, readonly) CGSize size;
-(id) initWithTableSize:(CGSize)argSize;
-(void)render;
-(Tile *) objectAtX: (int) x Y: (int) y;
`
Calling Class (Main)
@interface HelloWorld : CCLayer
{
 CGSize  size;
 Table  *tableLayer;
}
@property (retain) Table  *tableLayer;
Implementation
-(id) init
{
 // always call "super" init
 // Apple recommends to re-assign "self" with the "super" return value
 if( (self=[super init] )) {
  ......
                tableLayer = [[Table alloc] initWithTableSize:CGSizeMake(4,7) ];
  tableLayer.layer = self;
  [tableLayer render];
  self.isTouchEnabled = YES;
  self.isAccelerometerEnabled = YES;
  [self schedule:@selector(render:)];
  [[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / 30)];
}
 return self;
}
.
.
.
-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView: [touch view]];
    CGPoint touchCorrected;
    touchCorrected.x = location.x;
    touchCorrected.y = 480 - location.y;
    int x = (int)(touchCorrected.x/48);
    int y = (int)(touchCorrected.y/48);
    printf("X = %d Y = %d \n",x,y);
    if (x!=0 && y!=0) {
   Tile *tile = [tableLayer objectAtX:(1) Y:(1)];
   [tile setHighLight:YES];
     }
}

My program gets crashed when calling the following statement inside the touch end call back
   Tile *tile = [tableLayer objectAtX:(1) Y:(1)];

I have read few blogs but really having tough time to understand the concept behind messaging , could you please explain me what is cause for the application crash ends "objc_msgsend".
Answer: This is most likely a memory management error.  I would check out Hamster Emporium's blog post called "So you crashed in objc_msgSend()".  It's very helpful.
Comment: As a side note, Hampster Emporium is written by Greg Parker, one of the (quite brilliant) Objective-C runtime engineers at Apple. In otherwords, go read his blog!
Comment: Thanks for your reply , I have seen in many forums  people are referring to Hampster Emporium. I read three times the truth is since I'm a beginner  his writing was well advanced. I getting more doubts now , i will keep posting my queries. thanks for your help.


XHR failed loading GET in Java?

Question: This is strange because I am trying to get a servlet response from my ajax and the first time I load the page and trigger the request, I get the right response in the console log but the next time, I try clicking on the button to get the response it keeps giving me the error.
XHR failed loading: GET "http://localhost:8080/TestApplication/HomeServlet?format=json".
send @ jquery-3.2.1.min.js:4
ajax @ jquery-3.2.1.min.js:4
(anonymous) @ Home.jsp?apiname=&apiendpoint=&apiversion=&check=Check:33
dispatch @ jquery-3.2.1.min.js:3
q.handle @ jquery-3.2.1.min.js:3

This is baffling me and I would like to know why am i getting such a bizarre response.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

<form>
 API Name:

  <input type="text" id = "apiname" name="apiname">
   API ENDPOINT:

  <input type="text" id ="apiendpoint" name="apiendpoint">

  API VERSION:

  <input type="text" id="apiversion" name="apiversion">
   ACCESSIBLE:

  <input type="checkbox" name="source" value="internet"> Internet

    <input type="checkbox" name="source" value="vpn"> VPN

    <input type="submit" id="check" name="check" value="Check">

</form>

Comment: You may want to prevent the default behavior by passing the event to your anonymous function and calling `event.preventDefault()`. Submitting the form could have changed the url of the page which causes your ajax url to be different as well since you're referring to your servlet as a relative url. Can you see any differences between the successful and failed ajax calls?
Comment: @vi5ion:- Thanks a lot. It fixed the error.
Answer: Two solutions can be possible:
1) Change input button type from submit to button and try again, as you are also submitting form by clicking on it as well which might be causing the issue.
2) Try event.preventDefault() on the button click.
Answer: You may want to prevent the default behavior by passing the event to your anonymous function and calling event.preventDefault(). Submitting the form could have changed the url of the page which causes your ajax url to be different as well since you're referring to your servlet as a relative url.

XHR failed loading GET in Java?


Instead of www.domain.org:8080/app I need www.domain.org. Apache2.2, Tomcat7, Debian7

Question: Instead of //servername.domain.org:8080/appdir. I need //servername.domain.org.
How is this done?  I want to truncate the URL dropping the :8080/appdir.
What's running on the server. Debian 7.8, Apache2.2, libapache2-mod-jk, Oracle's Java 7, Tomcat 7
Couple of documents I'm using as a guide.
apache.org/docs/2.2/vhosts/examples.html
digitalocean.com/community/tutorials/how-to-configure-the-apache-web-server-on-an-ubuntu-or-debian-vps
Based on what I've read in the DigitalOcean doc I've been modifying the /sites/enabled/000-default file.
Here's my vhost.domain.org file.
/enabled sites/servername.domain.org

    JkMount /* ajp13_worker
    ServerName servername.domain.org
    DocumentRoot /usr/share/tomcat/webapps/
    ErrorLog /usr/share/tomcat/logs/error.log
    CustomLog /usr/share/tomcat/logs/access.log common

    Options -Indexes

 =======================================================================
I've tried this based on the "running different sites on different ports" from the Apache documentation.
And a couple of other iterations that didn't work.
Listen 80
Listen 8080
NameVirtualHost 172.20.30.40:80
NameVirtualHost 172.20.30.40:8080

ServerName servername.domain.org
DocumentRoot /usr/share/tomcat/webapps/appdir

ServerAdmin webmaster@localhost
DocumentRoot /var/www/
<Directory />
    Options FollowSymLinks
    AllowOverride None
</Directory>
<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
    AllowOverride None
    Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
    Order allow,deny
    Allow from all
</Directory>

ErrorLog ${APACHE_LOG_DIR}/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog ${APACHE_LOG_DIR}/access.log combined

=============================================================================
/enabled sites/default-000 file in it's original form.

ServerAdmin webmaster@localhost
DocumentRoot /var/www/
<Directory />
    Options FollowSymLinks
    AllowOverride None
</Directory>
<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
    AllowOverride None
    Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
    Order allow,deny
    Allow from all
</Directory>

ErrorLog ${APACHE_LOG_DIR}/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog ${APACHE_LOG_DIR}/access.log combined

Comment: Check out mod_proxy in apache.
Answer: The doc at this link provided a solution for me.
http://tomcat.apache.org/connectors-doc/generic_howto/proxy.html
I added this line to apache2.conf.
RedirectMatch ^/$ http://www.mycompany.com/myapp/
Stopped and restarted Apache2.
Now when I key in the url www.mycompany.com it takes me straight to the app.


Is redundant code acceptable if it improves readability?

Question: I have the following code to check if a game unit is a player or an enemy.  These are the only two categories.  I could delete the isEnemy method and run all checks for enemy as if(!isPlayer), but I personally feel that if(isEnemy) makes the intent of the code clearer.  Are there any established coding styles that have anything to say about this kind of situation?
public boolean isPlayer(Unit unit) {
    return unit == player;
}

public boolean isEnemy(Unit unit) {
    for (Unit e : enemies) {
        if (unit.equals(e))
            return true;
    }
    return false;
}

Comment: IMHO If you write code with a purpose, anything you add which doesn't need to be there is confusing.  You can waste more time trying to find the purpose of something which has no purpose than something which obviously has one.  In your example, it not clear how one method can be replaced with the other.
Answer: For your case, you have only two possible states - they're either an enemy, or they're a player.  If they're a player, they are not an enemy.  The cleanest way to express that would be !isPlayer.
If you had other possible states,then you may want to look into some sort of enumeration on the other states.
As a general rule of thumb:  Don't Repeat Yourself.  If one part of your code changes that you've duplicated (perhaps to fix a bug), you then have to change every occurrence of that bug.  It can turn into a maintenance nightmare.
Answer: Personally, I would implement isEnemy() as !isPlayer() but have the an assert that runs the loop to make sure it really is an enemy.
Answer: I think having both methods is acceptable.  If isEnemy() == !isPlayer() I would consider implementing isEnemy() as:
public boolean isEnemy(Unit unit) {
  return !isPlayer(unit);
}

This way you gain the readability of having two specific methods but not necessarily repeating yourself as if you can adjust isPlayer() and affect both methods.
Answer: In my opinion, that's absolutely acceptable. Especially in big project, readability is very import. Also consider that, if you add the third role in future, then you wouldn't be able to use if (!isPlayer).
Answer: By looking at your code you are identifying the enemy if it is present in the collection 'enemies'. So for you an enemy is not essentially someone who is not a player. If you want to enforce this semantic then I don't think you should get away with isEnemy() method.
Another reason you may need isEnemy() method is if you see a possibility of another type say Ally. Having isEnemy() method will make that addition simpler and cleaner.
But if above 2 conditions are not valid then get rid of it. As they say YAGNI :)


Proof of definite integral is finite

Question: it is given that, $0 < g(x) < 1$ and
\begin{eqnarray}
I_1 = \int^{+\infty}_{-\infty} g(x) dx \\
I_2 = \int^{+\infty}_{-\infty} g(x) x^2 dx \\
\end{eqnarray}
exists and are finite. I need to prove that
\begin{equation}
I_3 = \int^{+\infty}_{-\infty} g(x) \ln [g(x)] dx
\end{equation}
aslo exists and is finite.
It is clear that, $\lim_{x \to \infty} g(x) = 0$ but in this case $\lim_{x \to \infty}\ln[g(x)] = - \infty $. I tried to generate inequality for $\ln [g(x)]$ and writing
$$g(x) = \frac{1}{(x^2+a^2)^{1+\delta}} \hspace{1cm} for \hspace{.2cm} x>M$$ but not able to go anywhere after that.
Answer: Let $$A = \{x: |x|>1, g(x) < e^{-x^2}\}$$ $$B = \{x: g(x) \ge e^{-x^2}\}$$ $$ C = \{x: |x|<1, g(x) < e^{-x^2}\}$$
Clearly
$$ \int_B g(x) |\ln(g(x))| \, dx \le \int_B g(x) x^2 \, dx < \infty .$$
On $A$, we have $g(x) |\ln(g(x)| \le x^2 e^{-x^2}$ because $- y \ln y$ is a decreasing function on $[0,e^{-1}]$.  So
$$ \int_A g(x) |\ln(g(x))| \, dx \le \int_A x^2 e^{-x^2} \, dx < \infty .$$
On $C$ we have $g(x) |\ln(g(x)| \le e^{-1}$ because $-y \ln y$ attains its maximum at $y = e^{-1}$.
$$ \int_C g(x) |\ln(g(x))| \, dx \le \int_{[-1,1]} e^{-1} \, dx < \infty .$$

Proof of definite integral is finite