Como Fazer Transition no Hover

Question: Estou fazendo um efeito para MENU usando CSS e jQuery.
Problema
O transition funciona do elemento para ele mesmo com ação hover.
O contrário não funciona.
O CSS abaixo faz o seguinte:
Tem um MENU Mobile escondido a esquerda do site. E quando uso uma função jQuery para chamar a classe .showMenu, o MENU corre para a posição left:0. Mas quando clico de volta no botão que executa a função jQuery, o MENU não volta do mesmo jeito que veio - correndo.
O MENU simplesmente some.
// CSS
nav#menu-navigation{
    position:fixed;
    background-color: #FFF;
    width: 80%;
    max-width: 256px;
    height: 70%;
    top: 0;
    left: -400px;
    bottom: 20px;
    margin: auto;
    overflow: auto;
    transition: left 0.3s ease;
    border-top-right-radius: 15px;
    border-bottom-right-radius: 15px;
    &.show-menu{
        left: 0px;
        z-index: 1;
        transition: left 0.3s ease;
    }
}

// jQuery
$(document).ready(function(){

    $('.open-menu').on('click tap', function(){
        $('nav#menu-navigation, main').toggleClass('show-menu');
    });

});

Answer: Aparentemente o transition está OK:

$('button').click(function(){
  $('div').toggleClass('show');
});
div {
  position: fixed;
  overflow: auto;
  left: -100px;
  transition: left 0.3s ease;
}
div.show {
  left: 0px;
  transition: left 0.3s ease;
}
button {
  margin-top: 100px;
}

Teste

<button>Toggle</button>

Isso me leva a pensar que talvez o problema seja outro.
Olhando seu CSS, vejo que colocou z-index: 1; no .show-menu. Talvez você tenha colocado isso porque algum outro CSS estivesse mudando ele para 0 e precisou aumentar para 1 para ficar visível. Isso seria uma boa explicação para acontecer o que descreveu.
Então, tente adicionar z-index: 1; direto no nav#menu-navigation.
Comment: Parece que foi isso mesmo, hein. Eu já tinha corrigido. Coloquei um `transition: all .3s ease-in-out` no `hover` e funcionou. Mas para melhorar no desempenho mesmo que mínimo usei sua solução.

Como Fazer Transition no Hover


undefined local variable or method `current_user' when devise routes are defined within a scope

Question: I build a multitenant app and I have specific logic for authentication in two tenants so I defined the devises routes in my constrained scope (in order to have two sets of namespaced routes, with their own controllers):
scope(as: 'geea', module: 'geea', constraints: TenantConstraint.new('geea')) do
  devise_for(:users, {
    encryptor: :md5,
    controllers: {
      confirmations:      'geea/users/confirmations',
      sessions:           'geea/users/sessions',
      registrations:      'geea/users/registrations',
      omniauth_callbacks: 'geea/users/omniauth_callbacks',
      passwords:          'geea/users/passwords'
    }
  })

  devise_scope :user do
    namespace :backoffice do
      get    'signin',  to: 'sessions#new',     as: 'new_user_session'
      post   'signin',  to: 'sessions#create',  as: 'user_session'
      delete 'signout', to: 'sessions#destroy', as: 'destroy_user_session'
    end
  end
end

The problem is that causes Devise helpers not to be available in my controllers.
undefined local variable or method `current_user' for #<Geea::Frontoffice::HomeController:0x007fd14d4a36e0>

How could I deal with it?
Thanks!
Comment: check whether user is logged in correctly or not,sometimes if user was not logged in successfully then current_user method remains undefined.
Comment: `current_user` should always be defined, but returning nil or the User object. I had no problem before defining routes inside the scope.
Comment: Have you tried to move the ``devise_for`` block outside the scope, and keep the scope inside?
Comment: could you solve this? I'm having the same issue
Answer: I ran into the same issue. I was namespacing an api with a version. Devise fell under the namespaces. Try something like current_api_v1_user


Fisher's exact test vs. differential gene expression

Question: I identified SNPs that are associated with phenotype through GWAS. I labeled the types of genetic variants in those significantly associated SNPs and now I'm trying to assess the association of those variants with the phenotype with Fisher's exact test.
Looking at the output of the Fisher exact test in R, can one just by looking at the odds ratio and the p-value state that the genetic variant of interest is either enriched or depleted?
Having for example a p-value = 0.0003 and an OR=0.24 as the result in testing the association between ncRNA and phenotype, how would one interpret the OR? Can we interpret this in the context of gene expression as well?
I've read somewhere that for a 2x2 contingency table, the formula for computing the odds ratio and the fold change in expression analyses are the same thing. Please correct me if I'm wrong.
Is there a connection between Fisher's exact test and differential gene expression analysis?
Comment: to use this network effectively, do not edit the question so that it is no longer useful to anyone but yourself. The question should be a question. If you have the answer now, post it as an answer and allow the community to vote on it (as compared to Prof. Harrell's excellent take).
Comment: Link-only answers should, at best, be a comment. Better yet, take the time to spell out the ideas in the link you provided here: https://academic.oup.com/bioinformatics/article/23/4/401/181853
Comment: When you say you "identified SNPS... through GWAS" what *exactly* did you do? There are virtually thousands of methods which could be called GWAS. The real questions are  1. Did you control FDR or FWER? (If FDR, making individual comparisons is at best tenuous, borderline deceptive). And 2. If you use an association measure and significance test different from that of the workhorse behind the GWAS method, why would you expect them to agree?
Comment: @AdamO 1. The FDR was controlled at 0.1 significance. Why is making individual comparisons borderline deceptive? 2. My goal with the Fisher exact test was not to determine significance, but enrichment. Therefore, with my question I did not reach to this significance test to include an estranged significance in addition to the GWAS results, but to understand the interpretation of a small OR and a significant p-value which in my case of analysis indicates significant depletion of ncRNA. I was not aware at the time, that many software for enrichment analysis are based on Fisher exact.
Answer: As has been thoroughly discussed on this site, Fisher's "exact" test is not very accurate, the ordinary Pearson $\chi^2$ is more accurate, and you can save a lot of computing time by using it.
A more important challenge underlying your question, no matter which associate measure you use to describe the results, is that it's too easy to commit an "absence of evidence is not evidence of absence" error, i.e., in concluding that $p > 0.05$ means no association.  A simple Bayesian analysis would expose the problem.  Take a reasonable skeptical prior distribution and analyze the candidate features one-at-a-time.  For each one compute the posterior probability that the true unknown odds ratio exceeds 1.2.  You'll see a minority of features for which you can learn something, i.e, that the posterior probabilities are > 0.95 of < 0.05.  Now compute the probabilities that the odds ratios are close to 1.0, e.g, between 4/5 and 5/4, indicating that there is little association.  You'll see the vast majority of features having probabilities of minimal effect in the range of [0.2, 0.8], i.e., we can't say one way or another where the feature is associated with some outcome.  This exposes the meaninglessness of significance testing in this context.
Look here for simple simulations showing that below a certain sample size there is no correlation between the true odds ratios and estimated odds ratios.  Scary, but shows that you need high sample sizes to learn in high dimensions when the learning is not biologically driven.  Examples in the link also show how to use the bootstrap to expose the difficulty of the task through confidence intervals on importance measures or their ranks.
Comment: Hi Frank. Can you indicate the sense in which you mean *inaccurate* in relation to the Fisher exact test and the circumstances in which it is less so than the Pearson chi squared? In  very large samples  they tend to behave similarly, and in very small samples at least in the 2x2 case its very difficult to get their exact distributions to differ by much at all (when conditioning on the margins for both). Are you referring to the lack of available significance levels in very small samples when conditioning on the margins (which impacts both significance level and power)?
Comment: Please see https://hbiostat.org/bbr/prop.html#fishers-exact-test .  Pearson was wrong when he guessed that you need an expected frequency > 5 for his test to be accurate.  It's more like 1.0.
Comment: Thanks. I know the Expected > 5 rule is not correct; in some circumstances much smaller values lead to acceptable approximations; though in other circumstances 5 is not really sufficient. I'm not sure I agree with the idea that a conservative test correspond to p-values being too large; there's two different issues that seem to be being conflated. I agree that it's sometimes quite conservative because there's a lack of available significance levels, so sometimes alpha is considerably smaller than desired. The claim that p-values are too large is a separate issue, involving a different argument
Comment: To not worry much about overly conservative p-values is to be a classical $\alpha$-driven statistician (overstating it a bit to make a point).  I want p-values that have minimum absolute errors.
Comment: I would take issue with "This exposes the meaninglessness of significance testing in this context." It certainly might expose a lack of utility of dichotomising _hypothesis tests_, but an ordered listing of p-values from the significance tests will give a ranking of strength of evidence against the null hypotheses. It is the all-or-none aspect of significant/not significant that you should rail against, not the p-values.
Comment: True I rail against artificial thresholding of anything but there is plenty to dislike about an individual p-value especially when it is an inaccurate one.  That is really needed is to maximize the probability of making a correct decision.  This comes from Bayesian posterior probabilities, which also, unlike p-values, inform the research of which decisions cannot be made from the data.  In screening a large number of features, for example, with N not huge, most of the posterior probabilities of association will be in [0.2, 0.8] meaning you don't have much of a clue about feature selection.


Gelman & Hill's 'no', 'complete' and 'partial' pooling in the context of longitudinal data

Question: In Gelman and Hill's Data Analysis Using Regression and Multilevel/Hierarchical Models, they present a very compelling idea of 'random' effects offering a kind of compromise between no-pooling (i.e. including an indicator for every group variable and estimating a distinct intercept for each) and complete pooling (not including any group level predictors and thus forcing groups to have the same intercept). They say that including a 'random' intercept term (i.e. allowing the intercept term to have its own probability distribution) is an ideal compromise - as it serves to shrink group level effects towards the population level average when the group level data is scarce or noisy.
A common use of the 'random intercept' model, however, is in longitudinal studies in which the same individual is measured multiple times. In this case every group is a single individual. Here I don't see how the variance in the group level intercept can possibly be estimated - and the idea of 'partial pooling' no longer makes clear sense to me. Can anyone clarify the distinctions in the way random intercepts are understood between these two contexts? If a random intercept model in a longitudinal study with subjects measured at multiple time points can't be understood as 'partial pooling', how should they be better understood?
Comment: i don't understand what is not clear to you, mind you elaborate? The average of each individual is modeled as a random intercept. These intercepts are partially pooled together so that each intercept should be estimated more precisely since we take into an account that all subjects are a random sample from the same distribution
Answer: It's helpful to start with the equation of the multilevel model, which applies whether the data is cross-sectional (multilevel) or person-period (longitudinal):
At level 1 (within cluster): $y_{ij} = \beta_{0j} + e_{ij},  e_{ij}\sim N(0, \sigma_e^2)$
and at level 2 (between cluster): $\beta_{0j} = \gamma_{00} + u_{0j}, u_{0j}\sim N(0, \sigma_u^2)$
In the longitudinal context, $\gamma_{00}$ is the grand mean estimated from all the observed data points - the average value of the outcome y. If not all individuals are measured the same number of times, then this is becomes a weighted mean of the outcome. The random intercept $u_{0j}$ is how much each person's mean outcome value deviates from the grand mean. The spread of person mean deviations around $\gamma_{00}$ can be summarized by a variance estimate ($\sigma_u^2$).
Partial pooling is determined by the number of repeated observations and the level 1 and level 2 variances (essentially how much of the total variation is at the person level). So if person A had outcome data on two occasions and person B had outcome data on 5 occasions, the $u_{0j}$ prediction for person A is going to be pulled back toward $\gamma_{00}$ moreso than the prediction for person B.
Translating these ideas back and forth between the multilevel (groups as clusters) and the longitudinal (persons as clusters) cases takes time and effort, but is a critical part of fully understanding mixed effects models. If something still isn't clear, please post a comment.
Comment: Thanks for laying this out so clearly - its really helpful. The equation as expressed is much more intuitive to me than most I've seen. My question is just: how would things change if we add a 'time' variable in (i.e. estimate β1j)? γ00 would then come to indicate the mean value of Y at time = 0, correct? And u0j the variation about that mean. If this is correct and the intercept term is now limited to time = 0, what becomes of the partial pooling? All participants only have one observation at time 0. I really want to get my head around this, i've struggled a good while! Cheers
Comment: @Lachlan, good questions! $\gamma_{00}$ will be conditional time==0 when you add time to the model. However, what we are predicting in these models, and what gets pooled is $u_{0j}$, which represents, for each person, how much their scores *at any time point* deviate off the predicted mean value for the sample. This deviation is constant across measurement occasions, and thus uses all observations about an individual in pooling (or not).
Comment: @Lachlan , hey dude, could you please have a look at this question https://stats.stackexchange.com/questions/601314/how-to-interpret-error-variance-in-the-random-walk-plus-noise-model   . It is similar to this one, which you have already answered before   https://stats.stackexchange.com/questions/583916/how-to-interpret-the-standard-deviation-of-the-slope-random-effect-in-a-multilev    . I need once again your enthusiasm about the stuff you are an expert on)


Puppet syntax issue when configuring a Prometheus scrape on an SNMP exporter

Question: Some context
I have an SNMP exporter running as a service on a server which allows me to access the data of some PDU using the following URL: http://my.host.name:9116/snmp?target=10.0.1.200&auth=public_v1&module=apcups
I have a Prometheus server which I have configured using puppet on the same host. I want to add a scrape job to retrieve the information provided by the PDUs.
Relying on the tutorial on this page and some other sources, I was able to confirm that manually modifying the /etc/prometheus/prometheus.yaml file to insert the following gives me the expected result. For shortness I only include the relevant part of the configuration file.
- job_name: snmp_scrapper
  scrape_interval: 60s
  scrape_timeout: 10s
  metrics_path: /snmp
  static_configs:
  - targets:
    - my.host.name:9116
  params:
    target: [10.0.1.200]          # IP of the PDU on the private network
    auth: [public_v1]             # authentication method
    module: [apcups]              # module to retrieve APC PDU/UPS information

This works exactly as I expected, I can plot my power consumption in Prometheus and Grafana etc.
My Issue
To configure Puppet to produce the prometheus configuration above, I added the following job in the profile in which prometheus is configured (I have another job scraping node_exporter on a number of hosts from which I was able to take inspiration from):
        {
          'job_name'        => 'snmp_scrapper',
          'scrape_interval' => '60s',
          'scrape_timeout'  => '10s',
          'metrics_path'    => '/snmp',
          'static_configs'  => [{ 'targets' => ['my.host.name:9116'], }],
          'params' => {
            'target' => '[10.0.1.200]',
            'auth' => '[public_v1]',
            'module' => '[apcups]',
          }
        },

The problem is this produces the erroneous prometheus.yaml file below with additional quotes around the metrics_path and three elements inside params.
 - job_name: snmp_scrapper
   scrape_interval: 60s
   scrape_timeout: 10s
   metrics_path: "/snmp"
   static_configs:
   - targets:
     - my.host.name:9116
   params:
     target: "[10.0.1.200]"
     auth: "[public_v1]"
     module: "[apcups]"

The configuration parser of Prometheus then fails with the following error:
  FAILED: parsing YAML file /etc/prometheus/prometheus.yaml20231023-1016214-j3iqrx: yaml: unmarshal errors:
  line 47: cannot unmarshal !!str `[10.0.1...` into []string
  line 48: cannot unmarshal !!str `[public...` into []string
  line 49: cannot unmarshal !!str `[apcups]` into []string

Naively, I thought removing the quotes around /snmp and around the square brackets in the params would fix my problem, i.e.:
          'job_name'        => 'snmp_scrapper',
          'scrape_interval' => '60s',
          'scrape_timeout'  => '10s',
          'metrics_path'    => /snmp,
          'static_configs'  => [{ 'targets' => ['my.host.name:9116'], }],
          'params' => {
            'target' => [10.0.1.200],
            'auth' => [public_v1],
            'module' => [apcups],

But this results in a Puppet syntax error.
My question
How do I obtain the desired /etc/prometheus/prometheus.yaml showed at the top of this question through Puppet? My guess is there must be some sort of syntax that allows the production of a string of text without the quotes but I don't know how.
I am using Puppet version 8.2.0 and the puppet/prometheus v13.3.0 module.
Answer: You're halfway there - you don't want to remove the quotes, but move them:
'job_name'        => 'snmp_scrapper',
      'scrape_interval' => '60s',
      'scrape_timeout'  => '10s',
      'metrics_path'    => '/snmp',
      'static_configs'  => [{ 'targets' => ['my.example.com:9116'], }],
      'params' => {
        'target' => ['10.0.1.200'],
        'auth' => ['public_v1'],
        'module' => ['apcups'],

In both YAML and the Puppet DDL, [ and ] indicate arrays, in this case arrays of strings; target: [10.0.1.200] in YAML is a single-element array containing a single string (10.0.1.200), which could also be written as:
      target:
        - 10.0.1.200

To generate correct Prometheus config, you need to ensure that target, auth and module are generated as arrays, which simply means that they need to be Puppet arrays on the way in. This means having the [ and ] outside of the quotes, as they're part of the language syntax rather than part of the strings, but then because Puppet requires strings to be quoted, your actual values (10.0.1.200, public_v1 etc) need to be quoted, otherwise you get the Puppet syntax errors you're reporting.
The Puppet Prometheus module simply converts scrape_configs directly into YAML, so Puppet arrays are expressed as YAML arrays - and erroneous Puppet strings get expressed as YAML strings, even when you don't want them to be.


How can I use Http Client API(since java 9) in Java8 project

Question: Java 9 imports a new  HTTP/2 Client API which seems good to use but is there any way to use it in Java 8?
OR
Is there any shim/polyfill(from javascript) available to make it available in Java 8?
Comment: In case you are still interested here is a Java 8 backport: https://github.com/stefan-zobel/http2client-java8 (I'm the maintainer of this project)
Answer: Is there any way to use it in java 8?
No, because the jdk.incubator.http module has been added since Java 9.
So it wouldn't be possible to compile it with a --release 8 option on the compiler work with Java8. You would end up getting errors as:

$ javac --release 8 .../src/com/HttpGet.java

$ .../src/com/HttpGet.java:3: error: package jdk.incubator.http does not exist
import jdk.incubator.http.HttpClient;
                         ^

With minimal code to reproduce this as:-
import jdk.incubator.http.HttpClient;

public class HttpGet {
    public static void main(String[] args) {
        HttpClient httpClient = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.ALWAYS).build();
        System.out.println(httpClient.version());
    }
}

Moreover, the documentation clearly reads this upfront

Incubating Feature. Will be removed in a future release.
Comment: it's not *removal 100% of the time*, it might be simply *finalized* and left into idk after all; just a small wording issue I guess
Comment: since the incubating feature is mostly implemented by java source code, I tried to copy and compile it to a jar by myself, but the Java 8 compiler complained there is some internal API is missing...
The missing API is like `System.Logger`, `...misc.Unsafe`, `AsnycResult` etc.
Comment: @IanHu Not sure of what you copied. But eventually there is a possibility that a lot of it might be depending on internal APIs which might not again be available in Java8. Also do note the point of consuming such APIs with License. ;)
Comment: @Eugene When finalized, at least the package names will change (moving from `jdk.incubator` to `java.something`), so these specific packages _will_ be removed.
Comment: @Eugene Indeed. I quoted the javadoc linked though..it happens to be that it contradicts the thought behind the Incubator JEP.
Answer: In principle, the source for it is available. You could copy it, compile it and create a jar usable with Java 8 (possibly with some changes or missing features if the code needs Java 9 anywhere), similarly to ThreeTen-Backport providing java.time for Java 6/7.
But there doesn't seem to be one available yet (after a quick search). If you decide to go in this direction, make sure to follow the relevant licenses.
Comment: For the sake of completeness: Just for fun, I've attempted such a [backport](https://github.com/stefan-zobel/http2client-java8) not so long ago. In principle, I'd say it works though I'd still consider its status as experimental.
Comment: I tried to copy the source code from jdk9 and compiled it, but it failed with some missing internal API.


How to split an html page to where clicking a link on the top half will open it on the bottom half, not affecting the top half at all

Question: I want to have a top half with links and when clicked they will open various pages in the lower half of the screen and can be accessed by bootstrap tabs but i cant figure out how to split the screen.
Answer: You can create two div part, one for the part where link is displayed and another for its content.

Header

some content

    *In css-*
    #navDiv{
    position: fixed;
    top:0;
    width: 100%;
    height: 100px;
    background: white;
    z-index: 10;
    }

    #contentDiv{
    position: absolute;
    margin-top: 100px;
}

You can see the example here - https://next.plnkr.co/edit/kLjIPwbLgDCVjpKE?open=lib%2Fscript.js
Answer: you probably want to use an iframe element


attach function with parameter from javascript

Question: I have this function:
function addButtonLookup() {

    var element = document.getElementById("btnToolBar");
    var index;
    for (var i = 0; i < lookupArray.length; i++) {

        index = i;

        var btn = document.createElement('input');
        btn.type = 'button';
        btn.value = '' + lookupArray[i];
        btn.name = 'btnLookup' + i;
        btn.id = i;
        btn.className = 'CommonButtonStyle';
        element.appendChild(btn);
        btn.onclick = function() {
            debugger;

            tblExcpression.WriteMathElement(lookupArray[i], lookupArray[i]);
        };

    }

}

onbutton click the i is undefined
Comment: Typical mistake. See
[JavaScript Closures for Dummies](http://blog.morrisjohns.com/javascript_closures_for_dummies.html),  Example 5.
Answer: Instead of this:
btn.onclick = function() {
    debugger;

    tblExcpression.WriteMathElement(lookupArray[i], lookupArray[i]);
};

Try this:
btn.onclick = (function(i) {
    return function() {
        debugger;
        tblExcpression.WriteMathElement(lookupArray[i], lookupArray[i]);
    }
})(i);

The issue with the first version is that the i variable is copied from the current scope. However the i variable varies in the current scope (it's part of a for loop), this is why you're getting this weird behavior.
By passing the i variable as a paremeter to a new function (like the second example) the current i variable is copied.
You should take a look at how Closures work in JavaScript.


How to deal with a `Variable 'xxx' is used before being assigned.`

Question: I have a code block like below where I need to find something inside a loop, and also return a second variable. So I can't use a simple Array.find or Array.some good ole' for...of is my friend. map/filter don't allow a break and find can only return actual elements from the array, not a related calculation.
But the below within typescript is giving me an unavoidable error.
I'm wondering if either there's a more idiomatic way to do this, or a better structure / place to declare the variable?
Variable 'found' is used before being assigned.
    let found: ParseResult
    // breaks when first item found but we capture a different value
    for (const rule of ParserRules) {
      // const rex = new RegExp(route.match)
      const parsed = rule.rex.exec(input)
      if (parsed) {
        found = { parsed, rule }
        break
      }
    }
    // @ts-ignore
    return found    // FIXME used before defined?

Here are the various JS iterator methods I tried...

const ar = [1, 2, 3, 4]

const log = console.log

const finder = (list) => {
  console.log('map', list.map(it => it === 3))
  console.log('find', list.find(it => it === 3))
  console.log('some', list.some(it => it === 3))
  console.log('filter', list.filter(it => it === 3))

  console.log('find', list.find(it => {
    if (it === 3) return it * 2 // value coerced to T|F
  }))

  console.log('filter', list.filter(it => {
    if (it === 3) return it * 2  // value coerced to T|F
  }))

  const arr = list.forEach((k) => {
    if (k === 3) return ('here')
  })
  log('arr', arr)

  let found
  for (const elem of list) {
    log('elem of', elem)
    if (elem === 2) {
      found = elem
      break
    }
  }
  log('found', found)

}

finder(ar)
Comment: Can't you just assign a default value when you declare it?
Comment: Why not `arr[arr.indexOf(3)] * 2`? It's really unclear what your actual issue is.
Comment: //typescript is giving me an unavoidable error  -
What is the error?
Comment: Why not use `array.find` to get value that parses. and the check `const output = arr.find(); if (!!output) { return { rule: output, parsed: rule.rex.exec(input)  } }`?
Answer: The summary of your problem is that a function returning a value in a variable when, at times, the logic doesn't get a chance to assign any value to it.
You can either initialize the variable with a default value or, at the point of returning, check if it really has a value.
let found: ParseResult= {}

OR
return found || false    //Or an empty object etc

Answer: This can be done in many ways but what might suit your case would be
ar
  .map((rule) => {
    const parsed = rule.rex.exec(input)
    if (parsed) {
      return { parsed, rule }
    }
  })
  .find((x) => !!x)

Yes you are looping it once more but this is more readable. Also it would not be that costly.
If your processing is heavy, you can try this approach as well but this will be a custom implementation and will not come out of the box:
function getParsedValue(ar, input) {
  let parsed;
  const rule = ar
    .find((rule) => {
      parsed = rule.rex.exec(input);
      return !!parsed;
    })
  return !!rule ? { rule, parsed } : null
}


This is a question in number theory. It seemed I can't start the proof.

Question: How can this be solved?
I knew that the concept of an order of an integer is needed, but rather than that I think I'm really lost with the proofs.
Comment: Welcome to MSE.  Please type your questions instead of posting images.  Images can't be browsed and are not accessible to those using screen readers.  If you need help formatting math on this site, here's a [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)
Comment: Have you tried, say, evaluating $c^2$ as a function of $a$?
Comment: Hi, welcome to the community. Have you tried just expanding out $c^2 = (a-a^3)^2$ and $d^2$ and using the fact that $a^8\equiv 1\mod p$
Comment: I have not tried it yet. I think I'm being confused with the given p ≡ 1 (mod 8). Where does it actually be applied?
Comment: $p\equiv1\pmod{8}$ is to guarantee existence of an element of order $8$.
Answer: $$a^8-1\equiv 0 \implies (a^4+1)(a^4-1)\equiv 0 \implies a^4 \equiv -1 \pmod p$$
$$c^2=(a-a^3)^2=a^2-2a^4+a^6=a^2(1+a^4)-2a^4\equiv 2 \pmod p$$
$$d^2=(a+a^3)^2=a^2+2a^4+a^6=a^2(1+a^4)+2a^4\equiv -2 \pmod p$$
Comment: Nice ($+1$); technically, I think you mean $a^8-1\equiv0\land a^4-1\not\equiv0\implies (a^4+1)(a^4-1)\equiv0\land a^4-1\not\equiv 0\implies a^4\equiv-1\pmod p$
Comment: i.e. $\,a^4\equiv -1,\ b=\pm a^3\Rightarrow\, a^2+b^2\equiv 0\Rightarrow (a+b)^2\equiv 2ab\equiv \pm2\ \ $
Comment: Yes. Thank you!
Comment: @J.W.T and the algebraic essence is clearer if we exploit symmetry, as I highlight in my answer.
Answer: Hint: exploit innate symmetry: $\ \ \underbrace{\overbrace{-a^4 = 1^{\phantom{|}}_{\phantom{.}}\!\!}^{\!\!\!\!\textstyle \color{#0a0}{(-a^3)}a\!=\! 1}}_{\!\!\!\!\!\!\textstyle(\color{#c00}{-a^2})a^2\! =\! 1}\Rightarrow\ (a+\overbrace{a^{-1}}^{\!\!\textstyle \color{#0a0}{-a^3}})^2 = a^2+\underbrace{a^{-2}}_{\!\textstyle \color{#c00}{-a^2}}+ 2\, =\, 2$
Comment: $(b)$ is the same, replacing the sum by the difference $\,(a-a^{-1})^2\ \ $


Correlated Equilibrium - Transforming a non-linear objective function into a linear one

Question: I am trying to transform a non-linear objective function into a linear one, in order to create a LP. How might I go about to do this (I have never taken a course in linear programming).
I have that I would like to maximize the following objective function: $\mu(\alpha)$, where $\mu(\alpha) = \min{U_i(\alpha)}$. $U_i(\alpha)$ denotes the expected utility for player $i$ in a correlated Nash equilibrium and $\alpha$ denotes the corresponding probability distribution played by the players.
The contrains I have so far are the following:
$\sum_{a \in A} \alpha(a) = 1$, and $\alpha(a) \ge 0 $ for all $a \in A$. The other contraints that I have are the ones used for a standard correlated equilibrium, namely that:
for each player $i$ and pairs of action $a_i^{1}$ and $a_i^{2}$, we have that:
$\sum_{a \in A | a_i = a_i^{1} } [u_i(a) - u_i(a_i^{2}, a_{-i})]\alpha(a) \ge 0$.
The first 2 contraints are the ones requiring that $\alpha$ follows a proper probability distribution, and while the last sets are the ones that enforce the correlated equilibrium (by definition). How might I go about to modify this into an LP with the objective function I mentioned above. I know that it's not linear, so I need to change it somehow (and the LP ) appropriately.
Advice is appreciated :)
Answer: For those who are curious, I ended up realizing that I can define the non-linear objective function as a piece-wise set of linear and concave functions, then adding the appropriate constraint for each of these pieces in the original LP. The remainder of the work fell into place after that.


User.findOne() numa coleção que não é a 'Users'

Question: Eu escrevi um app que tem uma lógica de verificação de email e é disparada quando o usuário faz o cadastro. Estou usando dois modelos no Mongoose: um para os usuários e outro para o token de autenticação. No modelo do token eu armazeno o userID:

No meu UserController, quando o app precisa autenticar o token que foi mandado para o email do usuario, ele o faz procurando na coleção Token. Depois de achar o token, ele precisa buscar o userId que está no modelo, de acordo com a imagem cima. Para isso eu tenho uma função User.findOne().
Eu gostaria de capturar o _userId:ObjectId("numberos-numeros") que está no registro, mas eu gostaria de chama-lo dentro da função, mais ou menos assim:
User.findOne({ _userID: mongoose.Schema.Types.ObjectId._userID, ref: 'Token' })

Minha pergunta: tem um jeito de fazer isso, identificar o usário na coleção de usuário usando uma chave que está em outro coleção?
Obrigado!
Answer: A resposta é mais simples que eu imaginava:
async confirmationPost (req, res) {
    const token_ = req.body.token;
    await Token.findOne({ token:token_ }, function (err, tokenData) {
       if (!tokenData) {
          return res.status(),
       }
       else
       {
       tokenUser = tokenData._userId
       User.findOne({ _id: tokenUser }, function (err, user) {
       // logic-logic
       }

:-)
Eu podia capturar todo o conteúdo das informações do token, então foi só setar uma variável que ia na resposta do servidor e pegava o _userID.


Drupal sites/default/settings.php issue on pantheon

Question: I am a complete noob at this site business, and I'm facing what seems to be a very simple problem with my drupal site (hosted on pantheon):

I don't know where this file located nor how to copy it to the other .php files (whose location I also don't know). I would really appreciate detailed help.
Comment: I'm voting to close this question as off-topic because it is not about Drupal. If you need detailed information about where to locate it on *Pantheon*, I suggest you try Pantheon user support.
Answer: On Pantheon you can simply go to your codebase where the root of Drupal installation is placed you will find directories like includes, misc, modules, themes and sites from here you need to go into sites/default/ you will a file named default.settings.php you need to copy this file and place at the same location with name settings.php.
This is the main configuration file of your website and all config settings will go here.
Comment: Could you explain how to find this codebase on the pantheon site? I'm having trouble.
Comment: contact me on Skype- (ashu.bairagi)  there we can have detailed discussion


How to restore uploaded backup in Drupal 7 (public files or entire website) correctly?

Question: When trying to restore public directory I see:
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'temporary://cvetmagazin-2016-03-13T16-28-59.tar__0.gz' for key 'uri': INSERT INTO {file_managed} (uid, filename, uri, filemime, filesize, status, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6); Array ( [:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => cvetmagazin-2016-03-13T16-28-59.tar_.gz [:db_insert_placeholder_2] => temporary://cvetmagazin-2016-03-13T16-28-59.tar__0.gz [:db_insert_placeholder_3] => application/octet-stream [:db_insert_placeholder_4] => 166375 [:db_insert_placeholder_5] => 0 [:db_insert_placeholder_6] => 1457901164 ) в функции drupal_write_record() (строка 7316 в файле /home/user/drupal_fish/apps/drupal/htdocs/includes/common.inc).
However, Drupal accepts database dump without errors. How to fix that? Thanks.
Answer: I think it's a concurrency issue when D7 makes a file object in db.
try to use this modules Upload QC
please let me know if it works with you.
also try to check the temp file name. and make sure tat the database is restored correctly.
Comment: finally, it accepts both public dir restore and database separately, however, nothing changes visually, though new files has appeared in folders


How to notate single-line percussion staff using ABC notation?

Question: I want to have this effect by using ABC notation:

In LilyPond, I can use \new RhythmicStaff to create such a staff. What's the equivalent in ABC notation?
Answer: In ABC, use K: perc stafflines=1. (See Clefs and Transpositions in the ABC standard reference.)
For example:

X: 1
T: Percussion example
M: 4/4
L: 1/8
K: perc stafflines = 1
BB B2 B2 B/2B/2B/2B/2 |

X: 1
T: Percussion example
M: 4/4
L: 1/8
K: perc stafflines = 1
BB B2 B2 B/2B/2B/2B/2 |


Variance $= 0$, show that $X=\mu$ with probability one

Question: If the variance of $X$ is zero, show that $X=\mu$ with probability one.
Using Chebychev's inequality that is,
\begin{equation*}
P(|X-\mu|\geq k\sigma)\leq\frac{1}{k^2},
\end{equation*}
I just let $\sigma=0$,thus, $P(|X-\mu|\geq 0)$, as our absolute value is always greater than or equal to one, this probability equals one.. Does this look correct?
Answer: No, it does not look correct, because $P(|X - \mu| \ge 0)$ is not the same as $P(X = \mu)$, and because the Chebyshev inequality does not apply when $\sigma = 0$.  For this problem, it would make sense to show that $P(X\neq \mu) = 0$. Now the event $(X\neq \mu)$ is the increasing union of the events $(|X - \mu| \ge \frac{1}{n})$, for $n \in \Bbb N$. Thus $P(X\neq \mu) = \lim_{n\to \infty} P(|X - \mu| \ge \frac{1}{n})$. By Markov's inequality,
$$P\left(|X - \mu| \ge \frac{1}{n}\right)  = P\left(|X - \mu|^2 \ge \frac{1}{n^2}\right) \le n^2 \operatorname{Var}(X) = 0$$
for all $n \in \Bbb N$. Therefore $\lim_{n\to \infty} P(|X - \mu| \ge \frac{1}{n}) = 0$ and consequently $P(X\neq \mu) = 0$.
Answer: A more intuitive argument is just noting that for any non-negative random variable $X$ we have $\mathbb{E}(X) = \mathbb{E}(X \, ; X > 0) = 0$ if and only if $\mathbb{P}(X > 0) = 0$. (The expectation of $X$ over the set where it's positive can only be zero if the set itself is negligible.)  Since $\mathbb{V}(X) = \mathbb{E}[(X - \mu)^2]$, then $\mathbb{V}(X) = 0$ implies $\mathbb{P}((X - \mu)^2>0) = 0$ or equivalently $X = \mu$ almost surely.
Answer: The proof of Chebyshev's inequality uses the fact that $\sigma>0$.
See: https://en.wikipedia.org/wiki/Chebyshev%27s_inequality.
And see the proof af the Markov inequality which is the basis of the proof above.
See: https://en.wikipedia.org/wiki/Markov%27s_inequality.


Why are natural numbers countable?

Question: I get how Cantor's diagonalization argument works for real numbers, but I don't see why you can't apply the same logic to natural numbers. I was reading
this thread, but the explanations weren't intuitive to me, never taken set theory.
Comment: If you try to construct a number which is different from all listed natural numbers in a manner similar to the one used in Cantor's argument, your number will have infinitely many non-zero digits.
Comment: As explained in the link, after some time the natural number representations will have all zeroes
Comment: @rb612. I suggest that you go through the construction proof very carefully and you will yourself realise what happens in this case.
Comment: You know a set $S$ can also be said to be countably infinite if there is a bijection $f:\Bbb{N}\rightarrow S$. If $S$ is $\Bbb N$ the bijection is clear.
Comment: An explanation is not supposed to be "intuitive" if you don't have the right intuition. It should be *mathematical*. If you have problems understanding the intuition behind it, it's because you lack the needed intuition for mathematical argument *like that one*. Studying more set theory and getting more comfortable with these arguments is more or less *the only way* to develop such needed intuition. There are no shortcuts.
Comment: You could also ask why the diagonalization argument fails to prove that the set of rational numbers is uncountable. The answer is that the number you construct by the diagonal trick is not rational.
Comment: @Shailesh yes, but how is that any different from rational/irrational numbers?
Comment: Cantor's diagonal argument takes a list of real numbers and gives you a real number not on that list. Now, if you try to do the same to natural numbers, the diagonal argument will give you a "number" not on the list — but that "number" will usually have infinitely many digits, and hence isn't actually a number! Try it.
Answer: Definition -
A set $S$ is countable iff there exists an injective function $f$ from $S$ to the natural numbers $\mathbb{N}$.
Cantor's diagonal argument - Briefly, the Cantor's diagonal argument reads as follow:
Take $S = (0, 1) \subset \mathbb{R}$ and suppose that there exists an injective function $f$ from $S$ to $\mathbb{N}$. Then, we prove that there exists an $s \in S$ (the diagonal number) such that $f(s)$ is not defined (i.e. there is no $n \in \mathbb{N}$ such that $f(s) = n$). Hence, $f$ is not an injective function and $S$ is not countable, or alternatively uncountable.
Is $\mathbb{N}$ countable? - If you are concerned to prove this, just consider the function $$f(n) = n.$$
Obviolusly, this is a injective function since for every $n \in S = \mathbb{N}$, there is an $f(n)$ in $\mathbb{N}$. So, $\mathbb{N}$ is countable.
Is the set of even number countable? - Let $S$ be the even numbers set. Consider $$f(s) = \frac{s}{2}.$$
Again, this is a injective function, since for every even number $s \in S $, there is an $f(s) = \frac{s}{2}$ in $\mathbb{N}$. So, S is countable.
Conclusion - The Cantor's diagonal argument is just a method to prove that there is no injective function between two set. It's a tool to prove something, but it is not the only method for proving countability.
Comment: And for injectivity, it is sufficient to prove that every natural number "comes from" a different s in S. You have actually shown bijections.
Comment: Actually, I was waiting for a more deep answer, but maybe these are the most basic blocks. I explain my point: what makes the 'existence of an injective function to N' a sufficient condition to tell that a set is countable? This makes the set N a referential, but is this based on intuition or is there some theoritical foundation for it?
Comment: IMHO, "Briefly, the Cantor's diagonal argument reads as follow:" is a bit confusing because ["Cantor's diagonal argument"](https://en.wikipedia.org/wiki/Cantor%27s_diagonal_argument#Uncountable_set) isn't related with the "injective function" and it proves by constructing one string not in the countable set $T$.
Answer: Cantor's diagonal argument applied to any list of natural numbers written in decimal does indeed produce a decimal numeral not on the list.
A decimal numeral gives a natural number if and only if it repeats zeroes on the left; e.g. the number one is $\ldots 00001$.
So, the question you have to ask yourself is: why should the diagonal argument give a decimal numeral that repeats zeroes?
Comment: @rb612: It can: e.g. the diagonal of the list $1, 10, 100, 1000, 10000, \ldots$ is $\ldots 11111$, so the diagonal argument will give zero if you replace nonzero digits with zero. And indeed, zero is a natural number (and not on the list).
Comment: So therefore because it won't, because the set has all natural numbers, it will never repeat zeroes, and therefore it's not natural. My question now is, will it ever produce a natural number?
Answer: Cantor's diagonalization argument proves that the set $]0,1[$ is uncountable by negating the definition of countable set, i.e.

A set $S$ is called countable if there exists an injective function $f$ from $S$ to $\mathbb N$ (Wikipedia)

Specifically, it tries to describe a bijection from $]0,1[$ to $\mathbb N$ (note that this is the other way around, so he should be constructing at least a surjection) and then proves that it must be an injection by collecting and modifying all digits along a diagonal.
My point is, you don't have to test if $\mathbb N$ is countable because the definition of countability relies on $\mathbb N$! Trivially one can take the identity function in $\mathbb N$ and see that it is indeed an injective function like the one we're looking for.
Answer: The myriad other answers to this question more than cover the technical details, so I will try here to give an intuitive answer. The reason why diagonalisation doesn't work on the natural numbers is basically: because they can all be represented using a finite number of digits. OK, you might say, but how does this make them un-diagonalisable? Well, let's try the diagonal argument.
Suppose we have our list of natural numbers $a_1, a_2, a_3, \dots$ and we apply the diagonal construction to construct a number $b$ from an infinite list of digits $b = b_1 b_2 b_3 \dots$ such that digit $i$ of $a_i$ differs from $b_i$, which is digit $i$ of $b$. OK, then clearly this number is outside the set: this is the crux of the diagonal argument.
But is the number $b$ a natural number? Well, for starters, it doesn't look to hopeful, because there are an infinite list of digits $b_i$. Yes, you might say, but what if this infinite list of $b_i$ ends in all $0$s? Then we can just ignore the $0$s and interpret the rest as a natural number. But can $b$ end in an infinite string of $0$s?
The answer is no. Here's why. For the contradiction to work, we must have first assumed that all the natural numbers were in our list. From this, we can show that for every sufficiently large $i$, there is some $j$ such that $a_{j, j} = 0$ and so $b_j \neq 0$. Here $a_{j, k}$ just means digit $k$ from the number $a_j$ (as per diagram below). To prove this result, we consider the set of all numbers $A_i = \{a_1, a_2, \dots, a_i\}$. Now, either this is equal to the set $S_i = \{1, 2, \dots, i\}$, or there is some element of the set $S_i$ that is not in $A_i$. In either case, there is clearly a number not already in the list of at most $\log ({i + 1}) + 1$ digits i.e. its most significant digit is at most at position $\log ({i + 1}) + 1$. Since the log function grows much slower than linear, we know for sufficiently large $i$, $\log ({i + 1}) + 1 < i$. And so for all $j > i$, $\log ({i + 1}) + 1 < j$. Now, the number must appear somewhere, so it is equal to some $a_j$. But by $\log ({i + 1}) + 1 < j$, then $a_{j, j} = 0$, and so $b_j \neq 0$. Since we assumed an arbitrary $i$, this happens infinitely often, so $b$ has infinitely many non-zero entries. Thus $b$ can't be a natural number.
OK, maybe that strayed a bit from intuition... but basically, the idea is that the diagonal construction doesn't guarantee you a natural number, it only guarantees you a real number- because all infinite digit representations are real numbers, but not all are natural numbers.
Below: image for constructing a diagonal from the list. Note we go from top right to bottom left, starting as the least significant digit and moving to the most significant. Also, the least significant digit is at the far right of each number i.e. $a_{k, 1}$, as is the usual convention.

Why are natural numbers countable?


How to get the paragraph information in a custom display suite code item

Question: I want to add a custom field for a paragraph item in display suite,
but I don't know the name of variable.
I try a print_r($entity) and nothing is returned. How can I find out what the object name is?
Comment: Are you using the [paragraphs](https://www.drupal.org/project/paragraphs) module?
Comment: Yes I am using that
Comment: Not sure if I understand your Q correctly. So I will just throw this out there. You can add fields by going to Structure >> Paragraph Bundles then click on manage fields (assuming you already have a bundle, if not create one, then manage fields).
Comment: I know how to add them . I want to know how to display them in a specific way . So I want to use a custom display suite code field
Comment: I'm using a view and want to display the first paragraph of text type and the first paragraph of data type . But only the first one . Currently they all come out in the view
Answer:
I'm using a view and want to display the first paragraph of text type
  and the first paragraph of data type . But only the first one .
  Currently they all come out in the view

In Views click on your paragraph field, mine is called "test".
Then in Multiple Field Settings, change Display to 1
Comment: thanks but i also want the first paragraph of type "text" and the first paragraph of type "image"  .  how do i do that
Comment: This should do that. Exactly how did you setup your stuff? This is what I did. In content type Article, I added a paragraph field with Unlimited values. Then in bundle I added a text field with 1 value and an image field with 1 value.
Comment: how do you add those bundles to the view?  I can only add fields
Comment: @Dianacastillo I'm not talking about the view, in Structure >> Paragraph Bundles,  added a text field with 1 value and an image field with 1 value. Then all I did was add the paragraph field from Article, to the view.
Comment: no I need individual paragraphs of type either "image " or "text"  since they can add unlimited amounts of each , in different orders
Comment: @Dianacastillo I saw you accepted my answer ✅, problem solved?
Comment: you helped me with one part of the answer but i asked the other part here . thanks http://drupal.stackexchange.com/questions/224065/how-to-show-paragraph-bundles-of-different-types-in-a-view
Comment: @Dianacastillo If your bundle contains 1 field of text and 1 field of image, this answer should display you the first of text and the first of image.
Comment: no I want separate bundles , one with only text, one with an image and other things
Comment: @Dianacastillo oh **separate bundles**, ok, I see.


What could cause an Azure VM to stop responding completely?

Question: I have an Azure Linux VM running MySQL, which has stopped responding for the past 24 hours - ping, SSH, MySQL and everything else timeout when trying to connect to it. Yet the status shows as 'Running' normally in the portal.
I've tried restarting the server, stopping/start the server, resizing it. All complete successfully, but make no difference. I also detached the VHD from the VM and created a new VM with it instead, but the new VM has the same problem. I guess this means the problem is with the VHD itself. It had been running well for a couple of months before this. The only change recently this was adding a new, blank WordPress database for a new site with no traffic yet.
Is there anything I'm missing that could cause such a problem, or any way to solve it? It's incredibly frustrating as all my sites are down with no fix in sight :(
Comment: I would try to debug the network connection. See first public IP config (ifconfig), firewall (iptables), tracepath. The gateway may be wrong or there is a firewall in between. Try outgoing connections (wget, ssh, telnet). If you don't find it I would try to contact support, because it may have an external reason.
Comment: I wonder when there is NO SSH, how could possible we check the iptables? also, plublic IP Address in Windows Azure VM is not accessible from the VM at all. The only meaningful part is the support request! You should contact support, there is no much you could do! The other option is to download the VHD locally and run it in your own virtualized environment (that can attach VHD) and inspect the OS.
Answer: I've had this happen and it's an unfortunate situation. Sometimes when Microsoft patches the HyperV host that the VM runs on 3 things can happen if it fails to move it off before it reboots.

The VM goes down and comes up typically around 19 minutes later and all is fine.
The VM is hung in a funky state and requires you to force stop if via Powershell Azure commandlets. I blogged how to do this here.
An unfortunately thing happens much less often is that the VM itself is corrupt. You can't manage it, you can't get into it, and honestly I've found no way to fix it. I had to delete and rebuild the VM despite hours of trying to save it.

I realize this is an old post but wanted to provide a solution since I knew the answer in the hopes that it helps someone else as this still occasionally happens.


Problema com variável nula

Question: Estou a desenvolver um software em C# com o modelo MVVM, e com o Visual Studio.
É um software para gerir os membros de uma universidade.
Temos que utilizar também uma base de dados, com Code First.
O meu problema, é que me dá o seguinte erro:

"An exception of type 'System.NullReferenceException' occurred in
  UniversityMembers.exe but was not handled in user code
  Additional information: Object reference not set to an instance of an object."

Vou assinalar o erro no código em baixo:
public partial class MainWindow : Window
{
    private static VMUniversityMembers d = new VMUniversityMembers();
    ProjectContext db = d.ProjectContext;
    public MainWindow()
    {
        InitializeComponent();

        using (db)
        {

            var query = (DataContext as VMUniversityMembers).ProjectContext.UniversityMembers.SqlQuery("Select * from UniversityMembers");  **<---- Dá o erro aqui**

            foreach (var item in query)
            {
                listView.Items.Add(item);
            }
        }
    }
}

"VM UniversityMembers" é a View Model entre o Modelo "UniversityMembers" e a interface gráfica:
namespace UniversityMembers.ViewModel
{
    class VMUniversityMembers:BaseModel
    {
        private ProjectContext projectContext;
        private UniversityMember selectedMember = null;

        public List<UniversityMember> Members
        {
            get
            {
                return projectContext.UniversityMembers.Include("Position").Include("Sex").ToList();
            }
        }

        public ProjectContext ProjectContext
        {
            get
            {
                return projectContext;
            }
            set
            {
                projectContext = value;
            }

        }
        public UniversityMember SelectedMember
        {
            get
            {
                return selectedMember;
            }

            set
            {
                selectedMember = value;
            }
        }

        /**
         * Método para adicionar alunos
         */

        internal void Add()
        {
            var unmbm = new UniversityMember();

            projectContext.UniversityMembers.Add(unmbm);
            this.selectedMember = unmbm;
            this.OnPropertyChanged("UniversityMembers");

        }
        internal void Cancel()
        {

        }
        /**
         *Método  para guardar a informacao introduzida
         *
         */
        internal void SaveContext()
        {
            projectContext.SaveChanges();
            this.OnPropertyChanged("UniversityMembers");

        }
        /**
        * Método para eliminar um utilizador seleccionado na lista
        *
        */
        internal void Delete()
        {
            projectContext.UniversityMembers.Remove(SelectedMember);
        }
    }
}

E o modelo que uso é o UniversitYMembers:
    namespace UniversityMembers.Models
{
    class UniversityMember : Person
    {
       public string email;
      // public  Position position;
       public string migration;

        public string Email { get { return email; } set { email = value; } }
      //  public Position Position { get { return position; } set { position = value; } }

        public UniversityMember()
        {

        }
    }
}

A classe UniversityMembers extende na superclass Person, com outros atributos.
Answer: Vou considerar que DataContext é do tipo VMUniversityMembers, se não for, tá aí o erro. Parece estar depois.
A propriedade ProjectContext não parece estar sendo inicializada em lugar algum, parece que o problema está aí.
UniversityMembers certamente não está inicializada, aí também tem erro.
Algumas outras observações:
using (db)

Isso não funciona, não é assim que usa isso, não vai liberar nada aí, ou pior, vai liberar o que não pode, mas é outro assunto.
Isto:
public string email;
public string Email { get { return email; } set { email = value; } }

é o mesmo que isto:
public string Email { get; set; }

Coloquei no GitHub para referência futura.
O mesmo vale para todas as outras propriedade que fazem algo tão simples e padronizado.
Comment: Obrigado, vou alterar o código, e depois dou algum feedback.
Peço desculpa por alguns erros estúpidos, porque estamos agora a aprender a usar c# e o professor, não explica como deve explicar e ficamos um pouco sem saber o que fazer em caso de erros!
Comment: Se tiver alguma mais específico, eu tento dar uma melhorada.
Comment: muito obrigada, eu estou a fazer passo a passo, com as indicações que me deu, e ja posto o resultado. Obrigado :)

Problema com variável nula


How to find/hold vocal pitch within tone clusters

Question: I sing in a choir that performs a lot of music containing very close, tone-cluster type harmonies. We stand mixed rather than in sections, so it's especially challenging to find my pitch and maintain it. Worse, I'm an "inner voice" (tenor).
In rehearsal, I can cup one of my ears to hear myself better, but that looks pretty bad in performance.
1. What at-home exercises will improve my skill in this area?
2. How can I help myself within the ensemble?
I am comfortable hearing and singing intervals, fixed and moveable do, and singing common-practice music. I'm looking for techniques to address non-tonal music and finding/holding pitch within clusters/heavy dissonances.

A couple examples of the kind of music I'm/we're singing, timed to illustrative parts.
"...a riveder le stelle", by Ingvar Lidholm

Figure humaine, "VII: La menace sous le ciel rouge", by Francis Poulenc
Comment: I can't understand why the choir cannot be split into sections - particularly for rehearsals. To me, it's like having your foldback monitor only panned to the guitar, while you play bass. There may be some sense in it, but it escapes me! Hence comment only! Once you know your part, there shouldn't be a problem - in fact, in situations like this, I rely on other voices to  get my own pitch.
Answer: About the only rehearsals I've done in the last couple of years have been big bands, and that's been to get the ensemble playing really together. Funnily enough, the saxes all sit together, as do the trumpets, as do the trombones, as do the rhythm section. All that makes good sense. And, durng performances, the same happens.
I record it all, for various reasons. One being to hear exactly what goes on - not easy listening to trumpet figures while concentrating on my own parts, another being to listen to what I played - how it blended (or not), how the ad lib bits adlibbed, another being when I need to, I can replay parts and play along with them.
That last bit is an idea for you. It could be important where you place the mic, but that isn't too onerous.So, you go home, replay, look at the dots, sing along. Also play along on piano, etc.- your part - so it becomes ingrained.
I'd also have a look at others' parts too, to be aware of how they fitted in with my own. And, listening to recordings of the pieces, singing along, too. I'm well aware that the arrangements may be different, but it's another avenue. You might even stumble on the exact one the choir uses. Serendipity!
In response to the second question - I'd be waiting to be convinced there's a good reason why the choir is all mixed up. I went to an auditon a few years back, and the band was set up as if at a gig - drummer behind etc. I enquired why there could be no eye contact - it was supposed to be a rehearsal - and the answer was 'it's like a gig'. Well, rehearsals can be like gigs - they're usually called dress rehearsals'...
Answer: Better to cup your ear than to lose your pitch!
I don't think there are any special techniques beyond the obvious ones - lots of practice of sight-singing in atonal style and thorough familiarity with your part.   And experience, of course.
Comment: This is a comment, not an answer.
Comment: No it isn't, yes it is!


Number of Deformation Parameters of Simple Polyhedron Equals Number of Edges

Question: Suppose $P$ is a simple convex polyhedron with $n$ faces. Euler's formula and the handshaking lemma tell us that the number of edges $E=3n-6$. By a deformation of  $P$, I mean a polyhedron, combinatorially equivalent to $P$, resulting from slightly perturbing the $n$ planes defining $P$. (Since $P$ is simple, any sufficiently small perturbation of faces preserves the combinatorial type.) Let's say two deformations are the same if there is a Euclidean isometry taking one to the other. A perturbation of each plane is given by 3 parameters (normal and position), and the Euclidean group is 6 dimensional. I believe this means that the space of deformations of $P$ is $(3n-6)$-dimensional—that is, $E$-dimensional. So, a deformation of $P$ is determined by one real parameter for each edge of $P$.
What could this parameter possibly be? Clearly not dihedral angle, as scaling is a non-trivial deformation which preserves all angles. Taking $P$ to be the prism of a rhombus, as suggested in this answer, demonstrates that it can't be edge length. But these two quantities are the only geometric properties of an edge that I can think of. Perhaps this is just a complete coincidence? Or perhaps my dimension argument is wrong.
Comment: Perhaps [this article](https://arxiv.org/abs/1212.5812) might contain some useful references. The introduction confirms your computation and points to an older proof by Legendre.
Comment: The article seems to imply that the result—i.e., that the deformation space is $E$-dimensional—holds for any polyhedron, not just simple or simplicial ones. Is that right?
Comment: You are right, but I have no immediate idea for how to generalize my answer to match this.
Answer: Simple polyhedra might not be uniquely determined by the lengths of their edges, but simplicial polyhedra (all faces are triangles) are. This follows essentially from Cauchy's rigidity theorem.
The polar dual $P^\circ$ of your simple polyhedron $P$ is simplicial, and each edge of $P$ corresponds to an edge of $P^\circ$. If you assign to each edge $e\subset P$ the length of the dual edge, then this allows for a unique reconstruction. Simply reconstruct the dual from the edge lengths, and then dualize to obtain $P$.
There is one subtlety, in that the dualization process depends on the position of the polyhedron relative to the origin. So let us choose a conanical point for dualization, say, the average of all vertex coordinates. Put this point into the origin and you get a unique correspondence between $P$ and $P^\circ$.
The real number that you assign to each edge of $P$ in this way is not "obvious" from a visual inspection of the polyhedron, in contrast to edge length or dihedral angles. It not only depends on the edge $e$, its location or the incident faces, but on a full tubular neighborhood of $e$. But as you have seen, this complexity would have vanished if you instead would have considered simplicial polyhedra.


Chi-Square goodness-of-fit test on sample space or quantiles?

Question: I think there are two ways to perform the chi-Square goodness-of-fit test:

Divide the sample space into bins of equal size and see how many observed values fall in each bin. where the expected per bin depends on the fit.
Divide the cdf of the fit into B bins of equal size (e.g., five bins of size .2 each, or 8 bins of width .125 each) and see where each observed value would belong into. -> count observed values per bin of size  > calculate the chi square statistic (where the expected nr per bin is n/B or observations/bins, since the quantiles are distributed uniformly)

Is 2. a valid approach? And is there anything noteworthy about the second approach?
Comment: I think the number of bins will determine the value of $\chi_n$, where $n$ is the number of bins $-1$. I might be wrong
Answer: If I understood the question correctly, the first approach corresponds to the regular chi-squared test and the second one is over the cdf.
The fitting tests are all based on the idea; if some samples are coming from a certain distribution. If the error between the observed mean and the actual mean are Gaussian distributed, then their squared sum will be chi-squared distribution.
According to $2-$, deriving some statistic over the cdf bins is not a useless idea. If the samples resamble the cdf of the true distribution then you are done. On the other hand, the deviations from the true frequecies will indicate you the goodness of fit. However a special care should be taken for about the number of bins/number of samples as well as distribution of the error.


How to stop execution of a Cucumber feature if any of the scenarios had failed

Question: If I have 10 scenarios in a feature file and if one scenario fails then I want to stop executing or proceeding with next scenario. I want to terminate the execution for that particular feature file. How can I do that in Java?
Comment: Ideal would be not having any dependencies between scenario's.. so that if one scenario fails we know where to look for and which scenario is failing.. And also biggest advantage is we can execute the tests in parallel !!
Comment: For curiosity why do you want to do that.. do you have any dependencies between scenarios??
Comment: Yes It does have dependency.
Comment: Cucumber is not designed to support scenarios with dependencies between them.
Answer: I notice that the question is tagged with Java.
I've not tested the below answer. Its just based on assumption..
Well, we need to tweak the code based on the requirement..
 - We have the @Before and @After in Cucumber to serve this requirement.
If I were you, I would do like this...
In @Before, I would check (if any) scenarios were failed or not. If failed, then I'd terminate the thread for the current test and update the results.
In @After, I would update the scenario status and update the result json after test execution.
So, in every iteration (for every scenario) first the  @Before will be invoked, in which the logic will look for scenarios which were executed prior to the current scenario.
Also, needless to mention that, I agree with the comments added on the question. All the scenarios should be independent. (But with respect to the requirement, one is allowed to tweak ;) )
Expert Tips  mentioned really adds value to the quality of Cucumber and its usage. Hope this helps.
Good luck...!!
Comment: Thank you @Seb, It should be `@Before` and `@After` from Cucumber package cucumber.annotation.After/Before
Comment: Cucumber-JVM does not have BeforeScenario/AfterScenario hooks
Answer: Try using @BeforeClass and @AfterClass in "RunCukesTest" class.


select prometheus alerts newer than a given time

Question: I am working with grafana, trying to show a list of pods that are triggering a custom prometheus alert.
This query do the trick:
sum(ALERTS{alertname="myCustomAlert"}) BY (pod_name)

The problem is, it list all the alerts, and don't seems affected if I change the time interval to see only the ones launched in the last 5 minutes, or last hour
There is any way to limit in time the alert list? Lot of thanks!!
Answer: That expression will produce the number of alerts by pod_name firing at the current time (just as you would expect up{instance="foo"} to tell you whether instance foo is up now, whether you're looking at a dashboard that shows the last 5 minutes or the last hour).
If you want to see the values change over time, you could e.g. graph it. Then you'd see it change over time. And when the alert started and stopped firing for each pod.
And if you want the value at some past time, simply set the end time of the Grafana dashboard range to that time. (E.g. if your dashboard was showing the time range between 2 PM and 3 PM on January 1st, then your query would return the alerts firing at 3 PM on January 1st.
Comment: _"if your dashboard was showing the tim range between 2 PM and 3 PM on January 1st, then your query would return the alerts firing at 3 PM on January 1st."_ => No, its not. I am working with an alert fired some hours ago, and if I select a time range in grafana "last five minutes" the list still is showed. Also, the metric don't have any "date" or "time" label to filter it for :(
Comment: It's not about when the alert started firing, it's about whether it's still firing now (or whatever the end of your selected range in Grafana is).


How to replace every key in a nested object given a mapping in JavaScript?

Question: How to convert each and every nested object key when the structure and values remain the same. The key mapping is arbitrary, yet predetermined like:
x -> key1
y -> nested1
x.z -> nested1.key1
...

And in terms of a sample JavaScript object:
const inObj = {
  x: "A value",
  y: {
    z: "Another value"
  }
}

// ...

// Desired output
// {
//   key1: "A value",
//   nested1: {
//     key1: "Another value"
//   }
// }

Edit: I do not want to mutate the original object. By intuition, I thought of using an object for old and new keys and using map() function. However, I could not settle a logic for a nested and complex object with that.
Comment: do you want to keep the object reference? what have you tried? what does not work?
Comment: @NinaScholz I could not think of a neat solution, indeed. Added a brief edit anyway, thanks.
Answer: My favorite workhorse for this type of thing is the following little function.
function transform(obj, fn) {

    function transformer(x) {
        if (!x || typeof x !== 'object')
            return x;

        if (Array.isArray(x))
            return x
                .map((v, k) => fn(k, v, transformer))
                .filter(x => x)
                .reduce((a, x) => (a[x[0]] = x[1], a), []);

        return Object.fromEntries(
            Object.entries(x)
                .map(([k, v]) => fn(k, v, transformer))
                .filter(x => x));
    }

    return transformer(obj);
}

How does this work? It walks your object recursively and invokes a callback for each key-value (or index-value) pair. The callback receives three arguments: a key, a value and a "carry on" function and is supposed to return a new key-value pair. In the callback you can choose to continue recursion by calling the "carry on" function on the value, but you don't have to. If the callback returns undefined, the pair is eliminated.
Applied to your question, the callback might look like this:
REPLACE = {
    'x': 'key1',
    'y': 'nested1',
    'y.z': 'nested1.key1',
}

stack = [];

result = transform(inObj, (key, val, carryOn) => {
    stack.push(key)
    val = carryOn(val)

    let path = stack.join('.')
    if (path in REPLACE)
        key = REPLACE[path].split('.').pop()

    stack.pop()
    return [key, val]
})

You might want to wrap the whole thing into a function to avoid the global stack.


Not Able To Deploy Django App Because of This Error How To Fix It

Question: ERROR: mysqlclient-1.4.6-cp38-cp38-win32.whl is not a supported wheel on this platform.
!     Push rejected, failed to compile Python app.
!     Push failed
Answer: Try google, "mysql build from wheel".
Find your operating system.
Download.
Try again.
Answer: Go to Settings.py
Set DEBUG = 'None'
In case that does not work, refer to this tutorial - https://pythontuts.com/django/posts/301154532665841128/


Questions about a proof of Stokes' theorem in my calculus 2 lecture notes

Question: My lecture notes look to prove Stokes' theorem for the special case where a surface can be represented as the graph of some function, so $z=f(x,y)$.
The surface $S$ is parametrized as $r(x,y)=(x,y,f(x,y))$, where $(x,y)$ is in the region $U$ in the $xy$ plane.
Now assume $U$ has a boundary curve $C_u$ and $S$ has a boundary curve $C_s$.
My first question is where it is said that the line integral of the vector field $v=(v_1,v_2,v_3)$ over the curve $C_s$ is equal to the line integral of the same vector field over the curve $C_u$. Why is this the case?
Lecture notes for my first question
My second question is I believe about a total derivative but I'm not sure. My lecturer has written that since $z=f(x,y)$, $dz=(f_x)dx+(f_y)dy$ where $f_x$ and $f_y$ denote the partial derivatives of $f$ with respect to $x$ and $y$ respectively and $dx, dy, dz$ denote normal differentials, not partial ones. Can someone also explain this equality to me, please?
Lecture notes for my second question
Comment: @anomaly:  thank you for correcting the spelling of Stokes
Answer: The boundary $\partial U$ of the set $U$ in the $(x,y)$-plane has some parametrization
$$\partial U:\quad t\mapsto\bigl(x(t),y(t)\bigr)\qquad(0\leq t\leq 1)\ ,$$
and the boundary $\partial S$ of your surface $S\subset{\mathbb R}^3$ then has the parametrization
$$\partial S:\quad t\mapsto\bigl(x(t),y(t),f\bigl(x(t),y(t)\bigr)\bigr)\qquad(0\leq t\leq 1)\ .$$
Expanding the integrals
$$\int_{\partial S}{\bf v}\cdot d{\bf r},\qquad \int_{\partial U}\bigl(v_1 dx+v_2 dy+v_3 dz\bigr)$$
with
$$dx=x'\>dt,\quad dy=y'(t)dt,\quad dz=f_x\bigl(x(t),y(t)\bigr)\>x'(t)dt+f_y\bigl(x(t),y(t)\bigr)\> y'(t) dt$$
then shows that they have the same value.


Kicks out of bounds

Question: I have some situations

Kickoff touched by receiving team goes out of bounds, who gets the ball? I mean the RT doesn't fumble but only muffed the kickoff.
Kickoff muffed by RT (or after 10 yards) then touched by KT and finally it goes out of bounds? Who gets the ball?
Muffed punt by RT goes out of bounds, who gets the ball
Muffed punt by RT then touched by KT and finally it goes out of bounds, who gest the ball?
Answer: For all of these questions, unless the kicking team legally gains possession of the ball in the field of play, the receiving team will have the ball.   That doesn't happen in your scenarios, so the receiving team will have the ball for the next play in all four cases.
Touching the ball may give the other team certain rights in some situations, but it does not change possession.
From 2023 NFL Rules

6/2/3 Ball placed at out-of-bounds location.
6/2/3 25 yards from kick or at out-of-bounds location, RT choice.
and 4.  9/4/4 (assuming no illegal batting), out-of-bounds location.
Answer: Any punt goes out of bounds is a ball is put back by RT where it goes out of bounds.
In all those cases:

Punt Untouched out bounds
Muffed punt by KT
Muffed punt by RT
Muffed punt by RT and then the ball hitted by KT out.

For kickoff we have the penality only if goes out of bounds untouched.
If the kickoff

Muffed by RT
Muffed by KT
Muffed by RT then it hitted by KT out.
The play restarts in possession of RT at the spot where the ball goes out of play.
Am I right?

Kicks out of bounds


Generic of type RawRepresentable is misinterpreted as self it seems

Question: To use NSCoding with Swift's Enum type I made an extension on NSCoder:
extension NSCoder {
    func encodeEnum<Enum: RawRepresentable where Enum.RawValue == String>(value: Enum, forKey key: String) {
        self.encodeObject(value.rawValue, forKey: key)
    }

    func decodeEnumForKey<Enum: RawRepresentable where Enum.RawValue == String>(key: String) -> Enum? {
        guard let returnValue = self.decodeObjectForKey(key) as? String else { return nil }
        return Enum(rawValue: returnValue)
    }
}

The encodeEnum method works fine for a String-backed Enum, but when I try to decode the prior encoded Enum like so:
enum MyEnum: String { case Something, Other }
class MyEnumClass: NSObject, NSCoding {
    let myEnum: MyEnum

    init(myEnum: MyEnum) {
        self.myEnum = myEnum
    }

    required convenience init?(coder aDecoder: NSCoder) {
        guard let tmp = aDecoder.decodeEnumForKey("myKey") as? MyEnum else { return nil }

        self.init(myEnum: tmp)
    }
}

I get an error on aDecoder.decodeEnumForKey("myKey"):
Value of type `NSCoder` has no member `RawValue`

I'm pretty sure it has something to do with the generic and the condition that Enum.RawValue == String. But I do not understand while it's not working, but works for encodeEnum().
Answer: The problem is that in
guard let tmp = aDecoder.decodeEnumForKey("myKey") as? MyEnum else { return nil }

the compiler cannot infer the generic placeholder of
func decodeEnumForKey<Enum: ...>(key: String) -> Enum?

to be MyEnum, you have to cast the result to MyEnum? instead:
guard let tmp = aDecoder.decodeEnumForKey("myKey") as MyEnum? else { return nil }

so that the return type is inferred as MyEnum? from the calling context.


Replace default words in exposed filters

Question: I created an exposed view that allows users to sort content based on content type or date. In my content type drop down menu, the default choice is - Any -, I tried to replace it in the settings file's string override section, but while this works for numerous other defaults, it doesn't seem to be taking for exposed views. Any help would be much appreciated!
Answer: I have tried to resolve from backend/server side, but without success, so I have reviewed a way using Jquery (client side), while an backend alternative is achieved:
<code><script>
$("#here-field-name option[value='All']").html("Anytext");
</script>
</code>
Also, here is alternatives from backend perspective, maybe are useful for you how to default value to select list CCK with form_alter
I hope information be useful.
Answer: go to the folder : sites\all\modules\views\handlers and open the
views_handler_filter.inc file...
and search for :"- Any-" in the file...
one of them is located in the  "exposed_translate" function.
change it to whatever you what.
it is a little bit hacky but it works ;)


learning approach for an expert system

Question:
Step 1: I developed an expert system that classifies data into two classes, each rule in this expert system has a certainty factor (expert opinions).
Step 2: The input of the system is a group of sentences and the output is classified sentences into two classes like c1, c2.
Step 3: The user has to mark the sentences placed in the wrong.
Step 4: the system shall edit rules certainty factors depending on the user's feedback, to make the system more accurate.

I want a machine learning algorithm that uses my rules to classify the data.
not: l have a labeled dataset
Comment: I have a labeled dataset written as a CSV file, like
(sentence, class)
Comment: Welcome to Cross Validated! Could you please provide us with a bit more step-by-step information about what you mean? So step 1, you have a model that makes a binary prediction, with an associated probability/certainty. Step 2, you want to somehow combine a user input along with the model's output to generate a more accurate prediction? Or do you mean you want this same model to take into account a user's opinion, before giving prediction? I hope you understand the kind of information that is lacking, please clarify your question and I can have a crack at it.
Comment: depending on what "learn from users' feedback" looks like, this is either an example of [tag:online-algorithms] or [tag:reinforcement-learning], both of which are large topics. Please [edit] to be more specific about what particular problem you're facing and what you would like to know.
Comment: @VladimirBelik I edit it, I hope it is clear to you now
Comment: Alright, I understand your procedure, but don't fully understand your question. Are you asking what algorithm you should use to edit your list of rules based on user's feedback?
Comment: @VladimirBelik Yes, I want a method based on feedback from users that calibrates the certainty factor for the rules.
Comment: I think that is a near-impossible and probably unnecessary task. What you should do is have a machine learning algorithm BE the expert. Give it information and the correct answers, and it will figure out the best rules by constantly correcting/adjusting itself against the list of correct (user determined, perhaps) answers you give it.
Comment: okay, Which algorithm do you know to recommend to classify texts?
Comment: To be clear, I don't think you should toss out those rules you made. You can transform them into features to feed into the ML model, and the model will decide how much to weight each feature. You're asking about the algorithm - is your data in tabular form? (Like, a regular dataset with rows of examples, columns of features + column with correct answer)?
Comment: Perfect. If you can open the question back up, I will provide you with a detailed answer.
Comment: Hi @VladimirBelik, My question is reopening!
Answer: For future readers, OP and I had a small back and forth in the comments under his question that clarified what he was working on.
Direct answer to the posed question:
I think doing exactly what you asked (having an ML tool adjust your existing rules) is effectively impossible (extremely complex task).
My recommendation:
Instead of having ML adjust your existing "expert" rules, you should just have an ML algorithm become your "expert". You mentioned you have a labelled dataset, so you should just treat this as a supervised learning problem, where it is up to the ML algorithm to become the expert and "decide" what the best rules are for classifying your text. Again, since your dataset is already labelled (since you already know the correct classification for each sentence), your ML algorithm will receive constant feedback and try to adjust to get the best result.
Now the harder question is: "What data do I give the ML model so that it can make these predictions?"
Well, this is where your existing expert rules come in. Don't throw them away! You can transform them into features for the learner, and the learner will decide how to weight/utilize that information.
There's two ways you can do this. Let's say, as an easy example, that one of your expert rules is that "If sentence is longer than 7 words, it's generally class 1 and if it's shorter, it's generally class 2". From this rule, you can extract two features:
One feature is to feed "number of words in sentence" to the algorithm, and it will try to find the best cut off point (maybe it's 9 and not 7). You feed it the same data your rules use, and let it make the determination.
The second thing you can do is along with that raw data "number of words in sentence", you can feed in some kind of binary 1/0 determination based on your existing rules, so that the algorithm can potentially weight that in as well.
So for the same example, you have two features. Based on that rule you already have, you can feed in the # words in sentence, plus your own expert determination of what the class "should" be based on that information.
I hope this makes sense.
For the ML model, I would heavily recommend RandomForest. It easily handles different kinds of inputs (categorical, numerical etc.), it has few hyperparameters you need to tune, is quick to train, generally has great performance, and it gives an easily interpretable probability output associated with each class prediction. It's just overall a very "plug and play", beginner-friendly algorithm compared to others, and it generally delivers comparable results to other algorithms.
Best of luck!
Comment: Thanks Vladimir! I will read about RandomForest. really it Looks great idea.
Comment: @Eng.sh Fantastic! :) Did I fully answer your question?
Comment: Yes!  you did, I read some about RandomForest I seems simple Algorithm, I hope to get high accuracy with it. If not do you recommend another ML model, please?
Comment: @Eng.sh Great! In such case, please consider accepting the answer :) If you do not get good results with RandomForest, another model *probably* won't save you. You will need to do more feature engineering (it's generally much more important than the model you use).

learning approach for an expert system


htaccess wildcard subdomain redirect with https non www

Question: I have searched and search to no avail. If there is already an answer out there, please let me know.
But I am trying to redirect wildcard subdomains to a specific file with a GET request. At the same time need to redirect to https and non WWW
For Example:
http://user1.example.com -> https://example.com/index.php?user=user1
https://user2.example.com -> http://example.com/index.php?user=user2
Any help will be forever grateful and thank you in advance!
Answer: Try with below rule,
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(.*)\.example.com
RewriteRule ^ %{REQUEST_SCHEME}://example.com/index.php?user=%1 [R=302,END]

I am slightly unsure that request scheme will work in lower version of apache let me know the result.


gsutil "Copying mtime from src to dst" having moved source files?

Question: I use gsutil to backup photos from a dedicated box to google nearline storage.
Recently I moved all of my photos from that dedicated box to a new dedicated box.  I made sure to use the relevant archival rsync flags to avoid changing the files mtimes.
I've just run gsutil for the first time on the new box, walked away, and expected it to only move over any NEW files that hand't been backed up previously.
gsutil -m rsync -r /originals/. gs://my-bucket

Instead I came back to find an output comprising hundreds of lines of
Copying mtime from src to dst for gs://my-bucket/photo123456.jpg

I can see (via ls -ltu) that the last-accessed time was affected when I moved the files, but the modified time is correctly untouched, and in this instance showing a date from 2010.
I've cancelled the job for now.  What have I done wrong?  Can I fix this so it won't try to do that for all 3million files?
On further inspection I can see that the backed-up files in nearline have a modified date of 2015, when they were initially backed up.  The ones that produced the message today now have today's date on.
Why would that happen?  The backup job has run 1000 times since the files were originally backed up, without overwriting the files modified time, so why isn't it happy now?
I wonder if it could be because I'm running a newer version of gsutil now?
Answer: In this Stack Overflow question using the -c option with the gsutil rsync helped. This option:

Causes the rsync command to compute and compare checksums (instead of
  comparing mtime) for files if the size of source and destination
  match. This option increases local disk I/O and run time if either
  src_url or dst_url are on the local file system.

(Source: GCP docs)


Fatal error: Call to a member function link()

Question: i am receiving an error while editing extensions in opencart.
Fatal error: Call to a member function link() on a non-object in C:\xampp\htdocs\organics2you\admin\controller\module\couponpop.php on line 28
Answer: this problem because the different version just creat variable and pass object of url   as $data['url']=$this->url; and call it from your temp;


Run-length encoding giving wrong result

Question: I implemented a Run-length encoding that iterates through the input string, counting consecutive occurrences of each character. When the character changes, it appends the count followed by the character to the encoded string.
def run_length_encode(string):
    encoded = ""
    count = 1
    for i in range(1, len(string)):
        if string[i] == string[i - 1]:
            count += 1
        else:
            encoded += str(count) + string[i - 1]
            count = 1
    return encoded

# Example usage:
original_string = "AAAABBBCCDAA"
encoded_string = run_length_encode(original_string)

print("Original string:", original_string)
print("Encoded string:", encoded_string)

The issue is that the code I implemented does not count the last charater.
The above code return 4A3B2C1D instead of 4A3B2C1D2A.
Thanks
Answer: before returning encoded you need to  append the count and character when the loop terminates encoded += str(count) + string[-1]
def run_length_encode(string):
    encoded = ""
    count = 1
    for i in range(1, len(string)):
        if string[i] == string[i - 1]:
            count += 1
        else:
            encoded += str(count) + string[i - 1]
            count = 1
    encoded += str(count) + string[-1]
    return encoded

# Example usage:
original_string = "AAAABBBCCDAA"
encoded_string = run_length_encode(original_string)

print("Original string:", original_string)
print("Encoded string:", encoded_string)

Run-length encoding giving wrong result


iOS: Put checkmark on preselected row on viewDidLoad

Question: I'm using Xcode 5.1 with iOS7.  In my app I have a static uitableview made up of several sections, each has 2-3 rows.  I used a static table because this my settings view controller and the contents will not change.
In one such section I have 2 rows.  Each row has a label on the right side, similar to the iPhone's General --> Auto-Lock rows.
Like the auto-lock row, when the user selects the row it segues to another tableview controller made up of several rows.  Whenever a user selects a row here, I show a checkmark.  When the user backs out of this vc I show the name of their selection in the label on the right-side of the row, again just like the auto-lock example.
I use an unwind segue to pass the selected value back (from detail to master, you could say) so I know what the user selected and that's how I set the value in the label that's sitting on the row.
What I'd like to do is be able to already have the detail tableview row checked with the last value the user selected (again, like the auto-lock example).  I know the name of what they selected because I send it over in the prepareForSegue.  I don't know how to tell the tableview which row to put the checkmark because the detail table doesn't have any connection to the master table, sending 'indexPath.row' wouldn't work.  Because I have a small amount of rows, I could just check each row and see if its text is equal to the text that I sent over.  I'm not sure if that's the best way to do it, though, because I'd like to allow the user to enter their own text in these labels in a future release.  I'd appreciate any ideas.  Thanks!
EDIT: I should better clarify my issue and what help I'm looking for.  I have 2 rows in a Settings table that both segue to a detail table.  This detail table contains several rows of static data.  At the time the user selects a row from this detail table, I don't know which row from the Settings table is making the request; I just hand back the label on the row thru an unwind segue.  Because of this, I need to be able to look up the value of the data (sent from the Settings table) on the 'viewDidLoad' of the detail table. I'm sorry for not making this clearer from the beginning.
Answer: I would simply record the row (or also section, if you want) under a NSUserDefaults key. In viewDidAppear you can set the checkmark.
This would work in any event. If you allow editing and, say, deletion of a row, you can adjust this setting on the fly. Equally, changing the text of the label would be irrelevant.
- (void)tableView:(UITableView *)tableView
  didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

  ...
  if (indexPath.section == kTrackedSection) {
      NSInteger selectedRow = [[NSUserDefaults standardUserDefaults] integerForKey:kSetting];
      if (selectedRow == indexPath.row) { return; }
      UITableViewCell *otherCell = [tableView cellForRowAtIndexPath:indexPath];
      otherCell.accessoryType = UITableViewCellAccessoryNone;

      [[NSUserDefaults standardUserDefaults] setInteger:indexPath.row ForKey:kSetting];
      cell.accessoryType = UITableViewCellAccessoryCheckmark;
  }
}

Comment: Thanks, Mundi.  I think your first sentence is the problem I'm having.  I only have 2 rows on the master table but 6 on the detail.  There isn't a direct correlation between the rows on the master and the rows on the detail, so I can't say "row 4 on the master is the same as row 4 on the detail".  I know the value of the row because I send it to the detail in a segue.  I just don't know how to identify the correct row on the detail table in order to put a checkmark on the detail row.
Comment: If it is a static table you should know the where everything is. Just make sure you rely on your data model (such as the user defaults) to find out and persist.
Comment: It's true, I do know where everything is but because I want to give the user the ability to add/edit/move the rows in the detail tableview I was looking for help in interrogating that tableview by content.  I don't know how Apple does it, they do the same pattern in a dozen different places.
Comment: You asked how to store the selected row and I told you. That is independent from how many rows there are, or what the strings are. If you want, you can also store an array of strings in NSUserDefaults.
Comment: Thank you for your suggestion.  Since I already know how to add a checkmark to a row, because I already do this now as I indicated in my question, I don't think your suggestion will work for me.  I appreciate you taking the time to respond, though.
Comment: It is not about putting the checkmark on the cell, it is about persisting this information. Anyway, if the answer helped you, which it should, you should accept the answer.
Comment: Thank you but that answer did not help me because your answer did not address my question.  I have clarified my question.
Comment: Looks like a royal waste of time. Thank you.


Creating collection of class that isn't table with entity framework

Question: Is there any way I can create collection of objects that aren't table?
I mean something like -
class Deck
{
     [Key]
     public int DeckId { get; set; }

     [Required]
     public ICollection<Card> Cards { get; set; }
}

If I had a table for the cards it would be alright, but what will happen if I don't have a table for that class?
Comment: Why would you do this?  It would violate your separation of concerns.  If you need Deck to have cards, then use a DTO or view model, since the data concern isn't interested in cards.
Comment: Because i'm creating a card game and since there only one from each card I can't that any card will be duplicated. I have to check if the new card is already in use so I thought to create a Collection of the cards that in use. Do you have a better idea? @Maess
Answer: Yes you can. In code first you mark the entry with the NotMappedAttribute. Depending on your configuration it should be possible to put it into a partial class.
Here's an example that filters a mapped set of related data into a specific unmapped sub set of the same data.
using System.ComponentModel.DataAnnotations.Schema;

[NotMapped]
public ICollection<Cards> RemainingCards
{
    get
    {
        return AllCards.Where(s => s.SomeCiteria == true).ToList();
    }
}

Comment: So I have to create a table for the cards and then I will fetch it from the Deck class by my condition?
Comment: @Videron no that's just an example. you can hard code an array of 52 cards if you like ... the important part is the `NotMappedAttribute`
Comment: but I still need it will be saved on the database. My problem is that if I will save everything on table for cards I will have to check everytime something like this -
`return AllCards.Any(s => s.DeckId == Id && s.CardValue == Value);`
and it will check a lot of rows so I thought to minimize it by save it in list or array.
Comment: @Videron the question title says there's no table :-/


Is it possible to compute some measure of effect size from four means from a split-plot (both within- and between-subjects) 2x2 design?

Question: For a meta-analysis, we are interested in the comparison of two groups. From the articles, we can extract four means: two baseline measures on one of our dependent variables, and two measures collected after some manipulation took place. We also have the standard deviations for these means. The sample sizes are generally very small (which is one of the reasons why we usually have both pre- and post-measures; the researchers were probably aware of their low sample sizes and wanted to increase their power).
Although these means and SD's (variances) are often reported, the only statistics we have are usually from multivariate analyses, rendering them, at best, tricky to use (because the models (included covariates) differ substantially between studies). So we'd prefer to stick to the means and variances.
So, we want to compute the effect size. The go-to measure would be Cohen's d, to see how strongly these groups differ. We could ignore the baseline measure and compute d for post-test only, but this would of course yield a much lower power; ideally we'd look at change from baseline.
However, we don't have individual scores - we can't compute change over time per participant. We only have 'within-group variance' (to use oneway anova vocabulary).
I'd say this means that we might as well not have the baseline means: there is not way to use them to compute an effect size measure. But I want to make sure this is true - I'm not sure there's not something I miss. It feels like I do, but I'm not sure.
To provide an example, we have from one of the studies the following means (SD's):
<code>               pre            post
control        33.2 (12.4)    33.1 (11.2)
experimental   29.5 (13)      30.9 (14.1)
</code>
Our goal is to express this association (columns 'within', rows 'between' subjects) in an effect size measure.
Is my intuition/fear, that we're forced to discard the first column because we can't remove or model the dependency between the two columns, correct? Or am I missing something and is there a way to use all available data after all?
Answer: This was discussed by Becker (1988) (and others). The suggested approach is to calculate the standardized mean change within each group and take the difference. The computation of the standardized mean change for one group is explained in this answer. So, compute this for the first and second group and denote those two values as $d_C$ and $d_E$ (and the corresponding sampling variances as $v_C$ and $v_E$). Then the difference in the standardized mean change is simply $$d = d_E - d_C$$ with sampling variance $$v = v_E + v_C.$$
One difficulty here is that the computation of $v_C$ and $v_E$ requires knowing the correlation between pre- and post-test scores within the groups (which is often not reported). So, you may have to make an educated guess about the correlation and then do sensitivity analyses at the end.