how to declare C array of volatile struct

Question: I defined a struct and I do not want to put the volatile into the struct because other instance may not need it (e.g. RAM caching).
Now I need that a particular array of this struct be volatile.
typedef struct{
    uint8_t rxPacket[FIFO_SIZE];
    uint8_t length;
    int8_t rssi;
    uint8_t lqi;
}rawRx_t;

Is this the right way to have each (struct) element of the array volatile ?
static volatile rawRx_t rawRxBuffer[NB_MAX_RX_FRAME];

Comment: Yes............
Answer: Yes.
Paring it down and switching the type to something cdecl.org can parse, we get:
volatile int rawRxBuffer[];

and the corresponding output is:
declare rawRxBuffer as array of volatile int

the point is that it's an "array of volatile", i.e. each array element is volatile.


Add elements from list to new data frame column based on condition

Question: I have this dataframe:

id1
id2

2341
qw123

2321
-

-
de121

2341
qd111

And I want to add 3rd column id3 with randomly generated ids in a list:
['11231', '123141', '234512']
The thing that makes it difficult to me is how to attach the same random id from the list to each row where id1 is the same.
For example the output file should look like this:

id1
id2
id3

2341
qw123
11231

2321
-
123141

-
de121
234512

2341
qd111
11231

Any solution is appreciated!
Comment: `df['id3'] = np.random.choice(yourlist,len(df))`
Comment: @anky thanks for the replay, but what I need is to choose the same random id when id1 is the same, please look at the description again
Comment: see how groupby works and create a function with the same logic to call with apply
Answer: You can create a dict for mapping the unique id1 keys to the random numbers.  Then use .map() to map id1 values to these random numbers for assignment to new column id3, as follows:
num_list = ['11231', '123141', '234512']
id1_unique = df['id1'].unique()

m_dict = dict(zip(id1_unique,  np.random.choice(num_list, len(id1_unique))))

df['id3'] = df['id1'].map(m_dict)

Comment: Thanks this is working, but I also need to add random id, when `id1` column is empty. Currently with your code for each such case I have the same random id for each `id2` value. I tried to get the unique values from both columns and map them using `applymap` , but its not working properly. Do you have an idea how this code can be extended for this case?
Comment: @Y.C.T  Your list of 3 elements is too small so that sometimes you get same values for different `id's`   Try make a bigger list for better randomness.  As you have to assign the same number for the same id, the algorithm in some sense have to rely on id.  Hence, even using groupby(), you can't get the numbers when you groupby an empty item.
Comment: @Y.C.T  For the case of depending on both columns, I can't get it fully what you want to do without some sample data.  I would suggest you post another question with some samples of what you want to do with 2 columns and empty id.   It's better to break down multiple problems into different questions otherwise there is chance people will close your questions stating that your question is not focused.
Comment: @Y.C.T   Anyway, please accept the solution for this question if it works for you based on your initial scope of question.  I will further look into your new question if I can.


Why is my Read Method being called when I click update on the inline editing of a grid row

Question: Another frustrating day with the Kendo Grid. Anyway, my problem is this: When I click "Edit" on a grid row item, it goes into edit mode. Good. Then I modify a record, and click update. I would expect the "/Company/SaveAccountAdmin" method to be called.But no... The read method is called again. When I click "Cancel" the record just disappears! The $("#save") click event is just an attempt to force a save, but surely these events can be triggered off the grid command buttons? Any ideas anyone?
<code>/// <reference path="../kendo.all-vsdoc.js" />

$(document).ready(function () {

var CompanyId = $("#CompanyId").val();

var dataSource = new kendo.data.DataSource(
  {
      batch: true,
      pageSize: 10,

      transport: {
          create: {
              url: "/Company/SaveAccountAdmin",
              contentType: "application/json; charset=utf-8",
              type: "POST",
              dataType: "json",
              url: "/Company/ReadAccountAdmin",
          },

          read: {
              url: "/Company/ReadAccountAdmin"
          },

          update: {
              url: "/Company/SaveAccountAdmin",
              contentType: "application/json; charset=utf-8",
              type: "POST",
              dataType: "json",
              url: "/Company/ReadAccountAdmin",
          },
          //destroy: {},
          parameterMap: function (options, operation) {
              if (operation !== "read" && options.model) {
                  return { model: kendo.stringify(options.model) };
              }
          }
      },

      schema: {

          model: {
              id: "ComanyContactId",
              fields: {
                  CompanyId: { type: "number", editable: false, nullable: false, defaultVaue: CompanyId },
                  CompanyContactId: { type: "number", editable: false, defaultValue: 0 },
                  FirstName: { type: "string", nullable: false, validation: { required: true } },
                  LastName: { type: "string", nullable: false, validation: { required: true } },
                  Email: { type: "string", nullable: false, validation: { required: true } },
                  Phone: { type: "string", nullable: false, validation: { required: true } },
                  IsActive: { type: "boolean" }
              }
          }
      }
  });

$("#save").click(function (event) {

    event.preventDefault();

    var rows = $.map(dataSource.data(), function (value, index) {

        return {
            CompanyId: value["CompanyId"],
            CompanyContactId: value["CompanyContactId"],
            FirstName: value["FirstName"],
            LastName: value["LastName"],
            Email: value["Email"],
            Phone: value["Phone"],
            IsActive: value["IsActive"]
        }
    });

    var jsonCompanyContacts = JSON.stringify(rows);

    $.ajax({
        url: '/Company/SaveAccountAdmin',
        type: 'POST',
        traditional: true,
        data: { "jsonCompanyContacts": jsonCompanyContacts },
        success: alert("Data Saved")
    })
});

$("#AccountAdmins").kendoGrid({
    dataSource: dataSource,
    toolbar: ["create"],

    editable: "inline",
    sortable: true,
    pageable: true,
    navigatable: true,
    editable: "inline",
    columns: [
        { field: "CompanyId", title: "CompanyID", sortable: true },
        { field: "CompanyContactId", title: "Company ContactID", sortable: true },
        { field: "FirstName", title: "First Name", sortable: true },
        { field: "LastName", title: "Last Name" },
        { field: "Email", title: "Email", },
        { field: "Phone", title: "Phone", },
        { field: "IsActive", title: "Is Active" },
        { command: ["edit", "destroy"], title: " ", width: "210px" }]

});
</code>
});
Answer: My guess is that it is because you have the Read URL set for the Update command:
<code>      update: {
          url: "/Company/SaveAccountAdmin", // <-- Not used because it is changed below
          contentType: "application/json; charset=utf-8",
          type: "POST",
          dataType: "json",
          url: "/Company/ReadAccountAdmin", // <-- Read URL set
      },
</code>
Comment: Well spotted! I've been through so many combinations on this grid I cant see straight anymore.


Interpreting Ordinal Logistic Regression in R

Question: I am doing an 'Ordinal Logistic Regression' in R but I am struggling to interpret the output.
When looking at regression with continuous values I can understand the values and what they represent but when it becomes ordinal (categorical) data I don't see how these numbers translate.
I will give an explanation of what I've done to help explain the issue:

I have conducted a questionnaire study where I ask people to rate their response to a series of statements as either 'Strongly Disagree', 'Disagree', 'Neutral', 'Agree', or 'Strongly Agree'. In this example 'W1' is one of the statements.

I then want to have each statement in turn as the dependent variable and determine if any of the other factors about the respondents (age, gender, type of diagnosis etc.) significantly affects their response

The columns of data are:
Age:            Ordinal, '25-34', '35-44', '45-54', '55-64', and '65 and over'
Gender:        Categorical, 'Male', 'Female', 'Nonbinary', and 'Other'
Anxiety:       Categorical, 'Professional', or 'Self'
Anxiety_Years: Ordinal, '1-4', '5-9', and '10+'
W1:            'Strongly Disagree', 'Disagree', 'Neutral', 'Agree', or 'Strongly Agree'.

How do I interpret the coefficient values and/or the p-values to determine which factors are significant?
For example, if this were using continuous data then you would say 'for each increase of 1 for x, y increases by 14.542'.
What I'm struggling with is how I translate that idea into the categorical/ordinal data I have.
OUTPUT:
> m <- polr(W1 ~ Gender + Age + Anxiety + Anxiety_Years, data = data, Hess=TRUE)
> summary(m)
Call:
polr(formula = W1 ~ Gender + Age + Anxiety + Anxiety_Years, data = data,
    Hess = TRUE)

Coefficients:
                            Value Std. Error  t value
GenderMale              -0.798444     0.3716 -2.14868
GenderNon-binary        -0.935156     1.4992 -0.62378
GenderOther              0.149260     1.6584  0.09000
GenderPrefer not to say -1.194734     1.2101 -0.98730
Age.L                   -0.470849     0.5495 -0.85686
Age.Q                   -0.338398     0.5027 -0.67312
Age.C                   -0.005273     0.4160 -0.01267
Age^4                   -0.280396     0.3549 -0.79017
Age^5                   -0.585081     0.3522 -1.66134
AnxietySelf             -0.412993     0.2953 -1.39845
Anxiety_Years.L         -0.028738     0.2815 -0.10209
Anxiety_Years.Q          0.110843     0.2895  0.38290

Intercepts:
                           Value   Std. Error t value
Strongly Disagree|Disagree -2.7227  0.3519    -7.7375
Disagree|Neutral           -2.1205  0.3138    -6.7572
Neutral|Agree              -1.2890  0.2797    -4.6092
Agree|Strongly Agree        0.7458  0.2625     2.8415

Residual Deviance: 493.9012
AIC: 525.9012
>
> pval <- pnorm(abs(summary_table[, "t value"]),lower.tail = FALSE)* 2
> summary_table <- cbind(summary_table, "p value" = round(pval,3))
> summary_table
                                  Value Std. Error     t value p value p value
GenderMale                 -0.798443583  0.3715981 -2.14867502   0.032   0.032
GenderNon-binary           -0.935156341  1.4991854 -0.62377633   0.533   0.533
GenderOther                 0.149259763  1.6584121  0.09000161   0.928   0.928
GenderPrefer not to say    -1.194734361  1.2101003 -0.98730190   0.323   0.323
Age.L                      -0.470848554  0.5495048 -0.85685970   0.392   0.392
Age.Q                      -0.338397948  0.5027273 -0.67312434   0.501   0.501
Age.C                      -0.005272766  0.4160405 -0.01267369   0.990   0.990
Age^4                      -0.280395930  0.3548547 -0.79017116   0.429   0.429
Age^5                      -0.585080566  0.3521728 -1.66134492   0.097   0.097
AnxietySelf                -0.412992815  0.2953221 -1.39844851   0.162   0.162
Anxiety_Years.L            -0.028737810  0.2814997 -0.10208825   0.919   0.919
Anxiety_Years.Q             0.110843066  0.2894819  0.38290153   0.702   0.702
Strongly Disagree|Disagree -2.722745362  0.3518882 -7.73753063   0.000   0.000
Disagree|Neutral           -2.120546640  0.3138214 -6.75717664   0.000   0.000
Neutral|Agree              -1.289026602  0.2796661 -4.60916345   0.000   0.000
Agree|Strongly Agree        0.745845230  0.2624787  2.84154550   0.004   0.004
>
> exp(cbind(OR = coef(m), confint(m)))
Waiting for profiling to be done...
                               OR      2.5 %    97.5 %
GenderMale              0.4500289 0.21607986  0.930578
GenderNon-binary        0.3925245 0.01385979 11.097570
GenderOther             1.1609745 0.03345565 40.330263
GenderPrefer not to say 0.3027844 0.02703941  3.925079
Age.L                   0.6244721 0.20716802  1.824266
Age.Q                   0.7129115 0.26034476  1.904788
Age.C                   0.9947411 0.43621455  2.248073
Age^4                   0.7554846 0.37508201  1.512078
Age^5                   0.5570610 0.27777257  1.107730
AnxietySelf             0.6616670 0.36979179  1.179271
Anxiety_Years.L         0.9716712 0.55805392  1.687981
Anxiety_Years.Q         1.1172196 0.63264524  1.972616
>

EDIT
From Kat's suggestion, I have done a train and test, as well as a goodness to fit test.
Train and Test
The result was:
0.6140351

I have interpreted this to mean that the model misclassified 61% of the data and therefore isn't a very good model. I believe I have read somewhere that a misclassification rate of 10% or lower is what you would like to see.
#GET DATA
data<-read.xlsx("Linear_Regression.xlsx","TESTLR")

##REORDER
data$Gender<-factor(data$Gender, levels = c("Male", "Female", "Non-binary", "Prefer not to say", "Other"))
data$Anxiety<-factor(data$Anxiety, levels = c("Self", "Professional"))
data$Age<-factor(data$Age, levels = c("18-24", "25-34", "35-44", "45-54", "55-64", "65 or above"),ordered=TRUE)
data$Anxiety_Years<-factor(data$Anxiety_Years, levels = c("1-4", "5-9", "10+"),ordered=TRUE)
data$W1<-factor(data$W1, levels = c("Strongly Disagree", "Disagree", "Neutral", "Agree", "Strongly Agree"),ordered=TRUE)

##PREPARE TRAINING AND TEST DATA
set.seed(100)
trainingRows <- sample(1:nrow(data), 0.7 * nrow(data))
trainingData <- data[trainingRows, ]
testData <- data[-trainingRows, ]

##BUILD ORDERED LOGICSTIC REGRESSION MODEL
options(contrasts = c("contr.treatment", "contr.poly"))
polrMod <- polr(W1 ~ Gender + Age + Anxiety + Anxiety_Years, data = trainingData)
summary(polrMod)

##PREDICT
predictedClass <- predict(polrMod, testData)  # predict the classes directly
head(predictedClass)
predictedScores <- predict(polrMod, testData, type="p")  # predict the probabilites
head(predictedScores)

##CONFUSION MATRIX AND MISCLASSIFICATION ERROR
table(testData$W1, predictedClass)  # confusion matrix
mean(as.character(testData$W1) != as.character(predictedClass))  # misclassification error

Goodness to fit test
In addition to the code shown originally, I have also run:
lipsitz.test(m)

This does give me a result but also shows a warning. I have researched this warning but haven't been able to solve the issue.
I am now sure how to interpret these values to understand more about the model?
Lipsitz goodness of fit test for ordinal response models

data:  formula:  W1 ~ Gender + Age + Anxiety + Anxiety_Years
LR statistic = 13.996, df = 9, p-value = 0.1225

Warning message:
In lipsitz.test(m) :
  g >= n/5c. Running this test when g >= n/5c is not recommended.

Questions from Kat's explanation

For the gender, there are the options for Male, Female, Non-binary, Other, Prefer not to say. Your explanation of interpreting the Male is clear, and I can see how you would apply that to the other options on the list. What I'm unsure of is how do you comment about 'Female' as this isn't on the list?

When looking at the results, would you follow these steps:

a. Look at the p-values
b. Identify significant p-values (ones that are <0.01)
c. Calculate the 'odds less likely to agree' for the significant ones
d. Comment on these values you calculate

Is there a guide on the significance of 'odds less likely' and the confidence interval of when it is considered significant? In a statistics session I attended we were told about the guidance for interpreting p-values (see below) - is there something similar or 'odds less likely?

p-value < 0.001 very strong statistical evidence of an effect.
p-value < 0.01      strong statistical evidence of an effect.
p-value ≤ 0.05      some statistical evidence of an effect.
p-value >≈ 0.05     weak or limited statistical evidence for an effect
p-value > 0.1       no statistical evidence of an effect
Comment: Before interpreting coefficients, you should double-check that you fitted the model as intended. Did you notice the message *136 observations deleted due to missingness*? Looking at your raw data, columns Anxiety_Years, Pain_Years and Pain_Areas have lots of missing values. I can guess that for Pain_Years and Pain_Areas missing actually means "0 Pain_Years" and "No Pain_Areas" by default as these are the subjects with no pain.
Comment: In short, I suspect that all subjects who don't suffer from chronic pain got dropped.
Comment: Thank you @dipetkov - I have edited the data that I am looking at to just focus on the anxiety factors for now.
Comment: This is fine as long as it is clear that the model and interpretation are about a specific subpopulation of subjects.
Answer: I assume that you've already evaluated the assumptions necessary for ordinal regression. I see you've already determined the p-values. So it would help if you got the confidence intervals and the odds ratios.
Once you've determined these metrics, you'll be able to interpret the results more meaningfully. You'll find some great resources with UCLA (they offer R, in addition to numerous other stats software) or the Laerd website (all based on SPSS but still helpful interpretation content).
For example, here's one specific to ordinal regression in R. Here is more on interpreting the results. This is another useful resource, but this one didn't use R.
BTW, I see you're using base R. You'll probably find R a lot easier to work with if you use it with RStudio.

Update
**You didn't train and test nor use a goodness of fit test (at least that I can see); one or both of these are important to ensure your model suitably represents the data.
I didn't include an interpretation of the model in general, but you'll probably want to look at that, too.
Since I don't know what you asked in W1, I've created an arbitrary statement that will represent the W1:

Aliens are friendly.

Interpretation 1

For respondents that reported their gender as male, the odds of being less likely to agree that aliens are friendly is 2.22 (95% CI [1.07, 4.63]) times that of respondents that reported other genders, holding all other variables constant, t(1) = -2.15, p = .032.

(BTW—that's APA formatting.)
How did I get this information from what you gathered in your analysis?
First, look at the polarity of the $\beta$ value for gender: male (the coefficient value). Is it increasing? Is it decreasing?
The odds ratio is telling us more likely odds. You could write a more complicated interpretation and use that value. However, it is easier to find the inverse of these odds so that you know the odds of less likelihood.
The odds of less likely is $\frac{1}{OR}$ or $\frac{1}{0.4500289}$, which is approximately 2.22.
The high and low end of the confidence interval is going to flip as well. Instead of -> likely 0.21607986 -> even more likely .930578, you'll have  $\frac{1}{0.930578}$ <- least likely $\frac{1}{0.21607986}$ <- less likely or 95% CI [1.07, 4.63].
Your independent variables don't do a great job of explaining your outcome, so these low confidence values aren't typically reported. I chose to go over whatever represents age^5 since the repeatability meets a 90% confidence level threshold. (If you're not aware, the p-value represents—the confidence in your result's repeatability.)
Interpretation 2
In this interpretation, I refer to age^5 as age group five.

For the respondents that reported their age in age group five, the odds of being less likely to agree that aliens are friendly is 1.795 times that of respondents in other age groups, holding all other variables constant.

Let me know if I've left something important out of my explanation or if you have any other questions.
Comment: Hi :) I have made the edit that you suggested (including the OR)
Comment: @amydowse, I've updated my answer! Let me know if it's clear as mud or if you have any other questions.
Comment: Thank you so much @Kat for that clear explanation, that has helped a lot. I have edited my question with a couple of queries I still have


Image of open set under the function that maps vectors from Rn to R by selecting the ith component is open

Question: Let $A$ be a subset of $R^n$, with $x\in R^{n}$ Consider the projection function $\pi_i:\mathbb{R^n} \to\mathbb{R}$ given by $\pi_i(x)=x_{i}$.
Prove that if $A$ is an open set then $\pi_i(A)$ is open. Something I should mention is that I was asked to prove this using continuous functions
In order to prove this I tried to prove that $\pi_i^{-1}$ is continuous. and that would make the preimage of an open set under $\pi_i^{-1}$ open, taking the preimage of A under $\pi_i^{-1}$ $$(\pi_i^{-1})^{-1}(A)=\pi_i(A)$$ which would make $\pi_i(A)$ open.
I'm struggling with finding the expression of $\pi_i^{-1}$.
is this the right way to prove this?
Answer: Note that $\pi_i^{-1}$ is not well defined as a function. For example, in $\mathbb{R}^2$, we have that $\pi_1((1,2)) = 1 = \pi_1((1,1))$, so $\pi_1$ is not injective and hence not invertible.
One can prove the claim directly. Suppose $A$ is open, then for every $x$ we can find $\varepsilon>0$ such that $B_\varepsilon (x) \subset A$. It follows that for any $x$, the set $\{y \mid | x_i - y | < \varepsilon\} \subset \pi_i(A)$. Hence $\pi_i(A)$ is open.
Answer: Suppose without loss of generality that $i=1$. Let $U$ be an open set of $\mathbb{R}^n$, and let $x \in \pi_1(U)$. Then there exists some $y=(x,x_2,\ldots,x_n) \in U$ such that $\pi_1(y)=x$. Since $U$ is open, there exists some $\epsilon>0$ such that $B_n(y,\epsilon) \subset U$. This implies that $y_\delta:=(x+\delta,x_2,\ldots,x_n) \in U$ for all $-\epsilon<\delta<\epsilon$, since $d_n(y_\delta,y)=|\delta|$. This gives us that $B_1(x,\epsilon) \subset \pi_1(U)$, hence $\pi_1(U)$ is open.


Get data from mixin Vue.js

Question: I have a Vue component that requires a file that is a Vue mixin. The file that is required is part of a vendor package so I cannot modify that file. I need to get the notifications prop from the mixin. The end result is that I am going to access the notifications object and get the amount of read notifications so that I display this count as a computed property. It seems that using this.notifications does not work. How can I do this?
Here is my component:
var base = require('notifications/notifications');

Vue.component('spark-notifications', {

    mixins: [base],

});

Here is the notifications file that was required in the previous component:
module.exports = {
    props: ['notifications', 'hasUnreadAnnouncements', 'loadingNotifications'],

    /**
     * The component's data.
     */
    data() {
        return {
            showingNotifications: true,
            showingAnnouncements: false
        }
    },

    methods: {
        /**
         * Show the user notifications.
         */
        showNotifications() {
            this.showingNotifications = true;
            this.showingAnnouncements = false;
        },

        /**
         * Show the product announcements.
         */
        showAnnouncements() {
            this.showingNotifications = false;
            this.showingAnnouncements = true;

            this.updateLastReadAnnouncementsTimestamp();
        },

        /**
         * Update the last read announcements timestamp.
         */
        updateLastReadAnnouncementsTimestamp() {
            this.$http.put('/user/last-read-announcements-at')
                .then(() => {
                    this.$dispatch('updateUser');
                });
        }
    },

    computed: {
        /**
         * Get the active notifications or announcements.
         */
        activeNotifications() {
            if ( ! this.notifications) {
                return [];
            }

            if (this.showingNotifications) {
                return this.notifications.notifications;
            } else {
                return this.notifications.announcements;
            }
        },

        /**
         * Determine if the user has any notifications.
         */
        hasNotifications() {
            return this.notifications && this.notifications.notifications.length > 0;
        },

        /**
         * Determine if the user has any announcements.
         */
        hasAnnouncements() {
            return this.notifications && this.notifications.announcements.length > 0;
        }
    }
};

The beginning of the Laravel blade template:
<spark-notifications
            :notifications="notifications"
            :has-unread-announcements="hasUnreadAnnouncements"
            :loading-notifications="loadingNotifications"
            inline-template>

Here is the method in the spark.js which gets the notifications:
    data: {
            user: Spark.state.user,
            teams: Spark.state.teams,
            currentTeam: Spark.state.currentTeam,

            loadingNotifications: false,
            notifications: null,

            supportForm: new SparkForm({
                from: '',
                subject: '',
                message: ''
            })
        },

        getNotifications() {
                this.loadingNotifications = true;

                this.$http.get('/notifications/recent')
                    .then(response => {
                        this.notifications = response.data;

                        this.loadingNotifications = false;
                    });
            },

And, here is where everything is bootstrapped together app.js:
require('spark-bootstrap');
require('./components/bootstrap');

var app = new Vue({
    mixins: [require('spark')]
});

Answer: this.notifications is the correct way.  If that is not defined, it is because no notifications prop was passed to the component.
Edit: The reason it was null in the ready() function is that the http request retrieving the notifications hadn't returned yet.  OP was trying to get the count of unread notifications, which we got working like so:
Vue.component('spark-notifications', {

    mixins: [base],

    computed: {
        notificationCount:function(){
            var unread = this.notifications.notifications.filter(function(notif){
                return !notif.read;
            });
            return unread.length
        }
    }

});

Comment: On the `ready` function, when I `console.log(this.notifications);`, I get `null` in the console. I put the beginning of the blade template in the question so you can see what that looks like.
Comment: and `notifications` is defined somewhere else as well?
Comment: That is correct. Same Vue instance but in a completely different file using an `$http.get` request. The method that gets the notifications is called on the `created` method. Not sure how to get it from there to my Vue file. I can access within my blade file, but I need to do some calculations.
Comment: Well everything seems right so far, and we have a `null` instead of `undefined`, so the problem is further up the chain somewhere and we're passing in a null variable to the component.  can you share some additional code like how `notifications` is retrieved from the server and passed into Vue?
Comment: I added some more code in my question. It's kinda hard because all of the code is separated into modules, which makes for cleaner code, but having to look in a ton of files is a challenge.
Comment: hmmm ok and in the `created()` function you're calling `this.getNotifications()`? When you console log your `$http.get()` response do the notifications exist?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/109817/discussion-between-dc-tc-and-jeff).

Get data from mixin Vue.js


Prove a set in dense in R

Question: Fix and arbitrary $r$ such that $0 < r < 1$.
Define the set T = {$kr^n$ : $k$ is an integer and $n$ is a natural number}
Prove that T is dense in R
Comment: HINT: The sequence $\langle r^n:n\in\Bbb N\rangle$ converges to $0$.
Answer: Let $x\in\Bbb R$.  Let $\epsilon>0$.  Since $r^n\rightarrow0$, we can choose $n\in\Bbb N$ such that $r^n<\epsilon$.  Then the integer multiples of $r^n$ create an evenly spaced set of real numbers each less than $\epsilon$ from its neighbor.  So there will be one within $\epsilon$ of $x$.
Comment: This problem was much easier than I originally thought. I was able to figure it out immediately after seeing this...Thank you!
Comment: @Adiea You're welcome.  Please hit that little check mark on at least one answer, to mark the answer as accepted.  Thank you :-)
Answer: To show that $\mathbf{T}$ is dense in $\mathbb{R}$, it suffices to show that for each $x$ in $\mathbb{R}$, there exists a sequence $\{x_{n}\}\subset\mathbf{T}$ such that $x_{n}\rightarrow x$.
Let $x$ be arbitrary. Define $x_{n}= k_{n}r^{n}$ where $k_{n}$ satisfies $$|x-k_{n}r^{n}|=\min_{k\in\mathbb{Z}}|x-kr^{n}|.$$ Can you prove $x_{n}\rightarrow x$?

Prove a set in dense in R


How to show a local notification when the user clicks a button on iOS?

Question: In my iOS app, I want to show a local notification when the user clicks a button.
But according to the documentation, it looks like the notification can only be displayed:

after a certain amount of time or on a specific date
when the user enters or exits a specific location
when the app gets a push notification

The best I can do so far is:
<code>// content:
let content = UNMutableNotificationContent()
content.categoryIdentifier = "test_category"
content.title = "Title"
content.subtitle = "Subtitle"
content.body = "Notification body"
content.sound = UNNotificationSound.default

// trigger:
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
</code>
So how can I show a local notification on iOS when the user clicks a button?
Thanks.
Answer: Just make it 1 second
<code>let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
</code>
Comment: @matteoh the trigger can be nil and it will trigger without delay
Comment: Thanks, I tried that too but for some reason, nothing happens, I don't see any local notification. Did I miss something in my example above?
Comment: Check https://stackoverflow.com/a/71336816/5820010
Comment: Thanks! I tried that before but with more trials and errors, I finally managed to make it work!


CSS animation unexpectedly restarts from the beginning in some browsers

Question: In both IE11 and Webkit browsers, if you set display: none on a div containing an element that's in the middle of a CSS animation, and then set the container div back to display: block, the animation will restart from the beginning.
Firefox does not do this: it behaves as if the animation had been running in the background the whole time (which seems much more intuitive to me).
Which behavior is correct?
I've distilled this down to a bare-bones test case, which you can see in this jsfiddle. Try it in Firefox, then try it in Chrome/Safari/IE11, and note the difference in behavior.
Question 1: Which browser is compliant with the spec here? Or is the spec too vague to say?
Question 2: If one behavior or the other is compliant, is there a fix/workaround/hack that will compel the non-compliant browsers to behave correctly too?
I have read that using visibility: hidden instead of display: none on the will prevent this issue. This is not an option.
I know that I could use jQuery.animate() or other JavaScript-based animation techniques as a workaround. That is not what I'm asking about.
The code from the JSFiddle is reproduced below.
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title> - jsFiddle demo</title>

            <button id="start-animation">Start animating the yellow bar</button>

            While the animation is still running, <button id="hide-container">set display: none on the containing div</button>

            <button id="show-container">Set the container back to display: block</button>

            In Webkit and IE11, the animation starts over from the beginning. In Firefox, it behaves as if the animation had been running in the background all along.

Comment: Second answer on here use `height` to set it to `0` so all behave like FF if `visibility` not an option http://stackoverflow.com/questions/3331353/transitions-on-the-display-property After specs wise I am not sure but if the element is "out" of the document then why should it animate. When if it is still "in" like with visibility and height it should keep on going.
Answer: I don't know the answers regarding specs, but as far as another workaround goes:
Could you use opacity instead? Instead of your show and hide to toggle display, using opacity: 0 to hide the container?
Using animations as you set it up: http://jsfiddle.net/t5bhmnoy/7/
Using transitions - it was just an approach I tried anyway: http://jsfiddle.net/t5bhmnoy/6/


How come printing &some_buf[0] and &some_buf give different outputs?

Question: char buffer[4];
std::cout << &buffer << std::endl;
std::cout << &buffer[0] << std::endl;

When I run this code the first line is the hex address of first element in the buffer. The second line is four question marks (unless I cast as a null-pointer).
How is the second statement different from the first (semantically, they are the same?)?
Why does the second line appear as question marks and not random garbage characters?
Comment: `char*` is handled different from `void*` with `std::ostream& operator<<(std::ostream&, T)`.
Comment: "Pointer to array of `T`" and "pointer to `T`"  are not semantically equivalent.   `buffer` would be equivalent to `&buffer[0]` in that context, but not `&buffer`.
Comment: @molbdnilo, yes! That's where my understanding failed. I thought of both statements as "memory address of first element of buffer" rather than "pointer to array of T" and "pointer to T", but I know better now.
Answer: &buffer gives you the address of the buffer, in an appropriate pointer type. That type is char (*)[4].
&buffer[0] gives you the address of the first buffer element (a char), so the address is of type char*.
The standard stream classes have an overload that handles a char const*, but no overload that handles a char (*)[4]. There is however  a general overload for pointers, that accepts a void*. So the pointer to array is converted implicitly to a void*, and passed to that overload. You therefore see the address of the buffer.
In the second case, if buffer was initialized properly, you'd see its contents printed (what the "c-string" overload does). However, since you did not initialize it, your code has undefined behavior. The mere attempt to print the buffer has no well defined consequence.
Comment: @Locus - C++ most definitly does keep track of the size. The size is part of the type (`char[10]` for instance). What you are confusing it with is array decaying.
Comment: This is exactly what I was looking for. I'd like to ask a follow up question. Would there be any difference between a pointer of type char (*)[4] and, say, a pointer of char (*)[10]? C++ doesn't keep track of the length of arrays anyway, why couldn't we call it a char (*)[n] instead?
Comment: Yes, you are right, I didn't even know what array decaying was and thought that was the 'normal' situation.
Answer: &buffer is the address of the buffer. &buffer[0] is the address of the first character in the buffer. here in your case a garbage value that is because you didn't initialize it. Try to initialize it:
char buffer[] = "Hello there!";
std::cout << &buffer << std::endl;
std::cout << &buffer[0] << std::endl; // print from first element to the end(until the first null-character)
std::cout << &buffer[4] << std::endl; // print from fifth element to the end

The output:
0018FF38
Hello there!
o there!

I think it is a problem of osstream insertion operator << which assumes you to pass a char* and you pass to it the address of a character so as I guess it's a UB.
To get the address of the character you have to cast it to void*:
std::cout << static_cast < void* >(&buffer[0]) << std::endl;
std::cout << static_cast < void* >(&buffer[1]) << std::endl;

The output:
   0018FF38
   0018FF39

To confirm that it's an ostream << issue try to use printf:
printf("&buffer[0]: %p \n", &buffer[0]);

The output:
&buffer[0]: 0018FF38


Como defino ordenação personalizada no retorno de um DB?

Question: Hoje eu tenho um catalogo de produtos (imagens) simples que mostra todos os produtos juntos ou por categorias.
Porém, quando mostrar todos juntos só sei ordenar por ASC ou DESC, mas preciso ordenar diferente. Quando mostrar todos quero que apareça um produto X primeiro ou na posição que eu definir, e não uma simples ASC ou DESC, pois quando adiciono um Y, ou ele aparece no inicio (ordenando id by DESC) ou no final (ordenando id by ASC).
Gostaria de implementar no meu código (PHP+MySQL). Vi um exemplo aqui: http://mateusgamba.xpg.uol.com.br/ordenar_tabela.html (no caso o administrador irá escolher onde aparece o produto, que pode subir ou descer).
Caso o post esteja meio confuso estou a disposição para explicar melhor.
Comment: se voce nao quer em ordem crecsente ou decrecsente em qual ordem seria essa que voce gostaria? voce pode usar uma cararacteristica do produto x para definir uma ordem tipo cor tamanho visibilidade da imagem
Comment: Para esses casos, eu adiciono uma coluna chamada ranking, no mesmo sentido que o colega @miguel escreveu e mando ordenar por essa coluna.
Answer: Para fazer isso tem de armazenar a ordem costumizada que quer. Pode criar uma coluna na sua tabela com a ordem (int), e depois ordenar a partir daí com o SELECT * FROM produtos ORDER BY ordem ASC/DESC ..., tal como faz com o id. Ou seja, quando insere/edita o produto passa a inserir mais um dado, que é em que lugar (1 para o primeiro, 2 para o segundo, 3 para o terceiro ...) em que quer que ele fique.
Atenção que com isto, se não quiser que hajam produtos com lugares (ordem) iguais tem de trabalhar a sua lógica para:
INSERÇÃO
Portanto se tiver um produto com o lugar 5 (ordem é 5), mas se mais tarde vai inserir outro que acha que deve ficar no lugar 5 vai ter de incrementar +1 a ordem de todos os produtos cujo a ordem é >= 5, (UPDATE produtos SET ordem = ordem + 1 WHERE ordem >= 5) e depois insere o novo produto. Neste exemplo o primeiro que estava no lugar 5 vai passar a estar no lugar 6, 6 -> 7, 7 -> 8 etc...
EDIÇÃO: Subida de lugar (ex: de lugar 7 para lugar 2)
Aqui o funcionamento vai ser um pouco diferente, caso o produto esteja em  sétimo e queiramos alterar para que fique em segundo fazemos com que todos os produtos cuja ordem for entre 2 e 7 alterem o número do lugar em que aparecem. Ou seja, somente os produtos de ordem < 7 e ordem >= 2 é que vão ser incrementados em 1 na coluna ordem. Fazemos UPDATE produtos SET ordem = ordem + 1 WHERE ordem >= 2 AND ordem < 7, e logo a seguir fazemos o update da ordem do produto de 7 para 2 (UPDATE produtos SET ordem = 2 WHERE id = ID_SETIMO_PRODUTO)
EDIÇÃO: Descida de lugar (ex: de lugar 2 para lugar 7)
Aqui, seguindo a lógica oposta à de subida de lugar fazemos com que todos os produtos cuja ordem > 2 e ordem <= 7 é que vão ser DECREMENTADOS em 1 na coluna da ordem. Fazemos UPDATE produtos SET ordem = ordem - 1 WHERE ordem > 2 AND ordem <= 7 e logo a seguir a fazer o update da ordem do produto para 7 (UPDATE produtos SET ordem = 7 WHERE id = ID_SEGUNDO_PRODUTO).
DELETE
Aqui temos de decrementar em 1 à ordem de todos os produtos cuja ordem for superior à ordem do produto que apagamos. Se quisermos apagar o produto que está em sétimo fazemos UPDATE produtos SET ordem = ordem - 1 WHERE ordem > 7 e depois finalmente apagamos o produto DELETE FROM produtos WHERE id = ID_SETIMO_PRODUTO
Desta meneira garante que estejam sempre consecutivos e enumerados pela ordem que quer sem que hajam produtos com lugares (ordem) repetidos
Comment: Não entendi o problema de ter dois produtos com a mesma ordem. Eu uso ranking em uma série de situações, e deixo "empatados" os produtos de mesma relevância, sem nenhum tipo de problema. Inclusive, como exemplo, a pessoa pode fazer um `ORDER BY ordem, nome`, assim você tem o ranking e ordem alfabética no caso de empates.
Comment: É claro que há casos em que não há diferença e para si funciona assim. Mas entre dois produtos ranking 5, pode crer um antes do outro, desta maneira evitava-se isso
Comment: Entendo. Só perguntei pra ver se tinha algum detalhe que eu deixei passar despercebido, grato pelo retorno.
Comment: :) . Há alguma forma de tornar a resposta mais clara? Até acho que me expliquei bem
Comment: Acho que o caminho é esse mesmo, acho que se quiser incrementar, pode por uma tabelinha exemplo, ou um SQL Fiddle demonstrando, mas talvez seja exagero. Melhor esperar o Autor se manifestar pra ver se ele entendeu :)


Limit number of searchresults from a simple jQuery keyup searchbox

Question: Im trying to get a certain number of searchresults append when making a search in my #searchbox to be able not to append too much searchlistings in the result div. Im stalled here, no clue how to proceed.
var jsonData;

            $.getJSON("<?php echo base_url(); ?>/show_controller", function(json){
                jsonData = json;

            });

        $("#searchbox").keyup(function()
        {
            var searchvalue = $("#searchbox").val();
            $("#searchresult").empty();
            $("#step2").remove();
            $("#searchresult").append("
");
            $("#searchresult").append("Name	");
            $("#searchresult").append("Description	");
            $("#searchresult").append("Manufacturer	");
            $("#searchresult").append("Batch	");
            $("#searchresult").append("Sign for registration	");
            for(var i = 0; i < jsonData.length; i++)
                {

                    if(jsonData[i]['Name'].indexOf(searchvalue) != -1 || jsonData[i]['Desc'].indexOf(searchvalue) != -1)
                    {
                        $("#searchresult").append("
");
                        $("#searchresult").append("" + jsonData[i]['Name'] + "	");
                        $("#searchresult").append("" + jsonData[i]['Desc'] + "	");
                        $("#searchresult").append("Manufacturer(nodata yet)	");
                        $("#searchresult").append("Batch(nodata yet)	");
                        $("#searchresult").append("<input type='checkbox' class='user' id='" + jsonData[i]['id'] + "'>	'");
                        $("#searchresult").append("
");
                    }

                }
            $("#searchresult").append("
");
            $("#content").append("<input type='submit' id='step2' value='Next >>'>");
        });

Answer: If I'm reading your code right your jsonData variable contains all possible search results and then your keyup function filters within those search results and at the moment it displays all matching results but you want to limit it to only display the first x items that match?
If so then you just need to keep a count of how many things you've already appended and stop when that count goes over some preset limit or when you run out of data (whichever comes first).
I won't repeat the entire function here, but something like this:
var maxResults = 10; // or whatever your limit is

for(var i = 0, count = 0; i < jsonData.length && count < maxResults; i++)
{
   if(jsonData[i]['Name'].indexOf(searchvalue) != -1 || jsonData[i]['Desc'].indexOf(searchvalue) != -1)
   {
      // only increment count when you find a match
      count++;

      $("#vaccine_searchresult").append("
");
      $("#vaccine_searchresult").append("" + jsonData[i]['Name'] + "	");
      // etc
   }
}

Answer: You can limit it by checking the loop variable i - say if it goes beyond 10 then break the for loop.
Better way would be to pass max parameter to your server side url that returns the search results so that it will only return max results.
OTOH, you may add  overflow:auto css to your div to get scroll bars when there are many search results.
Comment: Great! had thought about the overflow property but dont know if thats going to sit well with the layout.
Answer: You should do this in the PHP code which the JSON is calling.
If for whatever reason you can't, then amend the following line:
//for(var i = 0; i < jsonData.length; i++)
var maxLimit = 15;
var limit = jsonData.length < maxLimit ? jsonData.length : maxLimit ;
for(var i = 0; i < limit ; i++)

Obviously this will limit the loop to 15 iterations, you can amend that as needed.
I'd also suggest you change the number of .append() calls you're making. It would be a lot more efficient if you built the entire table row as a string or jquery object and only appended it once, eg.
var tableHeadings = "
\
    Name	\
    Description	\
    Manufacturer	\
    Batch	\
    Sign for registration	";
$("#searchresult").append(tableHeadings);


.NET: Is "foreach" command?

Question: I have just a terminology question. I have read that if, foreach etc. are statements but what does it mean in the terminology - are these commands?
It is maybe "lost in the translation" problem
Answer: From Statement (programming)

In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program is formed by a sequence of one or more statements. A statement will have internal components (e.g., expressions).
Many languages (e.g. C) make a distinction between statements and definitions, with a statement only containing executable code and a definition declaring an identifier. A distinction can also be made between simple and compound statements; the latter may contain statements as components.

In a nutshell it is one of many instructions in the language that makes the program to perform some very basic action. Through combining statements you define a complex activity that makes sense to you as an author. You define it by using little building blocks namely those statements.
Comment: Thanks, also they are statements, so they are "commands" as they are executable
Answer: A command and a statement is generally the same thing.
However, when talking about commands, it's usually something that a user enters directly rather than a statement in a program.
Also, while a command generally is an instruction to do something, a statement can also be instructions that doesn't actually perform anything, like for example declaring a constant value:
<code>const int Answer = 42;
</code>
Comment: That is not a statement, it is a declaration  :)
Comment: @leppie: Good point. Let's use a declaration that is a statement as example instead. :)
Comment: That is still primarily a declaration, the fact that the compiler 'magically' store and initialize the value is kinda irrelevant.
Comment: @leppie: So any expression that ends with a semicolon is a statement, *except* if it happens to declare something also? Or is it just when I write something that it isn't a statement? ;)
Comment: Declarations end with a `;` too, but i'm getting tired. Go read the C# grammar, you might be surprised :)
Answer: A statement is an expression that has no return value (or void or unspecified).
Comment: Do you have any references for this?
Comment: Many statements actually have a return value, like `x = 42` for example.
Comment: @Guffa: If you terminate any expression with a `;`, it becomes a statement.
Comment: @Stefan Steinegger: You can find this in the C# spec, grammar section. Pretty much goes for any 'procedural' language.  (procedural is not quite correct, but I cant think of an easier description)

.NET: Is "foreach" command?


How to Sort a List Generically

Question: I am using an Html.Grid of a set of objects which are being pulled from a database (via LINQ to SQL). Here is the Grid code (I have changed the data to something contrived). The page is strongly-typed to People.
<code><%=Html.Grid<People>(Model)
// Display chose solution information.
    .Columns(column =>
        {
            column.For(person => person.Name);
            column.For(person => person.Address.City);
        }
    )
%>
</code>
Within the database, I would have a People table and an Address table linked by a foreign key. (Again, this is contrived - just trying to describe the problem.)
I want to allow the user to generically sort the columns. The previous developer had hard-coded in the sorting within the controller, like so...
<code>//
// GET: Results/Grid
public ActionResult Grid(int id, GridSortOptions sort)
{
    if (sort == null)
    {
        sort = new GridSortOptions();
    }

    Solution solution = repository.GetSolution(id);
    List<People> people = solution.People.ToList();
    if (!string.IsNullOrEmpty(sort.Column))
    {
        people = solution.People.ToList().OrderBy(sort.Column, sort.Direction).ToList();
    }

    return PartialView("Grid", people);
}
</code>
This works great when the object I am sorting is people (if I click on the person.Name column to sort it ascending or descending). However, when I want to sort the address column, I get an exception because People does not contain a City...Address does.
My question is...is there a way to do this sort generically without knowing what the type is ahead of time? Thanks.
Comment: Some of your code isn't very clear `ViewData["sort"] = sort;` is that suppose to be inversed? Is there only one level of Child objects or more than one?
Comment: @msarchet - I am inheriting this code from a previous developer. I do not believe that statement is necessary. Updating to reflect that. Thanks.
Answer: How about a javascript table sorter? Of course that won't work if your list is big enough to require paging.
Comment: Any you recommend? This may be a possible solution (although, as you said, paging could be a problem).
Answer: I posted a similar question a little while back. The answers I got on that post might help you get on your way:
Looking for a better way to sort my List<T>
Basically the answers suggest holding map of Func<> (or similar) and calling the appropriate one in the code block.

How to Sort a List Generically


image manipulation using slider in iphone

Question: Is there a way to apply brightness to uiimages. For example I have a UIImageview and inside that i have a uiimage. I want to manipulate its brightness with a help of UISlider without using GlImageprocessing.
Please help me to solve this problem and please don't suggest me about GlImageprocessing. I want to do it without using GlImageprocessing.
Answer: here is the code:-
<code>        CGImageRef inImage = currentImage.CGImage;
        CFDataRef ref = CGDataProviderCopyData(CGImageGetDataProvider(inImage));
        UInt8 * buf = (UInt8 *) CFDataGetBytePtr(ref);
        int length = CFDataGetLength(ref);
        float value2 =  (1+slider.value-0.5);
        NSLog(@"%i",value);
        for(int i=0; i<length; i+=4)
        {

            int r = i;
            int g = i+1;
            int b = i+2;

            int red = buf[r];
            int green = buf[g];
            int blue = buf[b];

            buf[r] = SAFECOLOR(red*value2);
            buf[g] = SAFECOLOR(green*value2);
            buf[b] = SAFECOLOR(blue*value2);
        }

        CGContextRef ctx = CGBitmapContextCreate(buf,
                                                 CGImageGetWidth(inImage),
                                                 CGImageGetHeight(inImage),
                                                 CGImageGetBitsPerComponent(inImage),
                                                 CGImageGetBytesPerRow(inImage),
                                                 CGImageGetColorSpace(inImage),
                                                 CGImageGetAlphaInfo(inImage));

        CGImageRef img = CGBitmapContextCreateImage(ctx);

        [photoEditView setImage:[UIImage imageWithCGImage:img]];
        CFRelease(ref);
        CGContextRelease(ctx);
        CGImageRelease(img);
</code>
define this at the top:-
<code>      #define SAFECOLOR(color) MIN(255,MAX(0,color))
</code>
Comment: where is SAFECOLOR definition ?
Comment: there is code related to image editing on github i am unable to find that link do google may be you can find the link it has all features of image editing
Answer: Have a look at Apple's demo app GLImageProcessing
, it's really fast:
Answer: Open Gl to UIImage Create
-(UIImage *) glToUIImage {
<code>NSInteger myDataLength = 320 * 480 * 4;
 // allocate array and read pixels into it.
GLubyte *buffer = (GLubyte *) malloc(myDataLength);
glReadPixels(0, 0, 320, 480, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

// gl renders "upside down" so swap top to bottom into new array.
// there's gotta be a better way, but this works.
GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);
for(int y = 0; y <480; y++)
{
    for(int x = 0; x <320 * 4; x++)
    {
        buffer2[(479 - y) * 320 * 4 + x] = buffer[y * 4 * 320 + x];
    }
}
// make data provider with data.
CGDataProviderRef provider = CGDataProviderCreateWithData(
                                                          NULL, buffer2, myDataLength, NULL);

// prep the ingredients
int bitsPerComponent = 8;
int bitsPerPixel = 32;
int bytesPerRow = 4 * 320;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();

CGBitmapInfo bitmapInfo = kCGImageAlphaNone;

CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;

// make the cgimage
CGImageRef imageRef = CGImageCreate(320, 480, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);

// then make the uiimage from that

UIImage *myImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);

//UIImageWriteToSavedPhotosAlbum(myImage,nil,nil,nil);

[[NSUserDefaults standardUserDefaults] setObject:UIImageJPEGRepresentation(myImage,1) forKey:@"image"];

return myImage;
</code>
}


Toggling visibility between two HTML elements in same space

Question: I have two HTML elements that share the same space- when one is visible, the other should not be.  However, if I just set the other's visibility to 'hidden', it still occupies space in the display hierarchy, whereas I want it to go away.  I don't want to remove the reference entirely, though, as I need to be able to toggle between the two elements.  Any ideas?
Answer: use display:none, not visibility:hidden
Comment: and display:block to turn visible again


How do I query for content that has not been updated (no revisions)?

Question: I am creating an API endpoint that serves as a content Feed that pulls in content according to some rules.
One group of content that I want to pull is articles that have been updated and that have been approved to be included in the feed. My approach for this was to include a boolean field for including it in the feed, and query for the number of revisions.
$firstGroup = $query->andConditionGroup()
    ->condition('type', ['article', 'video_game'], 'IN')
    ->condition('status', NodeInterface::PUBLISHED)
    ->condition('field_include_in_feed', 1)
    ->condition('revision_uid', '1', '>=');

$nids = $query->condition($firstGroup)->condition($secondGroup)->execute();

Based on this page from the documentation, I thought revision_uid would be a valid field, but I get an error that it is not. Likewise I get an error, if I use revision as well.
The error is a Drupal QueryException with the message 'revision_uid' not found.
What is the best way to query for content (with entityQuery) that has been updated if I can't use the revision fields?
Answer: Content that has not been updated would only have one revision, so you could count the number of revisions and use a having condition.
First you'll have to join the node_revision table to the node table
$query->leftJoin('node_revision', 'r', 'n.nid = r.nid');

Count the number of revisions
$query->addExpression('COUNT(n.nid)', 'revision_count');

Filter rows with a revision_count higher than 1
$query->havingCondition('revision_count', 1, '<=');

Comment: This looks like a great way to do it, but is it possible with `EntityQuery`? The `leftJoin()` function seems to only be available on the `Select` class from `Drupal\Core\Database\Query`.
Answer: Every entity stores a timestamp for when the node was created, as well as another for when the node was last updated. So, ideally, you could add a condition to your EntityQuery checking to see if the created value matches the updated value.
Unfortunately, the standard condition() syntax can't handle this. Drupal 7 gave us the where() syntax to execute arbitrary SQL that the Entity Query system couldn't handle, but this is not available in Drupal 8. Therefore, you have a couple of options as I see it:

Use a subquery to pull the created value, then use that returned value as the comparison value against updated in the main query.
Abandon (unfortunately) EntityQuery and use a dynamic or static query instead.

EntityQuery has some restrictions that are hard to get around, and field-to-field comparison is definitely one of them. Unfortunately, I don't know any other way to know definitively that an entity has been modified without revision info.


How do I get the change from the same quarter in the previous year in a pandas datatable grouped by more than 1 column

Question: I have a datatable that looks like this (but with more than 1 country and many more years worth of data):
| Country       | Year | Quarter | Amount |
-------------------------------------------
| UK            | 2014 | 1       | 200    |
| UK            | 2014 | 2       | 250    |
| UK            | 2014 | 3       | 200    |
| UK            | 2014 | 4       | 150    |
| UK            | 2015 | 1       | 230    |
| UK            | 2015 | 2       | 200    |
| UK            | 2015 | 3       | 200    |
| UK            | 2015 | 4       | 160    |
-------------------------------------------

I want to get the change for each row from the same quarter in the previous year. So for the first 4 rows in the example the change would be null (because there is no previous data for that quarter). For 2015 quarter 1, the difference would be 30 (because quarter 1 for the previous year is 200, so 230 - 200 = 30). So the data table I'm trying to get is:
| Country       | Year | Quarter | Amount | Change |
---------------------------------------------------|
| UK            | 2014 | 1       | 200    | NaN    |
| UK            | 2014 | 2       | 250    | NaN    |
| UK            | 2014 | 3       | 200    | NaN    |
| UK            | 2014 | 4       | 150    | NaN    |
| UK            | 2015 | 1       | 230    | 30     |
| UK            | 2015 | 2       | 200    | -50    |
| UK            | 2015 | 3       | 200    | 0      |
| UK            | 2015 | 4       | 160    | 10     |
---------------------------------------------------|

From looking at other questions I've tried using the .diff() method but I'm not quite sure how to get it to do what I want (or if I'll actually need to do something more brute force to work this out), e.g. I've tried:
df.groupby(by=["Country", "Year", "Quarter"]).sum().diff().head(10)
This yields the difference from the previous row in the table as a whole though, rather than the difference from the same quarter for the previous year.
Answer: Since you want the change over Country and quarter and not the year, you have to remove the year from the group.
df['Change'] = df.groupby(['Country', 'Quarter']).Amount.diff()

Comment: Exactly what I was after, thanks! I think I'd over complicated what I was actually trying to do rather than taking a step back and reconsidering the grouping.
Comment: Happens to the best ;). Glad I could help.


Dúvida ao projetar um banco de dados

Question: Qual a melhor forma de projetar um banco de dados para um sistema web, por exemplo, esse sistema é para médicos, e cada médico tem sua agenda, pacientes, caixa, etc. O que seria melhor:

Um único banco de dados onde os registros de todos os médicos são armazenados nas mesmas tabelas (tabela de agenda, pacientes, caixa); ou;
Cada médico ter seu banco de dados, e tudo ficaria separado, cada um com sua tabela de agenda, de pacientes, de caixa, etc;.
Sei que existem pós e contras, eu acredito que a melhor forma seria a primeira, por questão de manutanção. Mas pensando no desempenho, e imaginando que numa tabela de agenda com todos os médicos fazendo CRUD na mesma tabela, como seria o desempenho disso?
Eu gostaria de saber por argumentos qual a melhor forma projetar essa banco de dados. E o por que.
Talvez seja uma dúvida bem simples para muitos, mas eu não tenho muita experiência nessa área.
Comment: Para optar pela forma 2 tem que ver a que taxa suas tabelas são populadas. A taxa não parece ser muito grande, o banco costuma ser capaz de lidar com tabelas da ordem de centenas de milhares ou mesmo milhões de registros sem maiores problemas (desde que o volume de dados trazido nas consultas não seja absurdo). Forma 1.
Comment: @Piovezan mesmo em bilhões você irá de 30 para 32 buscas, se muito. Na verdade o pior cenário, e muito raro, é ir de 1 para 3, porque triplica (mas triplicar em cima de tão pouca busca não importa), o que eu citei dá 5% de perda.
Answer: Em essência o desempenho não faz diferença, existirá alguma, mas não será significativa. E depende da carga.
O primeiro pode ter um problema mínimo de performance porque as árvores dos índices poderão ser mais profundas e pode ter 1 ou 2 níveis a mais para analisar antes de chegar no item desejado, mas isso costuma ser irrisório.
O segundo tende pôr mais informação na memória já que é tudo separado e não usar frequentemente, então o cache começa trabalhar contra e não a favor, e haverá perdas pontuais.
Qual é melhor você não saberá de antemão nem conhecendo seu cenário teórico, só o uso real indicará o que funciona melhor, e poderá mudar de acordo com um mudança de padrão, até testes podem falhar porque envolve muita variável, mas dificilmente verá grande diferença.
Faça de acordo com a real necessidade, de acordo com requisitos, e se preocupe menos com a arquitetura, só deixe fácil mudar se um dia precisar, mas não será por causa da performance. Se tiver problemas de performance é porque tem várias outras coisas muito mais erradas, por exemplo não ter índice onde precisa, ou fazer buscas sem necessidade.
Todos os médicos fazendo CRUD não fará cosquinha porque ela estará 99,99% do tempo com a tela parada sem operação alguma no banco de dados. E o que seria todos os médicos? Todos do Brasil ao mesmo tempo? Aí talvez seja um problema e precisará de uma engenharia pesada. Todos de uma clínica? Tem quase zero impacto. Será algo importante para um hospital? Melhor contratar um engenheiro experiente para cuidar disso.

Dúvida ao projetar um banco de dados


Valor aparece e some após o click- Javascript

Question: Boa noite, fiz uma lógica em javascript dos inputs receberem o valor de um array, tudo certo porém, quando clica no botão para acontecer o evento os valores aparecem e somem do input rapidamente, segugue o código, Obrigado.

<form id="form" >

    Digite o código

<button onclick="separar()">Separar</button>

    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>

</form>

Comment: Qual a ideia? cada input ficar com um valor?
Comment: Cada input recebe um valor do array 'div', quando coloco o window.onload na frente da function os valores já iniciam corretamente nos inputs, mas sem, quando clico, aparece rapidamente e some.
Answer: Por padrão, o <button> assume o type como submit, quando dentro de um formulário. O que está acontecendo é que, ao clicar no botão o evento submit é disparado e então o formulário é "enviado" fazendo com que a página seje limpa.
Adicione o type="button" ao botão

var codigo = "23794130047008001672190051686005178110000010890"

var metade = Math.floor(codigo.length / 8);
var seis = Math.floor(codigo.length / 7);
var um = Math.floor(codigo.length/47);
var rest = Math.floor(codigo.length/3)

var res = codigo.substr(0,metade) + " ," + codigo.substr(5,metade)  + " ," + codigo.substr(10,metade)
+ " ," + codigo.substr(15,seis) + " ," + codigo.substr(21,metade) + " ," + codigo.substr(26,seis)
+ " ," + codigo.substr(32,um) + " ," + codigo.substr(33,rest);

var div = res.split(" ,")

function separar(){
    let teste = document.getElementsByTagName("input")

    for(i =0; i< teste.length; i++){
        teste[i].value = div[i]
        //console.log(teste[i].value = div[i])
    }
}
<form id="form" >
    Digite o código

<button type="button" onclick="separar()">Separar</button>

    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
</form>

Para pegar o código através de um input, adicione um input fora do formulário com um id pra ficar mais fácil de pegar depois. Adicione todo o código de separação dentro da função separar(). Para pegar os inputs use o id do form como referência para poder pegar todos os inputs de dentro dele. Segue o código de exemplo

function separar(){
    var codigo = document.getElementById("codigo").value;

    var metade = Math.floor(codigo.length / 8);
    var seis = Math.floor(codigo.length / 7);
    var um = Math.floor(codigo.length/47);
    var rest = Math.floor(codigo.length/3)

    var res = codigo.substr(0,metade) + " ," + codigo.substr(5,metade)  + " ," + codigo.substr(10,metade)
+ " ," + codigo.substr(15,seis) + " ," + codigo.substr(21,metade) + " ," + codigo.substr(26,seis)
+ " ," + codigo.substr(32,um) + " ," + codigo.substr(33,rest);

    var div = res.split(" ,")
    let teste = document.getElementById("form").getElementsByTagName("input")

    for(i =0; i< teste.length; i++){
        teste[i].value = div[i]
        //console.log(teste[i].value = div[i])
    }
}
<input type="text" id="codigo">
<form id="form" >
    Digite o código

<button type="button" onclick="separar()">Separar</button>

    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
</form>
Comment: Cara muito obrigado !! só uma pergunta se eu quisesse ao invés de definir esse valor fixo, pegar de um input por exemplo, como faria ? estou tentando com queryselector mas da esse erro: Uncaught TypeError: Cannot read property '0' of undefined
Comment: @israel Adicionei à resposta. Caso considere essa resposta como adequada, não se esqueça de marca-la como correta :)
Comment: Perfeito !! Muito Obrigado


Can jenkins deploy model solution to azure analysis service?

Question: I have a .asdatabase file that is model solution. My objective is to use jenkins to automatically upload it to azure analysis service. From what can I find, it's mostly client-based. Is there anyway to make it run on jenkins by using command?
Answer: The solution I came up with is use Automation in Azure. Use Jenkins to use POST to webhook as created by automation runbook.


Problems with theming a grid

Question: I am having problems trying to control the layout and fields together in a grid style of a view.
On the internet I saw several tutorials about how to theme views, and they suggest using functions in template.php, or using view template files. I cannot find a tutorial that helps me.
Specifically, when I use a template file, I cannot control the disposition of fields (controlling the disposition of each field; controlling the fields altogether; adding conditionals; adding classes; trying to use "views-view--," "views-view-field--," "views-view-fields--," or "views-view-grid--"), and when I use a function in template.php, I cannot get the variables/values of fields.
I must say that I know how to include a custom design using the Views module interface, to control the design per fields (or controling all fields of each item, if I include the design and fields in the last field). But I want to do this using some external way to custom display in a centralized way (also to not allow to change the design from the web interface, and to have the control in a files, not in the database).
When I say a centralized way, I mean, using a file or files to control the disposition of each field, control fields together, add conditionals, add classes, add functions, (such as a theme in Drupal).
I am using Drupal 6 and Views 2.
Answer: in views-view-grid--viewname.tpl.php, with print_r($variables), you will find the whole values in the 'view' array (is a very huge output, so I recomend only pull 1 item in this test).
here you will discover that 'result' carry the stdClass Object with the fields of views (not it all, seems that the images are not there), to print this you can use:
print_r($variables['view']->result);

with the id of the values, you can use these values for example, show a node title:
echo $variables['view']->result[$i]->node_title;

or you can use the id of the node to get, for example, images from nodes (seems that the images are not in result).
$nIdItem = $variables['view']->result[$i]->nid;
$node = node_load($nIdItem);
echo "field_image[0]['filepath']."'>";

so with this way is possible to control each field, set of fields, and/or add conditions, functions.
I do not know the performance or security implications of using this way, this may be a new question.

Problems with theming a grid


Showing that a function is a (family of) copula(s)

Question: I am currently working with the book An Introduction to Copulas by Roger Nelsen. I am having trouble solving one of the exercises in the first chapter. The exercise reads as follows:
Let $C$ be a copula, and let $(a,b)$ be a point in $[0,1]\times [0,1]$. For $(u,v)$ in $[0,1]\times [0,1]$, define $$K_{a,b}(u,v) = V_{C}([a(1-u), u+a(1-u)]\times [b(1-v), v+b(1-v]).$$ Show that $K_{a,b}$ is a copula.
For reference, the C-volume $V_{C}$ is defined as $V_{C}([u_{1},u_{2}]\times [v_{1},v_{2}]) = C(u_{2},v_{2}) - C(u_{2},v_{1}) - C(u_{1},v_{2}) + C(u_{1},v_{1})$.
The only thing I have not been able to show in this exercise is that $V_{K_{a,b}}([u_{1},u_{2}]\times [v_{1},v_{2}]) \geq 0$ for any rectangle $[u_{1},u_{2}]\times [v_{1},v_{2}] \subset [0,1]\times [0,1]$ , which is the last defining property of copulas given in the book. Any help/hints for this problem would be greatly appreciated.
For reference, it has already been demonstrated in the book that copulas are continuous. The following inequalities has also been established for any copula $C(u,v)$: For every $(u,v)$ in the domain of $C$, we have $\text{max}(u+v-1,0)\leq C(u,v)\leq \text{min}(u,v)$. Further, it has been established that bivariate copulas are nondecreasing in both arguments.
I have tried writing out the whole expression for $V_{K_{a,b}}([u_{1},u_{2}]\times [v_{1},v_{2}])$ and use the property that copulas are nondecreasing in both arguments to establish that $V_{K_{a,b}}([u_{1},u_{2}]\times [v_{1},v_{2}]\geq 0$. I have also found out (if it is not wrong), that one can write
$V_{K_{a,b}}([u_{1},u_{2}]\times [v_{1},v_{2}]) = V_{C}([a(1-u_{2}), u_{2} + a(1-u_{2})]\times [b(1-v_{2}),v_{2} + b(1-v_{2})]) - V_{C}([a(1-u_{2}), u_{2} + a(1-u_{2})]\times [b(1-v_{1}),v_{1} + b(1-v_{1})]) - V_{C}([a(1-u_{1}), u_{1} + a(1-u_{1})]\times [b(1-v_{2}),v_{2} + b(1-v_{2})]) + V_{C}([a(1-u_{1}), u_{1} + a(1-u_{1})]\times [b(1-v_{1}),v_{1} + b(1-v_{1})])$,
but I have not been able to use this to solve the exercise. However, the first and fourth term must be non-negative, due to $C$ being a copula. Therefore, I have tried to show that the sum of the first and fourth term must be greater than or equal to the sum of the second and third term, without success. I have also tried using the bounds above, but quickly got lost when splitting into cases based on the assumed relative sizes of the variables involved.
Thanks in advance to anyone that can provide any hints/help, and thanks to all that took the time to read this post.
Update: Using the fact that every $V_{C}$ in the above expression maps to $[0,1]$, one can see that $V_{K_{a,b}}([u_{1},u_{2}]\times [v_{1},v_{2}]) \geq 0$ if $V_{C}([a(1-u_{2}), u_{2} + a(1-u_{2})]\times [b(1-v_{2}),v_{2} + b(1-v_{2})]) +  V_{C}([a(1-u_{1}), u_{1} + a(1-u_{1})]\times [b(1-v_{1}),v_{1} + b(1-v_{1})]) \geq 2$
but this restriction is too strict to be useful. I am therefore currently looking for looser restrictions that might be useful. I have also tried to check whether or not the C-volume is monotonic in the size of the rectangle in $[0,1]\times [0,1]$ (if C is a copula), but have not been able to conclusively demonstrate this. In this pursuit, I also found this Is $H$-measure actually monotonic (at least on hyperrectangles)? , but I am not entirely convinced of the answer provided in the link.
Second update:
I probably should have mentioned that not only has continuity been established, but something a bit stronger, namely that if $C$ is a copula, then for every $(u_{1},u_{2}), (v_{1},v_{2})$ in the domain of $C$, we have $|C(u_{2},v_{2}) - C(u_{1},v_{1})| \leq |u_{2}-u_{1}| + |v_{2}-v_{1}|$. I have been trying to use this to estimate relevant bounds on different terms of $V_{K_{a,b}}([u_{1},u_{2}]\times [v_{1},v_{2}])$, but still without any luck.
Third update: I may have found a looser restriction than in the first update. If this is correct, it should be enough to show that $V_{C}([a(1-u_{2}), u_{2} + a(1-u_{2})]\times [b(1-v_{2}),v_{2} + b(1-v_{2})]) + V_{C}([a(1-u_{1}), u_{1} + a(1-u_{1})]\times [b(1-v_{1}),v_{1} + b(1-v_{1})]) + C(a(1-u_{2},v_{1}+b(1-v_{1})) - C(a(1-u_{2}), b(1-v_{1})) + C(a(1-u_{1}), v_{2}+b(1-v_{2})) - C(a(1-u_{1}), b(1-v_{2})) \geq v_{1} + v_{2}$.
This is because the first and second term has to be non-negative due to $C$ being a copula, and the difference between the third and fourth term and the difference between the fifht and the sixth term has to be non-negative due to $C$ being nondecreasing in both arguments. The remaining four terms of $V_{K_{a,b}}$ gives a net negative contribution to $V_{K_{a,b}}$, the upper bound of which I have estimated using the information in the second update.
Answer: It believe I have solved it now. If this is correct, it turns out that the answer was quite simple all along. Also, everything in the three updates above turned out to lead to a dead end as I was able to show using a special case that it was impossible in general to get a "lowest possible" bound on a C-volume that was also strictly positive. Hence, it should not be possible to verify the inequality I presented in the third update using only the information we have available. However, playing around with proving special cases led me to notice that if we write out $V_{K_{a,b}}([u_{1}, u_{2}]\times [v_{1}, v_{2}])$ in a particular manner, the solution presents itself quite nicely. Write all the four terms associated with $u_{i}, v_{j}$, where $i=1,2, j=1,2$, in one row for each pair $i,j$. Visually, this gives a $4\times 4$ matrix. One may now notice that each column of the matrix represents a C-volume. More specifically, one can write
\begin{align}
V_{K_{a,b}}([u_{1},u_{2}]\times [v_{1},v_{2}]) &= V_{C}([u_{1}+a(1-u_{1}), u_{2}+a(1-u_{2})]\times [v_{1}+b(1-v_{1}), v_{2}+b(1-v_{2})]) \\
&+ V_{C}([u_{1}+a(1-u_{1}), u_{2}+a(1-u_{2})]\times [b(1-v_{2}), b(1-v_{1})]) \\
&+ V_{C}([a(1-u_{2}), a(1-u_{1})]\times [v_{1}+b(1-v_{1}), v_{2}+b(1-v_{2})]) \\
&+ V_{C}([a(1-u_{2}), a(1-u_{1})]\times [b(1-v_{2}), b(1-v_{1})]) \\
&\geq 0
\end{align}
because each C-volume is non-negative due to $C$ being a copula.


MySql - Create a view with longtext cast into VARCHAR(255)

Question: I am willing to create a view on a table with a longtext column. But I would like that in my view this column be varchar(255). And Yes I would like to cut the "extra" text.
When I do a substr in the create script the data type is still longtext
Anyone could help me ?
Thanks
Answer: How about casting the longtext as a varchar?
<code> CREATE VIEW foo AS
 SELECT ID, CAST(MyLongText as char(255)) AS MyVarchar
 FROM Table
</code>
Comment: This is not a syntax that MySql known. Thanks anyway
Comment: @Samuel: oops, should be `char`. Corrected in the answer.


mongoose populate shows schema hasn't been registered for model populate

Question: created mongoose schema called movie with property of object reference to another collection of created by multer-gridfs storage but when called populate method i got null on fileID
The schema is

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const MovieSchema = new Schema({
    description: String,
    category: String,
    token: String,
    fileID: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'fs' //created by multer gridfs storage
    }
});

const Movie = mongoose.model('Movies', MovieSchema);

module.exports = Movie;

const express = require('express');
const multer = require('multer');
const path = require('path')
const router = express.Router();
const Movie = require('../models/Movie');

const GridFsStorage = require('multer-gridfs-storage');

const storage = new GridFsStorage({
    url: 'mongodb://127.0.0.1:27017/kannywoodtv-dev',
    file: (req, file) => {
        return {
            filename: req.body.name + path.extname(file.originalname)
        };
    }
});
const upload = multer({
    storage
});

router.post('/', upload.single('file'), (req, res) => {
    console.log(req.file)
    const movie = new Movie({
        description: req.body.Description,
        category: req.body.Category,
        token: req.body.Description,
        fileID: req.file.id
    });
    console.log(movie)
    movie.save(function(err) {
        if (err) {
            console.log(err);
            return;
        }

        res.json({
            "success": "true"
        });
    });

});

router.get('/movies', (req, res) => {
    Movie.find()
        .populate('fileID')
        .then(files => {
            res.send(files)
        }).catch(err => {
            res.send(err)
        })

})

module.exports = router;

fileID return when null when i called populate but return the objectsID of the field i reference if i remove populate
Comment: Did yypu try `.populate('fileID').exec()`?
Answer: add this line in your movieSchema
const Movies = mongoose.model('Movies', MovieSchema);
module.exports = { Movies };

and import it as
const { Movies } = require('../models/Movie');


Embed PHP into HTML

Question: I'm trying to use PHP to print out  values for my select statements but I can't get it to work. I've even tried just to print something out in my html with php, but i can't even seem to do that. Can anyone tell me what's wrong with this

    <?php echo "register Student:"; ?>

Comment: What's the name of the file?
Answer: Make sure you save your file as .php not .html.
myfile.php:

    <?php echo "register Student:"; ?>

You will also need to run this file on a server that has php installed. It won't run directly in the browser like an .html file will.
Answer: Keep these things in mind.

Your file name should always end with .php extension not .htm or .html
You should always run file on localhost/ where you set up your environment
Please follow the standard of W3C Use a "li" in you "ul"

Hope it works.
Answer: Name your file whatever.php
Make sure it is NOT whatever.html
If that doesn't work, be sure to check whether or not you installed php. I suggest a local testing ground such as XAMPP. If you don't want to do that, upload it to a free or paid hosting service.

Embed PHP into HTML


Send mail with Data Selector

Question: In Drupal 9 Rules 8.x alpha 7 - I have a rule working. However, I am trying to send an email to the user of the account that is changed.
I am trying to figure out the data selector to make this happen. I have tried token for an email: {{ profile.uid.entity.mail }}
I have tried profile.uid.entity.mail.value as a data selector and many other things I am finding online.
I have Entity is of Bundle and Field is of type in the conditions to grab the field in the user account.
If I put in a specific email it works. Anyone figure out the data selector for this?
Answer: Okay, it took a while but I got it to work. I am using the Profile module with the Drupal account. This rule is on Profile update.
In the Condition: you need 'Entity is of Type' - data_selector = profile, and value = profile
Then you need 'Entity has field' with data_selection = @user.current_user_context:current_user
and value as 'mail'
Than...You create an Action "send Mail' - in the Send to: direct input I used this {{ profile.uid.entity.mail }}
Added a message and tested.
It works!!!
Hope that helps someone.

Send mail with Data Selector


documenting private methods in ruby rails

Question: I can use rdoc to generate Darkfish documentation for rails code including my private methods, as in

rdoc app --all

but when I use the built in rake task:

bin/rake doc:app

it won't accept the "--all" option.
Is there an option for this?
Answer: I don't know how to pass the --all option to the rake task, a workaround is to add #:doc: to your private methods:
def some_private_method #:doc:
  ...
end


SQL Order By using multiple columns

Question: I have tried to look up for an answer here and outside, but can't seem to find a clear answer.
If we have this statement #1:
Select <columns>
From

Order By Column1 Desc, Column2 Desc

And this statement #2
Select <columns>
From

Order By Column1, Column2 Desc

In my opinion when you use #2, SQL sorts by Column1 in an ascending order and then by Column2 in descending order, while #1 sorts by both columns in a descending way. Am I correct?
I tried both in a query and the result was completely different, and fits my opinion... but I might still be wrong.
It's a long story but I don't understand why my app is generating the statement #1 instead of #2; it may be a platform bug which I need to report.
Comment: This is correct. `ASC` is implicit in an `ORDER BY` clause.
Answer: Yes, you are right.
The #2 way is the same as 'Order by Field1 asc, Field2 Desc'
Please note that it will order by Field1 before Field2.

SQL Order By using multiple columns


Manage computer from active directory manager

Question: Within dsa.mac when I right-click on a computer and choose "Manage", it displays the following error message:

Can't find path to computer \\computer.domain.tld.

If I try ping computer.domain.tld, DNS translates it to an IP but the computer does not answer.  It is right that ping does not answer?  Pinging a computer that is not joined to the domain replies as expected.
How can I correct this issue?
Comment: You're question is not clear it needs to be reworded. BTW, don't rely on ping as an indication that a service is up or not, most firewalls block ICMP PING these days.
Comment: I post image, but is in czech language, hope it hepls
Comment: It sounds like your Windows Firewall's Domain Profile does not allow ICMP or Windows management, or the client is offline. Can you post info about the firewall config?  Specifically, the Domain Profile.
Comment: If I try to disable firewall, then it works. What rule I must to allow when I whant to enable firewall?
Answer: Your question isn't really clearly worded, but my guess would be that the PC you are trying to connect to is either off, unplugged from the LAN, or your ping ICMP packets are being blocked (either from a firewall on the workstation, or some other network device).
I would start by checking the PC's physical connection, then verify it's logical connection to the network.
A pretty standard pattern of tests to perform from the PC consist of:

Ping the loopback address (IPv4 = 127.0.0.1; IPv6 = ::1) to test the NIC
Ping the PC's IP Address to test TCP/IP Stack
Ping the Default Gateway or another IP on the same subnet to verify L2
Ping an IP on another subnet to verify L3
Ping a known PC name or the domain name to verify DNS
Comment: If I try to disable firewall, then it works. That means I must allow something on client pc firewall. Any Idea what allouw by group policy?


xterm smooth sizing

Question: How do I configure xterm to resize smoothly and not by character increments?
Or is there another teminal app that will resize smoothly?
Comment: This question doesn't belong on serverfault. It's asking about how to make cosmetic customizations of an app that runs on your desktop.
Comment: sorry for that then, wasn't sure if it falls under stack overflow. It's a configuration issue, so I figured it falls under server fault more. My bad :(
Comment: It wouldn't belong on StackOverflow, but on SuperUser.
Answer: Sorry. xterm even tells xwindows that it's a char-cell sized app. And I don't think smoothly sized terms are very common either. (I don't see the point either, it's a very char based system, from teletypes onward..)
Comment: Of course, if you're willing to look for extremely perverse hackish solutions, those might exist. I know there's a program called 'blast' that installs and messes with a transparency bitmap for other programs' windows...
Comment: I have done it before with out allot of hacking. The reason is the tiling window manager gives xterm its space, but xterm only size to the characters, so most of the time there is a 2 pixel gap between it and the other windows.
Comment: This is typically why tiling window managers allow you to decide whether to obey applications "resize hints".  If you tell the WM to ignore those hints, then you applications like xterm can be sized however you want.
Answer: Have you tried konsole?  It resizes smoothly, if I understand your question correctly.

xterm smooth sizing


gdb can't insert a breakpoint when attach to a process

Question: I'm trying to attach gdb to a program started by socat like this:
socat TCP-LISTEN:5678,reuseaddr,fork EXEC:./test

In another terminal,
sudo gdb
attach `pidof socat`
br *0x080487D4

when execute continue command in gdb, it shows error like this:
Warning:
Cannot insert breakpoint 1.
Cannot access memory at address 0x80487d4

Command aborted.

0x080487D4 is in .text of test program. The follow-fork-mode of gdb is child, I have searched online but still can't solve it.
I debugged program successfully like this way a month ago, and don't know why it doesn't work now. But it's ok if debug the program directly using gdb like this:
gdb -q ./test

However, the way above doesn't meet my needs.
Through debugging, I think gdb expects that address is a valid address in the socat rather then test program. So how can I set breakpoints in test program? Without breakpoints in test program, it will run directly to the end when execute continue command. Setting breakpoints in socat program is useless.
Any advice? Thanks in advance.
Comment: How are you determining that that address is the correct address?  I don't see anything that you are doing to determine where `socat` has been mapped in memory.  Are you compiling as PIE code?
Comment: Why do you think you need sudo?
Comment: @DavidHoelzer, Thanks your reply.  The address is obtained from Ida pro when decompile `test` program, not related to `socat`. When a process forks with socat, gdb will follow the child process `test`, so I set a breakpoint on that address.  Should I set a breakpoint in `socat` rather then `test` program?
Comment: @sigjuice. Sometimes it would fail to attach to the process without `sudo`.  Even without `sudo`, the problem still exists.
Comment: Either you need sudo all the time or you do not at all.   Using sudo unnecessarily is likely to cause other problems.
Comment: @sigjuice I tried both using sudo and not just now. The problem still exists. I really don't know how to deal with it. Maybe try to test with another computer. Anyway, thank you.
Comment: When you say _it worked a month ago_, was it the same `test` executable and the same address `0x080487D4`?
Comment: The executable is the same, but the address is slighly different. Any other debug method recommend?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/138398/discussion-between-sigjuice-and-cq674350529).
Answer: I have figured out how to set breakpoints in test program.
When start test program using socat, it won't fork a test process until a socket connection comes. So trying to set breakpoints directly in test program fails.
I use a tool(for my purpose, choose pwntools) to connect to it and suspend it ,then use gdb to attach to the forked test process. Next, I can debug normally.
Any better ideas? Thanks in advance.


Por que o ponto é substituído por vírgula ao enviar o Sqlcommand do c# ao banco de dados?

Question:
Perceba que na primeira imagem o valor ainda está correto: 150.45
O problema é que quando envio o comando ao banco de dados o ponto é substituido por virgula, na segunda imagem eu capturei o comando pelo SQL Server Profiler e podemos notar que o ponto realmente foi substituido por virgula. Como posso resolver isso?
Answer: Acabei descobrindo como resolver o problema, vou compartilhar aqui talvez ajude outra pessoa.
<code>var cmdText = ($@"INSERT INTO PESSOASERVICOPRESTADO (CODPESSOA, DESCRICAOSERVICO,
VALORTOTAL, VALORPAGO, PAGO, DATASERVICO ) VALUES ({servico.CodPessoa},
'{servico.DescricaoServico}',
{servico.ValorTotal.ToString(CultureInfo.InvariantCulture)},
{servico.ValorPago.ToString(CultureInfo.InvariantCulture)}, '{servico.Pago}'
,'{servico.DataServico}')");
</code>
Basta adicionar o seguinte código ao comando SQl:
        ToString(CultureInfo.InvariantCulture),
dessa forma o Sql server ignora a configuração de região e manda a instrução com o ponto ao invés de trocar por virgula que causaria problema.


how many taxonomies i should use?

Question: there are different content types and associated with different taxonomies. for example forum content type associated forum taxonomy, article content type is associated with tag taxonomy and gallery content type is associated with gallery taxonomy. i want to show related contents in front page blog, but taxonomies different. how can i associate them? with using only one taxonomy for all content types or else?
Answer: Forum and Gallery taxonomies are used to maintain the information structure of their respective content types. They should not be mixed.
A tagging taxonomy, on the other hand, is generally freestyle, and allows a user to give keywords describing the content. There is no reason to restrict it to a single content type. Why not use your tags on all content types.
Comment: i don't understand "Why not use your tags on all content types".  do i only use tag taxonomy for all content type and not use forum and gallery taxonomies? can you open it some little more...
Comment: You need all three taxonomies! The tag vocabulary can be used on all content type. The Forum is NEEDED for your forum type, and the Gallery vocabulary for the gallery type.
Answer: Taxonomy fields, like any field, may be attached to multiple content types. It sounds like the view you're displaying on your home page needs to draw from one taxonomy. Therefore, your options are to use one taxonomy across all of the content types, or to build a different view with a better way to implement your concept of "related content."
Comment: according to your comment, i don't need multiple taxonomies. only one taxonomy is enough to make it. but what to do default taxonomies (tagging anf forum)?

how many taxonomies i should use?


"There is no css animation matching the one you specified" error from cut-and-paste dropdown example

Question: I'm using Semantic 1.4.1 (tried also with 1.6.1) and cut-n-pasted the dropdown example directly from the docs:

  <input type="hidden" name="gender">

Gender

Male

Female

I get the error
[Error] Transition: There is no css animation matching the one you specified. slide down in
    error ([native code], line 0)
    error (semantic.js, line 15438)
    animate (semantic.js, line 15438)
    initialize (semantic.js, line 15438)
    (anonymous function) (semantic.js, line 15438)
    each (jquery-1.7.1.min.js, line 2)
    each (jquery-1.7.1.min.js, line 2)
    transition (semantic.js, line 15438)
    show (semantic.js, line 4432)
    show (semantic.js, line 4432)
    focus (semantic.js, line 4432)
    dispatch (jquery-1.7.1.min.js, line 3)
    i (jquery-1.7.1.min.js, line 3)

and the menu doesn't drop down.  Tried this on both Safari and Chrome (on OSX).
I'm building 1.4.1 and 1.6.1 from src using gulp build.
Any ideas?
Answer: Turns out, it was having the creaky old jquery-1.7.1.  Once I upgraded to jquery-1.11.2 (with the migration tool as well), the HTML worked on my site the same way it works on the doc site.
Answer: Also try to add prefixes -webkit- to transition.less.
You can use the less autoprefixer to automatically add prefixes to css.


Question about Casella and Berger's proof of MLE invariance

Question: In Casella and Berger, p. 320, they have a proof of the invariance of the MLE. Let $g: \theta \mapsto \eta$ be a function. They define the induced likelihood as
$$
L^*(\eta \mid X) = \sup_{\{\theta: g(\theta) = \eta\}} L(\theta \mid X).
$$
This ensures that $g$ is one-to-one with respect to the likelihood functions because if $g$ is not one-to-one, there may be multiple values of $\theta$ that map to a given $g(\theta) = \eta$.
Then they note
$$
\sup_{\eta} L^*(\eta \mid X)
=
\sup_{\eta} \sup_{\{\theta: g(\theta) = \eta\}} L(\theta \mid X)
=
\sup_{\theta} L(\theta \mid X).
$$
The first equality just applies the definition of the MLE of $\eta$. However, the next inequality confuses me. They write,

The second inequality follows because the iterated maximization is equal to the unconditional maximization over $\theta$...

Can someone justify this claim or provide some intuition if the claim is supposed to obviously follow from definitions?
Comment: You're reading way too much into this.  The statement is an arithmetic triviality.  If you divide the domain of a function into pieces, find its largest value on each piece, and then take the largest of those largest values, you will have found the largest value of the function.
Answer: The occurrences of suprema (instead of maxima, which might not exist) are troublesome.  Let us therefore isolate the basic underlying idea and rigorously establish it.
Definitions
Suppose $f:\Theta\to\mathbb{R}$ is any real-valued function on a set $\Theta.$  By definition, its supremum is the least upper bound of the values of $f:$
$$\sup_{\theta\in\Theta} f(\theta) = \operatorname{lub}\, \{f(\theta)\mid \theta\in\Theta\}.$$
As a shorthand, I will write $f^{*}_\Theta$ for this supremum.
The least upper bound of a set of real numbers $\mathcal A,$ written $\operatorname{lub}\,\mathcal A,$ is a number $x\in \mathbb{R}\cup \{\pm\infty\}$ (having the obvious ordering relation) with two defining properties (which, according to the axioms of Real numbers, make it unique):

For all $a\in\mathcal A,$ $a \le x.$

If $y$ is any number in $\mathbb{R}\cup \{\pm\infty\}$ satisfying (1), then $y \ge x.$

The Underlying Idea
Let $\Theta= \bigcup_{\mathcal A \in \mathbf{A}} \mathcal A$ be a union of sets.  For each such $\mathcal A$ let $f_{\mathcal A}$ be the restriction of $f$ to $\mathcal A.$  The claim is

$$\sup_{\mathcal A \in \mathbf{A}} f^{*}_{\mathcal A} = f^{*}_\Theta.$$

This is demonstrated in two steps.
First, when we assemble a bunch of suprema of $f$ over subsets of $\Theta,$ they cannot exceed the supremum of $f$ on $\Theta.$  Indeed, consider a set $\mathcal A\in \mathbf A.$ Because $\mathcal A$ is a subset of $\Theta,$ none of its elements exceed $f^{*}_\Theta.$ Consequently (by part (2) of the definition) $f^{*}_{\mathcal A} \le f^{*}_\Theta.$ A fortiori, $f^{*}_\Theta$ is an upper bound of all the $f^{*}_{\mathcal A},$ proving that
$$\sup_{\mathcal A \in \mathbf{A}} f^{*}_{\mathcal A} \le f^{*}_\Theta.\tag{*}$$
Second, let $y$ be an upper bound for all the $f^{*}_{\mathcal A}$ and let $\theta\in\Theta.$ Because $\Theta= \bigcup \mathcal A,$ there exists an $\mathcal A$ for which $\theta\in\mathcal A.$ Because $y \ge f^{*}_{\mathcal A},$ $y \ge \theta.$  Therefore (by part (2) of the definition), $y \ge f^{*}_\Theta.$  Because all upper bounds of the $f^{*}_{\mathcal A}$ exceed $f^{*}_\Theta,$
$$\sup_{\mathcal A \in \mathbf{A}} f^{*}_{\mathcal A} \ge f^{*}_\Theta.\tag{**}$$
The statements $(*)$ and $(**)$ prove the claim.
Application to Maximizing Likelihoods
The likelihood $\mathcal L$ is a function on a set $\Theta$ of distributions.  (I drop the reference to the data $X$ because $X$ will never change during this discussion.)  Given another function $g$ on this set, $\Theta$ can be expressed as the union of its level sets,
$$\Theta = \bigcup_{\eta\in\mathbb R} g^{-1}(\eta) = \bigcup_{\mathcal A \in \mathbf A} \mathcal A$$
where $\mathbf A$ is this collection of level sets.  In terms of the notation used in the question, our previously proven claim is the middle equality in
$$\sup_{\eta\in\mathbb R} \mathcal L^{*}(\eta) =\sup_{\eta\in\mathbb R} \mathcal L^{*}_{g^{-1}(\eta)} = \mathcal L^{*}_\Theta = \sup_{\theta\in\Theta}\mathcal{L}(\theta),$$
precisely as stated in the question.
Conclusions
This relationship between the "induced likelihood" and likelihood has nothing whatsoever to do with properties of likelihood, random variables, or anything else statistical: it is purely a statement about upper bounds of values attained by a function on a set.  The least upper bound can be defined with respect to the entire set $(\mathcal{L}^{*}_\Theta)$ or it can be found in stages by first taking the least upper bounds of subsets of the set $(\mathcal{L}^{*}_{g^{-1}(\eta)})$ and then finding the least upper bound of those upper bounds.
Comment: Thank you for the clarification. I wasn't aware of this notation / am used to a different notation for level sets but this one also makes sense to me since a level set is the preimage of a singleton under a function. I would probably denote this by $g^{-1}\left(\left\{ \eta\right\} \right)$ but now that I've thought about it it's clear what $g^{-1}\left(\eta\right)$ refers to.
Btw +1 for this nice exposition.
Comment: Is $\bigcup_{\eta\in\mathbb{R}}g^{-1}(\eta)$ a shorthand notation for $\bigcup_{\eta\in\mathbb{R}}\left\{ \theta\in\Theta:g(\theta)=\eta\right\}$?
Comment: @stat Yes, the definition of the level set is that $g^{-1}(\eta)=\{\theta\in\Theta\mid g(\theta)=\eta\}.$