Filtrar imagens por categoria com Checkbox AngularJS

Question: Preciso filtrar HOMEM e MULHER. Na lista de filtro, aparecem 4 itens, sendo que deveria aparecer somente 2(homem e mulher), ou seja, por categoria.
Outro problema é que o filtro é por ng-show="picture.checked" e isso me trás somente 1 imagem por check, preciso que venha POR CATEGORIA, ou seja, quando eu clicar em mulher aparecer duas imagens, pois há duas imagens de mulher com a mesma categoria e o mesmo vale para o homem.
O que já tenho:

angular.module('ionicApp', ['ionic'])

.controller('MainCtrl', function($scope) {

  $scope.devList = [
     { categoria: "mulher", img: "http://extra.globo.com/incoming/14942281-f88-b8b/w448/Elisabeth-Reyes-mulher-Sergio-Sanchez.jpg" },
    { categoria: "mulher", img: "http://extra.globo.com/incoming/14942281-f88-b8b/w448/Elisabeth-Reyes-mulher-Sergio-Sanchez.jpg" },
    { categoria: "homem", img: "http://dicasmodafeminina.com/wp-content/uploads/2012/08/qualidades-de-homem-ideal-autoconfianca.jpg" },
    { categoria: "homem", img: "http://dicasmodafeminina.com/wp-content/uploads/2012/08/qualidades-de-homem-ideal-autoconfianca.jpg" }
  ];

  $scope.pushNotificationChange = function() {
    console.log('Push Notification Change', $scope.pushNotification.checked);
  };

  $scope.pushNotification = { checked: true };
  $scope.emailNotification = 'Subscribed';

});
body {
  cursor: url('http://ionicframework.com/img/finger.png'), auto;
}

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">

    <title>Checkboxes</title>

    <link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">

    <ion-header-bar class="bar-positive">

Checkboxes

    </ion-header-bar>

    <ion-content>

        <ion-checkbox ng-repeat="item in devList"
                      ng-model="item.checked"
                      ng-checked="item.checked">
          {{ item.categoria }}
        </ion-checkbox>

    </ion-content>

Comment: Alguém para ajudar?
Answer: Olá, refiz seu código adicionando uma lib e criando um filtro para resolver os dois problemas.

angular.module('ionicApp', ['ionic','angular.filter'])

.controller('MainCtrl', function($scope) {
  $scope.filtro = [];
  $scope.devList = [
    { categoria: "mulher", img: "http://extra.globo.com/incoming/14942281-f88-b8b/w448/Elisabeth-Reyes-mulher-Sergio-Sanchez.jpg" },
    { categoria: "mulher", img: "http://extra.globo.com/incoming/14942281-f88-b8b/w448/Elisabeth-Reyes-mulher-Sergio-Sanchez.jpg" },
    { categoria: "homem", img: "http://dicasmodafeminina.com/wp-content/uploads/2012/08/qualidades-de-homem-ideal-autoconfianca.jpg" },
    { categoria: "homem", img: "http://dicasmodafeminina.com/wp-content/uploads/2012/08/qualidades-de-homem-ideal-autoconfianca.jpg" }
  ];

  //função utilizada no filter do ng-repeat
  $scope.devListFilter = function () {
    return $scope.devList.filter(function (item) {
      return $scope.filtro.indexOf(item.categoria) !== -1;
    });
  };
  $scope.pushNotificationChange = function() {
    console.log('Push Notification Change', $scope.pushNotification.checked);
  };

  $scope.pushNotification = { checked: true };
  $scope.emailNotification = 'Subscribed';

});

 <meta charset="utf-8">
 <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">

 <title>Checkboxes</title>

 <link href="http://code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
 <link href="style.css" rel="stylesheet">

 <ion-header-bar class="bar-positive">

Checkboxes

 </ion-header-bar>

 <ion-content>

   <ion-checkbox ng-repeat="(key, value) in devList | groupBy:'categoria' track by $index"
       ng-model="filtro[$index]" ng-true-value="{{key}}" ng-false-value=""
       ng-checked="check">
    {{ key }}
   </ion-checkbox>

 </ion-content>

Comment: Sabe fazer com que esses check fiquem true e as imagens surjam na tela logo de cara para o usuário?
Comment: javascript:
$scope.filtro = []; -> $scope.filtro = ["homem","mulher"];

html:
ng-checked="checked" -> ng-checked="true"
Answer: Tente usar isso:
ng-repeat="picture in devList | filter:item.checked as results"

Dica: você pode deixar o trecho "as results" opcional para reutilizar os resultados, mais o filter:item.checked é o que você esta querendo.


Is there a Brainfuck API?

Question: So I stumbled upon a Brainfuck question, and I wondered, do any of its compilers/interpreters provide an API?

I'll make a separate question about accessing other APIs.
Comment: I do not think some interpreters have some, but brainfuck is simple to implement and you could add functionality to other characters other than the 8 characters.
Comment: Your question is actually, "Are there any libraries written for brainfuck", there's no API until there's something to interface with. Any general-purpose programming language has the potential to interface with any filesystem API, operating-system API, graphics API, network API. Your question doesn't really make sense.
Comment: @OregonTrail _Any general-purpose programming language has the potential..._ It does if the language allows at least access to portions of memory where the potential system API resides
Comment: Here's the other question: [does-some-brainfuck-compiler-intepreter-provide-a-mean-to-access-an-api](https://stackoverflow.com/questions/45740929/does-some-brainfuck-compiler-intepreter-provide-a-mean-to-access-an-api)
Comment: Damn this turned out to be a much more serious question than I thought..
Answer: In pure Brainfuck, there won't be anything, unless you write your own interpreter that uses specific chunks of memory for this.
One project that may interest you is ajyoon/systemf, an interpreter where you can make Linux system calls using a special ninth character.
EDIT: I ended up answering the wrong question of the asker, this is more an answer to the other one.
Comment: Great, this answers at lease for sure my other question!
Comment: I'll wait a day or two, then I'll accept this answer if nothing else comes up.
Comment: _I ended up answering the wrong question_ At this point I'd say you answered this question as well, as nothing else has come up I guess you're right that "there won't be anything".

Is there a Brainfuck API?


IV-estimation vs. Heckman's selection model

Question: I am trying to grasp the difference between IV-estimation and Heckman's selection model.
I do that by considering the following set-up. My outcome if interest is y (I observe it for all observations, incidental truncation is not the problem here!). I have an endogenous binary treatment variable w. Also, I have a binary control function x. Finally, I have an instrument z for my binary treatment variable w. I know how to use instrumental variables, but I have a hard time understanding Heckman's selection model in this case. The first stage should be a probit model, where I regress w on x and z. But I don't understand how my second stage is defined and which assumptions it relies on. I would like to know how to estimate both the average treatment effect and the average treatment effect on the treated. And also how the exclusion restriction kicks in (including or not including z in the second stage).
Hope that someone can provide intuition.
Comment: You might find usefull Heckman, Urzua, and Vytlacil .(2006). Understanding instrumental variables in models with essential heterogeneity. The Review of Economics and Statistics.
Comment: What do you mean by "binary control function"?
Answer: 1)The intuition of Heckman's model: there are two states of the world and a cost of choosing one of the states. The outcome variable in each state and the cost function have unobservables (error terms). The researcher only observes the data of one of the states, but cannot observe both states for the same unit.
2) The procedure: a) estimate a propensity score for each group of the data i.e. treated and untreated units. Under the assumption of joint normality of the unobservables, use a probit. Without curvature assumptions, use non-parametric estimation. With normality assumptions, you do not need an exclusion restriction (you may need it because of economic arguments). To use non-parametric estimation, you need the exclusion restrictions. b) For each group of variables, regress the outcome variables against the observables and the correction terms. With the abovementioned normality assumptions, those terms are the inverse Mills ratios which are a function of the propensity scores.
3)Average Treatment Effect: use the difference between the parameters of the outcome equations of the second step.
You might find usefull Heckman, Urzua, and Vytlacil .(2006). Understanding instrumental variables in models with essential heterogeneity. The Review of Economics and Statistics.


Store 3 signed floats (from -4 to 4) for each pixel of a 32 bit texture (R11F_G11F_B10F)

Question: Encoding
As part of a graphical application I'm currently working on, I need to store three signed floats per each pixel of a 32 bit texture. At the moment, to reach this goal, I'm using the following C++ function:
void encode_full(float* rgba, unsigned char* c) {
    int range = 8;
    for (int i = 0; i < 3; i++) {
        rgba[i] += range / 2;
        rgba[i] /= range;
        rgba[i] *= 255.0f;
        c[i] = floor(rgba[i]);
    }
    c[3] = 255;
}

Although this encoding function brings along a considerable loss in precision, things are made better by the fact that the range of considered values is limited to the interval (-4,4).
Nonetheless, even though the function yields decent results, I think I could do a considerably better job by exploiting the alpha channel (currently unused) to get additional precision. In particular I was thinking to use 11 bits for the first float, 11 bits for the second, and 10 bits for the last float, or 10 - 10 - 10 - 2 (unused). OpenGL has a similar format, called R11F_G11F_B10F.
However, I'm having some difficulties coming up with an encoding function for this particular format. Does anyone know how to write such a function in C++?
Decoding
On the decoding side, this is the function I'm using within my shader.
float3 decode(float4 color) {
    int range = 8;
    return color.xyz * range - range / 2;
}

Please, notice that the shader is written in Cg, and used within the Unity engine. Furthermore, notice that Unity's implementation of Cg shaders handles only a subset of the Cg language (for instance pack/unpack functions are not supported).
If possible, along with the encoding function, a bit of help for the decoding function would be highly appreciated. Thanks!
Edit
I've mentioned the R11F_G11F_B10F only as a frame of reference for the way the bits are to be split among the color channels. I don't want a float representation, since this would actually imply a loss of precision for the given range, as pointed out in some of the answers.
Comment: Can you please clarify if you want to pack them as 11 bit ints or 11 bit floats? In your example code you convert the floats to ints, but R11F_G11F_B10F stores packed floats.
Answer: I think using GL_R11F_G11F_B10F is not going to help in your case. As the format name suggests, the components here are 11-bit and 10-bit float numbers, meaning that they are stored as a mantissa and exponent. More specifically, from the spec:

An unsigned 11-bit floating-point number has no sign bit, a 5-bit exponent (E), and a 6-bit mantissa (M).
An unsigned 10-bit floating-point number has no sign bit, a 5-bit exponent (E), and a 5-bit mantissa (M).

In both cases, as common for floating point formats, there is an implicit leading 1 bit for the mantissa. So effectively, the mantissa has 7 bits of precision for the 11-bit case, 6 bits for the 10-bit case.
This is less than the 8-bit precision you're currently using. Now, it's important to understand that the precision for the float case is non-uniform, and relative to the size of the number. So very small numbers would actually have better precision than an 8-bit fixed point number, while numbers towards the top of the range would have worse precision. If you use the natural mapping of your [-4.0, 4.0] range to positive floats, for example by simply adding 4.0 before converting to the 11/10-bit signed float, you would get better precision for values close to -4.0, but worse precision for values close to 4.0.
The main advantage of float formats is really that they can store a much wider range of values, while still maintaining good relative precision.
As long as you want to keep memory use at 4 bytes/pixel, a much better choice for you would be a format like GL_RGB10, giving you an actual precision of 10 bits for each component. This is very similar to GL_RGB10_A2 (and its unsigned sibling GL_RGB10_A2UI), except that it does not expose the alpha component you are not using.
If you're willing to increase memory usage beyond 4 bytes/pixel, you have numerous options. For example, GL_RGBA16 will give you 16 bits of fixed point precision per component. GL_RGB16F gives you 16-bit floats (with 11 bits relative precision). Or you can go all out with GL_RGB32F, which gives you 32-bit float for each component.
Answer: "10 bits" translates to an integer between 0 and 1023, so the mapping from [-4.0,+4.0] trivially is floor((x+4.0) * (1023.0/8.0)). For 11 bits, substitute 2047.
Decoding is the other way around, (y*8.0/1023.0) - 4.0.
Comment: The numbers in question here are 11/10 bit floats, not integers.


Convert nested dictionary to create String Swift

Question: I have a dictionary which contains key and items model for the values.
 var selectedDic: [String: [Item]] = [:]

Actually I am trying to make a string with dictionary key and key has multiple value separated by comma.
And if I add more values to key it should add values to specific key.
price and publisher are keys and itemId is the value.

I need this string: price:10-25;publisher:576,925,1737
Dictionary Print:
[
  "price": [
    Babil.Item(name: Optional("10 - 25"),
    itemId: Optional("10-25"))
  ],
  "publisher": [
    Babil.Item(name: Optional("ABCD"),
    itemId: Optional("576")),
    Babil.Item(name: Optional("DEFG"),
    itemId: Optional("925")),
    Babil.Item(name: Optional("HIJK"),
    itemId: Optional("1737"),
    )
  ]
]

My code:
 var itemString: [String: String] = [:]
 var str: [String] = []

   for (key, value) in selectedDic {
            value.forEach { a in
                if str.firstIndex(of: key) == nil {
                    str.append(a.itemId!)
                }
            }

            let final = str.joined(separator: ",")
            itemString.updateValue(final, forKey: key)

        }

Comment: `let priceStr = itemString["price"]?.compactMap{ $0.name }.joined(separator: ","); let publisherStr = itemString["publisher"]?.compactMap{ $0.itemId } .joined(separator:",");
let finalStr = [priceStr, publisherStr].compactMap{ $0 }.joined(separator: ";")` or something like that? But it would help to know what's your current output, can there be more than one price? Why use a Dict and not another custom struct? Why `name` AND `itemId` are BOTH optional in `Item`? Is that normal?
Comment: @Larme Thank you first of all. But before creating string it duplicates value to other keys as well.  see - `["price": "10-25", "publisher": "10-25,576,925,1737"] `   10-25 in publisher too.
Answer: With:
struct Item {
    let name: String?
    let itemId: String?
}

let dict: [String: [Item]] = ["price": [Item(name: "10-25", itemId: "10-25")],
                              "publisher": [Item(name: "ABCD", itemId: "576"),
                                            Item(name: "DEFG", itemId: "925"),
                                            Item(name: "HIJK", itemId: "1737")]]

You could use:
var keys = ["price", "publisher"]
let reduced = keys.reduce(into: [String]()) { result, current in
    guard let items = dict[current] else { return }
    let itemsStr = items.compactMap {$0.itemId }.joined(separator: ",")
    result.append("\(current):\(itemsStr)")
}
let finalStr = reduced.joined(separator: ";")
print(finalStr)

The idea:
Iterate over the needed keys (and order guaranteed), construct for each keys, the itemsIds list joined by "," and then append that with the key.
Finally, joined all that.
Add-on questions:
Why is name and itemId optional? Is that normal?
Site note: giving the first part (easily reproducible input) can increase the change of answers, so we don't have to recreate ourselves fake data to check our answers.
Comment: Thank you. `name` and `itemId` yes normal at the moment back end service are on initial phase.
Answer: Try this:
The order of the keys can be different since it is a dictionary and order isn't signficant in a dict
print(
    yourDict.map { (key, values) -> String in
        "\(key): \(values.compactMap { $0.itemId }.joined(separator: ","))"
    }.joined(separator: ";")
)


How to remove rows from a datatable after grouping variables?

Question: I have one data x with id, date, and details columns:
id date                 details
1  28-07-2017 20:01:30  NA
2  28-07-2017 18:01:30  NA
1  28-07-2017 22:02:20  SQL
2  28-07-2017 19:01:30  SQL
1  29-07-2017 22:20:00  NA
3  30-07-2017 18:01:30  NA
3  31-07-2017 18:01:30  SQL
4  28-07-2017 18:01:30  NA

I want my data look like this:
id date                 details
1  28-07-2017 20:01:30  NA
1  28-07-2017 22:02:20  SQL
2  28-07-2017 18:01:30  NA
2  28-07-2017 19:01:30  SQL
3  30-07-2017 18:01:30  NA
3  31-07-2017 18:01:30  SQL
4  28-07-2017 18:01:30  NA

I want to group data x on the basis of id, then sort date in ascending order, then if there is a "SQL" value in the details column then delete the below rows of same id. There should be no records on each id once SQL stage arrives in details variable.
How can I do this in R?
Comment: Could you add a [reproducible example of the data?](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)
Answer: Use dput to convert your data into something that we can work with. Here's a link to understand it: https://gist.github.com/dsparks/3688652
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/low-quality-posts/16888328)
Comment: The data was in an unusable form when I commented. The asker updated the question (making the data easier to understand), making my initial comment irrelevant.
Answer: Use the dplyr package along with magrittr. Here's a quick stab at it.
library("dplyr")
library("magrittr")
newdata <- olddata %>% group_by(id) %>% arrange (date) %>% filter(details !="SQL")


Where does surjectivity fail in a mapping from the unit interval to the Cantor Set?

Question: I'm asked to state why there cannot be a surjective and continuous function $$g: [0,1]\longrightarrow
\text{Cantor Set} $$
I know that $g^{-1}$ exists and is continuous & surjective since the previous exercise was for me to show exactly that.
Now I know that if $g$ were a bijection, then if $g$ were to be continuous, then it would be a homeomorphism and would have to preserve connectedness of $[0,1]$, which it doesn't, implying that $g$ cannot be continuous.
But this requires me to have a bijectivity of $g^{-1}$, where does surjectivity alone enter in this case?
Comment: Hint: connectedness (or its failure)
Comment: The continuous image of a connected space is connected. See [this](https://math.stackexchange.com/questions/2018848/proof-that-a-continuous-function-maps-connected-sets-into-connected-sets). More simply: otherwise, IVT would be violated.
Comment: OH I see, I don't need a homeomorphism for the image of a connected space to be connected, I only need continuity. Thanks!!!!
Answer: If $g: [0,1] \to C$ is continuous then $g[[0,1]]$ is connected. The only connected non-empty subsets of $C$ are of the form $\{c\}$ ($C$ is totally disconnected), so $g$ is constant.
Comment: and so it isn't surjective because it is defined as a map $[0,1]\longrightarrow C$ but there are elements of $C$ that are not images of a set in $[0,1]$ by $g$ $\Leftrightarrow$ non-surjectivity.
Thank you! This was very clear.
Comment: @TakenSpark $C$ is uncountable and you only have one point in the image. It doesn't get less surjective than that.


In a repeated measures model where assessments are performed over time, should baseline data be excluded if baseline covariate is used?

Question: In a model where subjects are evaluated over time and a baseline (time=0) covariate is used (eg, score ~ baseline + group + time + group*time), it seems that baseline data are often suggested to be excluded from the dependent variable (eg, score). But excluding baseline data would seem to decrease the model accuracy.
The above model is statistically equivalent to a change from baseline analysis (eg, change from baseline ~ baseline + group + time + group*time). If time = 0 is not excluded, then all groups have change from baseline of 0 at time = 0, and the argument is that the 100% homogeneity at time = 0 biases the results.
Answer: An additional point not mentioned in the other answers is that when you include the baseline measurement as a covariate into the model you assume a constant correlation of this measurement with all subsequent measurements, which most often is not logical to assume.
Comment: Agree with Dimitris and perhaps Erik is right, tho Model 2 in User158565's answer is the de facto standard in most clinical trials, which often correctly assume that the higher the baseline (up to a point where the disease is too severe to modify), the more likely the drug is to effect change from baseline over time. Conversely, the lower the baseline, the drug is less likely to have a large effect over time given proximity to the scale floor.
Comment: This is a very good point, Dimitris, and is another reason tcb2 may want to move over to an SEM framework if they are intent on including baseline in their model. In SEM one can test whether a model in which that correlation is constrained to be the same for all subsequent measurements is a better fit to the data relative to a model in which you freely estimate the correlation at each occasion.
Comment: In clinical trials we for this reason always include a baseline by time (as a factor) interaction. The model above would never be used.
Answer: The two main model that get used in practice for randomized controlled trials in this setting are fit to only the post-baseline time points (with time as a factor variable):
score ~ baseline + group + time + group*time + time*baseline
or
change in score ~ baseline + group + time + group*time + time*baseline
with an unstructured covariance matrix (often allowed to be different for each level of group). I'll outline reasons for the modeling choices below. Most software has good implementations of these so-called mixed models for repeated measures (MMRM): e.g. the mmrm package in R or using PROC MIXED in SAS/STAT.
The reasons for the modeling choices include

Using score or change in score is equivalent in this setting (it would e.g. not be if you didn't include baseline and baseline*time interaction in the model). You can do either and it makes no differences for between group comparisons.
If you modelled baseline as another timepoint, this could be an alternative (in which case you'd not include baseline + time*baseline in the model) as long as you use an unstructured covariance matrix. Through the correlations between visits such a model would end up doing similar (but not identical) things as adjusting for a linear baseline values. However, this makes much stronger multivariate-normal-residual distributional assumptions that are often heavily violated (e.g. baseline often has a truncated distribution due to inclusion/exclusion criteria, which really messes up the properties of the model). The two models are not equivalent, at all, without additional assumptions.
baseline tends to matter a lot for outcomes, but the less so the further away you are from the baseline (unsurprisingly there's usually a declining correlation of observations over time). That's why you really want a time*baseline term in addition to the main effects.
You cannot have  baseline + time*baseline as covariates and at the same time model the baseline, because the baseline value perfectly predicts the baseline value. I.e. describing it as a random quantity conditioning on its own value does not make sense.
time should be a factor, because you don't want to assume a linear curve over time, unless you have strong prior data that this would be so.
Answer: The advice is to not include lagged dependent variables as fixed effects predictors in a longitudinal mixed model. See here.* Technically, you are not doing that with your formulation, however I would still be careful with this. One workaround might be to switch to a structural equation modeling (SEM) framework, particularly if you have few time points. This would allow you to specify regression paths from your baseline score to each of the subsequent scores. The extent to which your theory is contingent on the baseline effect being present would determine whether the switch to SEM makes sense.
*It may be worth posting this question to Paul Allison in that blog post. I know from firsthand experience that Paul is very responsive to questions. If you do so, please report back on what he says!
Answer: You have 3 choices:
Model 1: score ~ group + time + group*time) including baseline measurement
Model 2: score ~ baseline + group + time + group*time) excluding baseline measurement
Model 3: (score - baseline)~ group + time + group*time) excluding baseline measurement
Of course, you need to incorporate the correlation of the error terms into the model indirectly by specifying random effect, or directly by specifying covariance matrix of error terms, both.
Comment: Model 2 is the question at hand. Why exclude baseline measurement?
Comment: Basically, one variable cannot be the response variable and covariate, even for part of the observations. Mixed model accepts unequal number of observations from subjects. Suppose 90% subjects only have baseline, then what will happen if baseline appears in both sides of model.


Cross-Origin Request Blocked error for get request API

Question: I have a problem with a fetch on an API, here is my code:
<code>const OPTIONS = {
  method: 'GET',
  headers: {
    'X-Auth-Token': process.env.FOOT_KEY,
  }
};

export async function setLeagues() {
  const countries = [
    {
      name: "Ligue 1",
      leagues_id: 2015
    },
    {
      name: "Premier League",
      leagues_id: 2021,
    },
    {
      name: "Bundesliga 1",
      leagues_id: 2002,
    },
    {
      name: "Primera Division",
      leagues_id: 2014,
    },
  ]

  let allLeagues = [];

  for (const country of countries) {
    const { name, leagues_id } = country;
    const response = await fetch(
      `http://api.football-data.org/v2/competitions/${leagues_id}`,
      OPTIONS
    );
    const data = await response.json();
    allLeagues.push(data);
  }

  return {
    type: "SET_LEAGUES",
    payload: allLeagues
  }
}
</code>
But I have a console error :

However when I make the request with postman the returned response contains well:
Access-Control-Allow-Origin: *.
Finally the error seems to be present only on firefox but not on chrome.
I try to fetch this API : football-data.org/docs/v2/index.html#_cors_handling, who is CORS enabled.
Thanks you for your help !
Comment: try adding CORS headers
Comment: Can you specify please ? ^^
Comment: You mean : mode: 'cors' ?
if, yes this is the default settings, and anyway i try but that don't work.
Comment: You probably want to update the question to make it clear that you know the documentation for that API indicates it's CORS-enabled. You can cite the URL for the part of the docs a https://www.football-data.org/docs/v2/index.html#_cors_handling. And given that the API is CORS-enabled, it's odd that you'd be getting a CORS error when calling it, and also odd that you'd only get the error in Firefox
Comment: In Firefox, what's the HTTP status code of the response? You can use the Network pane in browser devtools to check. Is it a 4xx or 5xx error rather than 200 OK success response?
Comment: Hi, thank you for your answers, there is no error in the network ... All the request have 200 state.
Comment: @Heretic Monkey, thanks for your answer but like the author says : "This question is not about how to fix a "No 'Access-Control-Allow-Origin'..." error". I looked at the link he offered but I found nothing relevant to my question.
Comment: I suggest you self-delete this question. Disabling AdBlock and other extensions is already a well-known and well-documented troubleshooting step for CORS errors. This question and the answer aren't really useful to future readers, because they don't add anything new to the existing knowledge in this area.
Comment: Ok it's really weird: The problem is actually not resolved. it worked for a while but without changing anything it caused me the same error and impossible to find the solution. Sometimes the fetch works and sometimes he doesn't and I have this error. However, my requests are always 200.
Answer: this might be more work, but when I had a similar issue this is what I used.
I would recommend using cors-anywhere. Essentially you would host your own version of the service and make your requests using cors-anywhere as a proxy. Cors-anywhere will add the necessary headers and handle cors for you.
https://github.com/Rob--W/cors-anywhere
Also once you have it running, make sure to set you env vars so you only allow traffic coming from your website. I will look something like this: export CORSANYWHERE_WHITELIST=https://example.com


Javascript is Loading Page Too Soon - Django Edit Form

Question: I'm trying to edit an existing post (form) on my site but when I click 'edit' I get this in the console: Fetch finished loading: POST "http://127.0.0.1:8000/edit_post/18".
Status is 201 so I think the page is skipping over most of the javascript and directly posting it/saving to server. Also when I click 'edit' a text box is immediately supposed to appear with my post text already there. But this never opens, it just says fetch finished loading appropriately in the console.
How can I make sure all the Javascript is run first? I tried using preventDefault and keep running into Uncaught type errors. I'm pretty new to Javascript so I'm still learning this.
For example, one thing I tried within the event_handeler function was:
document.querySelectorAll("#textarea").addEventListener("submit", function(event) {
document.querySelector(`#post-edit-${id}`).innerHTML += "Sorry!";
event.preventDefault();
})

But I got uncaught type errors.
function edit_handeler(element) {
  id = element.getAttribute("data-id");

  document.querySelector(`#post-edit-${id}`).style.display = "block";
  document.querySelector(`#post-content-${id}`).style.display = "none";

edit_btn = document.querySelector(`#edit-btn-${id}`);
edit_btn.textContent = "Save";
edit_btn.setAttribute("class", "text-success edit");
if (edit_btn.textContent == "Save") {
edit_post(id, document.querySelector(`#post-edit-${id}`).value); //here

edit_btn.textContent = "Edit";
edit_btn.setAttribute("class", "text-primary edit");
}}

function edit_post(id, post) {
 const body = document.querySelector(`#post-content-${id}`).value;

fetch(`/edit_post/${id}`, {

method: "POST",
body: JSON.stringify({
body:body
})

 }).then((res) => {
 document.querySelector(`#post-content-${id}`).textContent = post;
 document.querySelector(`#post-content-${id}`).style.display = "block";
 document.querySelector(`#post-edit-${id}`).style.display = "none";
 document.querySelector(`#post-edit-${id}`).value = post.trim();
  });
 }

views.py
@csrf_exempt
def edit_post(request, pk): #used to take in pk here also

    post = Post.objects.get(id=pk)  # was id=pk

    form = PostForm(instance=post)
    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            form.save()

            return JsonResponse({}, status=201) # this works to edit and save to db
    else:
        if request.method == "GET":
            form = PostForm(instance=post)
            form_for_post = {'form': PostForm()}

            return render(request, "network/make_post.html", {
                "post": post,
                "form_for_post": form,
    })

relevant urls.py
path('edit_post/<str:pk>', views.edit_post, name="edit_post"),

relevant html - the first part is the textarea that should open up when you click 'edit.'
Next part is the edit button.
span id="post-content-{{i.id}}" class="post">{{i.text}}

                <textarea data-id="{{i.id}}" id="post-edit-{{i.id}}"
style="display:none;" class="form-control textarea" row="3">{{i.text}}</textarea>

<button class="btn-btn primary" data-id="{{i.id}}" id="edit-btn-{{i.id}}"
onclick="edit_handeler(this)" >Edit</button>

Answer: first the code format is a mess and really difficult to read, try to format it better using Prettier or anythin else before uploading next time.
To my knowledge onsubmit listener can be only bind to <form> element and it makes sense, you do not submit textarea but the form in which it's included.
Therefore you should target <form> elements with the addEventListener.
Also when a listener is called, the browser inserts en event object as a first argument into it.

Event listeners only take one argument, the Event Object, which is automatically passed to the listener, and the return value is ignored.
MDN documentation

and if you want to access attributes of the element you can do that by accessing event.target
One possible way of doing what you need:
JS:
function onsubmitHandler(event, url, ...others) {
  // prevents form from submitting and reloading the page
  event.preventDefault();
  // accessing element which caused firing this eventListener
  // in our case that is the form element
  let form = event.target;
  // now we need the textarea and its value
  let textarea = form.querySelector("textarea");
  let content = textarea.value;

  // other steps
  fetch(url, ...).then(res => ..)
}

HTML:
<form onsubmit='onsubmitHandler(event, url, ...others)'>
  <textarea>..</textarea>
  <button type="submit">..</button>
</form>

This way, the button triggers onsubmit event which is captured by the form element in which the button resides in.
and of course, you can pass values from Django template as:
<form onsubmit='onsubmitHandler(event, {{ url }})'>

Key points:

onsubmit or addEventListener("submit") fires on the form itself therefore it is the event's target and reloads the page - that is its native behaviour - which you can stop programatically event.preventDefault() inside the listener callback's function (the onsubmitHandler in our case)

Note that the submit event fires on the  element itself, and not on any  or  inside it.

If you use <form action="https://example.com" method="POST"> and do not attach any event listener to it, it will collect named inputs inside the form ` and append them to action url as query parameters => "https://example.com?car=car" and sends POST request with that url to a server. And it does not wait for anything and reloads the page.

I am not an expert and doing the same course as you are so if there is a mistake or something is unclear I apologize and feel free to ask.


Sincronizar itens nas comboboxes em tempo de execução

Question: Já faz algum tempo que tento imaginar um modo de como conseguir sincronizar uma combobox com outra. Estou querendo sincronizar comboboxes em tempo de execução. Quando o usuário selecionar uma categoria na combobox, dependendo da sua escolha, a combobox subcategoria irá mostrar as subcategorias da categoria selecionada.
Estou usando WPF e C# com EntityFramework 6.
Na minha aplicação, eu consigo ler na minha ViewModel o que foi selecionado na comboBox na View. Queria saber como faço para atualizar, dinamicamente,  uma combobox depedendo do que foi selecionado em uma outra combobox, utilizando o padrão MVVM. Seguem trechos do código:
<ComboBox Name="cbCategoria"
          ItemsSource="{Binding NomeCategorias}"
          SelectedItem="{Binding NomeCategoria}"
          Width="175" />

<ComboBox Name="cbSubCtg"
          ItemsSource="{Binding NomeSubCategorias}"
          SelectedItem="{Binding NomeSubCategoria}"
          Width="175" />

Como podem ver, lá na minha ViewModel eu guardo o que lido na ComoboBox cbCategoria na variável NomeCategoria.
Desde já agradeço qualquer ajuda.
Comment: Faz tempo que não trabalho com WPF, você já tentou usar o evento `SelectionChanged` do combo? Estou escrevendo um resposta que usa ele, mas não sei se é esse seu problema.
Comment: Estou usando este site para eu ter uma idéia (http://www.dotnetperls.com/combobox-wpf), mas não estou sabendo como faço para conseguir pegar o que foi lido na primeira combobox .
Comment: @jbueno Eu até consegui um exemplo falando isso, mas acho que não fica legal, pois, na minha cabeça, vou ter que colocar lógica no code behind da view. Acho que a solução do meu problema irá utilizar sim o `SelectionChanged`, mas não será só isso. Eu acho... rsrsrs
Comment: Meu problema está sendo em como atualizar isso em tempo de execução.
Answer: Consegui resolver meu problema! Usei o evento SelectedChanged na ComboBox que "comanda" na segunda. Agora estou conseguindo atualizar dinamicamente a segunda ComboBox. Segue o código:
private void cbCategoria_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var cbCategoria = sender as ComboBox;
            int ctgId = -1;
            string temp = string.Empty;
            ObservableCollection<string> listaCtg;

            nomeCtg = cbCategoria.SelectedItem as string;
            Debug.WriteLine($"Sub categoria lida no handler {nomeCtg}");

            using (DataContext db = new DataContext())
            {
                // Procura o nome da categoria selecionada na ComboBox
                var categoria = from x in db.Categorias
                                where x.CategoriaNome.Equals(nomeCtg)
                                select x;

                foreach (var p in categoria) { ctgId = p.CategoriaId; }

                // Procura o Id correspondente com a das categorias
                var subCtg = from x in db.SubCategorias
                             where x.Categoria.CategoriaId == ctgId
                             select x;

               listaCtg = new ObservableCollection<string>();

                foreach (var p in subCtg)
                {
                    temp = p.SubCtgNome;
                    listaCtg.Add(temp);
                    Debug.WriteLine($"Subcategoria aaaa {temp}");
                }
            }

            cbSubCtg.ItemsSource = listaCtg;
        }

Sei que ainda precisa de alguns ajustes, mas este exemplo dará idéia para outros membros desta comunidade. Espero que alguém contribuia com qualquer coisa, ainda dá para melhorar.
Answer: Eu faço de outra forma. Eu faça um Binding do segundo ComboBox no primeiro. Suponha que o ItemsSource do primeiro combo é List<Categorias> e cada item dessa lista tem um List<SubCategorias>
As classes seriam assim
public class Categoria
{
   public int CodigoCategoria { get; set; }
   public string NomeCategoria { get; set; }
   public ICollection<SubCategoria> SubCategorias { get; set; }
}

public class SubCategoria
{
   public int CodigoSubCategoria { get; set; }
   public int CodigoCategoria { get; set; }
   public string NomeSubCategoria { get; set; }
}

O Binding seria assim:
<ComboBox x:Name="cboGrupo"
          SelectedValue="{Binding CodigoCategoria, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
          SelectedValuePath="CodigoCategoria"
          DisplayMemberPath="NomeCategoria" />

<ComboBox x:Name="cboSubGrupo"
          ItemsSource="{Binding ElementName=cboGrupo, Path=SelectedItem.SubCategorias, Mode=TwoWay}"
          SelectedValue="{Binding CodigoSubGrupo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
          SelectedValuePath="CodigoSubCategoria"
          DisplayMemberPath="NomeSubCategoria" />

Você precisa fazer o carregamento do primeiro ComboBox. Segue um exemplo com EntityFramework.
public void Carregar(){
  // selecionar as categorias no banco incluindo as subcategorias
  List<Categorias> categorias = db.Categorias
                                  .Include(cat => cat.SubCategorias)
                                  .ToList();
  cboGrupo.ItemsSource = categorias;
}

Desta forma, ao alterar uma categoria no primeiro ComboBox, automaticamente mudam as subcategorias.
Comment: Alterei a resposta. Faço um binding do ItemsSource do segundo combo no primeiro combo, para a propriedade SelectedItem. Essa propriedade é um objeto do tipo Categoria, e esse objeto tem uma lista de SubCategorias. Como o modo desse binding é TwoWay, quando você muda um item no primeiro combo, já atualiza o ItemsSource do segundo. É necessário adicionar o Include ou join na consulta.
Comment: Gostei muito da sua abordagem, me parece que está mais perto do MVVM! Irei usar na minha aplicação. Muito obrigado!
Comment: Tentei usar na minha aplicação, mas não entendi muito como funciona. Vc poderia explicar melhor?
Comment: Interessante. Queria saber se o método `public void Carregar()` esta na ViewModel ou se está no CodeBehind?
Comment: Ele está no Behind da View pois precisa acessar o combobox, mas se quisesse deixar na ViewModel, o ItemsSource do primeiro grupo seria um Binding pra sua coleção da ViewModel. As duas formas funcionam.


how to add a range of IP addresses in debian

Question: I want add a range or IP address 192.168.1.128 to 192.168.1.254 to my debian host
I know, there is an range file (such as ifcfg-eth0-range0) in RedHat/CentOS, they have IPADDR_START/IPADDR_END, but how to do in debian?
Answer: You could an ifup to use a script to add the addresses for you.  Create the following script as /etc/network/if-up.d/eth0
#!/bin/bash

if [ "$IFACE" eq "eth0" ]; then
    for IP in {128..254}; do
        ip addr add 192.168.1.${IP}/24 dev eth0
    done
fi

# EOF
/24 should be replaced by the appropriate subnet mask.
A corresponding script in /etc/network/if-down.d/eth0 should be created using "ip addr" del in place of "ip addr add".
Be sure to run chmod +x on both scripts.
You can test the script using the command IFACE=eth0 /etc/network/if-up.d/eth0.
You could also create the file as /usr/local/sbin/eth0-aliases and run it from an up option in /etc/network/interfaces.  Add up /usr/local/sbin/eth0-aliases to the eth0 stanza.   If you use this mechanism you don't need the if condition in the script.
Answer: You have to do it manually for each interface. Edit /etc/network/interfaces and add each one to that e.g.
auto lo
iface lo inet loopback

auto eth0
auto eth0:1
auto eth0:2
iface eth0 inet static
         address 192.168.10.1
         netmask 255.255.255.0
         gateway 192.168.10.100

iface eth0:1 inet static
         address 192.168.10.2
         netmask 255.255.255.0
         gateway 192.168.10.100

iface eth0:2 inet static
         address 192.168.10.3
         netmask 255.255.255.0
         gateway 192.168.10.100
.
.
.

Answer: Linode published a great article on how to do this
http://www.linode.com/wiki/index.php/Multiple_IPs
Comment: Note that this doesn't cover how to add a range.  It just describes the "descriptive method", i.e. multiple `iface eth0:1` stanzas.
Comment: This link has rotted. While you're at it, add something relevant to this answer so it can stand alone.
Answer: You can probably only add every IP on its own to a virtual interface. Refer to this FAQ entry.


Ionic barcodescanner App clear memory usage

Question: I'm using barcode scanner on iOS made with ionic. During debug I observe that memory usage keep growing (I saw it on xcode) when the app open the camera to make a scan and after 5 utilisations (5 scans) the app crash with this message : Message from debugger: Terminated due to memory issue.
I've made a lot of searches with nothing satisfying. Can someone know how to avoid the memory increasing or clear it before opening the scanner again ?
Im testing on iPhone 5 / iOS 10.
Comment: "Can someone know how to avoid the memory increasing or clear it before opening the scanner again ?"  How should anyone possibly know what you are doing in your code and project and where the memory increase is occuring? Also, you can check Instruments and memory use to know where your memory is leaking.
Comment: The memory increasing is occuring when I start the scan (thus when the app open the camera).
Comment: Then something in your code is retaining and not releasing. It is probably impossible for anyone to help you with a direct answer without access to your project, errorchecking and running instruments to see what objects cause any leaks and if you retain anything in your code etc.
Answer: For those who might encounter this problem I solved it by using a fork of this plugin here https://github.com/jlowe234/phonegap-plugin-barcodescanner.
I include here what was found as the cause of this issue (taken from here : https://github.com/phonegap/phonegap-plugin-barcodescanner/issues/312)

Hello guys, I investigated for this issue and i found the problem on the c++ class. A lot of objects are still in the memory also when barcode viewcontroller is closed (to see the picture below).

So we must delete those files because every time that we open the barcode viewcontroller it takes from 20 to 30 mb so it's a big problem.
I tried to investigate on the C++ code but i don't understand everything so i need of help.

I tested the fork and it's working fine for me. My app stopped crashing and the memory stopped increasing without reason.


Airflow: How to push xcom value from PostgreOperator?

Question: I'm using Airflow 1.8.1 and I want to push the result of a sql request from PostgreOperator.
Here's my tasks:
check_task = PostgresOperator(
    task_id='check_task',
    postgres_conn_id='conx',
    sql="check_task.sql",
    xcom_push=True,
    dag=dag)

def py_is_first_execution(**kwargs):
    value = kwargs['ti'].xcom_pull(task_ids='check_task')
    print 'count ----> ', value
    if value == 0:
       return 'next_task'
    else:
       return 'end-flow'

check_branch = BranchPythonOperator(
    task_id='is-first-execution',
    python_callable=py_is_first_execution,
    provide_context=True,
    dag=dag)

and here is my sql script:
select count(1) from table

when i check the xcom value from check_task it retrieves none value.
Answer: If i'm correct, airflow automatically pushes to xcom when a query returns a value. However, when you look at the code of the postgresoperator you see that it has an execute method that calls the run method of the PostgresHook (extension of dbapi_hook). Both methods do not return anything, as such it pushes nothing to xcom.
What we did to fix this is create a CustomPostgresSelectOperator, a copy of the PostgresOperator, but instead of 'hook.run(..)' do 'return hook.get_records(..)'.
Hope that helps you.
Comment: And does it work for different processes in airflow cluster?
I tried with this: https://gist.github.com/fpopic/35807489d9c36c7ea8bc4de6f966b5fc#file-select_postgres_operator-py-L38-L42

but if the next operator in dag uses the result that SelectPostgresOperator.execute returns I always got some exception, so what is the preferred way to do it? I see a lot of operators like A_to_B to put all logic (probably input/output hooks) in one operator to avoid sharing state (that might be big) between multiple processes.
Answer: Finally, I created a new Sensor ExecuteSqlOperator in the plugin manager under $AIRFLOW_HOME/plugins.
I used CheckOperator as an example and I modified the returned value: the basic running of this operator was exactly the reverse of what I needed.
Here's the of the default ExecuteSqlOperator:
CheckOperator
and here is my customized SqlSensor: ReverseSqlSensor
class SqlExecuteOperator(BaseOperator):
    """
    Performs checks against a db. The ``CheckOperator`` expects
    a sql query that will return a single row.

    Note that this is an abstract class and get_db_hook
    needs to be defined. Whereas a get_db_hook is hook that gets a
    single record from an external source.
    :param sql: the sql to be executed
    :type sql: string
    """

    template_fields = ('sql',)
    template_ext = ('.hql', '.sql',)
    ui_color = '#fff7e6'

    @apply_defaults
    def __init__(
            self, sql,
            conn_id=None,
            *args, **kwargs):
        super(SqlExecuteOperator, self).__init__(*args, **kwargs)
        self.conn_id = conn_id
        self.sql = sql

    def execute(self, context=None):
        logging.info('Executing SQL statement: ' + self.sql)
        records = self.get_db_hook().get_first(self.sql)
        logging.info("Record: " + str(records))
        records_int = int(records[0])
        print (records_int)
        return records_int

    def get_db_hook(self):
        return BaseHook.get_hook(conn_id=self.conn_id)


Prove that the co-ordinates of the centroid of a triangle is an average of that of vertices

Question: For a given triangle [ABC], how do I prove that the co-ordinates of the Centroid $O_{xy}$ (intersection of the medians) is the average of the individual vertices?
$O_x =  \left(\frac {A_x + B_x + C_x}{3}\right)$
$O_y =  \left(\frac {A_y + B_y + C_y}{3}\right)$
I tried proving the height of the $O_y$ coordinate - which should be equal to the sum total of heights of the points A, B, C - divided by 3 - but to no avail.
Answer: I'd calculate the centroid coordinates directly from the definition.  Place $A$ at the origin, $B$ at $(b,0)$ and $C$ somewhere in the upper half-plane.  Then the coordinates of the centroid are:
$$C_x = \frac{1}{A} \int_A x f(x) dx,$$
$$C_y = \frac{1}{2A} \int_A [f(x)]^2 dx,$$
where $A$ is the area of the triangle.  The lower bounding function, $g(x)$ is zero on the interval of interest because of our choice of positions.
Consider both a triangle with all acute angles, and one with an obtuse angle.
The function $f(x)$ will be split up into two sections for the acute triangle.  Calculating the centroid for the obtuse triangle involves calculating the integral for two right triangles, and subtracting one from the other.
Then, once you have these, calculate the average of the coordinates of the vertices, and see that they match what you just calculated.
Answer: The median through $C$ passes through the mid point of the opposite side ${1 \over 2} (A+B)$. Find an equation of this line.
Find the equation of another median and see where they intersect. Show that
this is the average of the points.
Answer: What is the average of the vertices ? $\dfrac{A+B+C}3~.~$ And where do the medians intersect ? A third above the middle, and two thirds below the vertex, or $\dfrac23\cdot\dfrac{X+Y}2+\dfrac13~Z,~$ where X, Y, Z form a permutation of A, B, C.
Answer: The median drawn from $A$ and the median drawn from $B$ intersect where $t$ and $u$ solve
$\displaystyle tA+(1-t)\frac{B+C}{2}=uB+(1-u)\frac{A+C}{2}$
Now rearrange terms so you get something that looks like $xA+yB+zC=0$, and $x$, $y$, and $z$ will all depend on $t$ and $u$.  Since $A$, $B$, and $C$ form a triangle, they are linearly independent.  That means that $x$, $y$, and
$z$ must all equal zero.  This gives you three equations for $t$ and $u$.  Solve and you have your intersection.  Verify that the median from $C$ intersects in the same place.


Problema ao criar projeto com Angular CLI

Question: Um bom dia pessoal,
Estou começando meus estudos em Angular 2, utilizo docker para gerenciamento de meus contêineres.
Logo no começo já estou tendo problemas, a criação do projeto vem apresentando erros.
Ao executar o comando:
ng new primeiro-projeto

Ocorre o seguinte problema...

Já fiquei nessa tela por um longo tempo e nada, aparentemente a criação do projeto simplesmente travou...
Versões utilizadas.

Alguem saberia me dizer o por que desse erro ?
Comment: De vez em quando o `powershel` trava mesmo, eu costumo da um `control+c` ou alguns enter dentro dele!
Comment: Esta mensagem parece normal e nao de erro.
Answer: Utilize o git bash (que vem quando você instala o Git para Windows).
O npm tem problemas no Windows principalmente com esta load bar quando está instalando pacotes.
Você pode testar também utilizando a flag para remover a load/progress bar :
npm install --no-progress

Espero ter ajudado.


Modulating from Bbm to Cm in Sword Art Online - Swordland (Main Theme)

Question: I was wondering how the modulation in Sword Art Online - Swordland (Main Theme) from the Bbm in measure 19 to the Cm in measure 27.
Particularly I'm curious about why does the B chord in measure 23 work in connecting this transition? Also whether my understanding of Abm (measure 24) and Bb (25/26) is working as some type of backdoor chord progression to the Cm in measure 27, and how come using Abm and Bb chords while still in the key of Bbm still works during this transition?
Comment: I upvoted you just for rephrasing the question.
Answer: The overall analysis goes like this:

measure            19  20  21  22  23  24  25    26  27
chord              Bbm Gb  Db  Ab  Cb  Abm Bbsus Bb  Cm
Roman numeral Bbm: i   VI  III VII bII
              Eb :                 bVI iv  V     V   vi

Although the modulation is to C minor, it helps to consider it in terms of Eb major. That clarifies the Bb chord as the dominant and the transition to C minor as a deceptive cadence. The Cb chord is thus clarified as a pivot chord, serving as the Neapolitan chord in Bb minor and the VI chord of Eb, borrowed from minor, along with the iv chord.
A part of what helps make this progression work is the fact that bars 23-26 are effectively in Eb minor, which is the iv relative to Bb minor. So the progression could be considered broadly as i (19-23) - iv (23-26) - vi/IV (27).
Answer: I doesn't modulate to c minor at all.  It just cuts the scene and starts up in the new key.  There IS, however, a pattern to the harmonic motion.
Throughout this song, the composer frequently moves to the relative minor of the tonic major of the current minor key.  (Phew!)
Before your head explodes trying to unpack that last sentence, let me just show it:
Start of song
e-minor --> c# minor (which has same key signature as E major).  This is a clear (and nice) modulation to c# minor.
This passage
e♭-minor --> c minor (which has the same key signature as E♭ major)
The difference is that in the first case, they modulated TO c# minor, but in this case, they are setting up a huge cadence to stay in e-flat (VI-vi-V-???), but do a sudden fakie to ( C# )  c minor anyway.
Short version: NOT a modulation, but still a planned part of this piece's harmonic progression.
Comment: Well, it bars 23-25 are VI-iv-V in e♭ minor, and bars 25-26 are a massive pedal tone over B♭, so this is a huge cadence in E-flat.  You're right about C#, it's C.  That's a typo because I was thinking about the earlier section, will edit that now.
Comment: I'm having trouble following this analysis. How is this passage in Eb minor; if Eb minor, why is the key signature Bb minor, when the other key sig changes are explicit; and where is the sudden fake-out to C#?


Responsive Blocks

Question: How can I make blocks shrink while staying on the same line as the window gets smaller? As of right now my blocks are going under other blocks as my window gets smaller. How can I make my theme responsive, but have the blocks stay on the same line?  I am using Drupal 7.
Comment: Each block has a weight property which dictates how they are rendered within the region in comparison to other blocks. You can alter this weight on page render, but not on window resize. You might have to use combination of CSS @media query and javascript to set where you want your block rendered when the window is resized.
Answer: To make your site or block responsive you can either create your own custom theme and in its css file you can follow these media queries as per your requirement or also you can try using Zen or else Bootsrap theme which gives by default resposive look to the site.
Answer: Use CSS to set their width to a percentage rather than a pixel number. But before that you have to set your most outer div's width to the layout's max-width so that it will fit in since the calculation of pixel to percentage is totally dependent on the width defined to any of the parent element.
Assuming you have a container div is 800px wide if you have a col div in the container as 384px wide then that would be 48%
384*100/800 = 48%

Comment: I know of a module that will let me make my own class for each block, but how would I make an out div without panels?
Comment: I found that panels and display suite are good choices.
Answer: If you don't want to go into code, you could take a look at the panels module https://www.drupal.org/project/panels . You can create a panel page where the regions have their widths in percentages. And then you can place blocks in these regions.

Responsive Blocks


Power of coprime numbers

Question: I would like to prove that $\gcd(a,b) = 1$ implies that for any $i,j$ in N, $\gcd(a^{i},b^{i}) = 1$, without using the factorization in prime numbers.
With the factorization it is very easy (you don't have similar factors, and no new factors appear with the power). But without it I'm stuck.
I tried to find a contradiction but nothing came out, supposing that there exists i,j in N such that $\gcd(a,b) = 1$ and $\gcd(a^{i},b^{i}) \ne 1$. Then I have that $a^{i} = k\cdot a'$ and $b^{j} = k\cdot b'$ I could do something to say that $k|a^{n} \Rightarrow k|a$, but I don't see how to prove this without the factorization again.
I also tried induction and proving just that $\gcd(a,b) = 1 \Rightarrow \gcd(a^{2},b) = 1$, but again withtout the factorization it is not clear to me.
Is there any way to do this without the factorization ?
Thanks
Comment: Hint : We have $Aa+Bb=1$, raise this to the power of $2i-1$.
Comment: Can we use "if $k|ab$ then $k|a$ or $k|b$"?
Comment: Welcome to MathSE! The part when you write "Then I have that ai=k.a′ bj=k.b′." is confusing. Use a middle dot instead of a lower dot to represent multiplication and I recommend you write at least a word like "and" between those two equalities.
Answer: Here it is proved that $\gcd(a,b)$ is the smallest positive integer that can be expressed as a linear combination of $a$ and $b$ ($ax + by$, where $x, y \in \mathbb Z$).
A simple corollary would be that, $\gcd(a,b)=1$ if and only if if there exists integers $x$ such that ax+by = 1$.
Next we show that, if $\gcd(a,b) = \gcd(a, c)=1$, then $\gcd(a, bc) = 1$. That $\gcd(a^i,b^j) = 1$ is a consequence of this corollary.
Proof.
If $\gcd(a,b)= 1$, then there exists integers $x$ and $y$ such that $ax+by=1$.
If $\gcd(a,c)= 1$, then there exists integers $u$ and $v$ such that $au+cv=1$.
Multiplying, we get
$$a^2xu + acxv+abyu + bcuv = 1$$
Rearranging, we get
$$a(axu+cxv+byu) + bc(uv)=1$$
Which implies $\gcd(a,bc)=1$

Power of coprime numbers


Windows Vista Explorer via Runas... or Best Way for Domain Administrator to Work in a Limited Account

Question: One thing that's annoyed me for a great while about administrating a Windows domain is trying to work primarily from a limited user account.  Much of what I do on my workstation on a day to day basis doesn't require admin rights, so I prefer to run as a limited user for security reasons.  The problem, of course, are all those times when I have to do something as a domain admin.
With Windows Vista "fast user switching" finally worked for machines in a domain, but I have a few problems with it: 1) Switching is slow, 2) About one out of five times, switching user accounts will cause Vista to forget my display settings to the point where they cannot be restored without a restart.  Fun stuff.
Often times I only need a file browser to run with elevated privileges, and it appears as though there's no way to run an Explorer instance in this manner (via Runas).  It also appears that browsing files via IE is now just running an Explorer process, and is thus limited in the same way.
I've been running FreeCommander via Sysinternals ShellRunas for this purpose, and it works.  It's just not a good experience.
I would kill for something closer to sudo.  Am I completely missing something obvious?
Comment: I may be being dumb here, but wouldn't UAC help you out here?
Comment: Perhaps it could... unfortunately it breaks a vertical app that I absolutely must run on this machine.
Answer: You are doing the right thing running as a limited account.
I solve this problem by doing rdesktop to another system (usually a server), and logging in as the domain admin.
Fast user switching is a good method, but if it is causing you headaches, then....
Comment: I remote in to servers.  But when I have to transfer files from my workstation or just set some permissions quickly, it sure would be nice if I could just open a share as an elevated user.
Answer: You can run Explorer under another user context, but you have to kill the existing Explorer first to do it, and it's really pretty ugly. If you really want to try it, open a command-prompt with "RunAs" and your domain administrator account. From that command prompt, use "Task Manager" to kill the existing "Explorer.exe" and then start a new one. You'll get an elevated "Explorer.exe" running as the domain administrator account.
It's really an ugly hack, though, so I wouldn't do it in practice.
Comment: Thanks for this.  I'll take your advise and not do it :)  Maybe Windows 7 will help me since some of my problems here are directly related to Vista (e.g. wonky user switching).
Comment: Win7 is perfect for this, I haven't had to pull out any of my runas tricks since moving to it.
Answer: I run into this all the time.
If you're looking to do a quick/simple permissions change or copy/rename/delete, just do a runas on notepad or mmc and use the file open dialog box to make the changes.

(source: microsoft.com)
You can browse to whatever folder you want, right-click for properties/permissions, copy and paste.  One thing to note is that the view won't refresh right away, hit F5 after renaming/ moving a file etc.
Comment: Ha!  Very clever!  I'll try this for a few days and see if I can get used to it.
Answer: I have a script that would launch runas then something else (e.g. MMC) elevated.
<code>Set objShell = CreateObject("Shell.Application")
app = wscript.arguments(0)
args = ""
for i = 1 to (WScript.Arguments.length - 1)
   args = args + wscript.arguments(i)
next
objShell.ShellExecute app, args, "", "runas"
</code>
If you hate the constant prompt for creds, perhaps using something that can take creds instead of runas ... but then storing creds in a script exposure plus perhaps eroding the benefit of running as lower account.
Comment: Thanks.  The problem however is running things like Explorer, for which this won't work.  BTW, you should check out ShellRunas.
Answer: I used to do this runas and Internet Explorer in Windows XP. You can then browse files inside the IE window. I have not had the need to try this in Windows Vista though.
Comment: Yeah, it's no longer possible.
Comment: Starting with IE 7 you can't browse the file system.  If you copy over the IE6 exe you can still do a runas on that however and it works.
Answer: if remote desktop is enabled, you can use RDP to connect to localhost with alternater creds. the problem is, that this loads the whole user session and a lot of unneeded stuff for just using one program.
EDIT: i haven't tried this with vista (or xp). i am using server 2008 as my workstation and it works great under it.
Comment: I don't think this would work for something other than server.  XP at least locks the console when you connect via RDP, it's still a single user OS.
Comment: Can you elaborate on this?  I get an error: "You are already connected to the console of this computer."
Answer: Do your runas on this:
explorer.exe /separate
The separate is an undocumented flag but it launches it in a separate process window (AKA it will not check for an existing explorer shell before launching)
Comment: I've tried this in the past, and it doesn't work on Vista.


SQL query - not null

Question: I have sql query:
Select id
    ,MAX(CASE WHEN (pos = "10") THEN date ELSE NULL END) position10
    ,MAX(CASE WHEN (pos = "18") THEN date ELSE NULL END) position18
    ,MAX(CASE WHEN (pos = "20") THEN date ELSE NULL END) position20

FROM table
WHERE
date BETWEEN "${od=2021-05-01 00:00:01}" AND "${do=2021-07-01 00:00:01}"
AND pos IN('10','18','20')
group by id

I got this table

id
position10
position20
position30

1
2021-05-02
2021-05-02
2021-05-3

2
2021-05-15
2021-05-16
2021-05-18

3
2021-07-08
NULL
NULL

And I want lines where NULL values are not picked up.
A try this:
SELECT * FROM (
Select id
        ,MAX(CASE WHEN (pos = "10") THEN date ELSE NULL END) position10
        ,MAX(CASE WHEN (pos = "18") THEN date ELSE NULL END) position18
        ,MAX(CASE WHEN (pos = "20") THEN date ELSE NULL END) position20

    FROM table
    WHERE
    date BETWEEN "${od=2021-05-01 00:00:01}" AND "${do=2021-07-01 00:00:01}"
    AND pos IN('10','18','20')
    group by id )T
WHERE (position10 IS NOT NULL)
       OR (position18 IS NOT NULL)
       OR (position20 IS NOT NULL)

But it still chooses to me where the NULL value appears somewhere.
Comment: WHERE (position10 IS NOT NULL)
       AND(position18 IS NOT NULL)
       AND(position20 IS NOT NULL)
Comment: Replace OR with AND?
Comment: OMG I am stupid :D I didn't even give me the problem here. Thx
Answer: You need to change OR to AND in WHERE clause
SELECT * FROM (
Select id
        ,MAX(CASE WHEN (pos = "10") THEN date ELSE NULL END) position10
        ,MAX(CASE WHEN (pos = "18") THEN date ELSE NULL END) position18
        ,MAX(CASE WHEN (pos = "20") THEN date ELSE NULL END) position20

    FROM table
    WHERE
    date BETWEEN "${od=2021-05-01 00:00:01}" AND "${do=2021-07-01 00:00:01}"
    AND pos IN('10','18','20')
    group by id )T
WHERE position10 IS NOT NULL
       AND position18 IS NOT NULL
       AND position20 IS NOT NULL

SQL query - not null


Which of following two C programs (iterative and inductive) is more efficient for finding the nth Fibonacci number?

Question: As stated above attempting to work out which of the following two programs is most efficient for finding the nth Fibonacci number and why.
The Fibonacci numbers are numbers in the sequence: 1, 1, 2, 3, 5, 8... where each number after the first two is the sum of the preceding two numbers.
//// iteration ////
int main()
{
int n;
int t1 = 0;
int t2 = 1;
int i;
int new_term;
printf("Enter N :");
scanf("%d", &n);
if (n == 1)
    new_term = 0;
else if (n == 2)
    new_term = 1;
else
{
    for (i = 3; i <= n; i++)
    {
        new_term = t1 + t2;
        t1 = t2;
        t2 = new_term;
    }
}
printf("%dth term of the series is %d", n, new_term);
return 0;
}

//// induction ////
int fibo(int n);

int main() {
      int n;
    printf("Enter n : ");
    scanf("%d", &n);
    printf("The %dth term of Fibonacci sequence is %d", n, fibo(n));
    return 0;
}

int fibo(int n)
{
    if (n == 1) return 0;
    if (n == 2) return 1;
    return fibo(n - 1) + fibo(n - 2);
}

Comment: This seems like a homework problem, so I won't answer it. But one is *vastly* more efficient than the other.
Comment: Iteration is probably slighly faster, for obvious reasons. Think and you'll find out why by yourself.
Comment: What happened when you timed them?  What happened when you checked CPU use when you ran them?  What happened when you checked memory use when you ran them?
Comment: The question would be better if you said where you were stuck. As @ThingyWotsit suggests, even if you can't analyse the programs, it's relatively easy to run them for various values of n, so it's hard to guess what the problem is.
Comment: Your recursive solution isn't quite right f(1) is 1
Comment: @MichaelWalz Iteration isn't just slightly faster, it's obscenely faster. The 50th term took me 35 seconds to compute with the recursive version. The iterative version did the billionth term in 0.6 seconds.
Comment: Welcome to Stack Overflow! I'm voting to close this question as off-topic because Stack Overflow is for finding solutions to coding problems.  For advice on improving working code, please use [codereview.se] instead.  Your programs would be suitable for the `comparative-review` tag over there.
Answer: This is an algorithmic question and must be seen as one.
The iterative version will find its results in O(n) steps.
For the recursive version, as you use no memoization, each term will be computed many times.
Suppose N(n) is the number of steps to produce the nth number. You need to compute fibo(n-1) and fib0(n-2) and sum them. So you need N(n-1) + N(n-2) + 1 steps. Neglecting the last sum, it comes that N(n) is in the same order of magnitude of fibo(n) which is known to be exponential.
Optimized recursive algorithms can compute fibo(n) in O(n) steps at the cost of storing numbers in a array (they are still less efficient than the iterative way), but your naive algorithm will have terrible performance.
Recursion generally allows for very simple algorithms with very poor performances.


Imprimir nulo ou nao nulo na matriz no Python

Question: Se a matriz tiver só zero imprima 'nulo' se não imprima 'nao nulo'
Eu fiz assim:
m=[[0,0,0],[0,0,0],[0,0,0]]
soma1=0
for novo1 in m[0]:
    soma1+=novo1
soma2=0
for novo2 in m[1]:
    soma2+=novo2
soma3=0
for novo3 in m[2]:
    soma3+=novo3

if soma1==0 and soma2==0 and soma3==0:
    print('nulo')
else:
    print('nao nulo')

Mas desse jeito eu tenho como que fazer manualmente.
Gostaria de saber como faço sem ser assim, mas considerando por exemplo uma matriz maior. Tipo se fosse uma matriz de 500 números não poderia fazer assim.
Comment: Deve retornar "nulo" se a matriz possuir todos os elementos igual a zero ou se a soma de todos os elementos é 0? Basicamente, [0, -1, 1] não possui todos os valores igual a zero, mas a soma será 0, neste caso qual deve ser a saída?
Comment: Porque você esta somando os valores com "0"?
Comment: nao entendi a pergunta desculpa ta falando da lista? se for é que eu estava testando aqui mas pode considerar outra lista por exemplo [[0,0,1],[0,0,0],[0,0,0]] na saida vai dizer que nao é nulo
Answer: Resolução
Utilizando dois for, um para percorrer "m" e outro para percorrer os seus sub-itens, criei outro array para o itens que serão somados, mas se você for utilizar apenas somas com zero é melhor trocar o array e colocar o valor estático, e por fim eu criei um flag chamada "isNulo" assim se existir algum valor que não seja zero ela é setada para "False".
Caso 1
m=[[0,0,0],[0,0,0],[0,0,0]]
soma=[0,0,0]
isNulo=True
count=0

for x in m:
  for y in x:
    soma[count]+=y
    if soma[count] != 0:
      isNulo = False
  count += 1

if isNulo:
    print('nulo')
else:
    print('nao nulo')

Executar
Caso 2
Caso seja o que o Anderson citou, "soma de todos os elementos é 0", apenas coloque o for fora do for interno
m=[[0,0,0],[0,0,0],[0,0,0]]
soma=[0,0,0]
isNulo=True
count=0

for x in m:
  for y in x:
    soma[count]+=y
  if soma[count] != 0:
    isNulo = False
  count += 1

if isNulo:
    print('nulo')
else:
    print('nao nulo')

Executar
Caso 3
A mesma ideia do caso 2, mas sem a necessidade da soma com valores diferentes de zero
m=[[0,1,-1],[0,0,0],[0,0,0]]
isNulo=True
count=0

for x in m:
  soma = 0
  for y in x:
    soma+=y
  if soma != 0:
    isNulo = False

if isNulo:
    print('nulo')
else:
    print('nao nulo')

Executar
Comment: muito Obrigado!
Comment: E o que aconteceria se a "matriz" tivesse mais que 2 dimensoes?
Answer: Não precisa ficar somando os elementos, basta percorrer as listas e ir verificando se cada valor é diferente de zero.
Uma maneira de resolver é primeiro criar uma função que verifica se uma lista possui somente zeros:
def somente_zeros(lista):
    for elemento in lista:
        if elemento != 0:
            return False;
    return True;

Repare que se encontrar algum elemento que não é zero, a função já retorna False (não tem somente zeros), pois neste caso eu nem preciso percorrer o restante da lista.
Se o for terminar, significa que ninguém entrou no if, e portanto todos os elementos são iguais a zero, e a função retorna True.
Agora é só percorrer a matriz. No fundo, a matriz é apenas uma lista de listas: uma lista na qual cada elemento também é uma lista. Então basta fazer um for nos elementos da matriz, e usar a função acima para verificar se ele só tem zeros:
m = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

# para cada linha da matriz
for linha in m:
    # se encontrou algum elemento diferente de zero, já imprime a mensagem e sai do loop
    if not somente_zeros(linha):
        print('nao nulo')
        break
else:
    print('nulo')

O for percorre cada linha da matriz e passa-a para a função somente_zeros. Se a lista tiver algum elemento diferente de zero, entra no if, que já imprime a mensagem "nao nulo" e sai do loop (o break interrompe o for).
Se nenhuma das linhas entrar no if (ou seja, todos os elementos são iguais a zero), o break não é chamado e o bloco else é executado (sim, em Python, um for pode ter um bloco else associado).

Como solução geral para "matrizes" com mais de duas dimensões (ou seja, lista de listas de listas de listas...) você pode criar outra função auxiliar para converter a matriz para uma lista de uma dimensão:
from collections.abc import Iterable

def flatten(matriz):
    result = []
    for elemento in matriz:
        # se for um elemento iterável (exceto strings), faz o flatten recursivamente
        if isinstance(elemento, Iterable) and not isinstance(elemento, str):
            result.extend(flatten(elemento))
        else:
            result.append(elemento)
    return result

Com isso, não importa a dimensão da matriz, ela será reduzida para uma única lista, contendo todos os elementos. Sendo assim, você só precisa percorrê-la e verificar se algum elemento não é zero:
m = [
    [
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
    ],
    [
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
    ],
    [
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
    ]
]

for elemento in flatten(m):
    if elemento != 0:
        print('nao nulo')
        break
else:
    print('nulo')

A ideia é a mesma da função somente_zeros: se encontrar algum elemento que não é zero, imprime "nao nulo" e interrompe o loop (não precisa verificar o restante, pois já encontrei um elemento que não é zero).
Se o for chega ao fim, quer dizer que todos os elementos são zero. O bloco else é executado e imprime "nulo".
Comment: @ hkotsubo, Cool! (+1)
Answer:
Use Numpy

Voce esta construindo o que chama de matriz através das listas do python, eu tenho minhas dúvidas se voce pode chamar isso de matriz no sentido matemático da palavra. Utilizando o numpy voce pode construir matrizes através de arrays genuinos e fazer varias operações especificas para matrizes. Resolvendo sua questão:
import numpy as np
m1 = np.array([np.zeros(100),np.zeros(100)])
m2 = m1.copy()
m2[0][10]=1

# Testando m1
print("Nulo") if m1.sum()==0 else print("Não Nulo")
Nulo

# Testando m2
print("Nulo") if m2.sum()==0 else print("Não Nulo")
Não Nulo

Editada

Com numpy voc pode tambem contar o zeros em uma matriz com apenas um comando, então poderiamos fazer assim tb:
m1 = np.array([[0,0,0],[0,0,0],[0,0,0]])
print('Nulo') if not np.count_nonzero(m1) else print('Não Nulo')
Nulo

m2 = m1.copy()
m2[0,0]=1
print('Nulo') if not np.count_nonzero(m2) else print('Não Nulo')
Não Nulo

Answer: Como True > False podemos simplesmente calcular o mínimo recursivamente:
def all_0(x):
  if type(x) is list: return min([all_0(y) for y in x])
  else              : return x == 0

aplicável a "matrizes" de qualquer tamanho, homogéneas ou heterogéneas (listas generalizadas)
print(all_0([[0,[0,0,0],1,0],[0,0,0],[0,0,0]]))           ## False

print(all_0([[0,[0,0,0],0,0],[0,0,0],[0,[[0,0,],0],0]]))  ## True


How to notate triplets longer than 1 measure?

Question: I was listening to the theme from "Game of Thrones" and noticed this section (listen for the drum). There is a hemiola that takes four beats, but the song fits 3/4 best. That would make the hemiola cross measures, and the best way of notating it that I can think of is a triplet of half notes. How is this typically notated? If there is a better way if notating the hemiola, I'd appropriate it if you would include that in your answer, but also include how to notate multi-measure triplets.
Comment: What time point in the track are you referring to. (Your link just starts from the beginning of a 5-minute music track for me). Most computer music notation apps don't support tuplets that cross barlines (Lilypond does support them), but composers have been writing them and music publishers have been printing them for more than 100 years. You just ignore the barline and write the notes in the (approximate) rhythmic positions when they will be played, as you would for a tuplet within a measure.
Comment: The drums at 0:15 aren't doing anything special. Are you talking about the upper strings at [0:53](https://youtu.be/l7XVNPm3tjA?t=53s)? These are just dotted quarters in 3/4.
Comment: @Sam I am not talking about the strings. If you listen to the drums at the end of the line/phrase sequence (I think it's at about 0:16:30, but my pausing skills aren't that precise) and compare them to the middle strings, the drum plays three notes as the strings play four beats (2 eighth, 2 quarter, 2 eighth).
Comment: @alephzero Can you post an example picture? I'm confused over where the bar line would go in relation to the notes. Do you just leave it out?
Comment: How do we find 0:16:30 in a clip that's 5 minutes 5 seconds long? I don't recognize your any of your descriptions of the rhythm (other than the possible 3/4 time signature) anywhere in the clip.
Comment: @cat40 When you say "the strings play four beats" and describe it as 2 quarters and 2 eighths, this is only three beats. It's four *pitches*, but three *beats*. Is this what you mean? In this case, the drums are playing three quarter-note pulses while the middle strings play quarter-quarter-eighth-eighth.
Comment: @sam I said 2 eights, 2 quarters, and 2 eights, to maintain chronological order. This sums to 2 quarters and 4 eights, which is 4 beats. And 3 quarter notes would not have the hemiolated feel that the drum has, though I may be wrong about the rhythm.
Answer: I haven't listened to the music you link to; besides, it sounds from the comments like the rhythm may not in fact be in triplets.
However, if you do want to notate triplets across a barline, you can just use a different triplet value and tie across the barline. Both the examples below give the same rhythm: nine consecutive crotchet triplets. However, the 3/4 example requires using quaver triplets and ties.
Answer: Bob Broadley's answer shows the best that most (commercial) notation programs can do without "faking" the output, but in complicated situations this style of notation can be easier to read:

The notes in the tuplets are spaced relative to the other notes in the score as if the bar-lines did not exist.
(Note, the image was requested by the OP to explain my comment - I also couldn't hear what the first part of the question is asking about)
If this sort of cross-rhythm is a fundamental part of the structure of the music, you might want to write different time signatures on different staves of the score, like


Django Celery task error while invoked in Post request

Question: I have a below task to run notifications asynchronously
@shared_task(name="notifications_task")
def notifications_task(activity_type,obj=None, target=None):
    dispatch_notification_activity(activity_type,obj, target)

In the views,py in a post request, I am calling this notfications_task as below
 notifications_task.delay(UpdateTypeEnum.STOCK_WATCHED, obj=user, target=instance)

The Function dispatch_notification_activity takes care of the push notifications, since it takes more Time , I am running it asynchronously
getting the below error while calling the notifications_task :     kombu.exceptions.EncodeError: Object of type UpdateTypeEnum is not JSON serializable
Traceback (most recent call last):
  File "E:\stocktalk-api-platform\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "E:\stocktalk-api-platform\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "E:\stocktalk-api-platform\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "E:\stocktalk-api-platform\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "E:\stocktalk-api-platform\venv\lib\site-packages\django\views\generic\base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
    raise exc
  File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 502, in dispatch
    response = handler(request, *args, **kwargs)
  File "E:\stocktalk-api-platform\apps\stock_watchlist\views.py", line 42, in post
    notifications_task.delay(UpdateTypeEnum.STOCK_WATCHED, obj=user, target=instance)
  File "E:\stocktalk-api-platform\venv\lib\site-packages\celery\app\task.py", line 421, in delay
    return self.apply_async(args, kwargs)
  File "E:\stocktalk-api-platform\venv\lib\site-packages\celery\app\task.py", line 561, in apply_async
    return app.send_task(
  File "E:\stocktalk-api-platform\venv\lib\site-packages\celery\app\base.py", line 718, in send_task
    amqp.send_task_message(P, name, message, **options)
  File "E:\stocktalk-api-platform\venv\lib\site-packages\celery\app\amqp.py", line 538, in send_task_message
    ret = producer.publish(
  File "E:\stocktalk-api-platform\venv\lib\site-packages\kombu\messaging.py", line 164, in publish
    body, content_type, content_encoding = self._prepare(
  File "E:\stocktalk-api-platform\venv\lib\site-packages\kombu\messaging.py", line 249, in _prepare
    body) = dumps(body, serializer=serializer)
  File "E:\stocktalk-api-platform\venv\lib\site-packages\kombu\serialization.py", line 220, in dumps
    payload = encoder(data)
  File "C:\Users\Fleetstudio\AppData\Local\Programs\Python\Python38\lib\contextlib.py", line 131, in __exit__
    self.gen.throw(type, value, traceback)
  File "E:\stocktalk-api-platform\venv\lib\site-packages\kombu\serialization.py", line 53, in _reraise_errors
    reraise(wrapper, wrapper(exc), sys.exc_info()[2])
  File "E:\stocktalk-api-platform\venv\lib\site-packages\kombu\exceptions.py", line 21, in reraise
    raise value.with_traceback(tb)
  File "E:\stocktalk-api-platform\venv\lib\site-packages\kombu\serialization.py", line 49, in _reraise_errors
    yield
  File "E:\stocktalk-api-platform\venv\lib\site-packages\kombu\serialization.py", line 220, in dumps
    payload = encoder(data)
  File "E:\stocktalk-api-platform\venv\lib\site-packages\kombu\utils\json.py", line 65, in dumps
    return _dumps(s, cls=cls or _default_encoder,
  File "C:\Users\Fleetstudio\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 234, in dumps
    return cls(
  File "C:\Users\Fleetstudio\AppData\Local\Programs\Python\Python38\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Users\Fleetstudio\AppData\Local\Programs\Python\Python38\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "E:\stocktalk-api-platform\venv\lib\site-packages\kombu\utils\json.py", line 55, in default
    return super().default(o)
  File "C:\Users\Fleetstudio\AppData\Local\Programs\Python\Python38\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
kombu.exceptions.EncodeError: Object of type UpdateTypeEnum is not JSON serializable

Comment: Your task arguments (by default) must be json-serializable, as the error suggest. Neither enum values, nor the User object are. You can set the serializer to pickle to support that, but it's not encouraged
Comment: I am quite new to DRF, can you help me to rectify it ?? please
Answer: As @Alexandr pointed out, task arguments must be JSON serializable. You can pass user and target id, and enum value, and then serialize them inside the task, something like this:
notifications_task.delay(UpdateTypeEnum.STOCK_WATCHED.value, obj_id=user.id, target_id=instance.id)

And inside the task:
@shared_task(name="notifications_task")
def notifications_task(activity_type_val, obj_id=None, target_id=None):
    # Get activity type enum object from value
    activity_type = UpdateTypeEnum(activity_type_val)
    # Get object by id
    obj = YourUserModel.objects.get(id=obj_id)
    # Get target by id
    target = YourTargetModel.objects.get(id=target_id)
    # Now call yout method
    dispatch_notification_activity(activity_type, obj, target)

Comment: As the error says, you passed *Object of type UpdateTypeEnum*. Note that I passed `UpdateTypeEnum.STOCK_VATCHED.value`, which is integer (I guess, if UpdateTypeEnum is IntEnum).  Also, you have to restart celery worker after making changes for them to be really applied.
Comment: I'm glad you fixed it. From the last line, where it says object is not json serializable, since Celery sends/recevies messages to/from a broker in a json format, using different api for different broker. Just like a basic rest api, you cannot send objects instances, there has to be a serializer in between.
Comment: It works now , initially I missed this part  (UpdateTypeEnum.STOCK_WATCHED.value, obj_id=user.id, target_id=instance.id), Thanks so much for your help, please let me know from which part of the log you identified this issue. So in feature, I can also also detect this


while committing changes I got the below error

Question: error: cannot spawn C:\Program Files (x86)\Git\usr\bin\gpg.exe: No such file or directory
error: gpg failed to sign the data
fatal: failed to write commit object
Answer: This happens, if your PATH has space in it.
Below link has the answer to your question;
Error: Cannot Spawn C:\Path To\TortoiseGit\Bin: No such file or directory


2-way data binding for my control

Question: Let's say I have my custom view, defined as follows to for data binding support:
@InverseBindingMethods({@InverseBindingMethod(type = com.jaredrummler.materialspinner.MaterialSpinner.class,
        attribute = "app:selectedIndex", event = "app:selectedIndexAttrChanged", method = "getSelectedIndex")})
public class MaterialSpinner extends TextView
{
 //...............
   public Integer getSelectedIndex()
   {
       return selectedIndex;
   }

  @InverseBindingAdapter(attribute = "app:selectedIndex")
  public static Integer getSelectedIndex(MaterialSpinner spinner)
   {
       return spinner.getSelectedIndex();
   }
  //**************

Next I need to create event selectedIndexArttrChanged:
@BindingAdapter({"app:selectedIndexAttrChanged"})
public static void setSelectedIndexListener(MaterialSpinner view, final InverseBindingListener selectedIndexChange)
{
}

But I'm not sure how to setup event. Since it's static, I can't put notifyPropertyChanged there. Do you have any tips?
If I make BindingAdapter non static, my app crashes with error message:

java.lang.IllegalStateException: Required DataBindingComponent is null
  in class ActivityMainBinding. A BindingAdapter in MaterialSpinner is
  not static and requires an object to use, retrieved from the
  DataBindingComponent. If you don't use an inflation method taking a
  DataBindingComponent, use DataBindingUtil.setDefaultComponent or make
  all BindingAdapter methods static.
Answer: I'm going to assume that your MaterialSpinner doesn't extend AdapterView. If it did, you should already have two-way data binding enabled for android:selectedItemPosition.
One thing is that you don't need an InverseBindingAdapter and InverseBindingMethod. You only need one or the other. In your case, since your InverseBindingAdapter is really just calling the getter, you should keep the InverseBindingMethod instead (less code).
To hook up the binding listener, do something like this:
@BindingAdapter({"app:selectedIndexAttrChanged"})
public static void setSelectedIndexListener(MaterialSpinner view,
     final InverseBindingListener selectedIndexChange)
{
    if (selectedIndexChange == null) {
        view.setOnItemSelectedListener(null);
        return;
    }
    view.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {
            selectedIndexChange.onChange();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            mAttrChanged.onChange();
        }
    });
}

I recommend that you look at the source for the BindingAdapters that come with data binding. If you use Android Studio to look up AdapterViewBindingAdapter, for example, you'll see an implementation you can use for a template.

2-way data binding for my control


Trying to find polynomial-time algorithms for knapsack-like problems

Question: Consider two related problems:

You have $n$ cannisters that must go into $m$ trucks that can each carry $k$ cannisters. You require that no truck becomes overloaded, and for each cannister, there is a specified subset of trucks in which it may be safely carried. Is there a way to load all $n$ cannisters into the $m$ trucks such that no truck is overloaded, and each cannisters goes into a truck that is allowed to carry it?
Now, any cannisters can be placed in any truck, but there are certain pairs of cannisters that cannot be placed together in the same truck. Is there a way to load all $n$ cannisters into the $m$ trucks such that no truck is overloaded, and no two cannisters are placed in the same truck when they're not supposed to be?

The question I have is whether either of these has a polynomial-time algorithm to solve it. When I think in terms of greedy algorithms, I can't really come up with anything, so is there a clever trick (or algorithm paradigm) that can be used to solve these in polynomial time?
Answer: For question (1), yes, there is, using maximum matching / flow. Consider the bipartite graph $(L, R)$ -- each of the nodes $l_i$ in $L$ correspond to a canister, and each of the nodes $r_i$ in $R$ correspond to a truck. For every pair of allowed canister $(l_i, r_i)$, such that it is allowed to put canister $l_i$ inside truck $r_i$, construct an edge with capacity $1$ between them. Now, add two additional nodes $v_t$ and $v_s$. Add an edge from $v_t$ to every canister $l_i$, each with capacity $1$. Add an edge from every truck $r_i$ to $v_s$ with capacity $k$. A maximum flow in this graph corresponds to an assignment of canisters to trucks.
Question (2) is NP-hard, because Clique Cover can be reduced to this problem by setting $k=n$ and considers the complement graph.
Answer: Yes, there is a clever trick for approximating solutions to the knapsack problem. Since the knapsack problem is pseudo polynomial, we can find a full approximation scheme for it such that out approximation can be made arbitrarily close. The details are here:
http://math.mit.edu/~goemans/18434S06/knapsack-katherine.pdf
Basically, the trick is rounding your numbers.


PHP file permissions

Question: How can I set permissions of a file to let a PHP program read and write but not be read by the public.  When I set read permissions it denies PHP to the files.
Comment: Is this PHP program being invoked via a web server like Apache? Or is it a command line script run by the user that owns the file?
Answer:
change ownership to the apache user (either apache, www-date or http, depending on OS).
modify permission, chmod 700 or chmod 750
Comment: `600` / `640`, unless one is working with executable files... (sorry, pet peeve of mine that everyone seems to force all their files executable, makes admin tasks like _finding_ executables a hell...)
Comment: I think you meant `www-data` rather than `www-date`
Comment: double doh ... yea i meant read/write w/ no execute. www-date if he's using debian.
Comment: How do I do this - change ownership to the apache user (either apache, www-date or http, depending on OS).
Comment: You'll need access to the console either via ssh or directly logged in. Do you have such access?
Comment: umm, so ssh is shell (command prompt), what do I use? `chown file.txt "apache"` or something like that
Comment: yes, you'll need to figure out which user owns the apache process.

PHP file permissions


Alterar valores de uma array bidimensional - PHP

Question: Olá.
Preciso montar um foreach para atualizar os valores do array abaixo:
Array
(
   [0] => Array
       (
        [id] => 1
        [profissao] => Ajudante de cozinha
        [interesse] =>
       )

   [1] => Array
       (
        [id] => 2
        [profissao] => Manobrista
        [interesse] =>
       )

   [2] => Array
       (
        [id] => 3
        [profissao] => Porteiro
        [interesse] =>
       )

   [3] => Array
       (
        [id] => 4
        [profissao] => Vigia
        [interesse] =>
       )

   [4] => Array
       (
        [id] => 5
        [profissao] => Zelador
        [interesse] =>
       )

   [5] => Array
       (
        [id] => 6
        [profissao] => Arrumadeira
        [interesse] =>
       )

   [6] => Array
       (
        [id] => 7
        [profissao] => Babá
        [interesse] =>
       )

   [7] => Array
       (
        [id] => 8
        [profissao] => Babá folgista
        [interesse] =>
       )

   [8] => Array
       (
        [id] => 9
        [profissao] => Caseiro
        [interesse] =>
       )

   [9] => Array
       (
        [id] => 10
        [profissao] => Copeira(o)
        [interesse] =>
       )
)

Comment: Como você quer que a array fique no final?
Comment: Só preciso atualizar os valores do interesse, ([interesse] => 1), percorrer o vetor e atualizar os valores @bfavaretto
Answer: Você pode percorre-la assim:
foreach($myArray as $key => $subarray) {
      $myArray[$key]['interesse'] = '1';
      // ...
}

DEMO


The PATH variable is set to empty, how to fix it

Question: I was trying to set up a new environmental path in my server, but instead of using bash.basrc I used /etc/profile. After editing I tried to recompile the file using source profile and it gave an error not a valid identifier. Now When I run echo $PATH it shows nothing, none of my programs are running,and I cant even edit the file to check if there was any error any help would be appreciated. I am using cent-os
Comment: To start use: `export PATH=/bin:/usr/bin` on command line.
Comment: Please add some snippets of the scripts/codes you modify and add labels to it.
Comment: For one thing you don't "compile" shell scripts. It sounds like you introduced a syntax error, but since you're not showing us any code it's hard to tell.
Answer: maybe you can not use vim but you can use it like this:
<code>/usr/bin/vim /etc/profile
</code>
rewrite your file and full fill your path.
Answer: Well, I've just got into the same situation. turned out i used 'set PATH <>' by mistake in one of my scripts (instead of setenv).
i just 'unset PATH' and then i was able to see PATH again.
hope that would help someone


Calculating a mixed model using pdIdent var-cov matrix

Question: I have a question in mixed models. I'm quite new at this field and I'm trying to calculate a model in which "y" is predicted according to multiple covariates (Age,gender,BMI) and the random variable "randX". randX has two different unique values and I have 150 repeats with each of the values. I want the var-cov matrix to be a diagonal matrix with the same variance for both of randX types (but zero variance between the types). I read a lot about this subject and this is what I did so far. I have no idea if this is the right model.
model <- lme(y ~ Age+gender+BMI, data = df, random=list(randX = pdIdent(~Age+gender+BMI)), method = "REML")
please help me with that.
Thanks.
Comment: If randX has only two possible values, it cannot be a random effect.
Answer: Considering randX as a random effect means that the observed values of randX are viewed as one possible sample from a broader population of values. And these values are assumed to follow a $\text{N}(0, \sigma^2_{\text{randX}})$ distribution. In R, the syntax 1 | randX is used to specify a random effect on the intercept at the randX level.
Comment: Thank you for your answer. I know that this is the way to do it for a General symmetric positive-definite var-cov (default). I use this code in this case: model <- lme(y ~ Age+gender+BMI, data = df, random=~1|randX, method = "REML"). However, I want to apply a Multiple of an identity var-cov matrix and I don't know how.
Comment: In this case, you do not have a covariance matrix, only a variance...
Comment: That is true. So how do I implement it using lme?