How to remove elements from array satisfying condition

Question: I want to delete json elements which are satisfying the condition. For that I used the given code
var index = -1;
for (var i = 0; i < data.dashLayout.dashlets.length; i++) {
  if (data.dashLayout.dashlets[i].rowNo == selectedrowno) {
    if (index == -1 || data.dashLayout.dashlets[i].rowNo < data.dashLayout.dashlets[index].rowNo) {
      index = i;
    }
  }
if (index != -1) {
       data.dashLayout.dashlets.splice(index, 1);
    }
}

But iteration is not completing because the data.dashLayout.dashlets.length is reducing with splice. How can I solve this issue? I want to delete all items that are satisfying the condition. Please help
Comment: Loop backwards. Or adjust `i` inside the `if` that does the `.splice()`. (Also, there's no JSON in your code: JSON is a string format. What you have is objects and an array.)
Comment: @nnnnnn looping backwards is definitely the easier option
Answer: Another two solutions
var a = [2,5,8,13,9,1,4,8,10], l = a.length, c = 5;

// using reverse loop
while(l--){
    if(a[l] < c) a.splice(l, 1);
}

// using filter
var b = a.filter(function(e, c) {
    return --e > c;
});

console.log(a); // [5, 8, 13, 9, 8, 10]
console.log(b); // [5, 8, 13, 9, 8, 10]

Answer: If you split the array in the loop .the array will be reducing you should not iterate fully , so you have to think different idea . so my solution is  you have to store the index based on that you have to remove the array .In the mean time every time the index will be changed so you have to use -1
var index = -1;
var arr = []  // make array
for (var i = 0; i < data.dashLayout.dashlets.length; i++) {
    if (data.dashLayout.dashlets[i].rowNo == selectedrowno) {
        if (index == -1 || data.dashLayout.dashlets[i].rowNo < data.dashLayout.dashlets[index].rowNo) {
            index = i;
        }
    }
    if (index != -1) {
        // data.dashLayout.dashlets.splice(index, 1);

        arr.push(index);  //stored it
    }
}

// to remove

for(var i in arr){
    if (i == 0) {
        data.dashLayout.dashlets.splice(arr[i], 1); // to remove init
    } else {
        data.dashLayout.dashlets.splice(arr[i] - 1, 1); // now index is changed now use -1
    }
}

Answer: I would recommend using the filter method of the Array object. Filter method will return a new array which only contains the elements you want. Please see the definition of the filter method here
The usage will be like the code below
var newDashlets = data.dashLayout.dashlets.filter(function(dashlet, i) {

    // Here your code returns true if you want to keep dashlet.
    // Return false if you don't want it.

});

Answer: in jquery
data.dashLayout.dashlets = $.grep(data.dashLayout.dashlets, function (dashList, indexpos) {
    if (dashList.rowNo == selectedrowno) {
        if (dashList.rowNo < data.dashLayout.dashlets[index].rowNo || index == -1) {
            index = indexpos;
            return false;
        }
    }
});

Answer: Using map in jquery
data.dashLayout.dashlets = $.map(data.dashLayout.dashlets, function (dashList, indexpos) {
     if (dashList.rowNo == selectedrowno) {
         if (dashList.rowNo < data.dashLayout.dashlets[index].rowNo || index == -1) {
             index = indexpos;
         } else {
             return dashList;
         }
     }
 });


Problema com window.location

Question: Estou tento problemas com window.location = "index.php", ele não está redirecionando da pagina login.php para index.php, veja o código:

Aqui está meu código de resposta é muito maior que isto mas vou postar só a verificação:
if (isset($cookies['auth_token'])) {
    Cookies::set('auth_token',            $cookies['auth_token']);
  Cookies::set('password',              $ttrPassword);

    $_SESSION[SITE_NAME . '_session'] = $ttrUsername;

    echo json_encode(array('status' => 'success','message'=> "
 Autenticação bem sucedida, estamos te redirecionando
"));
} else {
    echo json_encode(array('status' => 'error','message'=> "
 Não foi possível autenticar com o Twitter.
"));
}

Qual problema, é no retorno do json, ou meu javascript está incorreto?
Comment: nossa, cara vlw poe como resposta q marco como resolvido
Comment: Eu já ví, e não tem nada haver com meu problema
Comment: mesma coisa... não redireciona...
Comment: como assim? Não entendi sério.
Answer: No seu PHP você esqueceu de definir a posição redirect que você faz a comparação no JS.
1 == a.redirect ? window.location = "index.php" : ....

Então é só definir um valor para ela no seu PHP que irá funcionar:
 echo json_encode(
         array('status' => 'success',
                'message'=> "
 Autenticação bem sucedida, estamos te redirecionando
",
                "redirect"=>$algum_valor));

Comment: funcionou mas agora parou de novo não sei por que
Comment: Vc já tentou usar window.location.href = ' x';

Problema com window.location


Is there a module to conditionally set a fields value depending another field?

Question: is there a module that can set a value of a field which depends on the value of another field first? I know i can do it via js, but was wondering if something was out there already. conditional field module doesnt work in my case as it dosent set the value depending on the result of another.
example: I am creating a basic page and I have a select box field with the following: white/black/red. when i select red, i want the body to be filled in with 'yes' and if its black i want the body to be filled in with 'no'.
Comment: "You may draw on anything available to Drupal, including other fields" - **how** this does not work for you?
Comment: oh i forgot to mention im talking about the content creation page.
Comment: No there isn't a module that can arbitrarily set the value of any field based on the contents of another inside an arbitrary, undefined context. Such a thing would be too difficult to implement, and impossible to use effectively. If you need something that complex it's time to pull out the custom modules :)
Comment: And? It works for me on nodes all right. What's your problem again? You want to narrow choices in select Y based on what got selected in field Z? Or what?
Comment: when something is selected in field Y it should auto input a string into field Z. maybe a quick js snippet would just do it.
Comment: I don't think there is a module for that. Would be damn complicated, and to use it you would need write scripts just as complicated as simple jQuery.
Comment: check this module, maybe it will help https://drupal.org/project/fieldactions
Comment: @duckx Did you find an alternate? I want to do similar thing.
Answer: No other module available apart from conditional field, you need to create your own module with hook form_alter() and use some code like
<?php
function wishlist_status_form($form_state) {
$form['status'] = array(
    '#type' => 'textfield',
    '#title' => 'Status',
    '#suffix' => '

',
  );

$form['ajax-submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
        'callback' => 'wishlist_status_change',
        'wrapper' => 'my-wrapper',
    ),
    '#value' => t('Save'),
  );
return $form;
}

function wishlist_status_change($form, $form_state) {
    dpm($form_state, 'state callback');
    return 'test';
}
?>

Answer: I guess you need to check on the fields you set as dependant and dependee! In your case the body field should be the dependant and the selection field should be dependee.
Hope it helps!
Answer: It might be difficult to change the value of a field without some coding. But it if you just want to store the value based on the value of some other field you should take a look at Computed Field
Answer: Perhaps you can use the Rules module and create 2 rules.

Event: After saving new content.

Condition:

Entity has field. Parameter: Entity: [node], Field: field_colours (Or whatever your field is called.)

Data comparison. Parameter: Data to compare: [node:field-colours], Data value: Red

Actions: Set a data value. Parameter: Data: [node:field-body], Value: Yes

You can create a similar rule for 'black'.


What to Play Over a Dominant 7#11?

Question: I'm currently working on an arrangement of Christmas Time is here that is in the key of E.
The first chord played in this arrangement is an Emaj7, followed by a D7#11 which is not diatonic to the song, so I'm not sure of

The function of this chord and
In an improvisational situation, what can be played over the D7b#11?
Comment: The bVII7 can be found throughout jazz. Here's an awesome resource with citations of other songs with bVII7s. It also details the different functions the chord can have: [http://brunojazz.com/vt-bVII7chord.htm](http://brunojazz.com/vt-bVII7chord.htm). Some songs he doesn't mention: Killer Joe (bar 2), Freddie the Freeloader (bar 11), There is No Greater Love (bar 3). This question may also be of interest: [Why do many songs in major keys use a bVII chord?](https://music.stackexchange.com/questions/29817/why-do-many-songs-in-major-keys-use-a-bvii-chord). This is a valuable question, +1
Answer: I agree with Laurence's answer, I just want to point out that the appropriate scale is the 4th mode of the A melodic minor scale: D lydian b7 or D mixolydian #11. Note that the name of the chord should indeed have a #11, not a b5, because the chord scale contains a 5:
1 2 3 #4 5 6 b7
The scale is obtained by applying the minimally necessary alterations to the scale of the key (E major) so that the notes fit the chord. Only two notes need to be changed to achieve that: the D# becomes a D (the root of the chord), and the C# becomes a C (the seventh of the chord).
This 'recipe' (minimally necessary alteration of parent scale) usually results in the most pleasingly sounding scale over chords that contain only a few tones outside the key.
The function of a bVII7 chord in a major key is usually to add a bluesy feel. This is achieved by lowering the 7th degree of the parent scale (D#) to a b7 (D), and using a dominant seventh chord (instead of a maj7 chord), i.e., lowering the C# to a C.
Answer: This, I imagine, from the sample first page at Sheet Music Direct? (Why not do it in the original key of Eb?  E isn't always 'easier' for guitar, particularly when we explore jazzy chords and substitutions, which, almost by definition, will make much use of non-diatonic notes and chords.) It's followed by a repeat of the same 2-bar phrase.  The printed chord name is wrong, it's D9(#11) - not Dmaj9(#11) which would include a C#.
The chord sequence doesn't take us anywhere, so it's not functional, just an pleasant alternative harmonisation of the G# melody note.  The bVII chord is a popular choice for this sort of thing in 'jazzy' arrangements.
If you want a scale to play over it, look at the notes in the bar.  D, E, F#, G#, (A), B, C.   You could name this scale one way rooted on D, another way rooted on E.  It doesn't really matter which you choose.
Comment: When the question worries that a chord isn't diatonic, and wants to improvise, it's ALWAYS a guitarist!   Who else would even dream of improvising all over a pretty Christmas melody insteas of just playing it, or accompaning a singer tastefully?   :-)
Comment: Playing it in Eb - musician  :-)
Somehow, Eb is a great key for dirty jazz chords, on any instrument.
Comment: Actually it's an arrangement by Rich Severson who is a jazz guitarist on the west coast.  I found the music and edited my original question, but it is a D7#11.

Thanks for your help!
Comment: I see he's called it D7#11 but actually plays D9#11.  I know one brand of harmony theory holds that an extended 'pile of thirds' chord contains all of them up to the last stated one, but it ain't so in practice.   D7#11 has a different flavour to D9#11.
Comment: Also, playing it in F = pianist. Playing it in E = guitarist.
Answer: Overview
Two reasonable functional explanations are available using jazz harmony. First for most ♭VII7-I progressions, the ♭VII7 chord is interchangeable with the iiø7 chord. Hence, you can think of the | D7(♯11) | E∆7 | progression as being a iiø7-V7alt-I with a missing V7 chord: | F♯ø7 (B13♭9) | E∆7 |. *Second: you can alternatively think of the D7(♯11) chord as using D half-whole diminished, in which case the D7(♯11) is interchangeable with B7(♯11), the V7 chord for E∆7.
Standard ii-V-I Explanation
For your example, D9 (the ♭VII7 chord) is interchangeable with F♯ø7 (the iiø7 chord). Those two chords share the same notes:
D9 contains the notes:   D-F♯-A-C-E
F♯ø7 contains the notes:   F♯-A-C-E
This means that the | E∆7 | D7(♯11) | E∆7 | progression is effectively the same as | E∆7 | F♯ø7 (B13♭9) | E∆7 |. You can think of this as a I-iiø7-V7-I progression with a missing V7. In fact, iiø-V7alt licks in EMaj tend to sound great over the ♭VII7 chord.
If you replace the D7 chord with F♯ø7, you might think to improvise over F♯ Locrian. However, the D7 chord is actually D7(♯11), which means you need to play a G♯ rather than a G♮. This leads you to think of the iiø7 chord in terms of F♯ Locrian ♯2. The Locrian ♯2 scale is an advanced but an extremely common choice among modern jazz musicians for a iiø7 chord like F♯ø7. If you want more description of that scale, check out this outstanding answer. In fact, F♯ø7 and D7(♯11) are extremely similar: the F♯ Locrian ♯2 scale and the D Lydian Dominant scale are both formed from an A melodic minor parent scale.
Diminished Scale Explanation
Instead of thinking about the D7♯11 chord as using A melodic minor, we can think about this chord as using the D half-whole diminished scale (D E♭ F F♯ G♯ A B C). This scale fits D7(♯11) because it contains:

the ♯9 (D, the root of the D7♯11 chord)
the ♭9 (C, the ♭7 of the D7♯11 chord)
the ♮13 (A, the ♯11 of the D7♯11 chord)

However, when dealing with a diminished scale, the dom7 chords are interchangeable as you move up/down minor thirds. For this example, D7(♯11) is interchangeable with B7, A♭(♯11), and F(♯11). So you can think of the progression | D7(♯11) | E∆7 |as being equivalent to | B7(♯11) |, the V7 chord to E∆7.

What to Play Over a Dominant 7#11?


On User Creation, send user registration email in his language preference

Question: Is there a way to send the welcome message to a new user in his preferred languages ?
As an Administrator of the website, I create all the users with their preferred languages. I Check the button to notify the user when the user is created.
The email is sent correcly but not in the languages that I specify for a particular user.
I already install the I18n module and made the translation between each languages.
Thanks a lot
Answer: I think you need to change the way drupal detect the language of the current user.
You can do so by going to /admin/config/regional/language/configure and check "Follow the user's language preference.". You may need to move this option as the first detection method.


ggplot2, applying two scales to the same plot? Top down barplot

Question: See plot here:

(from here)
How do I reproduce both the upper and lower portion of the barplot using ggplot2?
For example, I can produce the upper portion with
ggplot(data.frame(x=rnorm(1000, 5)), aes(x=x)) + geom_bar() + scale_y_reverse()

However now if I add any other geom_, such as another geom_bar() the scale for y is reversed. Is it possible to apply the scale_y_reverse() to only a specific geom_?
Answer: Another option is to make two separate plots and combine them with arrangeGrob from the gridExtra package. After playing with the plot margins, you can arrive at something that looks decent.
library(gridExtra)
library(ggplot2)

set.seed(100)
p2 <- ggplot(data.frame(x=rnorm(1000, 5)), aes(x=x)) + geom_bar() + theme(plot.margin=unit(c(0,0,0,0), 'lines'))
p1 <- p2 + scale_y_reverse() +
    theme(plot.margin=unit(c(0, 0, -.8, 0), 'lines'), axis.title.x=element_blank(),
          axis.text.x=element_blank(), axis.ticks.x=element_blank())

p <- arrangeGrob(p1, p2)
print(p)

Comment: phantom downvoter! state your name and explain yourself!
Answer: ggplot only like to have one y-axis scale. The easiest thing would be to basically reshape your data yourself. Here we can use geom_rect to draw the data where ever we like and we can condition it on group time. Here's an example
#sample data
dd<-data.frame(
  year=rep(2000:2014, 2),
  group=rep(letters[1:2], each=15),
  count=rpois(30, 20)
)

And now we can plot it. But first, let's define the offset to the top bars by finding the maxima height at a year and adding a bit of space
height <- ceiling(max(tapply(dd$count, dd$year, sum))*1.10)

And here's how we plot
ggplot(dd) +
  geom_rect(aes(xmin=year-.4, xmax=year+.4,
    ymin=ifelse(group=="a", 0, height-count),
    ymax=ifelse(group=="a", count, height), fill=group)) +
  scale_y_continuous(expand=c(0,0))

And that will give us


strange error 'npm WARN firstname.lastname@example.com requires a peer of joi@* but none is installed...?

Question: What does 'npm WARN firstname.lastname@example.com requires a peer of joi@* but none is installed. You must install peer dependencies yourself.' mean? And how can I solve it?

when i run:
npm install express-validation --save

I get:
npm WARN email@example.com requires a peer of joi@* but none is installed. You must install peer dependencies yourself.

so then i run:
npm install -g npm-install-peers

then:
npm-install-peers

then I get:
This package doesn't seem to have any peerDependencies

so then i run:
npm install express-validation --save

I get:
npm WARN firstname.lastname@example.com requires a peer of joi@* but none is installed. You must install peer dependencies yourself.

Answer: You can install it yourself with npm install joi --save
Answer: The package name is wrong. If you are trying to validate data in your app you should consider start looking for express-validator.
Express-validation requires a peer of joy and i dont know what both means.

strange error 'npm WARN express-validation@1.0.2 requires a peer of joi@* but none is installed...?


how to access an element with this shape with CSS selectors

Question: My question is how can I select this element in CSS by edit ?
element :
click

Answer: You can use an attribute selector by adding square brackets [].
Attribute selectors can target:

The name of the attribute: a[edit]
The value of the attribute if it has one: a[href=***]

But since 'edit' is not a valid attribute for an -Element, it's advisable to add an data- prefix in the html-code.

a[data-edit]{
  background:red;
}
edit
Comment: Is 'edit' a valid attribute for an  element? Didn't find it in the docs... so it might be advisable to add data-?
Comment: `` and `a[data-edit] {  }`.
Comment: How to add data because yes your right. edit is not a valid attribute so I tried this and it did not work. However this is a good answer and I voted up.
Comment: you'd use `.class[data-edit]`
Comment: Can I access it by example1.[data-edit]?


Is there such thing as a reverse T-Test?

Question: My understanding of the T-Test is that it is a test for checking if two samples are different enough to be considered from different distributions.
In the test the default position is that they are from the same distribution, and the burden of proof is showing that they are different.
Is there a reverse of this? The starting assumption is that the samples are from different distributions and I want to convince others that they are the same.
Comment: Many questions on site discuss the difficulty in swapping the null and alternative in hypothesis testing (though not all about the t-test). You can't show two things are the *same*, but if you define an equivalence (that population means within some specified distance of each other would be "equivalent") then you can get somewhere (this is called *equivalence testing*).
Comment: One place to start --- https://stats.stackexchange.com/questions/21967/seeking-to-understand-asymmetry-in-hypothesis-testing
Comment: And [look here](https://stats.stackexchange.com/search?q=equivalence+test*+answers%3A1) for posts on equivalence testing
Answer: You can look into TOST (two one-sided t-tests). Essentially, they let you know whether 2 distributions are not significantly dissimilar.


Visibilities permissions of children links in the Toolbar

Question: In a project started with the Thunder distribution, I'm currently managing the permission of the "editor" group.
By default, it only have access to the content menu, and it's a good thing.
But what if I want to give  permission to some children links (and only some specific children) of the others menu ?
Exemple:
I give to this group the ability to access, add, edit and delete some taxonomy terms.
I can access to the relative admin page, but the structure -> taxonomy link in the Admin Toolbar is not appearing.
For now I have to manually create those links, but I think it's not the right way to do this because they will constitute duplicate link for the "administrator" group.
I suppose I need to give visibility right for the parent link "structure", but how?
Answer: This is not a problem with the Admin Toolbar module, I think that you're not given the correct permissions.
In Drupal >= 8.5 you need to give the following permissions:

Use the administration pages and help
Use the administration toolbar
Tags: Create terms
Tags: Delete terms
Tags: Edit terms
Access the taxonomy vocabulary overview page

In Drupal < 8.5 as the Access the taxonomy vocabulary overview page not exists you need to assign the following permissions:

Use the administration pages and help
Use the administration toolbar
Tags: Create terms
Tags: Delete terms
Tags: Edit terms
Administer vocabularies and terms

The problem here is that the user will have the permission to create new vocabularies.
You can read about this in New term overview and create permissions and in Add a dedicated permission to access the term overview page (without 'administer taxonomy' permission)
Comment: Using D8.4, I missed the "Use the administration pages and help" permission. Thanks for the resources too :)
Comment: @Cawet good luck with your project ;-)


Java, print a short as binary with all 16 bits

Question: For example:
10 -> 0000 0000 0000 1010
15 -> 0000 0000 0000 1111
I tried using Integer.toBinaryString() but that prints
10 -> 1010
15 -> 1111
Is there a function that can print the short with all 16 digits or do I have to write my own.
Answer: You could pad the left side with 0s:
int x=10;//or whatever
String.format("%016d", Integer.parseInt(Integer.toBinaryString(x)));

Answer: Appending manual 0's may help
String.format("%16s", Integer.toBinaryString(1)).replace(' ', '0')

will generate 0000000000000001
Answer: You may also use the following trick to display leading zero/s. For more detail look at this thread.
int displayMask = 1 << (size - 1);
StringBuffer buf = new StringBuffer( size);
for ( int c = 1; c <= size; c++ )
{
    buf.append( ( value & displayMask ) == 0 ? '0' : '1' );
    value <<= 1;
}

According to this answer Integer.toBinaryString() leading zeros only for Integer/int. It will not work for byte.
Answer: You can use String.format() to add padding before your result. The padding must be spaces, because Integer.toBinaryString() returns a String. Then all you need to do is replace the spaces with zeros (0) and split every nibble (fourth bit).
import java.util.*;

public class BinaryNumberPrinter {
  public static void main(String[] args) {
    int[] numbers = { 10, 15 };

    for (int number : numbers) {
      String binaryValue = join(splitEveryFour(toShortBinary(number)), " ");
      System.out.printf("%d -> %s%n", number, binaryValue);
    }
  }

  public static String toShortBinary(int value) {
    return String.format("%16s", Integer.toBinaryString(value)).replace(' ', '0');
  }

  public static List<String> splitEveryFour(String value) {
    return Arrays.asList(value.split("(?<=\\G....)"));
  }

  public static String join(Iterable<? extends CharSequence> s, String delimiter) {
    Iterator<? extends CharSequence> iter = s.iterator();
    if (!iter.hasNext()) return "";
    StringBuilder buff = new StringBuilder(iter.next());
    while (iter.hasNext()) buff.append(delimiter).append(iter.next());
    return buff.toString();
  }
}

Expected Output:
10 -> 0000 0000 0000 1010
15 -> 0000 0000 0000 1111


Como validar o schema JSON em C#?

Question: Segue json (tem apenas 1 erro, pode ter vários erros):
{
  "errors": [
    {
      "code": "XX-55",
      "path": "customer.id",
      "description": "Cliente não encontrado"
    }
  ]
}

Outro exemplo do retorno: (Vários erros)
{
  "errors": [
    {
      "code": "XD-011",
      "path": "items[0].product",
      "description": "Informe o nome do produto"
    },
    {
      "path": "items[0].quantity",
      "description": "must be between 1 and 999999"
    },
    {
      "code": "BJ-009",
      "path": "items[0].price",
      "description": "Todos os valores devem ser maiores que zero"
    }
  ]
}

Como eu posso saber se o schema é desse formato ? Porque o código do retorno pode vir diferente do código acima json. O que me interessa é o código json acima.
Estou usando JsonConvert.DeserializeObject para converter, mas o schemma pode ser diferente. Como eu posso saber no string tem desse formato: erros, code, path e description ?
Comment: Consegue saber à partida como o `schema` está estruturado? Ou seja, tem, em algum lado do seu código, a definição do `schema`?
Comment: @JoãoMartins Não, ele somente retorna assim:  `{"errors":[{"code":"XX-55","path":"customer.id","description":"Cliente não encontrado"}]}`
Comment: Tem biblioteca pronta para isso: https://www.newtonsoft.com/jsonschema
Comment: Só não consigo fazer ela funcionar :/
Comment: Certo, essa biblioteca ia dizer-lhe para testar, mas para isso precisa obrigatoriamente de saber qual a estrutura do `schema` antes de o poder validar.
Comment: @JoãoMartins pior que não tem, somente aquele código acima mesmo.
Comment: @JoãoMartins isso não serve: https://www.liquid-technologies.com/online-json-to-schema-converter ?
Comment: Funciona, mas é um conversor _online_. Teria que incluir algo do género na sua aplicação. Pode receber qualquer `schema`? E não sabe quantos ou quais antes, certo?
Comment: @JoãoMartins talvez existe outra forma de fazer isso sem utilizar essa biblioteca, ou seja sem saber a estrutura do schema. Só aquele código acima Json que me retorna. Eu não sei quantos ou quais antes.
Answer: Uma forma é criar um deserializador usando a biblioteca Newtonsoft.
O primeiro passo é gerar as classes que representam o objeto JSON. Um jeito de fazer isso é usar um serviço online ou por ser um objeto simples você poderia inferir os atributos e propriedades. Eu gerei esse aqui com o seu exemplo.
namespace QuickType
{
    using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class Root
    {
        [JsonProperty("errors")]
        public Error[] Errors { get; set; }
    }

    public partial class Error
    {
        [JsonProperty("code", NullValueHandling = NullValueHandling.Ignore)]
        public string Code { get; set; }

        [JsonProperty("path")]
        public string Path { get; set; }

        [JsonProperty("description")]
        public string Description { get; set; }
    }

    public partial class Root
    {
        public static Root FromJson(string json) => JsonConvert.DeserializeObject<Root>(json, QuickType.Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this Root self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
    }

    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters = {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }
}

Agora você já tem a classe Root que representam o seu objeto.
Então você usa o método FromJson da classe para converter a string que tem o JSON em objeto.
var myJson = Root.FromJson("sua string com os dados do JSON");
if (myJson.Errors != null)
{
    // Indica que o objeto foi deserializado e contem o item "Errors" no root.
}

Você pode incrementar o código para verificar se não vai ocorrer nenhuma Exception se sua entrada puder ser qualquer coisa, mas no geral se for um objeto JSON ele vai tentar deserializar.

Como validar o schema JSON em C#?


Area between the ROC curve and the Random Guessing Line

Question: How close is my classifier to random guessing?
I need to quantify the inability of a binary classifier to obtain better results than random guessing in a single number evaluation metric.
The random guessing line (RGL) from (0,0) to (1,1) has an AUC of 0.5. But so does the blue curve (grey area).

Wouldn't it be more suitable to use the area between the RGL and the ROC-curve to estimate how "close" a classifier is to actual random guessing?
Comment: The ROC curve should not cross below the diagonal as yours does.  This ROC implies there is a problem with your model; it is misspecified in some fundamental way (cf, [ROC curve crossing the diagonal](https://stats.stackexchange.com/q/54525/7290)). If your curve were always above the diagonal, the area between the ROC & the diagonal would be the same as AUC-.5.  Ie, you'd have a different number, but the same information.
Comment: Have you considered you will be pretty far from the diagonal when you have few data points?
Comment: *Assuming the data set is big enough, so "no stair steps" and uncertainties from limited sample size.
Comment: My point being, your measure has a systematic bias on the number of data points. That's not something desirable in general.
Answer: First, the 0.5 random guess line is just a visual reference, what we really want to know if how well the classifier performs overall. I'm also not sure how your proposed method would provide a different result, assuming that you subtract first section that is below the 0.5 line.
Second, the AUC also has a nice statistical property where it is equivalent to the Wilcoxon-Mann-Whitney U Test statistic. This is the probability that the classifier will rank a randomly chosen positive instance higher than a randomly chosen negative instance.
In this case, we don't need to see the AUC value to know this is a poor classifier (and one unlikely to be seen in real life, as it implies that true positive values are consistently rated under a certain probability threshold while false positive values are more evenly distributed).
Answer:
How close is my classifier to random guessing?

You could test this by using Kolmogorov-Smirnov.
In Python:
<code>from scipy import stats

stats.ks_2samp(actual, preds)
</code>
Small K-S statistic and high p-value suggest that your classifier is no better than random.
(Also this might help: How to determine whether a classifier is significantly better than random guessing?)
Comment: Does class imbalance affect the k-s statistic?


Correct way to create or update with multiple belongs_to in Rails

Question: New to Rails and Ruby and trying to do things correctly.
Here are my models. Everything works fine, but I want to do things the "right" way so to speak.
I have an import process that takes a CSV and tries to either create a new record or update an existing one.
So the process is 1.) parse csv row 2.) find or create record 3.) save record
I have this working perfectly, but the code seems like it could be improved. If ParcelType wasn't involved it would be fine, since I'm creating/retrieving a parcel FROM the Manufacturer, that foreign key is pre-populated for me. But the ParcelType isn't. Anyway to have both Type and Manufacturer pre-populated since I'm using them both in the search?
CSV row can have multiple manufacturers per row (results in 2 almost identical rows, just with diff mfr_id) so that's what the .each is about
manufacturer_id.split(";").each do |mfr_string|
  mfr = Manufacturer.find_by_name(mfr_string)

  # If it's a mfr we don't care about, don't put it in the db
  next if mfr.nil?

  # Unique parcel is defined by it's manufacturer, it's type, it's model number, and it's reference_number
  parcel = mfr.parcels.of_type('FR').find_or_initialize_by_model_number_and_reference_number(attributes[:model_number], attributes[:reference_number])
  parcel.assign_attributes(attributes)

  # this line in particular is a bummer. if it finds a parcel and I'm updating, this line is superfulous, only necessary when it's a new parcel
  parcel.parcel_type = ParcelType.find_by_code('FR')

  parcel.save!
end

class Parcel < ActiveRecord::Base
  belongs_to :parcel_type
  belongs_to :manufacturer

  def self.of_type(type)
    joins(:parcel_type).where(:parcel_types => {:code => type.upcase}).readonly(false) unless type.nil?
  end
end

class Manufacturer < ActiveRecord::Base
  has_many :parcels
end

class ParcelType < ActiveRecord::Base
  has_many :parcels
end

Answer: It sounds like the new_record? method is what you're looking for.

new_record?() public
Returns true if this object hasn't been saved yet — that is, a record
  for the object doesn't exist yet; otherwise, returns false.

The following will only execute if the parcel object is indeed a new record:
parcel.parcel_type = ParcelType.find_by_code('FR') if parcel.new_record?

Comment: I guess I could also just do 'if parcel.parcel_type.ni?' but more what I"m looking for is a way to have a fresh Parcel have it's Manufacturer and Type already pre-populated (I can get the Mfr by creating the parcel via the Mfr)
Comment: Hmm, that might be a little unnecessarily complex if it's only really saving you one line of code without any performance gains. To be honest I'm not sure if you can even build a child object with more than a single parent pre-populated automagically by default. Your best bet might be one of the [ActiveRecord callback](http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html) methods if you truly want to leave everything up to ActiveRecord.
Comment: Gave you the answer as you are right, it's needlessly complex. The only place I really needed to do it was in a back-end import script so no biggie.
Answer: What about 'find_or_create'?
I have wanted to use this from a long time, check these links.

Usage:
http://rubyquicktips.com/post/344181578/find-or-create-an-object-in-one-command
Several attributes:
Rails find_or_create by more than one attribute?
Extra:
How can I pass multiple attributes to find_or_create_by in Rails 3?


Building Confidence Interval for Population Proportion

Question: I'm having trouble understanding how the 95% confidence interval equation for population proportions gets simplified.
Here is the initial equation:
$$
Pr(\overline{X} - 2\hat{SE}(\overline{X}) ≤ p ≤ \overline{X} + 2\hat{SE}(\overline{X}))
$$
Here is what I should get after simplifying (z-score in the middle):
$$
-2 ≤ {\overline{X} - p \over \hat{SE}(\overline{X})} ≤ 2
$$
My issue is that when I subtract $\overline{X}$ in the three parts of the equation and then divide by $\hat{SE}(\overline{X})$ again in all parts of the equation, I obtain $ p - \overline{X} \over \hat{SE}(\overline{X})$, which is not the formula for the z-score.
Comment: What is your definition of the standard error estimator?
Comment: $\frac{p - \bar X}{\hat{SE}(\bar X)}= -\frac{ \bar X-p}{\hat{SE}(\bar X)}$
Answer: You can go from $$-2 ≤ {p-\overline{X} \over \hat{SE}(\overline{X})} ≤ 2$$  by multiplying everything by $-1$ (changing the direction of inequalities) to get $$2 \ge {\overline{X} - p \over \hat{SE}(\overline{X})} \ge -2$$ and then reordering to arrive at $$-2 ≤ {\overline{X} - p \over \hat{SE}(\overline{X})} ≤ 2$$
Comment: thank you very much for the help! One comment, I imagine the sign before -2 in the second equation should be reversed as well and so ≥.
Comment: @Alex_A I have corrected the middle line changing the final $\le$ to $\ge$ so it now reads as  $2 \ge {\overline{X} - p \over \hat{SE}(\overline{X})} \ge -2$.  Thank you for pointing this out


Marquee content not showing

Question: I have Designed a marquee wrapper with css keyframes. But the marquee content is not showing.
I have designed this from https://codepen.io/nickcil/pen/BygPMY
But don't know why the marquee content is not showing up..
The animation and all that stuff is working absolutely fine.
Sir, please help me identify the problem.

.landing-ratecard-wrapper {
  position: relative;
  padding: 15px 20px;
  background-color: rgba(0, 0, 0, 0.45);
  border-radius: 4px;
  margin-top: 40px;
}
.landing-ratecard-wrapper .ratecard-title {
  color: #fff;
  font-weight: 500;
  font-size: 18px;
  margin: 0;
}
.landing-ratecard-wrapper .marquee {
  flex-grow: 1;
  overflow: hidden;
  box-sizing: border-box;
  position: relative;
}
.landing-ratecard-wrapper .marquee .marquee--inner {
  display: block;
  width: 200%;
  position: absolute;
  top: -15px;
  animation: marquee 20s linear infinite;
}
.landing-ratecard-wrapper .marquee .marquee--inner span {
  width: 50%;
  float: left;
}
.landing-ratecard-wrapper .marquee .marquee--inner span .rate {
  width: 200px;
  display: inline-block;
  margin: 0 10px;
  float: left;
  transition: all 0.2s ease-out;
  color: #fff;
}
.landing-ratecard-wrapper .marquee .marquee--inner:hover {
  animation-play-state: paused;
}
@keyframes marquee {
  0% {
    left: 0;
  }
  100% {
    left: -100%;
  }
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>

Rate Card

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

Answer: You are missing height for
.landing-ratecard-wrapper .marquee {
      flex-grow: 1;
      overflow: hidden;
      box-sizing: border-box;
      position: relative;
      height: 150px;
    }

Also set top to 0 in class landing-ratecard-wrapper .marquee .marquee--inner

.landing-ratecard-wrapper {
  position: relative;
  padding: 15px 20px;
  background-color: rgba(0, 0, 0, 0.45);
  border-radius: 4px;
  margin-top: 40px;
}
.landing-ratecard-wrapper .ratecard-title {
  color: #fff;
  font-weight: 500;
  font-size: 18px;
  margin: 0;
}
.landing-ratecard-wrapper .marquee {
  flex-grow: 1;
  overflow: hidden;
  box-sizing: border-box;
  position: relative;
  height: 150px;
}
.landing-ratecard-wrapper .marquee .marquee--inner {
  display: block;
  width: 200%;
  position: absolute;
  top: 0;
  animation: marquee 20s linear infinite;
}
.landing-ratecard-wrapper .marquee .marquee--inner span {
  width: 50%;
  float: left;
}
.landing-ratecard-wrapper .marquee .marquee--inner span .rate {
  width: 200px;
  display: inline-block;
  margin: 0 10px;
  float: left;
  transition: all 0.2s ease-out;
  color: #fff;
}
.landing-ratecard-wrapper .marquee .marquee--inner:hover {
  animation-play-state: paused;
}
@keyframes marquee {
  0% {
    left: 0;
  }
  100% {
    left: -100%;
  }
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>

Rate Card

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

Hope this helps.
Comment: You are welcome. :) If this answers your question kindly mark it as answer.

Marquee content not showing


Manually deleting images (from db and file_usage table)

Question: I was given 'temporary' images for a number of bio pages, and now have better quality images to replace them with.  Removing or replacing the old images in the Admin UI is failing (without giving me any error messages or indications of anything wrong: the old image is just there no matter what I do).  If I connect to the server by SSH and rm CEO.jpeg from bash, then the database is out of sync with the file system, and when I upload the new version of CEO.jpeg, I get an error because that is already in the database.
If I just edit the file_usage table and set count to 0, will that have any nasty side effects?  (I will also, of course, manually delete the file from the file system.)   Do I have to manually track down each node and edit it too?  Or can I just go to those nodes in the Admin UI after manual removal and add the new versions of the images?
(I've checked answers to this question and this question but the situation in those is very different.)
Answer: This is probably more of a comment but the code won't fit in...there should be no reason for the UI to fail on the file delete, unless the web server daemon doesn't have write permission to the files folder. That would be the first thing I'd check, then try again.
If that fails, you might want to give it a go manually:
$nids = db_query("SELECT nid FROM {node} WHERE type = 'the_type'")->fetchCol();

foreach (node_load_multiple($nids) as $node) {
  $node->field_name[LANGUAGE_NONE] = array();
  node_save($node);
}

That will take care of the whole lot (removing the data from file_managed, file_usage, and deleting the file from the disk if it exists and is writeable).
Comment: I've updated the answer, I just tested it and the short version is the way to go. It's just 'magic' :)
Comment: I checked the permissions, and the files are owned by apache, so (unless I'm missing something, which is possible) I don't think that's where the problem is.
Comment: Can I just edit the file_usage table, or do I need to track down each node too?


Como deixo essa lista duplamente encadeada e circular?

Question: <code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Tipo_Lista{
    char cod[50] ;
    struct Tipo_Lista *Prox;
    struct Tipo_Lista *Ant;
};
struct Tipo_Lista *Primeiro;
struct Tipo_Lista *Ultimo;

void FLVazia(){
    struct Tipo_Lista *aux;
    aux = (struct Tipo_Lista*)malloc(sizeof(struct Tipo_Lista));
    Primeiro = aux;
    Ultimo = Primeiro;
    Primeiro->Ant = NULL;

}
void Insere(char *x){
    struct Tipo_Lista *aux;
    aux = (struct Tipo_Lista*)malloc(sizeof(struct Tipo_Lista));
    strcpy(aux->cod,x);
    Ultimo->Prox = aux;
    aux->Ant = Ultimo;
    Ultimo = Ultimo->Prox;
    aux->Prox = NULL;
}
void Imprime(){
    struct Tipo_Lista *aux;
    aux = Primeiro->Prox;
    while(aux != NULL){
        printf("Item = %s\n",aux->cod);
        aux = aux->Prox;
    }
}
void Imprime_Atras(){
    struct Tipo_Lista *aux;
    aux = Ultimo;
    while(aux->Ant != NULL){
        printf("Item = %s\n",aux->cod);
        aux = aux->Ant;
    }
}
void Pesquisa(char *x){
    struct Tipo_Lista *aux;
    struct Tipo_Lista *aux2;

    int flag = 0;
    aux = Primeiro->Prox;
    while(aux != NULL){

        if(strcmp (aux->cod,x) == 0){
            aux2 = aux->Ant;
            aux = aux->Prox;
            printf("Achou item %s seu anterior é %s seu próximo é %s ", x,aux2->cod,aux->cod);
            flag = 1;
            aux = NULL;
        }
        else
        aux = aux->Prox;
    }
    if(flag == 0){
        printf("Item %s Não se encontra nesta Lista!!!!",x);
    }
}

void Remove(char *x){
    int retorno;
    struct Tipo_Lista *aux;
    int flag = 0;
    aux = Primeiro->Prox;
    while(aux != NULL){
        retorno = strcmp (aux->cod,x);
        if(retorno == 0){
            if(aux->Prox == NULL){
                Ultimo = aux->Ant;
                aux->Ant->Prox = NULL;
                aux = NULL;
                flag = 1;
            }
            else{

            printf("Removeu item %s\n",x);
            aux->Ant->Prox = aux->Prox;
            aux->Prox->Ant = aux->Ant;
            aux = NULL;
            flag = 1;
        }
        }
        else
        aux = aux->Prox;
    }
    free(aux);
    if (flag == 0){
        printf("Item %s Não se encontra nesta Lista!!",x);
    }
}

int main(int argc, char *argv[]) {
    char op = '2';
    int i;
    char codigo[50];
    FLVazia();
    while(op != '0'){
        printf("Encontre com o codigo: ");
        gets(codigo);
        Insere(codigo);
        printf("\n\n\nContinuar com o cadastro? 1 = sim 0 = Não: \n\n");
        op = getch();
    }
    Imprime();
    printf("\n\n Entre com um item para pesquisa: ");
    gets(codigo);
    Pesquisa(codigo);
    printf("Item a ser removido: ");
    gets(codigo);
    Remove(codigo);
    Imprime();
    getch();
    Imprime_Atras();
    getch();
        return 0;
}
</code>
Comment: Poderia dar mais detalhes sobre o que você quer? Qual parte do código você gostaria de alterar ou melhorar?
Comment: esta tudo duplamente encadeado , gostaria de torna-la circular agora , de forma que quando eu chamasse a função pesquisa , passando o último elemento ela me retornasse o penúltimo como anterior e o primeiro como próximo , e se passasse o primeiro que ele me retornasse o último como anterior e o segundo como próximo.
Comment: Para uma lista ser circular o ultimo elemento deve apontar o próximo para o primeiro elemento da lista, já o primeiro elemento da lista deve apontar o seu anterior para o ultimo da lista.

Minha sugestão é modificar o método "Insere" ele deve ter o papel de controlar a lista circular, também irá ser preciso modificar o método Remove pois ele deve ser inteligente o suficiente para casos de eliminação do ultimo elemento que ocasiona a modificação dos ponteiros de referencia.
Answer: Seguinte o ultimo elemento tem que apontar para o cabeça de lista e o cabeça de lista para o ultimo elemento,você pode pega o ponteiro do cabeça de lista pegando o campo próximo do penúltimo elemento da lista.


How do I identify a SARIMA model?

Question: I'm not given a data set but rather just the model: (1 + .2B − .35B^2)(1 − 0.8B^12)Xt = Zt (Zt is a white noise RV). I'm trying to find SARIMA(p,d,q)x(P,D,Q)s for this model, but I'm not sure if I have enough information. Should I be looking at the ACF and PACF of this model in R? I know that I'm supposed to find d,D to make the model stationary, so I guess I can use R to find the roots and see whether this model is stationary. As for p,P,q,Q, I'm completely lost. When I multiplied everything out, I got an AR(14) model, but I don't think that's related to p,q,P,Q. Can anyone point me in the right direction?
Answer: By inspection the SARIMA model is (2,0,0)(1,0,0)12 because there is 1 ar polynomial with 2 coefficients with 0 differencing and 0 ma polyNomials THUS from left to right we have  2,0,0
Since there is 1 seasonal ar structure AND no seasonal differencing and no seasonal ma structure we have from left to right (1,0,0) 12
Comment: Thank you very much for responding. Could you please elaborate on why there's no differencing, or rather what that would look like?
Comment: if there was a regular differencing it would look like (1 − 1.0B^1)Xt                          or simply (1 −B^1)Xt . Seasonal differencing if included with look like                         (1 − B^12)Xt

How do I identify a SARIMA model?


Is there a way to notate octaves for chords?

Question: Say I wanted someone to play a C major triad in the 4th octave at one point in a song I've written, while I wanted them to play the same chord (a C major triad) in the 5th octave instead of the 4th at a later point.  Is there a way to notate this when writing a chord progression out, not just writing music?
An example progression in the type of notation I'm using is: C/G/Am/F/C/G/Am/F (in this progression I'd want to specify the first C chord as being played with the root note starting in the 4th octave while the second C chord as being played with the root note starting in the 5th octave)
Answer: With chord symbols alone, no. Chord symbols are not designed to show exact voicings of chords. The most they can show is inversion which is denoted by a slash.
Typically when voicings must be exact, a more detailed notation will be used like in sheet music or tablature.
Comment: ...Or possibly a chord window?
Answer: You can't really specify a certain octave for chord symbols.
The easiest reason is probably, that different octaves mean different things to different people.
Some people see C3 as middle C, and some see C4 as middle C. So even if you would specify, that you want the root of the chord to start on C4 and later on C5, there would be people who still play both chords an octave lower than you intended.
So if you would like them to play it exactly as you want it, there's basically no other way than notating it within a staff.
However, if you have no other option and are forced to make it clear with chord symbols, I would just write C(8va) on the second C chord. Normally you use 8va to show that people have to play the notes one octave higher than written on the staff. So even tho they still don't know the octave of the first C chord, they at least should get that they have to play the second C chord an octave higher than the first one.
Comment: @user3235 --  My point was that, if middle C is interpreted to be C3 by some players, then two players will play the same piece of music in two different octaves; this undermines the proposed solution of using staff notation and 8va for clarity. I suppose this only holds true if you take, e.g., the first ledger line below the treble clef staff to be middle C; if you take it to be C4 you are safe from confusion (unless you play a transposing instrument). But in 40 years of playing with other musicians, middle C has always been middle C on an 88 key piano, no matter the instrument.
Comment: Tim, even though C4 is becoming the standard, there are multiple companies and groups using others designations for middle C, for instance Yamaha and the makers of Cakewalk.
https://www.pgmusic.com/forums/ubbthreads.php?ubb=showflat&Number=338513
Comment: Never seen C4 as anything except middle C.
Comment: @user3235 -- there is no confusion among musicians about what middle C is. In any case, I don't see how this would explain why chord symbols can't specify octaves; if octave ambiguity were an issue for chord symbols, it would also be an issue for staff notation, but it is not.
Comment: @DavidBowling Andy was making the claim that different manufactures and groups have specified other labels than C4 for middle C, and I confirmed that with a citation, not to mention I have two Yamaha keyboards that list middle C with C3.
I agree that there is no confusion among musicians because on each instrument, it is clear which note is middle C. It's also not an issue for staff notation because there are no real alternatives to standard notation (excluding microtonal) for pitch representation.
Answer: If you're just making notes to yourself to remember the accompaniment of a song, you could invent a system. Personally, I use "i" and "!" to mean that the bass goes higher or lower, respectively, than one might think (e.g. Ami or B7/D#!!).


Why the callback in mongoose code getting document as null?

Question: I have following code:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test')
var Schema = mongoose.Schema;
var schema = new Schema({name : String, inventory: {}});
var Character = mongoose.model('Character',schema);
var Frodo = new Character({name: 'Frodo',inventory:{ringOfPower: 1}});
Frodo.save();
Character.findOne({name : 'Frodo'},function(error, character){
    console.log(character);
});

I am running it as node optionminimize.js and null is getting logged to the console.It got persisted in mongodb alright, I opened a mongodb shell and ran
db.characters.findOne({name:'Frodo'})

and get following result:
{
        "_id" : ObjectId("582fc3bab386f00ed0e7fede"),
        "name" : "Frodo",
        "inventory" : {
                "ringOfPower" : 1
        },
        "__v" : 0
}

Why the document parameter in the callback is receiving null?
Answer: Frodo.save() is a async call so it returns a Promise, and you search by Charachter.findOne immediately the line after which happens before the Frodo.save() promise is resolved.
So, the search must be executed after the character is saved successfully, otherwise it returns null as you mentioned, so your code need to be like this:
Frodo.save()
  .then(function() {
    Character.findOne({name : 'Frodo'}, function(error, character) {
        console.log(character);
    });
  })


Remove the default value

Question: Is it possible to remove the default value an exposed filter (implemented by the Better exposed filter module) in a view? I would like to have users choose a value.
I tried using this in the template file, but nothing changed.
function custom_theme_form_views_exposed_form_alter(&$form, &$form_state) {
  // dpm($form);
  if ($form['#id'] == 'views-exposed-form-betterexposed-page-1') {
    foreach(element_children($form) as $key => $value) {
      if (isset($form[$key]['#type']) && $form[$key]['#type'] == 'select') {
        array_shift($form[$key]['#options']);
      }
    }
  }
}

The HTML markup is now the following.
<form action="/be1" method="get" id="views-exposed-form-betterexposed-page-1" accept-charset="UTF-8" class="jquery-once-1-processed">

            Published

 <input class="bef-select-as-radios form-radio" type="radio" id="edit-status-1" name="status" value="1" checked="checked">  Yes

 <input class="bef-select-as-radios form-radio" type="radio" id="edit-status-0" name="status" value="0">  No

      <input type="submit" id="edit-submit-betterexposed" name="" value="Apply" class="form-submit">

</form>

I also tried the following code.
function custom_theme_form_views_exposed_form_alter(&$form, &$form_state) {
foreach(element_children($form) as $key => $value) {
    if (isset($form[$value]['#type']) && $form[$value]['#type'] == 'select') {

      $options = $form[$value]['#options'];
      $newOptions = array();

      for ($i = 0, $optionsCount = count($options); $i < $optionsCount; $i++) {
        $optionsKey = array_keys($options[$i]->option);
        $optionsValue = array_values($options[$i]->option);

        $newOptions[$optionsKey[0]] = $optionsValue[0];
      }

      unset($form[$value]['#multiple']);

      $form[$value]['#type'] = 'radios';
      $form[$value]['#options'] = $newOptions;
      $form[$value]['#theme'] = 'select_as_radios';
    }
  }
}

I now get the following notice and warning messages.

Notice: Trying to get property of non-object in
  custom_theme_form_views_exposed_form_alter()
  Warning: array_keys() expects parameter 1 to be array, null given in
  custom_theme_form_views_exposed_form_alter()
Answer: May be something like this (with hook_form_FORM_ID_alter function):
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  // dpm($form);
  if ($form['#id'] == 'MY_EX_FORM_ID') {
    foreach(element_children($form) as $key => $value) {
      if (isset($form[$key]['#type']) && $form[$key]['#type'] == 'select') {
        array_shift($form[$key]['#options']);
      }
    }
  }
}

EDIT:
Ok, it seems that better exposed filter doesn't allow to remove default value from radio if settings are default (with default settings, filter -> is one of, BEF Settings -> checkboxes/radio buttons). I realized that in my project radios have been made from checkboxes type (with alter function), that's why in my example it's working fine..
here is a working example:

in hook_form_form_id_alter function:
foreach(element_children($form) as $key => $value) {
    if (isset($form[$value]['#type']) && $form[$value]['#type'] == 'select') {

      $options = $form[$value]['#options'];
      $newOptions = array();

      for ($i = 0, $optionsCount = count($options); $i < $optionsCount; $i++) {
        $optionsKey = array_keys($options[$i]->option);
        $optionsValue = array_values($options[$i]->option);

        $newOptions[$optionsKey[0]] = $optionsValue[0];
      }

      unset($form[$value]['#multiple']);

      $form[$value]['#type'] = 'radios';
      $form[$value]['#options'] = $newOptions;
      $form[$value]['#theme'] = 'select_as_radios';
    }
  }

Answer: I came across this issue myself, and found a solution. It's not ideal, but it works.
Rather than setting your filter value to be required, allow it to add an - Any - option; in hook_form_alter(), remove the All option, and set the #value and #default_value of your form to a falsy value (e.g 0, NULL).
Removing the - Any - option will cause the form to not have a valid default, and instead have no Radio button selected. Unfortunately, in the form validation handler, it will reach a point where the form is determined to be invalid and display an error to the user.
Setting #value and #default_value to something that PHP interprets as false, will avoid reaching this error condition, and you will be left with your radio button options, but with none selected by default.
You could use code similar to the following one.
function YOUR_MODULE_form_views_exposed_form_alter(&$form, $form_state) {
  if(isset($form['field_YOUR_FIELD'])){
    // Set the value and default value to a falsy value, so that when the form is validated in _form_validate,
    // it doesn't throw an error due to the missing option, which we remove ('All').
    // This is done in order to have the radio buttons UNSET by default, which isn't possible with views
    // and Better Exposed Filters. We instead allow the All value to appear, and then remove it.
    if($form_state['input']['field_YOUR_FIELD'] == 'All'){
      $form['field_YOUR_FIELD']['#value'] = NULL;
    }
    $form['field_YOUR_FIELD']['#default_value'] = NULL;
    unset($form['field_YOUR_FIELD']['#options']['All']);
  }
}

Remove the default value


Javascript: Setting all array values to the same

Question: I want to make a new array (of X elements) with all the elements set to 0.
X is set before.
Anyone could make the most compact and easy code for that? Thank you for your
help.
Comment: @EdHeal Thanks for the negativity :D
Answer: Just create a function:
<code>function makeArray(size, defaultValue) {
    var arr = [];
    for (var i = 0; i < size; i++) arr.push(defaultValue);
    return arr;
}

var myArr = makeArray(10, 0);
</code>


Drupal 8 create a template override for a view block within a custom module

Question: The Question:
In Drupal 8: How do I add a template override for a view block and have that twig file reside in a custom module - not my theme?
Further Information:
I have already created a custom module that creates a content type, imports data from an RSS feed and generates nodes into the content type it created.  The module also contains a view YML file so that the view for my content type is created when the module is installed.  The view only has one display which is a block.
I would like to create a template override for the block and house the template override within the module (rather than within my theme).  The template override does the following:

Adds the appropriate classes to the block
Adds an image beside the block title when the title is displayed
Wraps the {{ content }} in a div with an appropriate class
Loads the custom module's library to apply CSS

The goal is to have a module that a non-technical person can install, assign a block to the desired region and have all the templates, CSS, JS, etc pull from the module.  I don't want them to have to copy a template into their theme, etc.  I want the block to be a view so that the user can use the Views UI to make any desired updates to the view block's fields, number of returns, etc.
I was able to get Drupal to recognize the template by using hook_theme_registry_alter() but the variables from the block are null.  Both the {{ label }} and {{ content }} are null when I kint them in the template override.
Here is the hook_theme_registry_alter() code:
/**
 * Implements hook theme_registry_alter
 **/
function MYMODULE_theme_registry_alter(&$theme_registry){
  $theme_registry['block__views_block__MYVIEW_block_1']['path'] = drupal_get_path('module','MYMODULE') . '/templates/';
  $theme_registry['block__views_block__MYVIEW_block_1']['template'] = 'block--views-block--MYVIEW-block-1';
}

It should be noted that when I used hook_theme_registry_alter() for a view page template override in my module it worked.  My guess is that the variables were pulled from the page alias.
Please include detailed information because I am still learning about the various hooks and how variables are passed.  Thanks in advance!
Answer: To get the same variables as a block template add it as base hook:
/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return [
    'block__views_block__MYVIEW_block_1' => [
      'render element' => 'elements',
      'base hook' => 'block',
    ],
  ];
}

Now you can place the twig template in mymodule/templates/, path and filename are discovered automatically.
Comment: I was also able to use this recommendation to override the views field template by returning something like this:
`'views_view_field__my_view__my_display__field_my_field' => [
      'render element' => 'elements',
      'base hook' => 'views field'
    ]
`
Comment: I just had to do something like this again:
`'views_view_table__my_view' => ['base hook' => 'views table']` (no "render elements" needed) allowed me to add a  in my view.


How to configure an email server so that outgoing emails are not classified as spam

Question: How to configure an email server so that outgoing emails are not classified as spam? I've spent the entire day on this and I'm puzzled by the results I'm getting.
Among other things, I have:

Added DNS record for SPF: v=spf1 mx a ptr ip4:35.666.24.123/32 ?all
Added DNS record for SenderID: v=spf2.0/pra,mfrom a mx ip4:35.666.24.123 ~all
Corrected reverse DNS records (so that when receiving servers want to verify that the IP address sending them mail actually belongs to the domain the mails are coming from)
Set up my server to sign every message with a DKIM key and added respective DNS records: _domainkey       TXT   o=~; firstname.lastname@example.com
dkim._domainkey   TXT   v=DKIM1; p=MIG...QIDAQAB
Changed the HELO of my server to match the DNS records.

Here is my SpamAssassin score from http://dkimvalidator.com/:
SpamAssassin Score: 2.973
Message is NOT marked as spam
Points breakdown:
 0.1 DKIM_SIGNED            Message has a DKIM or DK signature, not necessarily valid
 0.0 T_DKIM_INVALID         DKIM-Signature header exists but is not valid
 0.0 TVD_SPACE_RATIO        No description available.
 0.4 RDNS_DYNAMIC           Delivered to internal network by host with
                            dynamic-looking rDNS
 2.5 TVD_SPACE_RATIO_MINFP  Space ratio

The default threshold for marking as spam is score 5, so I'm barely below it. Throw one "viagra" in there and that's it! ;)
For comparison, here are the results using my ISP's email:
SpamAssassin Score: -0.719
Message is NOT marked as spam
Points breakdown:
-0.7 RCVD_IN_DNSWL_LOW      RBL: Sender listed at http://www.dnswl.org/, low
                            trust
                            [18.104.22.168 listed in list.dnswl.org]
-0.0 RCVD_IN_MSPIKE_H3      RBL: Good reputation (+3)
                            [188.8.131.52 listed in wl.mailspike.net]
 0.0 TVD_SPACE_RATIO        No description available.
-0.0 RCVD_IN_MSPIKE_WL      Mailspike good senders

I sent the exact same email from both my own server and my ISP's email. Somehow the TVD_SPACE_RATIO_MINFP was flagged with a 2.5 penalty for only the message sent from my own server. According to their wiki, it's "the ratio of spaces to non-spaces in each paragraph". Is this a bug? Or is it counting spaces from metadata as well or something?
According to the validator, my ISP doesn't have SPF or DKIM records. Yet somehow SpamAssassin is giving them -0.7 while giving me 3.0? Also, I'm somehow flagged for invalid DKIM, yet it's not affecting the score? Why am I flagged when the validator also says (in a different section of the results) that the validation of my DKIM resulted in "pass"?
Edit: this is not a duplicate. This question is not about "how to write an email", it's about how to configure an email server. The parts regarding SPF, DKIM and HELO I already covered in my original post and explained the problems I had with them. Such problems are not described in the "duplicate" posts.
Comment: Have you reviewed everything in [How to send emails and avoid them being classified as spam?](http://serverfault.com/questions/48428/how-to-send-emails-and-avoid-them-being-classified-as-spam)
Answer: That should be the ratio of spaces to non-spaces in a paragraph... try trimming out some whitespace (or add a bunch more text), and that should reduce that factor in that particular SpamAssassin setup.
BTW, SpamAssassin setup is semi-arbitrary, so "your mileage may vary."
Comment: No, the same message is getting a different result depending on which server sent it.
Comment: Again, SpamAssassin is semi-arbitrary, and some rules may override others.
Comment: Eg. The fact that you "fail DKIM" may make the SpamAssassin daemon more-critical of the message. (and the different clients may format mail a bit different, too)


Newlookuprow not return 2 Informatica

Question: I have a problem with the dynamic lookup of the Informatica. My new lookup row is only returning 0 (duplicate) and 1 (Insert) it never returns 2(update). When i added a new row with the same natural key and update a column in a row the lookup returns 1 rather 2 which is update!
Comment: Can you please add some details? One quick thought I have is that length  of one of the ports is not enough, e.g. if you use string(5) to compare 'abcdefg' would result in 'abcdefg' != 'abcde' thus returning a NewLookupRow as 1.
Comment: hello i tried what you said but still i have the same problem! Do i have to check all the ports of lookup up table? I have a look up table with 5 ports and i compare only the 3  of them.
Comment: now is working but i have another problem. Lets say i add another row with the same key but i update the description to my table. It shows number 2 correctly but it shows the old row with number two rather 0 which is duplicate.
Answer: You have (at least) of things to look for:

Check in the property label of the lookup transformation that the
"Insert Else Updated" and "Update else insert" are checked (they are
not by default).
Check also the port that could cause an update are correctly associated (in the port label) and have not the "Ignore in comparison" flag checked.
Comment: the label property is checked. Now the ignore in comparison flag is checked and i can not unchecked it. it doesnt let me!
Comment: now is working but i have another problem. Lets say i add another row with the same key but i update the description to my table. It shows number 2 correctly but it shows the old row with number two rather 0 which is duplicate.
Comment: The comparison should be on the business key. Try to read this tutorial: http://www.dwbiconcepts.com/etl/14-etl-informatica/16-dynamic-lookup-cache.html
Answer: Okay i solved it! The problem is that you need to sort your table ports before creating the dynamic lookup!
Comment: Are you sure that was this that solved your problem? The port order should not have any effect.

Newlookuprow not return 2 Informatica


How to prove $\lim\limits_{n\to \infty}(a_n+2b_n)=L+2M$ using the formal definition of limit of sequence?

Question: Let $\{a_n\}^{\infty}_{n=1},\{b_n\}^{\infty}_{n=1}$ be sequence. Assume $\lim\limits_{n\to \infty}a_n=L,\ \ \lim\limits_{n\to \infty}b_n=M$, how to prove $\lim\limits_{n\to \infty}(a_n+2b_n)=L+2M$ using the formal definition of limit of sequence?
I remember the formal definition goes as following(not sure for sequence though): $\forall \epsilon\gt 0,\exists N\in\Bbb{R}:x\gt N\implies |a_n-L|\lt \epsilon$
Then we can set $\forall \epsilon\gt 0,\exists N\in\Bbb{R}:x\gt N\implies |a_n-L|\lt \frac12\epsilon$
$\forall \epsilon\gt 0,\exists N\in\Bbb{R}:x\gt N\implies |b_n-M|\lt \frac14\epsilon$
Then $\forall \epsilon\gt 0,\exists N\in\Bbb{R}:x\gt N\implies |2b_n-2M|\lt \frac12\epsilon$
Then $|a_n-L|+|2b_n-2M|\lt \epsilon$.
But I am not sure write a proof, could someone help?
Comment: These should be the formal definitions of the given limits:$$(\forall \epsilon > 0)(\exists N \in \Bbb{R})(\forall n \in \Bbb{N})(n > N \implies \lvert a_n-L \rvert < \epsilon)$$
$$(\forall \epsilon > 0)(\exists N \in \Bbb{R})(\forall n \in \Bbb{N})(n > N \implies \lvert b_n-M \rvert < \epsilon)$$
Answer: You pretty much got all of the ingredients you need for a proof. Here is how I would put it together.
Let $\epsilon>0$ be arbitrary.
Since $\lim_{n\to\infty}a_{n}=L$, we may choose an $N_{1}$ such that $|a_{n}-L|<\epsilon/2$.
Since $\lim_{n\to\infty}b_{n}=M$, we may choose an $N_{2}$ such that $|b_{n}-M|<\epsilon/4\implies |2b_{m}-2M|<\epsilon/2$.
Let $N=\max\{N_{1},N_{2}\}$. Then, if $n\geq N$, we have
$$
|(a_{n}+2b_{n})-(L-2M)|=|(a_{n}-L)+(2b_{n}-2M)|\leq|a_{n}-L|+|2b_{n}-2M|<\frac{\epsilon}{2}+\frac{\epsilon}{2}=\epsilon.
$$
Answer: Let $\epsilon\gt0$ be given. Then, there exist $N_1,N_2\in\mathbb N$ such that
$$|a_n-L|\lt\epsilon$$
for all $n\ge N_1$
and
$$|b_n-M|\lt\frac{\epsilon}2$$
for all $n\ge N_2$
Thus,
$$|2b_n-2M|\lt{\epsilon}$$
for all $n\ge N_2$
Adding the two inequalities,
$$|a_n-L|+|2b_n-2M|\lt2\epsilon$$
for all $n\ge\max{(N_1,N_2)}$
By the triangle inequality,
$$|a_n+2b_n-L-2M|\le|a_n-L|+|2b_n-2M|\lt2\epsilon$$
for all $n\ge\max{(N_1,N_2)}$
Here, $2\epsilon$, like $\epsilon$, is arbitrarily small.
Thus,
$$\lim_{n\rightarrow\infty}(a_n+2b_n)=L+2M$$


Using one class's properties in another OOP PHP

Question: I have the following class
namespace PG\Referrer\Single\Post;

class Referrer implements ReferrerInterface
{
    /**
     * @var $authorReferrer = null
     */
    protected $isAuthorReferrer = null;

    /**
     * @var $dateReferrer = null
     */
    protected $isDateReferrer = null;

    /**
     * @var $searchReferrer = null
     */
    protected $isSearchReferrer = null;

    /**
     * @var $taxReferrer = null
     */
    protected $isTaxReferrer = null;

    /**
     * @param array $values = null;
     */
     public function __construct(array $values = null)
    {
        if ($values)
        $this->setBulk($values);
    }

    /**
     * Bulk setter Let you set the variables via array or object
     */
    public function setBulk($values)
    {

        if (!is_array($values) && !$values instanceof \stdClass) {
            throw new \InvalidArgumentException(
                sprintf(
                    '%s needs either an array, or an instance of \\stdClass to be passed, instead saw %s',
                    __METHOD__,
                    is_object($values) ? get_class($values) : gettype($values)
                )
            );
        }

        foreach ($values as $name => $value) {//create setter from $name
            global $wp_query;

            if (array_key_exists($value, $wp_query->query_vars)) { //Check that user don't set a reserved query vars
                throw new \InvalidArgumentException(
                    sprintf(
                        '%s is a reserved query_vars and cannot be used. Please use a unique value',
                        $value
                    )
                );
            }

            $setter     = 'set' . $name;
            $condition  = isset($_GET[$value]);

            if ($setter !== 'setBulk' && method_exists($this, $setter)) {
                $this->{$setter}($condition);//set value (bool)
            }
        }
        return $this;
    }

    /**
     * @param bool $authorReferrer
     * @return $this
     */
    public function setAuthorReferrer($isAuthorReferrer)
    {
        $this->isAuthorReferrer = $isAuthorReferrer;
        return $this;
    }

    /**
     * @param bool $dateReferrer
     * @return $this
     */
    public function setDateReferrer($isDateReferrer)
    {
        $this->isDateReferrer = $isDateReferrer;
        return $this;
    }
    /**
     * @param bool $searchReferrer
     * @return $this
     */
    public function isSearchReferrer($isSearchReferrer)
    {
        $this->isSearchReferrer = $isSearchReferrer;
        return $this;
    }

    /**
     * @param bool $taxReferrer
     * @return $this
     */
    public function setTaxReferrer($isTaxReferrer)
    {
        $this->isTaxReferrer = $isTaxReferrer;
        return $this;
    }

}

with its interface
namespace PG\Referrer\Single\Post;

interface ReferrerInterface
{
    /**
     * @param array $values
     * @return $this
     */
    public function setBulk($values);
    /**
     * @param bool $authorReferrer
     * @return $this
     */
    public function setAuthorReferrer($isAuthorReferrer);
    /**
     * @param bool $dateReferrer
     * @return $this
     */
    public function setDateReferrer($isDateReferrer);
    /**
     * @param bool $searchReferrer
     * @return $this
     */
    public function isSearchReferrer($isSearchReferrer);
    /**
     * @param bool $taxReferrer
     * @return $this
     */
    public function setTaxReferrer($isTaxReferrer);

}

This class sets up 4 conditionals that I need to use in another class. The values that is used in this class is also set from the other class, so basically the user sets values in the other class (lets call it class b) that is then used by class Referrer and returns the 4 conditionals which is then used by class b.
The reason why I'm doing it this way is because there will be two other classes that will need to do the same, but will returns different info
What is the more correct way to achieve this?
EDIT
To clear this up
class Referrer
The properties $isAuthorReferrer, $isDateReferreretc will either have a value of null or a boolean value depending on what is set by the user.
Example:
$q = new Referrer(['authorReferrer' => 'aq']);

In the code above, $isAuthorReferrer is set via the setBulk() method in the class to true when the variable aq is available in the URL or false when not present. The three other properties will return null because they are not set in the example.
The above works as expected, but I need to do this in another class, lets again call it class b. The arguments will be set to class b, and in turn,  class b will set this arguments to class Referrer, class Referrer will use this arguments and return the proper values of its properties, and class b will use this results to do something else
Example:
$q = new b(['authorReferrer' => 'aq']);

Where class b could be something like this (it is this part that I'm not sure how to code)
class b implements bInterface
{
    protected $w;
    protected $other;

    public function __construct($args = [])
    {
        //Do something here
        // Do something here so that we can use $other in other classes or functions
    }

    public function a()
    {
        $w = new Referrer($args);
    }

    public function b()
    {
        // use $w properties here
       // return $other for usage in other classes and functions
    }
}

Comment: So, calling `b::a()` to create an instance of `Referrer` using the parameters passed to the constructor? Just store `$args` in a property and reference it later from `a()`. I'm not sure why you'd need an interface for `Referrer` in this case, given that you're not varying the implementation of that class in your examples.
Comment: Honestly, I'm confused. Can you perhaps trim that down to a simple class with one or two methods instead of several pages of code which don't really add anything to the problem description? Maybe also add some additional sample code about your "other" class to illustrate how you want to use what?
Comment: Not sure I understand what you're trying to do, but it looks like you might be trying to implement an abstract class with an interface. Some clarification would be helpful.
Comment: @deceze added example code of usuage
Comment: @JeremiahWinsley added extra info. :-)
Answer: The best way is to inject the referrer to your classes in order to do loose coupling between them and the referrer (this pattern use the benefit of your ReferrerInterface):
class b implements bInterface
{
    protected $referrer;

    public function __construct(ReferrerInterface $referrer, array $values = array())
    {
        $this->referrer = $referrer;
        $this->referrer->setBulk($values);
    }

    public function getReferrer()
    {
        return $this->referrer;
    }

    public function b()
    {
        // use $this->referrer properties here
    }
}

// Instantiation (use your dependency injection if you have one):
$referrer = new Referrer();
$b = new b($referrer, ['authorReferrer' => 'aq']);

I do not understand what is $other so I removed it but explain me if you want me to I add it again.
If you need to use the properties of the referrer in b, you should add some getters in your ReferrerInterface to allow that. I would use setAuthorReferrer($isAuthorReferrer) to set the value and isAuthorReferrer() to get it for instance.
Comment: Thanks for your detailed answer. Will test this later today, but this does seem what I'm looking for. `$other` is just something I used as an example, so you don't have to worry about that :-)
Comment: Ok! Tell me if you have a problem when testing it!


drawing to canvas on android motion events

Question: I'm new to programming and have been mostly self teaching and using books with lots of help from questions other people have asked in this forum.
I am currently working through android game development for dummies and have run into several problems most of which I have been able to solve myself but this compiler error I can't make go away. it' doesn't recognise the canvas.drawCircle in the code. and I can't figure out why.
any help or thoughts very much appreciated.
Thanks in advance
Tom
public class CrazyEightsView extends View {

    private Paint redPaint;
    private int circleX;
    private int circleY;
    private float radius;

    public  CrazyEightsView(Context context) {
        super(context) ;
        redPaint = new Paint();
        redPaint.setAntiAlias(true);
        redPaint.setColor(Color.rgb(99, 00, 00));
        circleX=100;
        circleY=100;
        radius=30;
    }

    @Override
    public void onDraw (Canvas canvas) {

    }

    public  boolean onTouchEvent (MotionEvent event) {
        int eventaction = event.getAction();
        int X =(int)event.getX();
        int Y =(int)event.getY();

        switch (eventaction){
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                circleX = X;
                circleY = Y;
                break;

                invalidate();
                return true;
        }

        canvas.drawCircle (circleX, circleY, radius, redPaint);
    }
}

Comment: Move this inside the draw method

          canvas.drawCircle (circleX, circleY, radius, redPaint);

invalidate() will refresh the draw.
Answer: As Raghunandan sais, do not try to draw in any method other than onDraw(). Set your X and Y values in onTouch() and then invalidate the view. This will call onDraw() again.
Comment: Thanks for anyone else with a similar issue this is what my code looks like now
@Override
public void onDraw (Canvas canvas) {canvas.drawCircle (circleX, circleY, radius, redPaint);
invalidate();
}public boolean onTouchEvent (MotionEvent event) {
   int eventaction = event.getAction();
   int X =(int)event.getX();
   int Y =(int)event.getY();
  switch (eventaction){
   case MotionEvent.ACTION_DOWN:
    break;
   case MotionEvent.ACTION_MOVE:
    break;
   case MotionEvent.ACTION_UP:
    circleX = X;
    circleY = Y;
    break;
    default:
   }
    return true;
Answer: Move this inside the draw method
      canvas.drawCircle (circleX, circleY, radius, redPaint);

To force a view to draw, call invalidate().
http://developer.android.com/reference/android/view/View.html#invalidate()
invalidate() will refresh the draw (calls onDraw(canvas).
http://developer.android.com/reference/android/graphics/Canvas.html
Modify the below according to your needs.
    public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    CrazyEightsView ev= new CrazyEightsView(this);

    setContentView(ev);
}

public class CrazyEightsView extends View {

    private Paint redPaint;
    private int circleX;
    private int circleY;
    private float radius;

    public  CrazyEightsView(Context context) {
        super(context) ;
        redPaint = new Paint();
        redPaint.setAntiAlias(true);
        redPaint.setColor(Color.rgb(99, 00, 00));
        circleX=100;
        circleY=100;
        radius=30;

    }
    @Override

    public void onDraw (Canvas canvas) {
                    // draw your circle on the canvas
        canvas.drawCircle (circleX, circleY, radius, redPaint);
    }

    public  boolean onTouchEvent (MotionEvent event) {
            int eventaction = event.getAction();
            int X =(int)event.getX();
            int Y =(int)event.getY();

            switch (eventaction){
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                circleX = X;
                circleY = Y;
                invalidate();// call invalidate to refresh the draw
                break;

            }
            return true;
    }
    }

 }


Using Powershell, how do I eject an ISO image from a Hyper-V virtual machine?

Question: I'm using the Hyper-V module for PowerShell, and I've successfully mounted an ISO file onto a virtual machine. Question is: how do I eject (or unmount) it?
I'd prefer to use the PSHyperV stuff, if there's a solution. Failing that, dipping into WMI from PowerShell would be acceptable.
(Using Windows 2008 R2, if it makes a difference)
Answer: <code>Set-VMDisk
</code>
HERE's a Powershell Hyper-V commandlet reference guide for future use.
Comment: A little more? I'm aware of Set-VMDisk. What's the magic incantation to get it to eject the ISO?
Comment: seriously dude the full usage is detailed in the linked document, there's loads of options, no way for any of us to just tell you what you need, you've not provided enough information.
Comment: I want to *unmount* an ISO file. What part of that is not clear? The documentation shows how to *mount* one, which I can already do.
Answer: From the virtual machine I found that using Powershell did it for me:
mountvol DRIVELETTER: /d


Question relating equivalence relations/classes

Question: So, for a course I'm following we got some practice exams to prepare for the finals. However, for some of these we do not have answers, nor can I find someone who is certain of his answer on the following question.
I was hoping someone here can give me some insight to the question(s) listed below.
I figured that when trying to solve (a) I would have to take an arbitrary equivalence class of R and proof that it is also in S. But I am unsure of how to actually formally proof this.
For question (b) I have absolutely no clue, as I originally thought it was false.

Let $R$ and $S$ be two equivalence relations on a finite set U satisfying $R \subseteq S$.
(a) Prove that every equivalence class of R is a subset of an equivalence class of S.
(b) Let $n_R$ be the number of equivalence classes of R and let $n_S$ be the numer of equivalence classes of S. Prove that $n_R \geq n_S$
Comment: I don't know what you've done so far, but it might be helpful to look at a small example: let $U=\{1,2,3,4\}$, $R=\{(1,2),(2,1)\}\cup\Delta$, $S=R\cup\{(3,4),(4,3)\}$, where $\Delta$ denotes the diagonal. What do the equivalence classes of $R$ look like and what do those of $S$ look like? Once you know these, it should be possible to prove (a).

After you've done that, part (b) immediately follows from (a). Namely, if you take any equivalence class of $S$, it contains at least one equivalence class of $R$.
Comment: Another hint: if $y \in [x]_R$, this means $(x,y) \in R$. so $(x,y) \in S$.
Comment: Okay, so I think the equivalence classes of R are: [[1]] = {1, 2} and [[2]] = {1, 2}. While the equivalence classes of S are: [[1]] = {1, 2}, [[2]] = {1, 2}, [[3]] = {4}, [[4]] = {3}.

But I think I did something wrong, as $nr < ns$. Maybe I did not understand the definition of equivalence correctly.
Comment: What you're forgetting here, is that all elements of $U$ need to be in some equivalence class. You're right that the equivalence classes of $1$ and $2$ are $\{1,2\}$ in both cases, but I'm afraid you're not quite right about the $3$ and $4$. Since $(3,4)\in S$, it follows that both $3$ and $4$ are in the equivalence class of $3$ in this case. Just figure out what $[3]_R$ and $[4]_R$ look like.
Answer: The basic thoughts you need are these:
(a) Take an arbitrary object $o$ in the domain of the relations.
By definition, if $o$ and $x$ belong to the same $R$ equivalence class, then $oRx$. By hypothesis, if $oRx$ the $oSx$. By definition, if $oSx$ then $o$ and $x$ belong to the same $S$-equivalence class.
Hence, putting things together, if $o$ and $x$ belong to the same $R$ equivalence class, then $o$ and $x$ also belong to the same $S$-equivalence class.
So the $R$-equivalance class containing $o$ must be a subset of the $S$-equivalance class containing $o$. But $o$ was arbitrary. So it follows immediately that every $R$-equivalence class is indeed a subset of some $S$-equivalence class.
(b) If $R \subseteq S$ then $S$ is no more discriminating than $R$, so $S$ partitions the universe no more finely than $R$. That evidently means there are at least as many $R$-equivalence classes as $S$-equivalence classes.
Comment: Woh, that was actually really easy. I think I was more thinking about how R was a Set, rather then an actually equivalence relation. Thanks!


Populating Select2 with AJAX

Question: I am trying to populate a selec2 field on open with AJAX in Drupal 8. In my hook_form_alter, I have added the following code:
  $form['#prefix'] = '
';
  $form['#suffix'] = '
';

  $form['field_author']['widget']['#ajax'] = [
    'callback' => 'myPopulate',
    'wrapper' => 'form-ajax-wrapper',
    'event' => 'select2:opening',
  ];

which correctly calls to the callback function when I try to open the drop-down list:
function reloadOptions(array $form, FormStateInterface $form_state){
  $query = \Drupal::entityQuery('node');
  $query->condition('type', 'author');
  $query->condition('status', 1);
  $nids = $query->execute();
  $nodes = Node::loadMultiple($nids);

  foreach ($nodes as $node) {
    $options[$node->id()] = FieldFilteredMarkup::create($node->getTitle());
  }

  $form['field_author']['widget']['#options'] = $options;

  return $form;
}

The query is ok, and the way in which the options are loaded also seems ok. However, when I click on the selec2 field to open it, the ajax throbber is shown but the drop-down list does not open.
Any ideas why is this happening?
Thanks!
EDIT:
A capture of the behaviour of the selector2. As you can see, the drop-down list is not displayed after you click. However, if the ajax call is removed, it works correctly.
Answer: The ajax callback is pointing to the wrong function, should be:
callback' => 'reloadOptions',

It's better to make it return just the field rather than the entire form
$form['field_author']['#prefix'] = '
';
$form['field_author']['#suffix'] = '
';

$form['field_author']['widget']['#ajax'] = [
  'callback' => 'reloadOptions',
  'wrapper' => 'author-ajax-wrapper',
  'event' => 'select2:opening',
];

Adjust the reloadOptions fuction, so it returns just the specific field
return $form['field_author'];

Comment: Yes, the name of the callback is wrong. It was my mistake when I copied the code.

Regarding returning only the specific field, that makes the rest of the form disappears and shows only the select2. Likewise, it does not manage to display the drop-down list either.
Comment: `that makes the rest of the form disappears and shows only the select2` @GJW80 Did you add the prefix and suffix to the author field `$form['field_author']`, [like I show in my answer](https://i.imgur.com/18BWfbS.png) and removed the prefix & suffix from the `$form` like you have in [your question](https://i.imgur.com/qk19bwK.png)?
Comment: That's right, my bad. However, the drop-down list is not yet displayed.
Comment: @GJW80 it's working, the issue is that it keeps replacing it before the options show. You'll need to add `unset($form['field_author']['widget']['#ajax']);` to you callback so it replaces only once.
Comment: Also, user might have to click twice, so change your event to `ready` or  `load`.
Comment: If I use `ready` or `load`, ajax is not called in select2 opening. The unset in the callback appears not to have any effect, even if I click twice in the select.
Comment: What if you set it to empty? `$form['field_author']['widget']['#ajax'] = [];`
Comment: No, still the same.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/115374/discussion-between-no-sssweat-and-gjw80).
Answer: In the following post, a working solution has been provided: https://www.drupal.org/forum/support/post-installation/2020-10-20/populating-select2-with-ajax
@No Sssweat also provided an alternative solution, where an update button was hidden in the form and was automatically activated with JS when a new item was added.
Many thanks for your time.

Populating Select2 with AJAX


I am trying to get a variable to NODEJS using AJAX or req.body

Question: I want to send a variable/value that I have in client side javascript. The reason I am doing this is because my req.body.domain is coming back undefined and same when I try to send JSON, I am trying to send this to a nodejs route.
client side Ajax request
function digIt() {
    var xhr = new XMLHttpRequest();
    const domain = document.getElementById("digTool").value;
    const digToolInput = document.getElementById("digToolInput");
    digToolInput.innerHTML = domain;
    digToolInput.style.fontSize = "35px";
    const usMap = document.getElementById("us-map");
    usMap.classList.add("appear");
    digToolInput.classList.add("moved");

    console.log(domain);
    myJSON = { "domain" : domain  };
    console.log(JSON.stringify(myJSON));
    xhr.open('POST', '/tools', true);
    xhr.send(myJSON);
};

NodeJS Route for receiving the AJAX request
router.post('/tools', (req, res, next) => {
    console.log(req.body.myJSON);
    mid.canYouDigIt(domain);
    res.render('tools', {test: 'domain'});
    next();

});

html/jade
doctype html
html(lang="en")
    head
        link(rel="stylesheet" type="text/css" href="./css/style.css")
        link(rel="stylesheet" type="text/css" href="./css/animation.css")
        link(href="https://fonts.googleapis.com/css?family=Cutive+Mono" rel="stylesheet")
        link(href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Ubuntu" rel="stylesheet")

        title Nymadic #{title}

body

    section(id="container")

        section(id="navWrapper")

            img(id="logo" src="img/Nymadic_Logo_Edit_NEW.png" onclick="location='/'")

            div(id="navMenu")
                ul
                    li(onclick="location='/'") Home
                    li(onclick="location='/about'") About
                    li(onclick="wikiOpen()") Wiki
                    li(onclick="toolsOpen()") Tools
                    if !currentUser
                        li(onclick="location='/login'") Login
                    else
                        li(onclick="location='/profile'") #[img( id="navProfileLogo" src="/img/if_ninja_479478.png")] Profile
                            li(id="navLogout" onclick="location='/logout'") Logout

        section(id="sideBar")
            div
                img(id="logoSideBar" src="img/Nymadic_Logo_Edit_NEW.png" onclick="location='/'")
                form
                    input(id="searchBar" name="search" type="text" placeholder="Search for knowledge...")
                ul
                    li( v-for="page in mediaList" v-bind:name="page.title" v-on:click="toggleDetails(page)") {{ page.title }}
                        div( id="descriptionWrapper" v-bind:class="{less: page.showDetail}" )
                            p( ) {{ page.description }}
                            p(v-if="page.author" size="8" ) Created By: {{ page.author }}

        section(id="digToolWrapper")
            form( id="digToolInput" )
                ul
                    li #[input(id="digTool" name="domain" type="text" placeholder="Can you dig it?")]#[input(id="whois" value="whois" type="button" onclick="digIt()")]

Comment: did you set up body parser middleware for express?
Comment: Yeah, I have a login and registration page that works with a mongodb that all works fine.
Answer: You have printed the stringified JSON body, but failed to send do the same while sending.
While sending JSON data, you should use, JSON.stringify(data), so in your case,
xhr.send(JSON.stringify(myJSON));
And if possible, use new Web APIs like fetch() instead of XHR.
Fetch API has more advantages as mentioned here


μ and σ calculations for a random variable with a normal distribution

Question:
Possible Duplicate:
Calculating mu and sigma (μ and σ) of a normal random variable

If I have a random variable X with parameters μ and σ unknown. It is known that $P (X \ge 75) = 0.7764$ and $P (X \ge 83) =  0.7291$ . With this information Is it possible to determine the μ and σ values for $X$?
Comment: Duplicate: http://math.stackexchange.com/q/78854
Comment: looks like homework.
Comment: If you pay attention before you say the question is "duplicate", you would notice that in the previous question the probabilities were reversed and it was therefore impossible to calculate =)
Answer: The title says that $X$ has normal distribution, but the text does not.  If we do not know the distribution of $X$, we cannot find the mean $\mu$ and the standard deviation $\sigma$ from the given data.  If we know that $X$ has normal distribution, we can. So from now on we assume that $X$ has normal distribution.
Recall that if $X$ has normal distribution with mean $\mu$ and standard deviation $\sigma$, then $\frac{X-\mu}{\sigma}$ has standard normal distribution. Thus
$$P(X \le \mu +a\sigma)=P\left(\frac{X-\mu}{\sigma}\le a\right) =P(Z\le a),\qquad\qquad(\ast)$$
where $Z$ has standard normal distribution.
For example, let $a=-1.5$.  Informally, if $X \le \mu-1.5\sigma$, we say that $X$ is at least $1.5$ standard deviation units down from the mean. So by $(\ast)$, we see that the probability that $X$ is at least $1.5$ standard deviation units down from the mean is $P(Z \le -1.5)$.  Similar considerations apply to $P(X \ge \mu-1.5\sigma)$.  The probability that $X$ is no more than $1.5$ standard deviation units down from the mean is $P(Z \ge -1.5)$. By the way, this is about  $0.9332$.
Finally, we look at the particular question. First, a quick look at the geometry.  We have $P(X \ge 75)=0.7764$.  Since the normal is symmetric, we can see that $75$ is below the mean. Similarly, $83$ is below the mean. Since $0.7764$ is less than $0.9332$, we can see that $75$ is less than $1.5$ standard deviation units below the mean. Now it is time to calculate.
If you look in a table of the standard normal distribution, you will find that $0.7764$ is (approximately) the probability that a standard normal $Z$ is $\le 0.76$, and $0.7291$ is the probability that a standard normal is $\le 0.61$.  The same sort of information is also available through various programs, such as spreadsheets, statistics packages, and general purpose mathematics packages such as Maple or WolframAlpha.
By symmetry, this means that $P(Z \ge -0.76)=0.7764$, and $P(Z \ge -0.61)=0.7291$.
But our normal $X$ has probability $0.7764$ of being $\ge 75$.  That means that $75$ is $0.76$ standard deviation units down from the mean.  In symbols,
$$\mu-0.76\sigma=75.$$
Similarly, we obtain
$$\mu-0.61\sigma=83.$$
Now we have two linear equations in two unknowns, and we can readily solve them for $\mu$ and $\sigma$.  A natural start is to observe that $(\mu-0.61\sigma)-(\mu-0.76\sigma)=83-75$, so $\sigma=8/(0.15)$. Note that our calculation has adequate accuracy, but is not exact, since the table entries are not exact.


JSF dynamically include src in "ui:include src="#{bean.pagePath}"

Question: I tried to include multiple source page path using ui:include tag in different tabs. The problem is when i gave the source page path as static one means that page will be shown but if give the source page path from backing bean mean it won't include the page.
Here is my code
template.xhtml:

                <h:form id="tempFormId">

                            <f:subview>
                                <h:panelGroup id="mainTempPanelGroupId" layout="block">
                                    <ui:include src="#{useCase.path}" />
                                </h:panelGroup>

                            </f:subview>

                </h:form>

bean:
public String menuAction() {
    menuBtnRendered = true;
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    selectedModuleViewId = externalContext.getRequestParameterMap().get(
            "moduleViewId");

    tabsList.add(new Tab(getTabId(selectedModuleViewId),
                selectedModuleViewId, getModulePath(selectedModuleViewId)));

    return null;
}

I'm using @ViewScoped.
Answer: <ui:include> runs during view build time (when XHTML is turned into JSF component tree).
 runs during view render time (when JSF component tree needs to produce HTML).
So,
 isn't available when <ui:include> runs. This problem is detailed in this answer: JSTL in JSF2 Facelets... makes sense? (<ui:include> is a taghandler and has hence same lifecycle as JSTL tags).
You can solve this to a certain degree by using <c:forEach> to produce
s instead of
.

    <c:forEach items="#{multiTabBean.tabsList}" var="useCase" varStatus="loop">

            <f:subview id="tab_#{loop.index}">
                <h:panelGroup id="mainTempPanelGroupId" layout="block">
                    <ui:include src="#{useCase.path}" />
                </h:panelGroup>
            </f:subview>

    </c:forEach>

It's by the way interesting to see that you somehow used <f:subview> in your initial attempt which is completely useless over there (already taken into account by
), but it's actually helpful in here (it creates a new NamingContainer around the tab content).
Answer: The above Community's answer hasn't worked for dynamic tabView
<p:tabView dynamic="true" ...

If i use dynamic="true" and c:foreach for tabs, when i add or remove a tab, do update @tabViewId, the tabview will reload "All content of existed tabs" => this is not the way to attribute "dynamic" work, it's not lazy.
My project has a problem with this, i had to customize the method encodeEnd of TabViewRenderer and do something else, but it's not simple.
I wondering whether there is a way to include XHTML templates at rendered time?