Java Enum access to private instance variable

Question: Consider the example:
enum SomeEnum {
    VALUE1("value1"),
    VALUE2("value2"),
    VALUE3("value3")
    ;
    private String value;

    private SomeEnum(final String value) {
        this.value = value;
    }

    //toString
    public String toString() {
        return value;
    }
}

How come can we do this (and the value really changes)?
SomeEnum.VALUE1.value = "Value4";
System.out.println(SomeEnum.VALUE1);

Isn't that enum instance(s) are implicitly static and final? Also, since value is private, why can I access it outside other classes?
Comment: Oh! By the way, this question is a question on some code I saw, the code that I'm maintaining.
Answer: No-one seems to have addressed the private aspect. My guess is that you're accessing the private field from a containing type - that your enum is actually a nested type, like this:
class Test
{
    static void Main() {
        // Entirely valid
        SomeEnum.VALUE1.value = "x";
    }

    enum SomeEnum {
        VALUE1("value1");

        private String value;

        private SomeEnum(final String value) {
            this.value = value;
        }
    }
}

That's entirely legitimate and normal - you can always access private members of a nested type from the containing type.
If you make the enum a top-level type, you won't see this.
As for changing values - as everyone else has said, VALUE1 is implicitly static and final, but that doesn't stop you from changing VALUE1.value. Again, this is entirely in accordance with how Java works elsewhere - if you have a static field of type List, you can still add entries to it, because that's not modifying the field itself.
If you want to make SomeEnum properly immutable, make the value field final.
Comment: That just gives a perspective of `An enum type is a type whose fields consist of a fixed set of constants`. I can have a mutable property inside an enum and change it at any time in my own leisure.
Comment: @TheEliteGentleman: Yes, you can - and that's a really bad idea. An enum type is a type with a fixed set of *instances* of that type. So there's a set of static final fields within type `SomeEnum`, which are fields *of type* `SomeEnum`. Those are used to access the instances. Any extra fields that *you declare* work exactly like other fields - you can have static fields or instance fields, final fields or non-final fields etc.
Comment: @TheEliteGentleman: So your enums aren't just mutable, but are *being mutated*? If so, that sounds like code which really needs to be addressed ASAP.
Comment: Well, unfortunately, I maintain codes that do just that and I thought that it can't be since it breaks `enum` contracts (or I thought it does).
Comment: @TheEliteGentleman: It's not clear what you mean - the `enum` contract in the JLS certainly doesn't guarantee that the instances will be immutable. I would *strongly* recommend that you make them immutable though.
Answer: You can't do
SomeEnum.VALUE1 = "Value4";
System.out.println(SomeEnum.VALUE1);

but you can do
SomeEnum.VALUE1.value = "Value4";
System.out.println(SomeEnum.VALUE1);

and value really changes, but not the static final VALUE1.

Also, since value is private, why can I access it outside other classes?

You can access a private field in an outer/inner class, but I cannot find an example of where you can access it from another class (in the same package for example).
Comment: Sorry, just updated the question: It's `SomeEnum.VALUE1.value = "Value4";
Comment: Good answer. In other words, final provides only shallow immutability.
Comment: similar to `static` only makes the reference static, `volatile` only make the reference volatile, `transient` only makes the reference transient (but not the object referenced) `private`/`public` only makes the reference private/public but not the contents. etc. etc. ;)
Comment: True, but shouldn't I not be able to see `value` since it's private? I.e. I shouldn't be able to say, `VALUE1.value` at all (unless, I had a public getter method).
Comment: Can you give an example of where you are accessing from another class (and not an outer or inner class)
Comment: The person who wrote the example, later `removed` the `private` keyword. `value` is now default (and hence why he could see it outside other classes). This was a stupid exercise.
Answer:
Isn't that enum instance(s) are implicitly static and final?

Nope. Members of enum-instances such as value in your example can be mutable.
(The references to the instances (SomeEnum.VALUE1 etc in your example) are final and static though.

Also, since value is private, why can I access it outside other classes?

You can't. An enum is a "class" with an enumerable number of instances. That's all.
VALUE1 is in this case a an instance of the "class" SomeEnum, thus SomeEnum.VALUE1.value is an ordinary field like any other.

When you do
System.out.println(SomeEnum.VALUE1);

you invoke SomeEnum.VALUE1.toString which accesses the value field. You're not accessing the value-field immediately.
// Not possible since field is private.
System.out.println(SomeEnum.VALUE1.value);

Comment: Sorry, just updated the question: It's `SomeEnum.VALUE1.value = "Value4";
Comment: You can view `value` outside other classes. I did a test case and it worked.
Answer:
Isn't that enum instance(s) are implicitly static and final?

The Enum instances have these traits. But no one said, these instances are immutable like Integer or String. So you can modify the values.
That does not mean that this is recommended practice! It isn't.
Edit
To explain a little more:
"Enum implicitly static" means:
enum Foo { FOO };

Here FOO is static, although the normal Java syntax would suggest, that FOO is an instance variable wrongly named like a constant. You also access it like a static variable.
"Enum implicitly final" means:
enum Foo { FOO, BAR };
Foo.FOO = Foo.BAR;

is not allowed. The reference stored in FOO cannot be changed. You also cannot create new instances.
"Enum not implicitly immutable" means: Foo.FOO will give you an object. A standard object. If the object allows modifications of its own content - so it be. This is not forbidden.
Comment: That's **not** what I asked at all. Consider changing the answer before it gets downvoted.
Comment: @TheEliteGentleman: Looks like what you asked to me, unless I'm not seeing the edit...
Comment: @Jon Skeet, my question is not about modifying `VALUE1` but why `VALUE1.value` can be modified at all, even though it's a private instance. Doesn't the enum rules (of implicit `static` and `final`) apply to its instances too?
Comment: @TheEliteGentleman: Can you explain a little bit? Besides the wording I'm in the same ballpark as the other answers _and_ your own observations. I simply stated, that the traits you mentioned are not relevant to your problem, it's the (missing) immutable trait that's linked to your problem.
Comment: @TheEliteGentleman: You mean its fields (there's no such concept as a "private instance"), and no, certainly not. There's no transitive application of the `final` modifier *anywhere* in Java.
Comment: @JonSkeet: No, there was no edit you could miss at that point of time.
Comment: @A.H.: Okay, in that case it seems you did indeed answer exactly what was asked, and it's just the OP misunderstanding what it means for an enum value to be final.
Answer: The enums itself (VALUE1, VALUE2 and VALUE3) are static and final. They are three instances of the SomeEnum type and we can't change them (like deleting VALUE1 from the enum or adding a VALUE4 at runtime).
But we can add public fields to the instances (like in your example) and alter the content of those fields at runtime.
Answer: SomeEnum.VALUE1 = "Value4" ... actually does not work.
More important, VALUE1 will always only be equal to VALUE1 and not VALUE2 or VALUE3, independent of it's member value.
Comment: @TheEliteGentleman: Do you not think it's possible that the answerer had your original question open all that time? I think it's entirely possible - and that if you originally made a mistake in the question, and others are trying to help you, then it's nice to give them the benefit of the doubt. Your comment should have at least suggested that the answerer might have only seen the (incorrect) original version of your question. Between this and "Consider changing the answer before it gets downvoted" it feels like you're not really in the spirit of things...
Comment: Look at my question **carefully**. I said `SomeEnum.VALUE1.value = "Value4"`, not `SomeEnum.VALUE1 = "Value4"`.
Comment: @TheEliteGentleman: You did now, yes - but what did your question say *before* you updated it?
Comment: @JonSkeet, I updated my question 21 minutes ago. The OP answered 12 minutes ago. That is 9 minutes difference since my last update (of which I included the change).
Comment: @Jon Skeet, thanks. I assumed the OP just opened the question now since 9 minutes is long enough to see an updated change. I will consider being more user-friendly on posts.
Comment: @TheEliteGentleman: Consider a user who opens up SO, finds a bunch of questions and puts them in different tabs, then looks at each one in turn. Although there's notification of answers being added, I'm not sure there's notification of the question being updated...


Using two ids for a single Jquery Plugin

Question: I am trying to use a single plugin of jquery and I want to apply the same functionality to two different ids.
How can i achieve this, It is a type of next and previous functionality in which if we click on next then both the divs should scroll automatically..
If you see the html there are tow divs of same id which I should not use because the id should be unique if I am changing the id also how to call that id for the same plugin.
Request for the help
Here it is what I have tried.
stepcarousel.setup({
    galleryid: 'gallerya', //id of carousel DIV
    beltclass: 'belt', //class of inner "belt" DIV containing all the panel DIVs
    panelclass: 'panel', //class of panel DIVs each holding content
    autostep: {enable:true, moveby:1, pause:3000},
    panelbehavior: {speed:300, wraparound:false, persist:false},
    defaultbuttons: {enable: true, moveby: 1, leftnav: ['images/left-arrow.png', 200, -30], rightnav: ['images/right-arrow.png', 10,  -30]},
    contenttype: ['inline'] //content setting ['inline'] or ['external', 'path_to_external_file']
})

div id="gallerya" class="stepcarousel" style="height:731px;">

 How to prepare for financial analyst interview?

Are external training programs offered by company part of salary package?

Bank Interview Preparation

Best ways to Prepare for Campus Interview

Cognitive Abilities Test

College Interview Preparation

Discussing career goals in a job interview

Dressing up for Interview

Engineering Interview Questions

Favorite job destinations in India

Finance Interview Questions

Group Discussion Rules for Interview updated

How to Prepare for Dietician Job Interview

How to Prepare for Lab Technician Interview?

How to Prepare for Pilot Interview

How to Prepare for an Accounting Interview

How to Prepare for an Insurance Agent Interview?

How to answer basic interview questions?

                            Project Manager

                            A&E Consulting

                            Philippines

                            Project Manager

                            A&E Consulting

                            Philippines

Page that I am creating
Answer: Have you tried something like this:
Call .setup once with galleryid: 'galleryA', beltclass: 'beltA' and panelclass: 'panelA'.  And then again with galleryid: 'galleryB', beltclass: 'beltB' and panelclass: 'panelB'.
stepcarousel.setup({
    galleryid: 'galleryA', //id of carousel DIV
    beltclass: 'beltA', //class of inner "belt" DIV containing all the panel DIVs
    panelclass: 'panelA', //class of panel DIVs each holding content
    autostep: {enable:true, moveby:1, pause:3000},
    panelbehavior: {speed:300, wraparound:false, persist:false},
    defaultbuttons: {enable: true, moveby: 1, leftnav: ['images/left-arrow.png', 200, -30], rightnav: ['images/right-arrow.png', 10,  -30]},
    contenttype: ['inline'] //content setting ['inline'] or ['external', 'path_to_external_file']
})

stepcarousel.setup({
    galleryid: 'galleryB', //id of carousel DIV
    beltclass: 'beltB', //class of inner "belt" DIV containing all the panel DIVs
    panelclass: 'panelB', //class of panel DIVs each holding content
    autostep: {enable:true, moveby:1, pause:3000},
    panelbehavior: {speed:300, wraparound:false, persist:false},
    defaultbuttons: {enable: true, moveby: 1, leftnav: ['images/left-arrow.png', 200, -30], rightnav: ['images/right-arrow.png', 10,  -30]},
    contenttype: ['inline'] //content setting ['inline'] or ['external', 'path_to_external_file']
})

And then your HTML like this:


why does - result-document method="text" - export an xml declaration?

Question: Sadly this question is wrong - i can't seem to replicate the behaviour, thanks to Martin Honnen below for forcing me to revisit my assumptions - I can't delete it.
Saxon 11.4
if I run this
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="3.0">
    <xsl:template match="/">
        <xsl:result-document method="text" encoding="utf-8">
            <xsl:text>foo</xsl:text>
        </xsl:result-document>
    </xsl:template>
</xsl:stylesheet>

i would expect a text document
foo

but i get this
<?xml version="1.0" encoding="UTF-8"?>foo

I was trying to dynamically trying to select and output format based on a passed parameter, but obviously if i want a text output I don't want an xml declation in it.
P.S.
the input document can be any valid xml (unless I'm missing something)
so
<foo/>

Comment: What is the input? Is the shown result the primary or the secondary result document?
Comment: it doesnt matter what the input is does it?...it just matchs the root document node
Comment: Perhaps not but you haven't given enough detail for us or at least me to reproduce the result.
Comment: primary or secondary result?...hmmm...its just the output from the java saxon call, maybe this is the piece i dont understand, I'm just expecint the output to be in the specified "-o" file (which it is) and i expect it to be a text file, not text embedded in an xml file
Answer: You haven't shown us what the input is nor explained how exactly you run the transformation and look at the result but for me the (currently using SaxonJ HE 11.5) XML workbench, with no input, and the code
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="3.0">
    <xsl:template name="xsl:initial-template">
        <xsl:result-document method="text" encoding="utf-8">
            <xsl:text>foo</xsl:text>
        </xsl:result-document>
    </xsl:template>
</xsl:stylesheet>

gives just
foo

as the sole and principal result.
The same result if I use some input.
I have also run SaxonJ 11 from the command line (using the current/latest 11.6) and it doesn't show any XML declaration, neither when directly writing to the console nor when outputting to a file:
java -jar 'C:\Program Files\Saxonica\SaxonHE11-6J\saxon-he-11.6.jar' -s:.\sample1.xml -xsl:.\sheet1.xsl
foo
PS C:\Users\marti\OneDrive\Documents\xslt\blog-xslt-3-by-example\sole-xsl-result-doc-test> java -jar 'C:\Program Files\Saxonica\SaxonHE11-6J\saxon-he-11.6.jar' -s:.\sample1.xml -xsl:.\sheet1.xsl -o:result1.txt
PS C:\Users\marti\OneDrive\Documents\xslt\blog-xslt-3-by-example\sole-xsl-result-doc-test> type .\result1.txt
foo

So it is not quite clear what you are doing or in what way (command line, some API, some editor) your are using Saxon and get the result you show in your question.
Comment: let me add the command line...its just burried in some code
Comment: actually lets keep this simple.
if I use oxygen and give it the example input I have on the question it gives me the output i describe
Comment: actually - NO I DONT!...hmm
Comment: hmmmm...its not happening any more....ignore me...
Comment: I coudl do with giving you credit but deleting the question...its wrong.


OS.STAT().ST_SIZE gives me incorrect size in Python

Question: os.stat doesn't give me correct output I only get 8192 byte for every file. Code below
import os

path = "C:\\"

filelist = os.listdir(path)

for i in filelist:
    if os.path.isdir(os.path.join(path, i)):
        print os.path.join(path, i), "is DIR"
    else:
        # fs = filesize
        fs = os.stat(path).st_size
        # fs = os.path.getsize(path)

        print os.path.join(path, i), "size is", fs

Here is output:
C:\$Recycle.Bin is DIR
C:\Config.Msi is DIR
C:\Documents and Settings is DIR
C:\hiberfil.sys size is 8192
C:\pagefile.sys size is 8192
C:\PerfLogs is DIR
C:\Program Files is DIR
C:\Program Files (x86) is DIR
C:\ProgramData is DIR
C:\Python27 is DIR
C:\Recovery is DIR
C:\shared.log size is 8192
C:\System Volume Information is DIR
C:\Users is DIR
C:\vcredist_x86.log size is 8192
C:\Windows is DIR

Why the biggest number is 8192? All files that are not dir have much bigger size than that. Output is the same for os.stat(path).st_size and os.path.getsize(path). Thanks in advance.
Comment: `os.stat(path)` != `os.stat(os.path.join(path, i))`
Answer: You forgot to os.path.join(path, i) when checking the file size with os.stat(), so you always get the size for C:\ (which is 8192, windows specific stuff). Fixed script:
import os

path = "C:\\"

filelist = os.listdir(path)

for i in filelist:
    filepath = os.path.join(path, i)
    if os.path.isdir(filepath):
        print filepath, "is DIR"
    else:
        # fs = filesize
        fs = os.stat(filepath).st_size

        print filepath, "size is", fs

Answer: This worked for me:
def calc_folder_size(directory):
    # https://www.geeksforgeeks.org/how-to-get-size-of-folder-using-python/
    # assign size
    size = 0

    # get size
    for path, dirs, files in os.walk(directory):
        for f in files:
            fp = os.path.join(path, f)
            size += os.path.getsize(fp)

    size = int(size)

    # convert to GB
    if (size / 1e+9) > 0.001:
        size = size / 1e+9
        size = str(size) + " GB"
    else:
        # convert to MB
        size = size / 1e+6
        size = str(size) + " MB"

    return size

At least most of the time. Sometimes it doesn't agree with what Windows calculates, but it is pretty close when they are not the same.


Como recuperar as funções de um editor clonado?

Question:
Eu estou adicionando dinamicamente o summernote abaixo em verde. Estou clonando na verdade os de cima. Claro que ia ter um problema com isso senão não seria programação. As funções dos editores adicionados não funcionam. Alguém saberia me dizer o que eu devo fazer para contornar tal problema?
Estou usando o código abaixo para adicioná-lo.
$(document).on('click', '.adicionar', function() {
    var content = $("#perguntas_formatadas").html();
    $("#clone_perguntas_formatadas").append(content);
    $("#clone_perguntas_formatadas .form-group").attr("data-remove", 1);
});

Comment: Já experimentou voltar a aplicar o summernote ao elemento clonado? Algo como `$('#clone_perguntas_formatadas').summernote();`
Answer: Nunca usei Summernote, mas vendo a documentação básica da API existe as seguintes funções para obter o conteúdo digitado (em HTML) e também há como definir um conteúdo, inserindo dentro de um Summernote já existente, respectivamente:
$('#summernote').summernote('code');
$('#summernote').summernote('code', markupStr);

Então basicamente:

// Inicia o primeiro Summernote:
$('div#primeiro').summernote()
   .summernote('code', 'Esse é o primeiro summernote');

// Excuta quando clicar em "Copiar":
$('#copiar').on('click', function() {

  // Copia o conteúdo do primeiro Summernote:
  CodigoDoPrimeiroSummerNote = $('div#primeiro').summernote('code');

  // Cria outros Summernote clonados do primeiro:
  $('<x-summernote></x-summernote>').appendTo('#clones');

  $('x-summernote').last().summernote()
    .summernote('code', CodigoDoPrimeiroSummerNote);

});
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet"><link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.6/summernote.css" rel="stylesheet">

<button id="copiar" class="btn">Copiar</button>


Algorithm that decides whether collection of primes exists which satisfies 3 equations

Question: Suppose someone gives you a list of $n$ positive numbers $(a_1, \ldots , a_n)$, together with an upper limit $N$ and asks you to find prime numbers $p_1, \ldots ,p_n$ in the range $2, \ldots , N$ satisfying
$p_2 = p_1 + a_1$ and $p_3 = p_2 + a_2$ ... and ... $p_n = p_{n-1} + a_{n-1}$
How do you write down a general algorithm for deciding whether or not collection of prime numbers $(p_1, \ldots , p_n)$ exists that satisfies these 3 equations?
What will it look like?
Comment: The way you are formulating this question, since our initial set goes up to $a_n$, don't we only need to find primes $p_1, \dotsc, p_{n-1}$? Also the title and your post says "3 equation" however it looks like we have $n-1$ equations. You should edit your post to clarify these things.
Answer: Here is some pseudo-code for my brutish approach to it.
<code>Let A = {a1, a2, ..., an}
Let sieve = {p | p is prime and less than N}
If ((size of sieve < size of A) OR (some a[i] == 1 for i > 1))
    return False;
Let primeDiffs = {sieve[i] - sieve[i-1] | i in [2..(size of sieve)]}
For i in [1..(size of primeDiffs - size of A)] {
    For j in [1..(size of A)] {
        If(A[j] /= primeDiffs[i+j])
            continue
    }
    return True
}
return False
</code>
Essentially just generate all the primes that you need, build the set of the consecutive differences of those primes, and iterate over that set seeing if all of your set $\{a_1, a_2, \dotsc, a_n\}$ matches your current position in the set of differences.
You can do some clever checking on the $\{a_1, a_2, \dotsc, a_n\}$ set at the start like make sure none of $\{a_2, a_3 \dotsc, a_n\}$ are $1$ (the only primes with a difference of $1$ are $2$ and $3$).


Convergence of a stochastic process to another?

Question: I wonder if there is a notion of convergence of a stochastic process to another stochastic process. To be precise, I am looking for a theorem like the following,
Let $A_n$ and $B_n$ two stochastic processes with $n \in \mathbb{N}$. Then, if certain conditions hold (this is the part that I am looking for), $\exists$ N for which $n \geq N$ the following holds,
$$P(|A_n - B_n|> 0) <  \epsilon$$
or something like that (may be this is not the unique type of convergence).
Thanks!
Answer: Consider the stochastic process $C_n = A_n - B_n$. Any theorem about the convergence of $C_n \to 0$ is equivalent to a result you are asking for.
Comment: thanks! I did not think about this.


A Wordpress gallery for all types of media?

Question: How can I display any type of media within a gallery in Wordpress?
Answer: Take a look at this question, its got extra comments. But I'll copy the important things to answer your question - https://wordpress.stackexchange.com/questions/11662/get-all-images-in-media-gallery
So this would get all attachments in the media library;
<code>$media_query = new WP_Query(
array(
    'post_type' => 'attachment',
    'post_status' => 'inherit',
    'posts_per_page' => -1,
    )
);
$list = array();
foreach ($media_query->posts as $post) {
    $list[] = wp_get_attachment_url($post->ID);
}
// do something with $list here;
</code>
Or just get all items of a specific type;
<code>$query_images_args = array(
'post_type' => 'attachment', 'post_mime_type' =>'image', 'post_status' => 'inherit', 'posts_per_page' => -1,
);

$query_images = new WP_Query( $query_images_args );
$images = array();
foreach ( $query_images->posts as $image) {
    $images[]= $image->guid;
}
</code>
Comment: maybe i can,t understand your answer....but i want a gallery that display all type of media such as images,videos and flash files.....


The weighted average absolute value of pairwise sum of any finite sequence is larger than the weighted average of absolute value.

Question: How do we prove for any given real number $a_1,\ldots,a_n$, we have
$$\frac{1}{n^2}\sum_{i=1}^n\sum_{j=1}^n|a_i+a_j|\geq \frac{1}{n}\sum_{i=1}^n|a_i|$$
I have checked several easy cases for this:
When $n=1$, LHS $=2|a_1|$ and RHS $=|a_1|$, so it trivially holds.
When $n=2$, we are going to prove
$$2|a_1|+2|a_1+a_2|+2|a_2|\geq 2(|a_1|+|a_2|)\Longleftrightarrow 2|a_1+a_2|\geq 0$$
which is also trivial.
When $n=3$, we are going to prove
$$\sum_{i=1}^3\sum_{j=1}^3|a_i+a_j|\geq 3\sum_{i=1}^n|a_i|$$
which is equivalent to prove
$$2(|a_1+a_2|+|a_2+a_3|+|a_3+a_1|)\geq |a_1|+|a_2|+|a_3|$$
This can be proved simply by triangular inequality, and actually the coefficient $2$ is not sharp, $1.5$ is enough.
However, when $n$ gets larger, e.g., $n\geq 6$, simply applying triangular inequality is not enough because by in general it reduces to prove:
$$2\sum_{i<j}|a_i+a_j|\geq (n-2)\sum_{i=1}^n|a_i|$$
I don't know how to proceed, can anyone help me?

Edit: Since this problem is pointed out to be duplicate, I slightly generalize it. If $b_1,\ldots,b_n$ are convex combination coefficient, i.e., they are nonnegative and $b_1+\ldots+b_n=1$, then how to prove
$$\sum_{i=1}^n\sum_{j=1}^nb_ib_j|a_i+a_j|\geq \sum_{i=1}^nb_i|a_i|$$
Comment: Duplicate of https://math.stackexchange.com/q/73945/42969 and https://math.stackexchange.com/questions/507930/how-prove-this-inequality-sum-i-j-1nx-ix-j-ge-n-sum-i-1nx.
Answer: This is a discreet version of the problem which appeared at 64th Putnam in 2003.
The original was formulated in this format:
$$\int_{0}^{1}\int_{0}^{1}|f(x) + f(y)|dxdy >= \int_{0}^{1}|f(x)|$$
for continuous $f$.
Comment: Thanks a lot, now I understand how to proceed!


Por que quando eu coloco float right a cor do meu fundo desaparece?

Question: criei um cabeçalho, com um fundo, texto e imagem.
quero deixar o texto na esquerda e a imagem a direita.
coloquei o float:right mas ai o fundo acaba sumindo.

.fundo1 {
  background: linear-gradient(266.22deg, #BFF4FF 38.6%, rgba(255, 255, 255, 0) 163.18%);
  overflow: hidden;
}

.imglabelle {
  position: absolute;
  right: 0px;
  padding: 10px;
}

    Tudo para o seu bebê
 Entregas para todo o Brasil

Comment: A imagem deveria ficar alinhada à direita abaixo do texto mesmo ou lado a lado?
Comment: a direta lado a lado
Answer: Amigo o problema não é o float, é o position, vc colocou como absolute, então o ponto de referência dele é o body nesse caso... para o ponto ser o container pai é preciso que o pai tenha position: relative, assim o filho em absoluto fica relativo ao pai.
Além disso, faltou vc colocar um top no filho... vc só colocou right, mas tb é indicado colocar explicitamente uma orientação vertical

.fundo1 {
  background: linear-gradient(266.22deg, #BFF4FF 38.6%, rgba(255, 255, 255, 0) 163.18%);
  overflow: hidden;

  position: relative;
}

.imglabelle {
  position: absolute;
  right: 0px;
  padding: 10px;

  top: 0;
}

    Tudo para o seu bebê
 Entregas para todo o Brasil

Observação sobre o float
Em alguma situações quando vc usa float em um filho o container pai perde a referência do filho no content-flow, com isso o pai não reconhece a altura do filho. Uma técnica amplamente usada para corrigir isso é o clearfix, vc pode ler mais sobre isso nessas duas questões.
Float vs. inline-block. Quais as vantagens e desvantagens de cada um?
Qual é o efeito que a propriedade overflow: hidden está fazendo no código?
Exemplo, repare que o pai perdeu a referência de altura dos filhos. Nesse código abaixo vc só consegue ver o BG vermelho do pai pq eu dei um padding, mas se vc remover o padding a cor de BG do pai some.

.container {
  border: 1px solid black;
  background-color: #f00;
  padding: 2px;
}
.container div {
  float: right;
  border: 1px solid blue;
}

123

123

123

123

Comment: @Woss sim, no caso dele não aconteceu por causa do tamanho do próprio texto, mas vou deixar um pergunta sobre `clearfix` como referência
Comment: Acha que vale a pena colocar aqui que ao usar o float a altura do elemento pai deixa de respeitar o tamanho da imagem?


I Can't use my findViewById from AsyncClass

Question: I Can't use findViewById() from my Kclass=( How can i use it? `
private class BackGroundTask extends AsyncTask<Void, Void, Void>{

    @Override
    protected Void doInBackground(Void... params) {
        try {
            //execute - means sending
        response =httpClient.execute(request);
        HttpEntity entity=response.getEntity();
        String str=EntityUtils.toString(entity);
        Log.v("Json=", str);
        //adding new response to our Response Class
        resp.addNewResponse(str);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            Log.e(TAG, "Exception caught: ", e);
        }
        return null;
    }

    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        httpClient.getConnectionManager().shutdown();
        TextView textView = (TextView) findViewById(R.id.textView1);

        textView.setText("Done");
    }

  }
}

please write an exact code. This class is in another .java file. Not in MainActivity.java
Comment: Any `View` involving action within your `AsyncTask` is a bad idea, since an `AsyncTask` doesn't have anything to do with views and has different mechanisms on how to communicate with an `Activity`. Use a `Handler` or an `BroadcastReceiver` for that kind of communication.
Comment: @NKN Updating the UI from `onPostExecute` is fine.
Comment: @Simon true! But this is only usable once `doInBackground()` concluded, don't really know what kind of problem is the OP trying to solve...
Answer: The easiest way would be to not use findViewById() at all since you are in a separate file and that is an Activity method.
You can simply use an interface to create a callback in onPostExecute() and send back the String result to your Activity. Then in your callback you can simply set the text as you wish.
This answer gives an example of using an interface with AsyncTask
Answer: You may pass Activity context(YourActivity.this) to your AsyncTask and use activity.findViewById(...);
EDIT
Some code:
Add to AsyncTask:
private Activity mActivity;

public YourAsyncTask(Activity activity){
this.mActivity = activity
}

...
....

protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    httpClient.getConnectionManager().shutdown();
    if(mActivity!=null){
        TextView textView = (TextView) mActivity.findViewById(R.id.textView1);
    }
    textView.setText("Done");
}

Comment: If you don't understand - look for some Java lessons - you really need them)
Comment: but how can i call my AsyncTask(Activity activity) ??? I called it from another class like - BackGroundTask doItInBackGround = new BackGroundTask();
doItInBackGround.execute();
Comment: what param's i need write here?
Comment: facepalm, http://bit.ly/1lxhnC1 You need to learn some OOP principles & basic Java. Passing a variable is kind of most basic thing
Answer: private Activity activity;

and in constructor:
public BackGroundTask(Activity activity){
    this.activity=activity;
}

and in post Execute:
 protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    httpClient.getConnectionManager().shutdown();
    TextView textView = (TextView) activity.findViewById(R.id.textView1);

    textView.setText("Done");
}

If creating new background class from activity class call:
BackGroundTask doItInBackGround = new BackGroundTask(this);

If in a click listener or any class inside Activity call:
BackGroundTask doItInBackGround = new BackGroundTask(ActivityName.this);

Comment: declare a property in async task of type activity and from the constructor set it and in post execute use it
Comment: but how can i call my class if i add constructor? i called like   BackGroundTask doItInBackGround = new BackGroundTask();
doItInBackGround.execute();   and how can i call it now?


call function within a custom widget that is a callback

Question: I'm trying to call the function SetLoginButtonLabel in widget Login from inside the function SetLoginInfo -- SetLoginInfo is a call back from the widget LogInDB.  When I try to call it just using this.SetLoginButtonLabel I get error SetLoginButtonLabel is undefined.  I'm also trying hitch as shown below, but thats not working either.  There are several different functions I'd like to call from SetLoginInfo -- How could I use hitch or some other method to make this work?
Thanks
---Widget Login
...
postCreate: function() {
 var SetLab = lang.hitch(this, "SetLoginButtonLabel");

}

Login: function() //call the database
{

LoginDB.Login("http://xxx/John Smith", this.SetLoginINfo)
},

SetLoginInfo: function(LoginData) //call back from LoginDB
{
//I've tried:
this.SetLogingButtonLabel("status"); //get an undefined error

//and
SetLab("Logout");//this just seems to get lost

},

SetLoginButtonLabel: function(status)
{
//
}

.......

---Widget LoginDB
define(['dojo/store/Memory', 'dojo/_base/xhr', "dojo/data/ObjectStore", 'dojo/_base/json'],
//functions to get data and fill data stores
function (Memory, xhr, ObjectStore) {
    var TicketStore;
    return {
        //login
        Login: function (url, callback) {
            xhr.get({//send data
                url: url,
                handleAs: "json",
                load: function (result) {
                    var LoginData = result;
                    callback(LoginData);

                },
                error: function (err) { }

            });
        }

    }

});

Comment: I've also tried calling the DB widget like this:
 LoginDB.Login(s, lang.hitch(this.SetTOC));

still get undefined error
Comment: rather it is this:
 LoginDB.Login(s, lang.hitch(this, SetTOC));
Comment: This does work:
LoginDB.Login(s, this.SetLoginInfo, lang.hitch(this, this.SetLoginButtonLabel));
however I want to call a bunch of functions from setLoginIfo
Comment: SetTOC in the above comments should be SetLoginInfo (I changed the function name on my post
Answer: this made it work:
LoginDB.Login(s, lang.hitch(this, this.SetLoginInfo));

All of my calls within SetLoginInfo I put a this on the front:
this.SetLoginButtonLabel("Logged In");


consistency of an estimator in real data

Question: as we know in statistics we are interested in the properties of an estimator , as my estimator is consistent , in probability sense it can be shown as $P(|estimator - true| <- positive) = 1$ as interpretation is we increase sample size probability approaches 1 well.
But i'm in confusion since a long time what is a practical example of this equation ,. give me any real example how it approaches to 1 or what is statement actually saying, data example will be highly appreciated
Answer: A practical example would be great but it's difficult to come by unless we know the "true" relationship between our features and what we are trying to predict. This isn't always the case, maybe you could find some data in physics where a known relationship is present and we are trying to estimate the parameters. Anyway, this illustrative example is with some dummy data.
First lets assume a true relationship of
$$y = mx+c+n(0,\sigma)$$
$$y = 3x+5+n(0,2)$$
We then try to estimate this relationship given varying amounts of data. Here is the code to reproduce this example in R.
set.seed(42)

n_sample = 20

data = data.frame(x = seq(1,n_sample))

# y = 3x+5 + noise
data[['y']] = 3*data[['x']] + 5 + rnorm(n_sample,0,2)

fit = lm(y~x, data = data)

summary(fit)

For an n_sample of 20 out estimators are

intercept = 7.03
m = 2.84

however for n_sample = 10000

intercept = 4.976
m = 3.00

hence, as n_sample increases indefinitely our estimate converges to the true value.
Comment: if i just use P(|estimator−true| > positive) it approaches 0 im confused in ( 0 and 1)
Comment: plz sir answer about o and 1 what does it mean , i will wait


Does instrument cable impedance matter?

Question: I see many 1/4 TS 'instrument' cables for sale with no mention of impedance.
With:

the speed of light in vacuum of ~300 000 km/s
audio frequencies < 20 kHz

you get wavelengths of at least 15 km(!). (Don't forget the velocity factor!)
It seems that for the case of a high-impedance output (guitar) into a high-impedance input (amplifier), transmission line effects and thus the impedance of an instrument cable is negligible. Is this correct? What about the frequency response of those cables?
And what about connecting low impedance (<0.5 kOhm) inputs/outputs together?
Example: guitar amplifier head and cabinets? Can I still use 'instrument' cables for that purpose or does cable impedance start mattering in those cases?
Answer: You've correctly analysed why the cable impedance does not matter in the way it does for HF transmission lines. (Though, the assumption of vacuum light speed is actually not completely valid – the dielectric factors into this, but it doesn't change the fact that the wavelengths are many times longer than any guitar cable.)
That notwithstanding though, the capacitance of that cable does have an impact on the sound – quite a lot in fact. Not for being part of the impedance as it matters for HF wave effects, but because electric guitars use high-impedance inductive pickups. This inductance forms with the cable capacitance a 2nd-order low-pass filter, whose resonance and cutoff frequency scales proportionally to the inverse square root of the cable capacitance. Thus a cable with low capacitance gives a brighter, twangier sound. (Only applies to passive guitars and basses.)
Comment: @Xunie yeah, my answer was formulated misleadingly. Capacitance is indeed part of impedance. I edited.
Comment: You say that there's non-negligible 'capacitance' but the impedance *is* negligible? How can that be? A component's capacitance affects its reactance/impedance. So the impedance is not negligible afterall?

(**VERY** interesting how the pickups couple with the cable capacitance. *Never* thought of it that way!)
Comment: @Xunie the impedance is a complex, the real part of it (resistance) can be negligible whereas the imaginary part (inductance) is not ;). The inductance will affect the phase of the wave...
Comment: @Tom_C Capacitance **is** reactance. Together, the reactance and resistance of a component are considered its "impedance". How can the impedance be negligible if the capacitance (reactance) is not?
Comment: @Xunie I said "resistance" not reactance. A complex has a real and an imaginary part. The two of them do not have any reason to be linked.
Comment: @Tom_C Hey, thanks for trying to clarify. Sorry, but I edited my last comment a few times. I think we're miscommunicating here. Take a look at [this image](https://electronicsclub.info/images/imped.gif). How can the Impedance Z be negligible if the capacitive reactance X is not negligible? (If X > threshold, then Z > threshold.)
Comment: @Xunie to be negligible is always *against* something. Furthermore the relation the is wrong, the Z here is the *module* of the impedance (https://en.m.wikipedia.org/wiki/Electrical_impedance) which is a complex. (To add on this, you cannot ordonate complex numbers ;) )

Does instrument cable impedance matter?


Access $display_submitted in page template

Question: Is there a way to access a node's $display_submitted Boolean value from within a page.tpl.php?
Answer: While normally done in node.tpl.php, if the page is a node view page, the $node variable is also available in page.tpl.php
You can then use something like:
if (isset($node)) {
  // Check if display submitted variable is set for this node type
  if (variable_get('node_submitted_'. $node->type, 0)) {
    // Do stuff
  }
}

An alternative approach would be adding the required logic instead to an implementation of
hook_preprocess_page
Bonus update: You can see the $node variable added to page.tpl.php in core template_preprocess_page
if ($node = menu_get_object()) {
  $variables['node'] = $node;
}


If $f(b)-f(a)=(b-a)f'(\frac{a+b}{2})$ prove that any such function is a polynomial of degree $2$

Question: Consider $f:\Bbb R \to \Bbb R$ to be differentiable function. $f(b)-f(a)=(b-a)f'(\frac{a+b}{2})$ for all $a,b \in \Bbb R$ prove that any such function is a polynomial of degree $2$.
I am trying using Taylor's expansion that any point $a$ we have
$$f(x)=f(a)+(x-a)f'(a)+(x-a)^2/2f''(a)+\cdots$$.
then I observed that the function is not infinitely differentiable. So we can't use the Taylor Series. So, I don't think that proving that the higher order differentiation vanishes also won't help. We can use Lagrange mean value theorem, but how to proceed? Any hint!!
Comment: Is it given initially that the function is a polynomial?
Comment: The function IS infinitely differentiable because of the equation - since $f$ is differentiable, LHS of the equation
$$
\frac{f(x) - f(a)}{x-a} = f'\left( \frac{x+a}{2}\right)
$$
is differentiable for $x\neq a$, so for RHS. Varying $a$ shows that $f''(x)$ exists for all $x$.
Comment: The condition is also satisfied by constant functions and linear functions
Answer: You forgot to state $f$ is differentiable.
Prove that $f$ is infinitely differentiable (hint: use $f'(x)=\dfrac{f(x+y)-f(x-y)}{2y}$).  Differentiating twice with respect to $y$, the equation
$$
f(x+y)-f(x-y)=2yf'(x)\quad\forall x,y
$$
gives
$$
f''(x-y)=f''(x+y)\quad\forall x,y.
$$
Hence $f''$ is a constant, so $f$ is a polynomial of degree at most $2$.
Comment: Write $f'(x)$ in two different ways: $f'(x)=\frac{f(2x)-f(0)}{2x}$ and $f'(x)=\frac{f(2x-1)-f(1)}{2x-2}$. The first one suggests $f'(x)$ is differentiable if $x\neq0$, and the second says the same for $x\neq1$.
Comment: Did the question states that $f''$ exists?
Comment: Thanks a lot. You're right, I forgot to mention that $f$ is differentiable.
Comment: And logically if $f''$ is constant then $f''$ must be a polynomial, right?
Comment: Does there exists any $f$ which is non-polynomial function?


Why is __radd__ not working

Question: HI
Trying to understand how __radd__ works. I have the code
>>> class X(object):
    def __init__(self, x):
        self.x = x
    def __radd__(self, other):
        return X(self.x + other.x)

>>> a = X(5)
>>> b = X(10)
>>> a + b

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    a + b
TypeError: unsupported operand type(s) for +: 'X' and 'X'
>>> b + a

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    b + a
TypeError: unsupported operand type(s) for +: 'X' and 'X'

Why is this not working? What am I doing wrong here?
Comment: just trying to see how __radd__ works. I know that i can do this using __add__
Comment: I'm new to Python too, but shouldn't that be __add__?
Comment: Sorry, just found it: http://docs.python.org/reference/datamodel.html#object.__radd__
Answer: Python docs for operators
"These functions are only called if the left operand does not support the corresponding operation and the operands are of different types."
See also Footnote 2
Since the operands are of the same type, you need to define __add__.
Answer:
These functions are only called if the left operand does not support the corresponding operation and the operands are of different types.

I am using Python3 so please ignore the grammatical differences:
>>> class X:
    def __init__(self,v):
        self.v=v
    def __radd__(self,other):
        return X(self.v+other.v)
>>> class Y:
    def __init__(self,v):
    self.v=v

>>> x=X(2)
>>> y=Y(3)
>>> x+y
Traceback (most recent call last):
  File "<pyshell#120>", line 1, in <module>
    x+y
TypeError: unsupported operand type(s) for +: 'X' and 'Y'
>>> y+x
<__main__.X object at 0x020AD3B0>
>>> z=y+x
>>> z.v
5

Answer:
These functions are only called if the left operand does not support
  the corresponding operation and the operands are of different types.
  For example,

class X:
  def __init__(self, num):
    self.num = num

class Y:
  def __init__(self, num):
    self.num = num

  def __radd__(self, other_obj):
    return Y(self.num+other_obj.num)

  def __str__(self):
    return str(self.num)

>>> x = X(2)
>>> y = Y(3)
>>> print(x+y)
5
>>>
>>> print(y+x)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-60-9d7469decd6e> in <module>()
----> 1 print(y+x)

TypeError: unsupported operand type(s) for +: 'Y' and 'X'

Answer: Try this
class X(object):
 def __init__(self, x):

     self.x = x

 def __radd__(self, other):

     return self.x + other

a = X(5)
b = X(10)
print sum([a,b])

Why is __radd__ not working


When running silent uninstalls of MSIs, how do you know when it is done?

Question: If you have a msi you want to uninstall from the command line, doing MsiExec.exe /qn /X{26A24AE4-039D-4CA4-87B4-2F83217045F0} /norestart
for instance, returns immediately. But msiexec.exe is running for some amount of time, maybe for minutes. So if I'm scripting around this to want to then do an install - how do I know if it's done? I can't just watch msiexc.exe because it's also a service process, so won't ever go away...
Answer: Use "start" command with /wait to wait until process has exited.
start "" /wait msiexec /x ...
"" is a workaround, should any following attributes contain quotes. http://ss64.com/nt/start.html
Answer: The msiexec error codes are documented here. When you get an error code, such as zero meaning success, msiexec considers itself done.
To capture the error codes one could for instance wrap the execution in powershell, such as done here (shameless code copy/paste):
(Start-Process -FilePath "msiexec.exe" -ArgumentList "<<whatever>>" -Wait -Passthru).ExitCode

Modify to suit your needs.


Why is it possible to train a semantic segmentation neural network like U-net/Tiramisu from scratch using small data-set like few hundreds

Question: Why is it possible to train a semantic segmentation neural network like U-net/Tiramisu  from scratch  using small dataset like few hundreds.
While for the  image classification task, it is not advised to train your own network from scratch even if you have thousands of images per class.
I have seen, people using transfer learning (models trained on imagenet dataset )even when they have (ex. 5000 images per class for say 10 class classification) and not train the network from scratch.
One reason, I can think is, The no of parameters that need to be trained in semantic segmentation network is significantly lesser than typical image classification task. So lesser parameters helps training with lesser images.
Any other reasons?
https://www.microsoft.com/developerblog/2018/07/18/semantic-segmentation-small-data-using-keras-azure-deep-learning-virtual-machine/  :  talks about semantic segmentation using small dataset.
Answer: A classification task has a single label, whereas a segmentation task basically has a label for every pixel in the image, so a single segmentation map has as many "labels" as thousands of classification tasks.
A more information theoretic way to think about it is that a single classification label -- putting an image into one of 1000 classes -- has less than 10 bits of information. On the other hand, I think you'd be hard-pressed to compress a 1024 by 1024 segmentation map down any less than a few kilobits. Your small semantic segmentation dataset may contain as much information in it as a much larger image classification dataset.
Comment: Thanks for answer!! I understood where you are  going with this answer though I did not understand what you want to say in paragraph-2.  Can you be little more clear.
Answer: Because the classification is local rather than global and as there are many local positions in one image the network is able to learn them more easily. Eg) If I have a background class and car then there are many positions/angles where background and car boundaries form in a single image giving me more information than single classification.
I think in single object classification the problem is correlation of features. Remember you are just showing an image to the NN and asking it to decide what the correlated features are so it takes time to distinguish between the actual object and random correlation that occur in the background. This is a big problem in natural datasets where some classes are pictured in similar background/colours.
Additionally a network MAY NOT pick up on subtle features in small datasets or datasets with too many classes for best results. See https://arxiv.org/pdf/1411.1792.pdf to see how transfer learning improves generalisation on the SAME task. This insight is quite interesting and shows a minor failing of our optimisation approaches.
Comment: This doesnt answer my question
Comment: I answered your question in the first two paras by saying one image has a lot of information about classes due to the local nature of segmentation. The second and third say the difficulties in training CNNs on small datasets or too many classes( and why transfer learning is good). What more do you want answered?


I am using https://github.com/drupal-composer/drupal-project . How to add more scripts after "create-project"?

Question: I want to use https://github.com/drupal-composer/drupal-project to generate several customized projects.
If I want a contrib module to be available for all instances, what is the best way to get them when running "composer create-project"?
I thought to add this logic (to add contrib modules by default) in scripts/composer/ScriptHandler.php but this file doesn't seem to be suitable for customizations.
Is there an easy way to add other scripts to run on project creation?
Or which other way should I chose?
Comment: I dont know your needs, and as pointed on [video](https://youtu.be/vkD5jUHL190?t=939), "There is no 'recomended' workflow" (-Mathew Tift) after all, every project is unique. Use this video just as use case. In that, he uses one main repo for code base, and another for configuration (see [here how and why](https://youtu.be/vkD5jUHL190?t=1080) he takes this approach), if this dont fit for your needs, you have the flexibility to change where to you makes sense. Drupal 8 é interessante por isso, permite várias configurações, escolha a que venha ser melhor para ti. ;)
Comment: Take a look in this [video](https://www.youtube.com/watch?v=vkD5jUHL190) Erich Beyrent talk about 'Configuration As Dependency: Managing Drupal 8 Configuration with git and Composer', for sure that you will find your answer and beyond.
Comment: @Vagner in which part do they talk about using https://github.com/drupal-composer/drupal-project ? Seems like plain composer/drupal, so it doesn't help me here.
Comment: Ok @Vagner maybe you are suggesting me to use a two repos and different branches for each project?! That seems a very odd solution. The video has now 35 views, it doesn't seem "the" solution. Could you be more specific?
Answer: when you use create-project you're creating a new composer project with a  composer.json based on the package type.
The composer.json file is highly customizable. You can set install paths for specific modules/libraries and/or set a list of default modules to install when the project is created. You can also apply patches and run post-install scripts if nessecary. Plenty more options as well. I suggest jumping into the composer docs.
to add a module to composer.json run:
composer require drupal/module_name 8.1.*@dev

Once you have a composer.json the way you like, you can take that composer.json file, place in a different empty project directory and you can simply run composer-install and it will install the drupal project, all the modules in the appropriate directories specified inside the composer.json file, post install commands ect, it will also write a composer.lock file if one doesn't exist. No need to create a brand new project everytime, just manage custom composer.json files thats the beautfy of composer.
https://www.lullabot.com/articles/goodbye-drush-make-hello-composer
https://getcomposer.org/doc/01-basic-usage.md
https://getcomposer.org/doc/
Comment: But that composer.json will be used to install modules that are unique for each project, so sharing them across all instances doesn't seem practical. I think the best place to have this settings is in the upper level, in "drupal-composer/drupal-project" ... but then to change the composer.json there is also tricky, because it will be updated over time when I do a git pull to get updates.
Comment: If you share the same composer.json across all instances of course you will get the same results...  If you had different composer.json files you would have different results.

 If you do it at the `drupal-composer/drupal-project` level you still have to make sure versions are correct or the module wont be added to the project....

This is what composer is for, it wont allow you to add or update stuff if it will break based on incompatible versions. Managing versions is part of the game now, if you want to blindly update stuff composer wont allow you to do it.
Answer: There are various ways to do this.
drupal-project is a composer project like any other. Create your own repository, e.g. by forking on github. Then add all your standard modules there and use your own repository with create-project.
You can also create a repository with a composer.json that contains nothing but dependencies. https://github.com/webflo/drupal-core-strict is something like that, except that it enforces specific versions of core dependencies. Simply add the modules you want to use there, then add that with composer require on a new project and it will merge it together and download all those projects.


Changing form field title within hook_preprocess_form() does not work

Question: I have customize drupal user registration form which I want to change some field titles.
I implemented hook_preprocess_form() within theme and changed titles of some form fields, but it didn't work.
While debugging I found that it has '#children' item already there with rendered HTML inside it. Then I tried to change that value by using drupal_render_children(), but that also doesn't work.
What is the right way?
Answer: Use hook_form_alter() to change the form before it gets rendered.
Comment: In Drupal 7 you can use hook_form_alter in a theme's template.php file. Themes' hooks should always be executed after all modules' hooks.
Comment: You can change your module's weight in the system table to ensure it gets executed after all the rest. You'll then have everything everytime in your hook.
Comment: I cannot do that because the fields are inserted by other modules using hook_form_alter. It may or may not available within form alter hook depending on the loading order of modules.


Why does a Serialist composition sound like a random one?

Question: Why can random notes and a structured  Serialist composition sound the same?
This Reddit comment cites Ligeti:

The irony, noted Ligeti, was that the kind of music pioneered by Boulez and Stockhausen was actually extremely structured -- but it was so structured that the resulting music came across as random to the listener because the structure was so dense that it was hard to grasp:
"Ligeti expressed that division with forensic detail in 1958, in an analysis of Boulez's infamous piece Structures Ia, one of the icons of the short-lived experiment of "total serialism", in which every aspect of music - not just pitch, but volume and rhythm as well - are subjected to systematic organisation. He revealed the limitations and contradictions of the technique, and the paradox that the results of total determinacy actually sound random, chaotic, and indeterminate.
"Boulez was incredibly angry after he read the article," Ligeti remembers. "He had been very nice with me when we had met before, but suddenly he did not speak to me any more. For 10 years, he was a complete enemy. [...]"

Prof. Dan Román MM DMA (Hartt School of Music) from Rethink: The Abyss of Music in the 20th Century: (Paraphrased by reason of poor audio quality)

It [a Pierre Boulez's serialist piano composition] sounds even more chaotic. I had a college professor in music who loved to demonstrate a kind of competition: He recorded a performer just improvising notes and rhythms at random. Then he would play the random sample and the Boulez piece back-to-back to a room of students. To the students, both examples sounded the same.
So we have here an example of a composition which is completely structured - all its music determined by a discreet series of numbers, and another piece of music that is virtually unstructured entirely, yet to the listener, they sound the same.

David Bruce MComp, PhD in Composition at King's College London in Music vs. Pattern:

09:02 Of course we can also take things
09:04 too far the other way. Around the same
09:06 time as those total serial pieces John
09:08 Cage was writing his music of changes. I
09:11 say writing, but he was actually using
09:12 chants based on the Chinese I Ching to
09:15 dictate the score. So you could say this
09:17 is the total removal of pattern. Now what
09:20 has struck many people is how similar
09:21 these two apparently polar opposite
09:23 approaches end up sounding. This is
09:25 Stockhausen's Klavierstück III,
09:27 the completely patterned
09:30; and this is Cage's Music of Changes, the
9:33
completely patternless.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/75261/discussion-on-question-by-canada-area-51-proposal-why-does-a-total-serialist-c).
Comment: If we use musical rules than have nothing to do with natural mathematical relationships and how we listen to music then we can expect the result to be perceived as randomness. I'm with Ligeti.
Answer: This is a time where the "music as language" metaphor can be helpful. Think of a language you don't speak; let's say Hungarian. When you hear it, so much of it tends to sound random, no? It's not until you study the language and understand its grammar and sounds that you become more aware of the structure. (I also have my own thoughts on how not understanding a language tends to make people view that language as sounding "hostile" or "angry," and I wonder sometimes if the same is true in music.)
The same is true, I think, of total (or complete, or integrated) serialism. It may sound random at first, but it's in fact the opposite of random, and we can recognize that once we understand the grammar of the piece.
As for the little experiment in the quote, I wish they would have given a little analysis of the serialist piece and played it again to see if the listeners had a different reaction to it. Otherwise, the experiment is no different than someone playing you a recording of flawlessly spoken Hungarian followed by this or this, two examples of absolute gibberish that were designed to sound like English.
Comment: This is a great answer, and I find the metaphor to be deeply compelling. As a lover of a lot of total serialist music, it pains me to bring this up, but it is an important part of the story: In the famous letters between John Cage and Pierre Boulez, the latter actually seems to agree that his total serialist piece *Structures 1a* doesn't sound very different from Cage's randomly composed *Music of Changes*. There really was something of a crisis in the early generation of total serialists around this issue. Stockhausen's *Kreuzspiel* was seen as finding some possible solutions.
Comment: This is a good dialogue everybody; just wanna be clear here that I'm not actually asking the question of whether or not it's worth it but rather that it's a question each must ask themselves
Comment: @PatMuchmore That's an interesting anecdote that I didn't know; thanks for sharing! I agree, for what it's worth, but I also think it's important to at least try to hear these things, however much eye-rolling the attempts elicit from the undergrads :-)
Comment: @jjmusicnotes - _"is this worth it?"_  - I think it depends on what you're listening for. If you're listening for pleasure and enjoyment, it's _probably_ not worth it. If you're listening to learn what can be done in a composition and to expand your own personal horizons of the limits of music, it's worth it. Regardless, this answer is **definitely worth it**. (I can't stand most of that material but I've listened just to expose myself to it.)
Comment: @BrianTHOMAS -- I'm not sure that it is important to be able to identify these features by listening alone. In any case, most untrained listeners can't aurally identify motifs or transformations of phrases in traditional music, yet that does not invalidate those devices.
Comment: I was going to mention cage as well; glad you brought it up. Invariably composers like Boulez seem to have stumbled onto the threshold for surface-level comprehension. To extend Richard's metaphor, I'm similarly confused by English speakers who use a lot of jargon specific to their exact field when it doesn't relate to mine. I would venture that Ferneyhough and others fall into this category as well. I think that as you approach the threshold you need to ask "is this worth it?" And for those who have crossed (Cage), complexity's cycle continues to rotate.
Comment: @jjmusicnotes See, for me, I think it *is* worth it. Your jargon metaphor is great, and sometimes jargon really is just obscurantist and worthless. However, lots of times jargon isn't that—it's a necessary aspect of cognitive chunking as concepts get headier and more specialized. I'm not going to lie and say I totally understand and love Ferneyhough, but I've definitely found it worthwhile to study what he's doing and try to learn his "jargon." The experience has been rewarding; it reminds me of when David Foster Wallace talked about art that "makes the head throb heartlike."
Comment: If you have the notation of the piece it's possible to spot retrogrades and inversions and other transformations of the tone row - but is it actually possible to spot these by listening alone as the piece is performed?
Answer: Let me attemt a mathematical answer and start by giving an analogy.
It is very hard to generate actual random numbers in a computer, since programs run deterministically. What you want is numbers that, over the long run, appear with equal likelyhood and that have no correlation to other numbers in the sequence. So what is done instead of actual randomness is to use pseudo-random numbers - you come up with an algorithm that runs through all integer numbers in a given range (let's say, 0 to 2^32) exactly once, and then starts again, and you choose it in a way that the next number bears as little obvious semblance to the current one as possible.
Now, in music, "normal" compositions impose a structure on the tones that are played. Certain notes are given special functions like the tonic or the dominant by how often and in what places they are played; there are correlations between consecutive tones and chords, like the dominant leading back to the tonic, etc.
Just like with random numbers, there are two ways of breaking up these structures: either by actual randomness - you just play whatever - or an algorithm that mimicks some aspects of randomness, like using all 12 tones exactly once before you can start again, which gives you exactly equal probablilities. So in that sense, serialist compositions have a strong pseudo-random aspect.
Answer:
Why does a Serialist composition sound like a random one?

Most serialist compositions are essentially random in the way that humans perceive music.
A typical serial composition employs complex, dissonant harmonies without resolution.  Listeners are deprived of understandable, consonant harmonies and constant strong dissonances are statistically what you get in random successions of tones.
And in trying to break new ground rhythmically, serialist composers either use a great variety of durations, replete with long pauses and rapid runs of notes, or serialize the durations along with the pitch classes.
In either case, it becomes much harder for the listener to detect any rhythmic patterns.
When both the tone sequences and durations in a musical piece do not appear have any perceivable structure, the piece will sound random.


How can I determine if a user cancels a CredentialsPicker?

Question: How can I determine if a user cancels a CredentialsPicker?
Answer: You can try this in the Credential Picker sample. Using scenario 1, for example, you'll see that cancelation of the picker will return a CredentialPickerResults object (in the promise results or from the API in C#), in which the ErrorCode property (errorCode in JS) will contain x800704c7 which is the Win32 error code ERROR_CANCELLED.
If for some reason the credential picker cannot be displayed, that would generate an error from the credential picker itself (and be picked up by an error handler give to a promise.then). The case you're describing is that the credential picker succeeded, but the user canceled.
Comment: Thanks! [The MSDN Error Codes page](http://msdn.microsoft.com/en-us/library/windows/desktop/ms681383%28v=vs.85%29.aspx#error_cancelled) says the code should be 0x4c7. Do you know why it has the extra four bits set? Should I be ignoring the two most significant bytes?


Docker in docker - how to ensure it's cleaned up after itself?

Question: I've built a Swarm-based Docker setup for our on-prem DevOps pipelines. Docker-based pipeline agents are started and can perform build operations. I also have a few of those agents capable of building new docker images - this was enabled by binding \\.\pipe\docker_engine from the host with these containers.
This generally works... however in case there's an issue with the build process it'll likely leave a lot of garbage behind. This can partially be alleviated by using --force-rm. But ideally I'd like to have the containers clean up after themselves so that the next run is "pristine" regardless of what was ran inside it. I'd also like to let these special containers launch new containers for more complex CI pipelines, but again - I'm worried about them not cleaning up after themselves. Note: I'm less worried about security since this is all "in-house" stuff.
Is it possible to have a container which can launch nested containers inside of itself whilst making sure that if this top container is stopped & removed then all of the stuff created by this container will be stopped & removed as well?
Answer: If you run the containers in a dind (Docker in Docker) container as background, you can store the process id and ensure proper cleanup.
The cleanup can be hooked onto the interrupt or termination signals.
Here is an example script which you would have to execute on dind-container startup:
#!/bin/sh
cnt_name="dindContainer"

# intercept SIGINT and SIGTERM and hook a function onto them
trap 'cleanup' INT TERM

cleanup() {
    if [ -n "$ctr_proc" ]; then
        kill -TERM "$ctr_proc"
    else
        docker stop "$cnt_name" > /dev/null 2>&1
        sleep 5
    fi
}

cleanup
docker run \
    --rm \
    --name="$cnt_name" \
    alpine \
        sleep 1000 &

# store the container process id and wait for it to finish
ctr_proc=$!
wait "$ctr_proc"

Comment: I can try and use this for our Linux-based DIND dockers... but the question was primarily focused on Windows DIND (see tags).
Comment: @MBender I see. Signal event handling is unfortunately messy with Windows containers. A Windows container treats a SIGTERM like CTRL_SHUTDOWN_EVENT (SIGKILL), see [here](https://github.com/moby/moby/issues/25982#issuecomment-806001635).
You would have to write you on shutdown handler in most likely C#.

In either way, as it seems you also want to cleanup artefacts in your swarm like created images, you would be better off with a global prune cmd like [here](https://github.com/moby/moby/issues/31254#issuecomment-464668235). Adapt it to Windows of course.


Loading icon as background image loads

Question: The background image takes some time to load.
How can I check if the background image (applied using the background-image CSS tag) has finished loading?
Comment: I'd suggest you to add a background color similar to the background image.That would create better user experience.
Comment: [jQuery Load Event](https://api.jquery.com/load-event/) might help you.
Answer: You can include the loading icon as the default background image by default and then update the CSS via javascript once the slow-loading image has downloaded.
Here's a working example showing the technique:

$(document).ready(function() {
  var imgSrc = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg';
  var img = new Image();
  img.onload = function() {
    $("div").css("background-image", "url('" + img.src + "')");
  };
  img.src = imgSrc;
});
div {
  background-color: orange;
  padding: 50px;
  color: purple;
  font-weight: bold;
}

.

This div will have a solid color as background to begin with.

Watch its background change to an image once it's loaded.

Comment: Hello, your technique is great but this can be achieved only with CSS. CSS will dislay the color first and then the image when it has loaded. But to be adapted for a loading gif it can be a great technique :)

Loading icon as background image loads


Array com dados do banco de dados

Question: Preciso montar um array puxando os slug da minha tabela, exemplo:
<code>$array = array (
  'esportes',
  'mundo',
  'estado'
);
</code>
Tentei assim:
<code>$slug = $con->prepare("SELECT slug FROM categorias");
$slug->execute();
$array = array (
   foreach ( $slug as $row ) {
      echo "'.$row['slug'].',";
   }
);
</code>
Preciso usar esse array pra fazer uma url amigável que ta assim:
<code>$url = $_GET['url'];
$sep = array_filter ( explode ( "/", $url ) );
</code>
Aqui preciso do array:
<code>if ( isset ( $sep[0] ) && $sep[0] in_array ( $sep[0], $array ) ) {
   $Categoria = new Categoria;
   $Categoria->GetCategoria;
}
</code>
Alguém sabe alguma solução?
Comment: Se você usa PDO: https://www.php.net/manual/pt_BR/pdostatement.fetchall.php; senão, https://www.php.net/manual/pt_BR/mysqli-stmt.fetch.php
Comment: @Valdeir Par usando a primeira opção eu posso fazer aquele 'if?
Comment: O seu último `if..isset`? Depende da sua estrutura de dados e do retorno dos dados.
Comment: @Valdeir Par o retorno seria o array
Answer: Na sua consulta tente assim:
<code>$slug = $con->prepare("SELECT slug FROM categorias");
 $slug->execute();
 $array = array ();
   foreach ( $slug->fetchAll(\PDO::FETCH_ASSOC) as $row ) {
      $array[] = $row['slug'];
   }
</code>

Array com dados do banco de dados


Erro Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

Question: Sei que deve sim ter  outras respostas parecidas mas em nenhuma delas achei oque precisava. No banco possuo uma tabela com id, nome, version, upload e size. Preciso apenas pegar a versão do arquivo que selecionei pelo SELECT
o código esta a seguir:
<?php
$num = 1;
if($num == 1){
    $sql = mysqli_query( $link,'SELECT * FROM files id = 2');
    $resource = mysqli_query($sql) or die(mysqli_error($conexao));

    while($ln = mysql_fetch_array($result, MYSQL_NUM)){
        echo " ID: ". $ln['id'];
        echo " Nome: " .$ln['nome'];
        echo " Versão: ". $ln['version'];
        echo " Upload: ". $ln['upload'];
        echo " Size: ". $ln['size'];
        echo "Deu certo";
        echo '
'.$ln['version'].'	;
}
?>

Porém sempre que tento executar ele aparece o seguinte erro:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in.
Oque devo fazer?
Comment: `mysqli_fetch_array`; faltou um i
Comment: e `$result` não existe?
Comment: já verifiquei e acabei de corrigir, porém qual seria a forma certa de colocar o Select?
Comment: `SELECT * FROM files WHERE id = 2`. Faltou o WHERE
Comment: mas ele não possui  " ", ou ' '
Answer: Teu script tem no minimo 5 erros
Primeiro, esta linha esta errada:
$resource = mysqli_query($sql) or die(mysqli_error($conexao));

Outra coisa estranha é que para a conexão você tem duas variáveis $conexao e $link, uma delas deve estar errada.
Aqui você setou $resource, mas creio que o queria era $result
Fora que você esta passado o resultado de um mysqli_query em outro:
$sql = mysqli_query( $link,'SELECT * FROM files id = 2');
$resource = mysqli_query($sql) or die(mysqli_error($conexao));

Outro erro é que falta o WHERE no teu SELECT:
SELECT * FROM files id = 2

Deveria ser:
SELECT * FROM files WHERE id = 2

O que não faz sentido algum
E você esta misturando a API antiga do mysql com a API nova chamada mysqli, o correto seria:
favorita
Sei que deve sim ter outras respostas parecidas mas em nenhuma delas achei oque precisava. No banco possuo uma tabela com id, nome, version, upload e size. Preciso apenas pegar a versão do arquivo que selecionei pelo SELECT o código esta a seguir:
<?php
$num = 1;
if($num == 1){

    $result = mysqli_query($link, 'SELECT * FROM files WHERE id = 2') or die(mysqli_error($link));

    while ($ln = mysqli_fetch_array($result, MYSQLI_NUM)) {
        ...
    }

    mysqli_free_result($result);

Um exemplo bem simples de mysqli
<?php
//$link é a variavel da "conexão"
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* Verifica erros */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit;
}

$result = mysqli_query($link, 'SELECT ...') or die(mysqli_error($link));

/* array numerica */
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
    printf ("%s (%s)\n", $row[0], $row[1]);
}

/* array associativa */
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    printf ("%s (%s)\n", $row["Nome"], $row["Sobrenome"]);
}

/* associativa e numerica */
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
    printf ("%s (%s)\n", $row[0], $row["Sobrenome"]);
}

/* libera a memoria */
mysqli_free_result($result);

/* fecha a conexão */
mysqli_close($link);

Leia a documentação
uma dica, não saia fazendo as coisas aleatóriamente, documentações existem para serem usadas, segue os links:

http://php.net/manual/en/book.mysqli.php
https://dev.mysql.com/doc/refman/5.7/en/select.html


Countable or uncountable set 8 signs

Question: Let S be a set of pairwise disjoint 8-like symbols on the plane. (The 8s may be inside each other as well) Prove that S is at most countable.
Now I know you can "map" a set of disjoint intervals in R to a countable set (e.g. Q :rational numbers) and solve similar problems like this, but the fact that the 8s can go inside each other is hindering my progress with my conventional approach...
Comment: Intuitively the problem is the 8's can't pack against each other like line segments.  There must be a small disk between them even if one is inside the other.  In that disk must be an element of $\mathbb{Q \times Q}$.
Comment: The first thing you need is a rigorous definition of what qualifies as an "8-like symbol".
Comment: @Ross, some subtlety will be needed, because there are uncountably many pairwise disjoint "0-like" curves in the plane (such as for example all concentric circles).
Comment: @HenningMakholm:  I agree.  That is exactly why the gaps between are important and we need to define 8-like curves in a way that requires them.
Comment: @RossMillikan: The 8s _can_ pack against each other (and even fill the plane) - e.g. 8s consisting of two rectangles. It's the "second o" that creates the "gaps" which prevent the concentric circle argument from working with 8s.
Comment: @DavidBevan Disjoint figure-eights cannot fill the plane. If the figure 8s consist of circles, any line will only intersect each figure 8 in finitely many points. If the figure 8s consist of rectangles, any circle will only intersect each figure 8 in finitely many points. Lines and circles are uncountable, but the plane only fits countably many figure 8s.
Comment: I stand corrected.
Comment: I'm delighted to see this because I have a happy memory of one of the first serious mathematical discussions I ever had, around age 16 or so, of essentially this question; I wanted to prove that a set of pairwise-disjoint `+`-like symbols must be countable.
Answer: Let $\mathcal{E}$ denote the set of all your figure eights. Then, define a map $f:\mathcal{E}\to\mathbb{Q}^2\times\mathbb{Q}^2$ by taking $E\in\mathcal{E}$ to a chosen pair of rational ordered pairs, one sitting inside each loop. Show that if two such figure eights were to have the same chosen ordered pair, they must interesect, which is impossible. Thus, $f$ is an injection and so $\mathcal{E}$ is countable.
Comment: It means ordered pairs of ordered pairs, so a typical element would look like 4((p,q),(r,s))
Comment: Think about it, if you had two figure eights, $E$ and $E'$ which share a point in each of their loops. How could they do this and not intersect? I can't think of a simple analytical proof, but it's pretty clear by inspection.
Comment: I am confused, but I don't know why :( First question: what does Q^2 x Q^2 denote? Q x Q denotes a "2-D pair" in the rationals right, so what does this mean?
Comment: Oh, I see. I still don't understand this part: "they must intersect, which is impossible" Could you write out more? Thank you so much.
Comment: If figure eight $A$ is inside a loop of figure eight $B$, $A$'s index points cannot include a point from the other loop of $B$. If $A$ and $B$ are external to each other, then they can have no index points in common.
Answer: Let us associate each 8 with its center. If two 8's have exactly the same size and are too close together, then they will intersect. The same holds even if they only have almost the same size. That is, there are some $\epsilon,\delta$ such that two nonintersecting 8's of size between $r$ and $(1+\epsilon)r$ cannot be $\delta r$-close (that is, their centers need to be at distance at least $\delta r$.
Let us denote by $S_r$ the set of 8's of size between $r$ and $(1+\epsilon)r$. The circles at radius $\delta r/3$ around the centers are disjoint, and so if we choose for each 8 in $S_r$ a rational point inside the circle at radius $\delta r/3$ around its center, then these rational points will be distinct. This shows that $S_r$ is countable.
The set of all 8's is the union of countably many sets of the form $S_r$ (for example, we can take $r = (1+\epsilon)^z$ for all integers $z$). Since the countable union of countable sets is countable, we conclude that the number of 8's is countable.
Comment: It does work for other figures :)
Comment: We cannot suppose such thing. We could have arbitrary small $8$s.
Comment: I expanded my answer a bit. The idea is that the union of countably many countable sets is countable. So there's absolutely no problem in supposing that all 8's have some minimal size.

Countable or uncountable set 8 signs


store easy retrievable pairs from both key and vaule in Javascript

Question: I'm trying to find an efficient way to store pairs key:value pairs so that you can fast find the other value (while both are unique).
for example: lets say we wanna store pairs "unique_id: email"... and I want to be able to get the other value from either of the two values. What is the less resource consuming (both RAM and calc) way to do it?
Saving memory solution:

const data = {"1": "firstname.lastname@example.com",
              "2": "firstname.lastname@example.com",
              "3": "email@example.com"}

var email1 = data['1']; //fast research
var user1 = data.find("firstname.lastname@example.com") //slow research algorithm (find is some function that search through the item... probably in a more inefficient way than the above index-research.

efficient research solution?

const emails = {"1": "firstname.lastname@example.com",
                "2": "firstname.lastname@example.com",
                "3": "firstname.lastname@example.com"}

const ids = { "email@example.com": "1",
              "email@example.com": "2",
              "email@example.com": "3" }

var email1 = emails['1'];
var id1 = ids[ "email@example.com"];

Now... in the second case we are consuming more memory, in the first we have a less efficient research (or is there some algorithm that is as fast as index-research?).
For my application I actually have more than 2 unique values (like -and is just an example-id,gmail,microsoftid,passport_no). Of course with the second solution I'm using way more memory, and for my application memory usage is crucial.
So, what is the right way to do this? Is there some kind of js class that does this?
Answer: You could use a vector of key-values, so it will be O(n), both for a key and a value.
But native object has O(1) and O(n), so it isn't a big deal.
You could also make a ternary tree, when the left is both less than, the right is both greater than, middle is one is greater, the other is less (or 4ry tree, for better search), but dunno how to balance it well.


Can a realistic rubber mannequin be turned inside-out.

Question: A realistic human-shaped mannequin is made of topological-grade rubber.
All the body cavities that are accessible from outside without piercing any tissue, are faithfully reproduced, for example the digestive tract and the nostrils. Ear drums are assumed to be intact.
The interior of the dummy is coloured pink and the outside is sprayed blue.
Is it possible for the dummy to be turned inside-out to form a sphere with a few holes in such a way that only pink shows and only blue is hidden?
Comment: New advertisement phrase: "topological-grade materials".  To be understood only by mathematicians.
Comment: @MJD - 'Exterior' means what most people would think of. You can imagine someone being spray-tanned. There would be an arbitrary but clear boundary just inside each nostril. Similarly at the lips and the anus. Also the urethra - even though a cul-de-sac - would be pink inside. Someone has mentioned the Eustachian tubes as well.
Comment: What's not clear to me is whether "turned inside out" means "is there an embedding of this surface with this property?" or "is there a regular homotopy of this initial embedding to the inside-out embedding? " or "is there an isotopy of ...?"
Comment: It's not even clear to me what "exterior" means here. Do the pink and blue regions share a boundary? If so, what shape is it? A disjoint union of circles maybe?
Comment: Does the "interior" include "All the body cavities that are accessible from outside without piercing any tissue," and is the "outside" every other part of the surface?
Comment: I guess that you are forcing the regions of pink and blue to not be connected. Of course you can't under those conditions. Why ask?
Comment: Viewing the mannequin and it's GI tract as an arm warmer, it's possible to turn both inside out. The blue will then be on the inside, the pink on the outside.
Comment: @Charlie Frohman - Because I'm not a mathematician and I'm curious. The key is visibility. Thus if you turned the bladder/urethra (a dead-end) inside out I can see that a simple hole wouldn't do the job. You'd have to have a central pink region that abutted a surrounding pink region all round it's circumference. I'm trying to get my head around how adding colour affects the normally monochrome aspects of topology.
Answer: As far as I know, humans are homologous to a torus because of the digestive track. A torus cannot be bent into a sphere.
Comment: There is a nose.
Comment: Good point, ears are also connected to the nose.
Comment: This is not a true sphere because surface holes are allowed - just not big enough to see through.
Answer: It seems pretty clear that the blue region is connected and the pink region is not.  On the other hand I can imagine painting a blue band around a pink sphere and then deforming the sphere in such a way that the blue band is folded upon itself and "hidden" while the pink regions remain visible, but what you have then is not a "sphere with a few holes," you have something that looks (from the outside) like a sphere separated into two parts by a crack.


How to optimize for writes to memory in hot loop

Question: I have a loop in my code where I spend most of the CPU time:
%%write_to_intermediate_head:
    ; uint64_t count_index = (arr[i] >> (8 * cur_digit)) & (RADIX - 1);
    ; We will use rsi to hold the digit we're currently examining
    mov rsi, [rdx + rdi * 8] ; Load arr[i] into rsi
    mov r9, %1 ; Load current digit were sorting on
    shl r9, 3  ; Multiply by 8
    shrx rsi, rsi, r9
    and rsi, 255

    ; intermediate_arr[--digit_counts[count_index]] = arr[i];
    ; rdi is the loop counter i
    ; rsi is the count_index
    ; rcx is the digit_counts array
    ; rax is the intermediate_arr
    dec qword [rcx + rsi * 8]
    mov r9, [rcx + rsi * 8] ; --digit_counts[count_index]

    mov rsi, [rdx + rdi * 8] ; arr[i]
    mov [rax + r9 * 8], rsi

    dec rdi
    jnz %%write_to_intermediate_head

The variables: digit_counts, arr, and intermediate_arr are all in memory (heap and bss). The AMD profiler shows that many cycles are spent reading and writing to these memory locations. Is there any way to optimize this?
Comment: Write it in C and use an optimizing compiler?
Answer: Do your counts truly need to be qwords, or could you use a narrower type to cut your cache footprint in half with 32-bit (or even less with narrower)?  If you're getting cache misses, that's going to mean much more time spent waiting for loads/stores if OoO exec can't hide that latency.
I guess copying the data around is going to be most of the memory bandwidth / cache misses, though.  This looks like Radix Sort, and the amount of metadata to manage is smallish compared to the data.  (But having at least it hit in cache can help, making it more resistant to eviction by all the other data you're throwing around.)

No matter what you do, the access pattern of Radix Sort is inherently not very cache-friendly, although it's not terrible.  You're scattering writes across 256 possible destinations, along with updating the pointers.  But those 256 destinations are sequential streams so they can hit in L1d cache if you're lucky.
Hopefully those destinations aren't multiples of 4k apart (initially or most of the time), otherwise they'll alias the same line in L1d cache and cause conflict misses.  (i.e. force eviction of another partially-written cache line that you're soon going to write to.)

You have some redundant loads / stores which may be a bottleneck for load/store execution units, but if that's not the bottleneck then cache will absorb them just fine.  This section is mostly about tuning the loop to use fewer uops, improving things in the no-cache-miss best case, and giving OoO exec less latency to hide.
Using a memory-destination dec and then reloading the dec's store seems obviously inefficient in terms of total back-end load/store operations, and latency for OoO exec to hide. (Although on AMD, dec mem is still a single uop for the front-end, vs. 3 on Intel; https://uops.info/ and https://agner.org/optimize/).
Similarly, aren't you loading [rdx + rdi * 8] ; arr[i] twice, with the same RDI?  SHRX can copy-and-shift so you wouldn't even be saving uops by keeping around that load result for later.  (You could also use a simple non-indexed addressing mode for arr[i], by doing a pointer-increment like add rdi,8 and cmp rdi, endp/jne where end is something you calculated earlier with lea endp, [rdx + size*8].  Looping forward over an array can be better for some HW prefetchers.)
x86-64 has 15 registers, so if you need more for this inner loop, save/restore some call-preserved registers (like RBX or RBP) at the top/bottom of the function.  Or spill some outer-loop stuff to memory if necessary.
mov r9, %1 looks loop-invariant, so hoist that shl r9, 3 calculation out of the loop, and don't overwrite R9 inside the inner loop.

You do need to zero-extend the byte you extracted, but and rsi, 255 is not as efficient as movzx eax, sil.  (Or better, pick a register like ECX whose low byte can be accessed without a REX prefix). AMD can't do mov-elimination on movzx the way Intel can, though, so just saving code size for AMD, but optimizing latency if you ever run this on Intel CPUs.
Or better, AMD Zen has single-uop BMI1 bextr r64,r64,r64, so prepare a start/length pair in the low 2 bytes of a register.  As discussed, that's loop invariant.  i.e. before the loop mov ecx, %k1 / shl cl, 3 / mov ch, 0x8 (AMD doesn't have partial-register stalls, just false dependencies.  In this case true, since we want to merge.)   If that's inline asm syntax, %k1 specifies the 32-bit version of the register.  Or if it's memory, you're just loading anyway, and hoisting it will save another load!
(Intel has 2-uop bextr, presumably shift and bzhi uops.)
Or if you really want to load twice, movzx esi, byte [rdi + rdx] where RDI is a pointer to arr[[i] that you increment or decrement, and RDX is a byte offset.  But probably BEXTR is a better bet.
Comment: @lvrf: you could maybe check for wrapping in your digit counts and special case that.  Like include a `jnz` after a `dec`, or a `jnc` if you use byte offsets instead of counts; I'm not sure if AMD cares about the scale factor being 1 or not in addressing modes for memory access (not LEA).  But use perf record or whatever to see if those accesses cache miss.  e.g. Intel has a perf event `mem_load_retired.l1_miss` that maps to specific instructions; AMD probably has something similar.
Comment: @lvrf: yes, LEA can replace mov/shl.  It costs a couple bytes of extra code size, but does save a uop. (`[reg * 8]` has to be encoded as `[reg*8 + disp32=0]` since the no-base-reg encoding is how ModRM/SIB signals that there's just a displacement).  It may actually be worse latency on AMD, but outside the loop is fine (scaled-index). Of course, if you know it's a small integer (high bits aren't set), `rorx eax, %k1, 32-3` will also copy-and-shift.  (No need for 64-bit operand-size, other than in an LEA addressing mode: x86-64's defaults without prefix bytes are op size = 32, addr size = 64.)
Comment: I've removed the redundant load of `arr[i]` into rsi (I was somehow blind to that) and I'm now (on avg) beating the O2 optimized C version I wrote. To confirm, `dec qword [rcx + rsi * 8]` / `mov r10, [rcx + rsi * 8]` is **slower** than something like `mov r10, [rcx + r11 * 8]` / `dec r10` / `mov [rcx + r11 * 8], r10` (load, dec, store).
Comment: @lvrf: Another idea for getting away with 32-bit counts: maybe have two versions of your loops, and if the total input array size to be sorted is less than 2^32, then you can use the 32-bit counter version.  Or if any given bucket to be sorted further is small enough, then it can use 32-bit counters.
Comment: @lvrf: resources: Agner Fog's optimization guide (and especially microarchitecture guide) is essential reading.  https://agner.org/optimize/.  See also http://www.lighterra.com/papers/modernmicroprocessors/ re pipelines and OoO exec, and ROB / store buffer stuff, and https://www.realworldtech.com/sandy-bridge/ re: a specific microarchitecture.  (Unfortunately David Kanter hasn't published a similar Zen deep dive, but see https://en.wikichip.org/wiki/amd/microarchitectures/zen_2#Architecture).
Comment: https://blog.stuffedcow.net/2013/05/measuring-rob-capacity/ is great for understanding how OoO exec hides memory latency.  See also [Are loads and stores the only instructions that gets reordered?](https://stackoverflow.com/a/50496379). Re: the store, see [Can a speculatively executed CPU branch contain opcodes that access RAM?](https://stackoverflow.com/q/64141366).  Also other links in https://stackoverflow.com/tags/x86/info.  Agner Fog's microach guide is most helpful for tuning code that bottlenecks on the pipeline itself, not as much on cache misses.
Comment: Thank you so much for your response, this is so detailed and complete. First of all, this is indeed radix sort (full source: https://github.com/vfrazao-ns1/radix_sort/blob/main/radix.s). I've hoisted the operations on r9 outside of the loop and another idea came to mind, could I just do `lea r9, [%1 * 8]` instead of doing the mov followed by the shl? I guess if its not in the loop it doesnt really matter. I think the digit counts *may* need to be 64 bits wide since an array im sorting may have up to size_t elements and they could be all the same (theoretically at least).
Comment: Thanks again for all your help. I feel like I have the basics of x86 down but want to move on to some more intermediate learning materials - do you have any book or resource recommendations?
Answer: Other optimizations. The initial pass to generate counts can be done for all digits at the same time, using a matrix instead of an array. For 64 bit unsigned integers, doing 8 passes with 1 byte digits is close enough to ideal, as the counts | indexes will fit in the L1 cache. The initial pass stores counts in a [8][256] matrix, and 32 bit counts|indexes should be good enough.
For a large array much larger than cache, if the data to be sorted is reasonably uniform, then the first radix sort pass can be a most significant digit pass, creating 256 bins if using 1 byte digits, with the goal of each of the 256 bins fitting in cache, and doing radix sort least significant digit first on each of the 256 bins, one bin at a time. If the array is larger, the first pass can create more bins, 512 (9 bit digit), 1024 (10 bit digit), ..., then each bin can still be sorted using 1 byte digits with a smaller digit on the last pass.


is it possible to set a parameter for selecting a table?

Question: sorry for the noob question..but here's what i did
Dim cmd As New SqlCommand("Declare @mychar varchar(60) " & _
                              "Set @mychar = '" & TextBox2.Text & "'" & _
                              "Select * from @mychar", conn)
    Dim rdr As SqlDataReader = cmd.ExecuteReader
    While rdr.Read()
        ListView2.Items.Add(rdr("Account"))
    End While
    rdr.Close()

but i get an error saying "Must declare the table variable "@mychar"." what's wrong ? or is this not just possible ? thanks in advance..
Comment: you can add the param by 'cmd.Parameter.AddWithValue("@mychar",variable)'
Comment: By looking at your code, it looks like you want to construct dynamic query where table name is coming from TextBox2.Text. You dont need parameter for that. Just concatenate the TextBox2.Text to the select query. "Select * from " & TextBox2.Text
Comment: yeah..i just did that and it's awesome ! :D
Answer: Dim cmd As New SqlCommand(" Select * from " & TextBox2.Text & " ", conn)
    Dim rdr As SqlDataReader = cmd.ExecuteReader
    While rdr.Read()
        ListView2.Items.Add(rdr("Account"))
    End While
    rdr.Close()


Find the shortest distance from the point P = (2,2,5)

Question:
Find the shortest distance from the point $P = (2,2,5)$ to a point on the line given by $l:(x,y,z) = (-6t, -5t, -4t)$

So I've got the matrix that I think it should look like which is
$\begin{bmatrix}-6&-5&-4\\2&2&5\end{bmatrix}$ but what exactly am I solving here
Comment: Try Googling "shortest distance from point to a line".  This is a standard linear algebra problem.
Comment: I'm voting to close this question as off-topic because I posted it and people aren;t liking it so I want to get rid of it because they keep hurting my rep by giving me downvotes
Comment: You don't have enough rep to cast close votes, yet.  But to be nice, I guess I'll cast one for you.  If 4 more people decide to do the same, then this question will be closed.
Comment: No need to close it now @Bye_World
Comment: OK.  I've retracted the vote then.  Note that now I won't be able to vote to close again if you change your mind.
Comment: Thanks. I decided that it will be worth my terribly worded question getting downvotes because @user84413 provided a linear algebra solution that is needed so maybe someone else can use this to help them ya know?
Comment: That's fine.  Just so you know, though, this is such a common exercise that $1)$ it's [been asked here before](http://math.stackexchange.com/search?q=distance+point+line+is%3Aquestion+%5Blinear-algebra%5D) (many times) and $2)$ it even has a [Wikipedia page](https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line) where the [very last section](https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Another_vector_formulation) gives user84413's solution (though I do wish they'd have used the actual cross symbol $\times$ for the cross product rather than the wedge symbol $\wedge$).
Comment: Oh ok. Well shucks, in that case I'll close it @Bye_World
Answer: Hint: Let $u=\langle 2,2,5\rangle$ and $v=\langle 6,5,4\rangle$, and find $\displaystyle d=\frac{|u\times v|}{|v|}$.
Answer: The distance from $P$ to the point on $l$ at time $t$ will be given by:
$$d(t) = \displaystyle \sqrt{(2+6t)^2 + (2+5t)^2 + (5 + 4t)^2}$$
So our problem can be solved like a standard minimization problem from calculus: the value of $t$ that minimizes $d(t)$ corresponds to the point on the line closest to $P$.  However, taking the derivative of $d(t)$ is hard due to the square root.  Instead, you can minimize the function $(d(t))^2$, which is much easier.  This is valid since a value of $t$ minimizes $d(t) \iff$ it minimizes $(d(t))^2$.

Alternative method:
The vector $ \langle 2, 2, 5 \rangle$, the line $l$, and the line segment that represents the shortest distance between the two forms a right triangle with the origin as one of its vertices.  The hypotenuse has length $\sqrt{2^2 + 2^2 + 5^2} = \sqrt{33}$.
The length of the leg of the triangle given by the projection of the vector $P$ onto the line will be equal to $\sqrt{33} \cos(\theta)$, where $\theta$ is the angle formed between vector $P$ and the line.  How can we find this distance?
Let $\hat{ \mathbf{l} }$ be the unit vector pointing in the direction of the line into the $(+, +, +)$ octant.  By the properties of dot product, we have $\langle 2, 2, 5 \rangle \cdot \hat{ \mathbf{ l } } = | \langle 2, 2, 5 \rangle | | \hat{ \mathbf{ l } } | \cos( \theta) = \sqrt{33} \cos( \theta)$, so computing the dot product gives you the length of that leg of the triangle.  Finally, you can find the length of the second leg of the triangle (the shortest distance between $l$ and $P$) by using the Pythagorean theorem.
Comment: That's alright; you don't have to accept my answer, and we can wait on someone else.  I believe in having diverse solutions posted nevertheless.
Comment: The derivative of $d(t) = 0$
Comment: I'm recommending minimizing $f(t) = (d(t))^2$ by first finding $\displaystyle \frac{df}{dt}$.
Comment: there is no $f$
Comment: I'm just defining it to be the function $(d(t))^2$ for notational convenience.
Comment: This is not a calculus class, this is linear algebra. Shouldn't have to use any sort of calculus for this