Question regarding the notation of $\equiv$ and $\iff$

Question: What difference does the notation in those two terms make?
$$
=:⟺∀:(∈\iff∈)
$$
$$
=:⟺∀:(∈\equiv∈)
$$
Comment: Some of the answers here may help:  https://math.stackexchange.com/questions/2432462/whats-the-difference-between-biconditional-iff-and-logical-equivalence/2432471#2432471
Comment: Does this answer your question? [What's the difference between biconditional iff and logical equivalence?](https://math.stackexchange.com/questions/2432462/whats-the-difference-between-biconditional-iff-and-logical-equivalence)
Answer: The formula can be  read as
$X=Y \equiv_{Def}\forall(x)  ( x\in X \leftarrow\rightarrow x\in Y)$
( In words : saying that X = Y is logically equivalent ( by definiiton) to saying that X and Y happen to have exactly the same elements).
with

$\equiv_{Def}$ denoting logical equivalence ( more precisely, equivalence-by-definition)

and

$\leftarrow\rightarrow$ denoting material equivalence or material bi-implication, which is a truth fonctional operator.

The first relation is a metalogical relation; the second belongs to the object language.
The relation between logical equivalence and material equivalence is as follows : formulae $\phi$ and $\psi$  are logically equivallent when the material conditional $ (\phi\leftarrow\rightarrow\psi)$ is true in all logically possible cases.

The iff that is in the middle is a logical equivalence, more precisely, an equivalence-by-definition. equivalence-by-definition works in the same way as ordinary logical equivalence ( that is, two propositions are equivalent just in case it is impossible for them not to have different truth values, whatever possible case is considered).

Note : equivalence is interesting since it allows to substitute the LHS for the RHS ( and vice versa).

The iff that is on the left side is not a logical equivalence, but a material  bi-implication. Two propositions are materially equivalent just in case it factually happens that they have the same truth value, or if you prefer, just in case it factually happens that we do not have the first true and the second false, and reciprocally) .

Consider this application of the extensionality principle.

Let H be the set of animal that have a heart and K the set of animal that have kidneys.
The material conditional  $\forall(x)  ( x\in H \leftarrow\rightarrow x\in K)$ is true.
By the definition of set equality, the formula just above  is logically equivalent to saying that the two sets are equal, that is, it is a logicall impossibility ( once the definition is set forth) that the material conditional holds while $H=K$ does not, and vice versa.
But this is not to claim that having a heart is logically equivalent to having kidneys. It simply happens factually that , as a matter of fact, the two sets have exactly the same elements, but a world in which an animal has a heart without having kidneys ( or the other way round) is still logically possible.
To put it briefly: set identity is logically equivalent to co-extensionality; but , by itself, coextensionality holds even when it is only factual or contingent. Hence the material conditional on the LHS.
Comment: Thank you @Floridus!
Comment: You're welcome @NilsK .
Answer: One way of reading it is as a sigle formula, meaning: two sets are equal iff "condition".
In this case, it is an inconsistency to use two different symbols for the same concept: the bi-conditional.
Another reading is to consider it as an "abbreviation", meaning: we write $X=Y$ exactly when "condition" holds.
In this case, there is no benefit from translating the leftmost "iff" with a symbol. The abbreviation is not a formula of the object language but a statement in the meta-language, and it is not necessary to "formalize" it.


Whenever specific button clicked it does something in Pascal

Question: Hello.
Can anyone help me with scanning buttons always and when I click specific one it does something even Im writing? I want to be filling a record with like 9 attributes but when Im atc. at fourth I want to close it. I tried some readkey stuff :
procedure searching();
var p:char;search:string='';
begin
     repeat
       p:=readkey();
       write(p);
       search+=chr(p);
       until (p=#27) or (p=#13);
       if (p=#27) then menu()
       else
       ...

but the problem was that it written some character it was not possible to erase it and I knew that backspacing and writing again made my search filled with characters I did not wanted in there. Couldn't find a topic about it in pascal so im trying here. Don't flame for english please. Hope you get what I meant, also English is maybe the problem I can't find it, whatever. Waiting for answer, Thanks, Maroš.
Comment: Those are not *buttons*. They're *keys*. (Not being nitpicky - there is a major difference between keys on a keyboard and buttons on your screen.)
Answer:
but the problem was that it written some character it was not possible to erase it

Why not? Just handle #8 (backspace) and truncate your last character from the search string. You can use both System.Delete (by deleting the last character) and System.SetLength (by setting the length to current length - 1).
Comment: Thank you I will try that. I was just wondering if there is any "nicer" solution to that. Thanks for helping, im gonna try if it will work out.
Comment: SOLVED Thank you !


What could be causing drupal to want to reinstall itself after I clear cache?

Question: I am trying to update Drupal from 7.17 to 7.18. I uploaded a copy of my site from a test server to my production server. Everything installs fine, I actually see the site working, and I can navigate it. Then, as soon as I perform updates on modules and core, I run database updates, and then the site automatically navigates me back to install.php to reinstall the site from scratch. I have tried to reinstall the site several times from scratch, manually and using Drush.
What is the mechanism that determines to redirect to install.php? How can I determine how and why this is happening?
Even though the install.php page is showing up in the browser, drush status shows that the site is up, running, successfully connected to the database with correct theme. According to Drush, everything is working properly.
Answer: That occurs because Drupal can't connect to its database. Ensure you have the settings.php file in the sites/default folder. The settings.php file must be readable by the account used to run the web server; it must contain valid database connection string credentials for that server. Make sure that $base_url in that file is either commented out (as it is by default), or it's a valid URL for that domain.
See _drupal_bootstrap_database() for the place where the install.php redirect occurs.
Also, make sure you run update.php and clear all the caches, whenever  possible.
Comment: All the files are in the correct place. Remember, I can upload the site and actually use it before I do updates. As soon as update db is finished running, the site redirects back to install.php. In an attempt to make sure my settings.php file was not corrupted, I also deleted the defaults directory and installed a fresh copy from a new d7 download. same issue. In a last ditch effort, I chmod'ed 777 the entire drupal install. nothing.
Answer: Just to add, after my site (D7.23 on Ubuntu 12.04.3) randomly decided it needed to be installed again, I found out that an archive process had changed the permissions on the sites/default directory to 755.
At first I didn't think it was this because the change in permissions was less restrictive i.e. giving user and group more permissions; but I guess there is a security check somewhere in Drupal that will only accept the sites/default if it has the permissions 555 — the thinking being that the folder may have been tampered with. The same also seems to be true for settings.php in that my install requires it to be 444, if not, I get the install UI.
Answer: I found the solution to this issue.
See the solution given by bryancasler on the page https://www.drupal.org/node/984112
How to fix this problem

Go to xampp\mysql\bin
Open my.ini
Change "max_allowed_packet from 1m to 16m
Save my.ini

Now restart MySql through the XAMPP control panel.
Thanks.
Comment: Thank you Sai. I have spent hours on this and your solution worked for me.


$base_root problem

Question: In /core/lib/Drupal/Core/DrupalKernal.php the $base_root shows incorrect value:
Line 1113
  protected function initializeRequestGlobals(Request $request) {
    global $base_url;
    // Set and derived from $base_url by this function.
    global $base_path, $base_root;
    global $base_secure_url, $base_insecure_url;
<code>// Create base URL.
$base_root = $request->getSchemeAndHttpHost();
</code>
The value the $base_root is showing is the machine name, not the requested url. Specifically, the $base_root value is like: https://machinename.windows.domain.com instead of the request url like: https://ourcompany.com
I've searched the database, exported configs, and all files in the installation for the "machinename", but the only place it exists is on the windows server as "my computer" name.
Our environment is set up with an AWS loadbalancer, AWS cert on loadbalancer, that relays traffic to the windows EC2 server.
Running very recent Apache, PHP and Drupal 8.7.14. Running updated modules using composer. I don't think this is a bug.
The problems this causes is that when there is a redirect url, or self reference, such as in the webform or workflow module, you get an error because the machinename url is not accessible externally.
I wrote code to hack DrupalKernel.php that changes the $base_root using str_replace(). Also did this to RedirectResponseSubscriber.php, which FIXES my problem. But, this is the worst kind of hack programming.
Is there a way to force symfony $request->getSchemeAndHttpHost() to give my proper url? Maybe a setting I missed?
I've been very reluctant to post this question because of the obvious criticism it can draw. I've seen a lot of "working as intended" responses around $base_url issues which don't help my case.
Comment: No, trusted host patterns is a security feature preventing the client from providing fake hostnames. The problem you have is that you don't even get the hostname the client is requesting, so you don't have to worry about which hostname you trust until you get the configuration right to receive the client request data correctly in your hosting environment behind a CDN.
Comment: Maybe a setting I missed? Check "Reverse Proxy Configuration" in settings.php.
Comment: Reverse Proxy Configuration contains proper values in settings.php.  Both the urls are allowed and work properly on the server. machinename url does not resolve from web, but does resolve on server. Thanks for the suggestion.
Comment: Proper settings would result in a symfony request which includes the hostname the client has requested and not the machine name resolved from your internal DNS. See https://symfony.com/doc/current/deployment/proxies.html
Comment: I think the reverse proxies for Symfony are set in Drupal settings.php using $settings['trusted_host_patterns']

$settings['trusted_host_patterns'] = array(
  '^mysite\.com$',
  '^computername\.domain\.com$',
  '^localhost$',
  '.*'
);

If there is another way to configure Symphony reverse proxy in Drupal, would appreciate guidance.

Also getting redirect error like in this issue is related: https://www.drupal.org/project/drupal/issues/2753591
Answer: Check the "Reverse Proxy Configuration" in settings.php:
<code>/**
 * Reverse Proxy Configuration:
 *
 * Reverse proxy servers are often used to enhance the performance
 * of heavily visited sites and may also provide other site caching,
 * security, or encryption benefits. In an environment where Drupal
 * is behind a reverse proxy, the real IP address of the client should
 * be determined such that the correct client IP address is available
 * to Drupal's logging, statistics, and access management systems. In
 * the most simple scenario, the proxy server will add an
 * X-Forwarded-For header to the request that contains the client IP
 * address. However, HTTP headers are vulnerable to spoofing, where a
 * malicious client could bypass restrictions by setting the
 * X-Forwarded-For header directly. Therefore, Drupal's proxy
 * configuration requires the IP addresses of all remote proxies to be
 * specified in $settings['reverse_proxy_addresses'] to work correctly.
 *
 * Enable this setting to get Drupal to determine the client IP from the
 * X-Forwarded-For header. If you are unsure about this setting, do not have a
 * reverse proxy, or Drupal operates in a shared hosting environment, this
 * setting should remain commented out.
 *
 * In order for this setting to be used you must specify every possible
 * reverse proxy IP address in $settings['reverse_proxy_addresses'].
 * If a complete list of reverse proxies is not available in your
 * environment (for example, if you use a CDN) you may set the
 * $_SERVER['REMOTE_ADDR'] variable directly in settings.php.
 * Be aware, however, that it is likely that this would allow IP
 * address spoofing unless more advanced precautions are taken.
 */
# $settings['reverse_proxy'] = TRUE;

/**
 * Specify every reverse proxy IP address in your environment.
 * This setting is required if $settings['reverse_proxy'] is TRUE.
 */
# $settings['reverse_proxy_addresses'] = ['a.b.c.d', ...];

/**
 * Reverse proxy trusted headers.
 *
 * Sets which headers to trust from your reverse proxy.
 *
 * Common values are:
 * - \Symfony\Component\HttpFoundation\Request::HEADER_X_FORWARDED_ALL
 * - \Symfony\Component\HttpFoundation\Request::HEADER_FORWARDED
 *
 * Note the default value of
 * @code
 * \Symfony\Component\HttpFoundation\Request::HEADER_X_FORWARDED_ALL | \Symfony\Component\HttpFoundation\Request::HEADER_FORWARDED
 * @endcode
 * is not secure by default. The value should be set to only the specific
 * headers the reverse proxy uses. For example:
 * @code
 * \Symfony\Component\HttpFoundation\Request::HEADER_X_FORWARDED_ALL
 * @endcode
 * This would trust the following headers:
 * - X_FORWARDED_FOR
 * - X_FORWARDED_HOST
 * - X_FORWARDED_PROTO
 * - X_FORWARDED_PORT
 *
 * @see \Symfony\Component\HttpFoundation\Request::HEADER_X_FORWARDED_ALL
 * @see \Symfony\Component\HttpFoundation\Request::HEADER_FORWARDED
 * @see \Symfony\Component\HttpFoundation\Request::setTrustedProxies
 */
# $settings['reverse_proxy_trusted_headers'] = \Symfony\Component\HttpFoundation\Request::HEADER_X_FORWARDED_ALL | \Symfony\Component\HttpFoundation\Request::HEADER_FORWARDED;
</code>
There are more infos in the symfony documentation https://symfony.com/doc/current/deployment/proxies.html
Debugging
For debugging add a line to index.php and check the headers the CDN sending:
index.php:
<code><?php

/**
 * @file
 * The PHP page that serves all page requests on a Drupal installation.
 *
 * All Drupal code is released under the GNU General Public License.
 * See COPYRIGHT.txt and LICENSE.txt files in the "core" directory.
 */

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

// remove after debugging
var_dump($_SERVER);
</code>
Comment: This answer works really well for configuring the reverse proxy, which I had not done. I found the IP address using var_dump($_SERVER); in index.php. Went with $settings['reverse_proxy_trusted_headers'] = \Symfony\Component\HttpFoundation\Request::HEADER_X_FORWARDED_ALL;  Removing the server name from my trusted_host_patterns fixed the $base_root issue. THANK YOU! I've struggled with this issue of and on for months.

$base_root problem


boolean[] vs. BitSet: Which is more efficient?

Question: What is more efficient in terms of memory and CPU usage — an array of booleans or a BitSet? Specific BitSet methods are not used, only get/set/clear (==, =, Arrays.fill respectively for an array).
Answer:
Boolean[] uses about 4-20 bytes per boolean value.
boolean[] uses about 1 byte per boolean value.
BitSet uses about 1 bit per boolean value.

Memory size might not be an issue for you in which case boolean[] might be simpler to code.
Comment: Note that 1 bit per boolean in the BitSet is the asymptotic value. Under the covers is uses a long[] so it is granulated into 64 bit chuncks.
Comment: It' would be good to mention that usually you only need the 4 byte pointer per value. Because it's cached. Except you explicitly use new Boolean();

But of course it's way more than boolean[]
Comment: `Boolean[]` uses 4 or 8 bytes for each value, but definitely not up to 20 bytes. If you assume that the application creates a new `Boolean` object for each element (though there's no reason to assume that), then most implementations would need 24 bytes for the object, which adds up to the 4 or 8 bytes for the reference, so even up to 32 bytes in total. But who would do that in practice…
Comment: Yes, the common implementation nowadays is with compressed class pointers, my bad. But the maximum header still is a header of 16 bytes, which makes a 24 bytes object and hence, 32 bytes for the object plus an uncompressed 64 bit reference. I'm not sure whether it makes sense to assume a sane person if they are using a `Boolean[]` array in a situation where `boolean[]` would suffice. Anyway, the phrase "uses about 4-20 bytes per boolean value" is misleading.
Comment: @Holger any sane person would use autobixing but the default object header size on the OpenJDK is 12 bytes and on Zing its 8 bytes. With an 8 bytes alignment, the Boolean should be 16 bytes.
Answer: From some benchmarks with Sun JDK 1.6 computing primes with a sieve (best of 10 iterations to warm up, give the JIT compiler a chance, and exclude random scheduling delays, Core 2 Duo T5600 1.83GHz):
BitSet is more memory efficient than boolean[] except for very small sizes. Each boolean in the array takes a byte. The numbers from runtime.freeMemory() are a bit muddled for BitSet, but less.
boolean[] is more CPU efficient except for very large sizes, where they are about even. E.g., for size 1 million boolean[] is about four times faster (e.g. 6ms vs 27ms), for ten and a hundred million they are about even.
Comment: This is a misleading answer with no test code and a specific context. I encourage anybody reading this to read through the other answers here and think a little for themselves, about their specific situation.
Comment: I suspect that some of the BitSet style operations (and, or, not) are faster as BitSet instead of array. Worth noting which operations are better. The title is going to mislead everyone into never using a BitSet again
Comment: @starblue Could you explain why for very large data, `boolean[]` and `BitSet` are about the same on CPU efficiency? It feels like `boolean[]` still should be more efficient.
Comment: @Utku Probably an effect of caching, so that for accesses to main memory you need to do read-update-write also when writing a byte. Notice that 1 million bytes, the largest size where `boolean[]` was faster, is about the size that could plausibly fit into a cache.
Comment: The test doesn't use set operations, and is biased towards writing.
Comment: These are just facts from a particular benchmark, I don't see what is misleading about them.  Of course, if this is important to you, do your own benchmarks for your particular situation.  Personally I would prefer `BitSet` because it expresses intent, except if I had many runs with relatively small bit sets and a need to optimize for runtime.
Comment: Time complexity of `BitSet#flip` method: change the state of an arbitrarily long sequence of bits in constant time. - Effective Java, Joshua Bloch, Item #17 Minimize mutability
Answer: Here you can see a Memory/Time benchmark comparing a boolean[][] trianguar matrix versus BitSet[] triangular matrix.
I create, set and read the (size * (size-1) / 2) values and compare memory usage and time...

Hope this help...
Here the code... (just a quikly dirty test code, sorry ;)
import java.util.BitSet;
import java.util.Date;

public class BooleanBitSetProfiler {

    Runtime runtime;
    int sum = 0;
    public void doIt() {

        runtime = Runtime.getRuntime();
        long[][] bitsetMatrix = new long[30][2];
        long[][] booleanMatrix = new long[30][2];
        int size = 1000;
        for (int i = 0; i < booleanMatrix.length; i++) {
            booleanMatrix[i] = testBooleanMatrix(size);
            bitsetMatrix[i] = testBitSet(size);
            size += 2000;
        }
        int debug = 1;
        for (int j = 0; j < booleanMatrix.length; j++){
            System.out.print(booleanMatrix[j][0] + ";");
        }
        System.out.println();
        for (int j = 0; j < booleanMatrix.length; j++){
            System.out.print(booleanMatrix[j][1] + ";");
        }
        System.out.println();
        for (int j = 0; j < bitsetMatrix.length; j++){
            System.out.print(bitsetMatrix[j][0] + ";");
        }
        System.out.println();
        for (int j = 0; j < bitsetMatrix.length; j++){
            System.out.print(bitsetMatrix[j][1] + ";");
        }
        System.out.println();
    }

    private long memory () {
        return runtime.totalMemory() - runtime.freeMemory();
    }
    private long[] testBooleanMatrix(int size) {
        runtime.gc();
        long startTime = new Date().getTime();
        long startMemory = memory();
        boolean[][] matrix = new boolean[size][];
        for (int i = 0; i < size; i++) {
            matrix[i] = new boolean[size - i - 1];
        }
        long creationMemory = memory();
        long creationTime = new Date().getTime();
        for (int i = 0; i < size; i++)  {
            for (int j = 0; j < matrix[i].length; j++) {
                matrix[i][j] = i % 2 == 0;
            }
        }
        long setMemory = memory();
        long setTime = new Date().getTime();
        for (int i = 0; i < size; i++)  {
            for (int j = 0; j < matrix[i].length; j++) {
                if (matrix[i][j]) sum++;
            }
        }
        long readTime = new Date().getTime();
        System.out.println("Boolean[][] (size " + size + ")");
        System.out.println("Creation memory " + printMem(creationMemory-startMemory) + ", set memory " + printMem(setMemory-startMemory));
        System.out.println("Creation time " + printTime(creationTime-startTime) + ", set time " + printTime(setTime - creationTime) + " read time " + printTime(readTime - setTime) + "\n");
        runtime.gc();
        return new long[]{(setMemory-startMemory)/(1024*1024), (readTime-startTime)};
    }
    private long[] testBitSet(int size) {
        runtime.gc();
        long startTime = new Date().getTime();
        long startMemory = memory();
        BitSet[] matrix = new BitSet[size];
        for (int i = 0; i < size; i++) {
            matrix[i] = new BitSet(size - i - 1);
        }
        long creationMemory = memory();
        long creationTime = new Date().getTime();
        for (int i = 0; i < size; i++)  {
            for (int j = 0; j < matrix[i].size(); j++) {
                matrix[i].set(j, (i % 2 == 0));
            }
        }
        long setMemory = memory();
        long setTime = new Date().getTime();
        for (int i = 0; i < size; i++)  {
            for (int j = 0; j < matrix[i].size(); j++) {
                if (matrix[i].get(j)) sum++;
            }
        }
        long readTime = new Date().getTime();
        System.out.println("BitSet[] (size " + size + ")");
        System.out.println("Creation memory " + printMem(creationMemory-startMemory) + ", set memory " + printMem(setMemory-startMemory));
        System.out.println("Creation time " + printTime(creationTime-startTime) + ", set time " + printTime(setTime - creationTime) + " read time " + printTime(readTime - setTime) + "\n");
        runtime.gc();
        return new long[]{(setMemory-startMemory)/(1024*1024), (readTime-startTime)};
    }

    private String printMem(long mem) {
        mem = mem / (1024*1024);
        return mem + "MB";
    }
    private String printTime(long milis) {
        int seconds = (int) (milis / 1000);
        milis = milis % 1000;
        return seconds > 0 ? seconds + "s " + milis + "ms" : milis + "ms";
    }
}

Answer: A bit left-field of your question, but if storage is a concern you may want to look into Huffman compression. For example, 00000001 could be squeezed down by frequency to something equivalent to {(7)0, (1)1}. A more "randomized" string 00111010 would require a more complex representation, e.g. {(2)0, (3)1, (1)0, (1)1, (1)0}, and take up more space. Depending on the structure of your bit data, you may get some storage benefit from its use, beyond BitSet.
Answer: As for memory, the documentation for a BitSet has pretty clear implications. In particular:

Every bit set has a current size, which is the number of bits of space
  currently in use by the bit set. Note that the size is related to the
  implementation of a bit set, so it may change with implementation. The
  length of a bit set relates to logical length of a bit set and is
  defined independently of implementation.

The source for Java library classes is openly available and one can easily check this for themselves. In particular:
The internal field corresponding to the serialField "bits".
89
90     private long[] words;

As for speed; it depends on what one is doing. In general, don't think about speed ahead of time; use whichever tool makes the most sense semantically and leads to the clearest code. Optimize only after observing that performance requirements aren't met and identifying bottlenecks.
Coming to SO and asking if A is faster than B is silly for many reasons, including but certainly not limited to:

It depends on the application, which nobody responding generally has access to. Analyze and profile it in the context it is being used in. Be sure that it's a bottleneck that's actually worth optimizing.
Questions like this that ask about speed generally show that the OP thinks they care about efficiency but wasn't willing to profile and didn't define performance requirements. Under the surface, that's usually a red flag that the OP is headed down the wrong path.

I know this is an old question but it came up recently; and I believe this is worth adding.
Answer: It depends as always.
Yes BitSet is more memory efficent, but as soon as you require multithreaded access boolean[] might be the better choice. For example for computing primes you only set the boolean to true and therefore you don't really need synchronization. Hans Boehm has written some paper about this and the same technique can be used for marking nodes in graph.
Comment: I think I found the paper by Hans Boehm: http://www.hpl.hp.com/techreports/2004/HPL-2004-209.pdf Result: You don't need synchronization. You just hope that the threads see what the others have done. It's no problem if they don't, they will simply be doing duplicate work. But in practice, the changes will usually be visible, and the algorithm will speed up linearly.
Comment: You'll still need synchronization to make sure that all threads see what the other threads have written. [Here](http://jeremymanson.blogspot.de/2007/08/atomicity-visibility-and-ordering.html) is a pretty good introduction. I'd love to read the paper by Hans Boehm - too bad the link is dead.
Comment: provided that your boolean array doesn't grow, that'd certainly be better for concurrent use.
Answer: Going from Java to CPU is totally VM specific.  For instance, it used to be that a boolean was actually implemented as a 32-bit value (quite probably is true to this day).
Unless you know it is going to matter you are better off writing the code to be clear, profile it, and then fix the parts that are slow or consuming a lot of memory.
You can do this as you go.  For instance I once decided to not call .intern() on Strings because when I ran the code in the profiler it slowed it down too much (despite using less memory).
Answer: I believe that a BitSet is more memory- and CPU-efficient, is it can internally pack the bits into int, longs, or native data types, whereas a boolean[] requires a byte for each bit of data.  Additionally, if you were to use the other methods (and, or, etc), you would find that the BitSet is more efficient, as there is no need to iterate through every element of an array; bitwise math is used instead.
Comment: @EFraim: By reducing the amount of memory used you're increasing the chance of having everything in cache. Cache misses are very expensive. I wouldn't be at all surprised to see this factor make BitArray faster.
Comment: Memory efficient - probably true. CPU efficient - most certainly not. It is almost always less efficient to perform two bitwise operations (shift/and or shift/or) and up to two memory accesses (though most likely cached) than a single memory access on x86.
Comment: For example: a bitset would outperform boolean[] if the whole bitset fits in the cache, but not the boolean[], and random access were required.


Referencing SD card from Kotlin

Question: I am writing an Android app on the Jetpack Composable platform with Android Studio. I need to read and write files on an SD card that is installed in the tablet. I can define the path to the card as follows:
private val externalStorageVolumes = context.let { ContextCompat.getExternalFilesDirs(it.applicationContext, null) }

private val sdCardStorage = externalStorageVolumes[1]

The problem is: I want to access the card from a view's ViewModel, but as you can see I need to pass a reference to a context. Apparently one should not refence any context from a ViewModel, as that can lead to memory leaks.
Is the any way to read and write to a SD card from a ViewModel that does not need a context? Thanks!
Answer:
Apparently one should not refence any context from a ViewModel, as that can lead to memory leaks

That is what AndroidViewModel is for. It mediates access to the Application, which is a singleton Context safe to use from a ViewModel.
Even better is to have your data storage logic be managed by a singleton repository class, as part of a layered architecture. You would have the repository get access to the Application singleton via dependency inversion (Dagger/Hilt, Koin, etc.).
Comment: Thanks! This seems to be what I am looking for!

Referencing SD card from Kotlin


ASP.NET MVC & WEB API autenticação com token

Question: Tenho uma dúvida sobre o bearer token. Eu tenho dois cenários na minha aplicação. 1º é um painel admin que trabalha com ASP.NET MVC e angularjs e o 2º é o WEB Api que troca requisições com um aplicativo WPF. Minha dúvida é sobre o token, se é indiferente eu utilizá-lo para um controller ASP.NET MVC e um controller Web api.
 public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        try
        {
            DbEngine db = new DbEngine();
            var user = db.AutenticacaoAPI(context.UserName, context.Password);
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            if (user.Status)
            {
                identity.AddClaim(new Claim(ClaimTypes.Name, user.Value.ST_NOME));
                identity.AddClaim(new Claim(ClaimTypes.Email, user.Value.ST_LOGIN));
            }

            context.Validated(identity);
        }
        catch
        {
            context.SetError("Usuário e senha inválidos", "Error");
        }
    }
}

e o código do Controller para requisitar as informações do usuário somente para testar o serviço
[Authorize]
    [HttpGet]
    public JsonResult UserInfo(string login)
    {
        using (DbEngine db = new DbEngine())
        {
            try
            {
                return new JsonResult
                {
                    Data = db.GetUser(login),
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet

                };
            }
            catch (Exception ex)
            {
                return ex.ReturnException(HttpStatusCode.InternalServerError);
            }
        }
    }

Aqui é o retorno do token

E aqui a chamada que me devolve este erro mesmo com o token no header

Agradeço a ajuda.
Answer: O seu problema não é com o ASP.NET Identity ou com o ASP.NET MVC, mas sim ao tentar serializar o proxy da Entity Usuario.
Este Proxy é criado para que seja possível realizar o LazyLoad nas consultas, então tente desativar o LazyLoad e passe à utilizar o .Include()) sempre que necessário.
Comment: Obrigada, vou tentar desativar para ver se funciona. Agradeço sua ajuda
Comment: Eu desativei o Lazy Load mas continuou o mesmo problema, então pesquisei mais um pouco e achei a solução nesse link: http://stackoverflow.com/questions/5588143/ef-4-1-code-first-json-circular-reference-serialization-error aí eu só inseri `db.Configuration.ProxyCreationEnabled = false;` e consegui fazer o get. Vou marcar como a resposta certa porque você me deu a direção correta para solucionar meu problema, agradeço sua ajuda.


Appropriate Instruments

Question: My model is:
$$Y=\beta_0+\beta_1X_1+\beta_2X_2+\beta_3X_3+\beta_4X_4.$$
I want to check if 'weather' (not included in the above model) is an appropriate instrument. $X_1$ represents price. If I determine that 'weather' is an appropriate instrument I will use my new model (which includes this instrument) to obtain the own price elasticity.
In order to check if an instrument is appropriate we run a first stage least squares regression. If we deem that the instrument is strong, we then run a two stage least squares regression (TSLS regression).
When running the first stage least squares regression, do we run $Y$ against 'weather' and look at if 'weather' is significant (or check the F-statistic to see if it is below/above $10$ as a rule of thumb), or do we run $X_1$ (price) against 'weather'?
Would I then do the same with the other variables? So, run $X_2$ against 'weather', etc.
Or should I include all the other variables in the regression? And then evaluate if the weather variable is significant? (So run, $Y$ against 'weather', $X_1$, $X_2$, $X_3$ and $X_4$, or run $X_1$ against 'weather', $X_2$, $X_3$ and $X_4$).
When running a TSLS regression, we test for $H_0:$ exogeneity and $H_1:$ endogeneity. When doing this, do we look at the J-statistic and multiply this value by the number of independent variables (here would be $4$)? And then compare to the chi-squared table of values with $4-1=3$ degrees of freedom?
Or, would it be much better to run a Durbin-Wu-Hausman (DWH) test? When I run this test on EViews, I obtain an output with J-statistics and p-values for 'restricted test equation', 'unrestricted test equation' and the difference in J-statistics. What do the 'restricted test equation' and 'unrestricted test equation' represent? If my p-values are not significant, would it be correct to conclude that we do not reject the null hypothesis and so the variables are exogenous and the instrument is not appropriate?
Lastly, does a Cragg-Donald F-statistic of value $5.0323$ signify that the instrument (weather) is weak? And which test provides more conclusive results? (Cragg-Donald, DWH or multiplying the J-statistic by number of instruments and comparing to the chi-squared tables)?
Thank you!
Answer: For the first stage you want to run X1 (price) against its instrument (weather). The goal is to verify there is a sufficient correlation.
Then for the second stage you'll want to check that the F-statistic is e.g. > 10. You could also check the prediction power of the 2SLS (final) model with cross-validation.
Regarding other variables (X2 etc), are you interested in their causal effect or not ?
Comment: You have to look at the first stage F statistic of the excluded instruments (with one instrument that's the square of the t statistic of the instrument's coefficient in the first stage). The second stage F doesn't tell you anything.

Appropriate Instruments


Does logstash filter runs in sequence?

Question: So we have this logstash configuration with filter similar to this: (I excluded the output)
So I was wondering if the mutate should come first before I run my ruby code to anonymize the fields.
The anonymizer ruby is the ruby script that will anonymize.
<code>input {
    http {
        port => 5045
        host => "0.0.0.0"
        add_field => { "category" => "client" }
    }
}

# The filter part of this file is commented out to indicate that it is optional.
filter {

        # the following line will create 1 additional copy of each document (i.e. including the original, 2 in total)
        # the copy will have a "type" field added only if the category is client.
        if [category] == "client" {
            clone {
                clones => ["anonym"]
            }
            # anonymized the field(s) of the cloned document through anonymizer.rb
            if [type] == "anonym" {
                ruby {
                    path => "/<path>/anonymizer.rb"
                    script_params => {
                        "key" => "<logstash_fingerprint_key>"
                    }
                }
            }
        }

        # update sample_schema_v1 to sample_schema_v2
        if [schema] == "sample_schema_v1" {
            mutate {
                update => { "schema" => "sample_schema_v2" }
            }
        }
}
</code>
Comment: the filters are run in sequence, from top to bottom. So with how it's currently configured, the ruby filter would be executed before the mutate filter.
Answer: Yes, it is executed in sequence.
Tested and verified.

Does logstash filter runs in sequence?


FATAL EXCEPTION: main Process:-Quando abri o aplicativo dar erro ANDROID

Question: toda vez que tento abrir uma consulta dar erro, estou utilizando php junto com java segue o erro abaixo:
 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: br.com.alencardeveloper.escola.sisescolar, PID: 11602
    java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.alencardeveloper.escola.sisescolar/br.com.alencardeveloper.escola.sisescolar.alunos}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5443)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
        at br.com.alencardeveloper.escola.sisescolar.alunos.onCreate(alunos.java:45)
        at android.app.Activity.performCreate(Activity.java:6245)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5443)

meu codigo no VerAlunosAdapter.java é
    package br.com.alencardeveloper.escola.sisescolar;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.util.List;

public class VerAlunosAdapter extends BaseAdapter {

    private Context ctx;
    private List<VerAlunos>lista;

    public VerAlunosAdapter(Context ctx2, List<VerAlunos> lista2){
        ctx = ctx2;
        lista = lista2;
    }

    @Override
    public int getCount() {
        return lista.size();
    }

    @Override
    public VerAlunos getItem(int position) {
        return lista.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = null;
        if(convertView == null){
            LayoutInflater inflater = ((Activity)ctx).getLayoutInflater();
            v = inflater.inflate(R.layout.item_lista, null);
        } else {
            v = convertView;
        }

        VerAlunos c = getItem(position);

        TextView itemNome = (TextView) v.findViewById(R.id.ItemNome);
        TextView itemIdade = (TextView) v.findViewById(R.id.ItemIdade);
        TextView itemTelefone = (TextView) v.findViewById(R.id.ItemTelefone);
        TextView itemCelular = (TextView) v.findViewById(R.id.ItemCelular);
        TextView itemTurma = (TextView) v.findViewById(R.id.ItemTurma);
        TextView itemTurno = (TextView) v.findViewById(R.id.ItemTurno);
        //TextView itemProgress = (TextView) v.findViewById(R.id.ItemProgresso);

        itemNome.setText(c.getNome());
        itemIdade.setText(c.getTelefone());
        itemTelefone.setText(c.getTelefone());
        itemCelular.setText(c.getCelular());
        itemTurma.setText(c.getTurma());
        itemTurno.setText(c.getTurno());

        return v;
    }
}

o codigo em alunos.java é:
package br.com.alencardeveloper.escola.sisescolar;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;

import java.util.ArrayList;
import java.util.List;

public class alunos extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    ListView listViewAlunos;

    private String HOST = "http://sis.colegioaplic.com.br/android";

    VerAlunosAdapter verAlunosAdapter;
    List<VerAlunos> lista;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        listViewAlunos = (ListView) findViewById(R.id.listViewAlunos);

        lista = new ArrayList<VerAlunos>();
        verAlunosAdapter = new VerAlunosAdapter(alunos.this, lista);

        listViewAlunos.setAdapter(verAlunosAdapter);

        listaAlunos();

        super.onCreate(savedInstanceState);
        setContentView(R.layout.alunos);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.tela_principal, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_principal) {
            // Handle the camera action
            Intent abreTelaPrincipal = new Intent (this, TelaPrincipal.class);
            startActivity(abreTelaPrincipal);
        } else if (id == R.id.nav_aluno) {
            Intent abreTelaAlun = new Intent (this, alunos.class);
            startActivity(abreTelaAlun);
        } else if (id == R.id.nav_notas) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
    private void listaAlunos(){
        String url = HOST + "/alunos.php";

        Ion.with(getBaseContext())
                .load(url)
                .asJsonArray()
                .setCallback(new FutureCallback<JsonArray>() {
                    @Override
                    public void onCompleted(Exception e, JsonArray result) {
                        for(int i = 0; i < result.size(); i++){
                            JsonObject obj = result.get(i).getAsJsonObject();

                            VerAlunos c = new VerAlunos();

                            c.setId(obj.get("id").getAsInt());
                            c.setNome(obj.get("nome").getAsString());
                            c.setIdade(obj.get("idade").getAsString());
                            c.setTelefone(obj.get("telefone").getAsString());
                            c.setCelular(obj.get("celular").getAsString());
                            c.setTurma(obj.get("turma").getAsString());
                            c.setTurno(obj.get("turno").getAsString());
                            c.setMedia(obj.get("media").getAsString());

                            lista.add(c);
                        }
                        verAlunosAdapter.notifyDataSetChanged();
                    }
                });
    }
}

a activity está abaixo:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_alunos"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_tela_principal"
        app:menu="@menu/tela_principal_drawer" />

</android.support.v4.widget.DrawerLayout>

Segue abaixo o app_bar_alunos.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".alunos">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include
        android:id="@+id/listViewAlunos"
        layout="@layout/content_alunos" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

segue abaixo content_alunos.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".alunos"
tools:showIn="@layout/app_bar_alunos">

    <ListView
        android:id="@+id/listViewAlunos"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout >

Answer: Olá, Daniel!
Tente dessa forma
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.alunos);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        listViewAlunos = (ListView) findViewById(R.id.listViewAlunos);

        lista = new ArrayList<VerAlunos>();
        verAlunosAdapter = new VerAlunosAdapter(alunos.this, lista);

        listViewAlunos.setAdapter(verAlunosAdapter);

        listaAlunos();

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

Seu app dava crash devido uma NullPointerException que indica que você está tentando referenciar uma View que não existe no layout atual.
No seu caso, a View até existe, em tese, mas você tenta acessar ela antes mesmo do layout ser anexado à Activity. Esse método setContentView(R.layout.alunos); deve ser o primeiro a ser chamado, antes de qualquer referência à qualquer View dentro da Activity.
Após feito o procedimento acima, substitua esse include
<include
   android:id="@+id/listViewAlunos"
   layout="@layout/content_alunos" />

Por esse
<include layout="@layout/content_alunos" />

Espero que isso ajude!
Comment: Faça assim, [edite](https://pt.stackoverflow.com/posts/375483/edit) sua pergunta e inclua o `layout` da `Activity`
Comment: Desculpa Daniel, inclua também `app_bar_alunos.xml`
Comment: Resumindo, a lista em está qual `layout`? É em `content_alunos.xml`?
Comment: tentei e não funcionou ainda, eu percebi está dando erro nesta linha listViewAlunos = (ListView) findViewById(R.id.listViewAlunos);
Comment: já editei Ivan.
Comment: Incluir também isto
Comment: Eu creio que deste alunos será o ultimo
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/92379/discussion-between-daniel-alencar-souza-and-ivan-silva).


Why do guitarists re-fret their guitars?

Question: I heard that my friend is gonna cut some tracks, and they said they want to re-fret their guitars first. Well I know that a re-fret is replacing the frets with new one. What will change if we re-fret? Are there any other alternatives to a re-fret?
Comment: A *fret dress* can be an alternative to a re-fret, but eventually a re-fret will be needed.
Comment: Some guitarists re-fret brand new guitar because they want different fret shape but I think this is not subject of this question
Answer: Why do guitarists re-fret their guitars?
We re-fret guitars because you can get fret wear from playing. The most common type is when the upper frets of the guitar, usually around 17-20, will wear down because of playing and once the frets are worn down then the strings will begin to rattle more and the guitar will sound less clear.
There are materials that frets could be made of that would wear down more slowly or not at all, but those materials are harder, which means the frets would be much more difficult to put on the guitar in the first place, more difficult to make level and even, and the tone would be different.
Here's a picture of a particularly worn fret, that needs to be replaced:
Comment: @ToddWilcox  Great edit Todd.  Too bad I can't upvote the edit.  I'm proud of you though ;-)
Answer: If you play a steel string guitar enough, the steel strings eventually wear down the frets to a point where the intonation is out of balance because the frets lose their crown (which provides a precise point of contact for the string when fretting).  And certain frets will wear more than others which makes it impossible to maintain a low action across all frets without fret buzz.  The other common thing that happens is that certain frets under certain strings will get divots in them that will mess with your tone and alter the pitch of the fretted notes and cause buzzing.
By far the most common metal used for fret wire is nickel.  It is used because it is softer and easier to shape and easier to crown and otherwise work with.  The problem comes in to play when you constantly grind steel strings (a harder metal) against the softer nickel frets.  You can re-fret with harder steel fret wire, but even steel frets will eventually show some wear (just not as quickly).
Most of the fret wear will be under the plain steel strings.  The wound strings are not as harsh on the frets because they are fatter and wound with a softer metal.  The frets that experience the worst damage vary according to how you play the guitar.  A rhythm guitarist who plays mostly open chords will tend to wear out the frets closer to the headstock first while a lead guitarist who plays up the neck will wear out the higher frets first.  Bending will tend to wear flat areas on the frets due to the constant back and forth friction.
Minor fret wear and even shallow divots can be taken out with what is known as a fret dress.  During a fret dress, the guitar technician will remove all the strings and protect the fretboard with masking tape and use a fret file to file the frets down to the least common denominator.  He/she will then level all of the frets - and use a straight edge tool to be sure all the frets are the correct height relative to one another.  Finally, he/she will use a crowning file to round the top of each fret such that the crown (high point) is in the exact center of each fret and there is a narrow more exacting point of contact for the strings (vs.a flat surface).
You may be able to get by with several fret dressings before you have to re-fret.
Another alternative to a total re-fret is a partial re-fret.  A partial refret won't save you as much money as you think because it will include leveling and crowning the saved frets, but can still be half the cost of a total re-fret if you only need to replace between 4 - 8 frets (the ones worn too much to dress).  A partial re-fret will be more satisfactory if the same gauge and type fret wire can be found to match the existing frets.
One of the reasons I play many different guitars is because I know if I played the same one all the time, I would be paying for expensive fret dresses and re-frets more often than desired.  For this reason, I have multiple practice guitars and my main stage guitars only get played during live shows.  By spreading the fret wear over several different guitars I get more mileage from all of them.
But next time I re-fret any of my guitars, I am planning to pay extra (material and labor) to get case hardened steel frets installed so hopefully they will last a long long long time.


$\frac{(n+1)\log 2}{\log(2n + 2)} \ge \frac{x \log 2}{2 \log x}$

Question: Show for $$16 \le 2n \lt x \le 2n+2$$ ($n \in \mathbb{N}$ and $x\in\mathbb{R}$)  that $$\frac{(n+1)\,\mathrm{log}\,2}{\mathrm{log}(2n + 2)} \ge \frac{x\, \mathrm{log} \,2}{2\, \mathrm{log}\, x}$$
I can derive only $$\frac{(n+1)\,\mathrm{log}\,2}{\mathrm{log}(2n + 2)} \ge \frac{x}{2\, \mathrm{log}\, x}$$ I suspect something may be wrong in my propositions. (As you might guess, I try to verify the derivation of the Tshebyshev estimation given here, page 4. This question has been asked already but as far as I can see, left unanswered.
Answer: Note that $f:[e,\infty)\to\mathbb{R}$ given by $f(x)=\dfrac{x}{2\log(x)}$ is an ascending function.
If $2n<x\le 2n+2$, we have $f(2n)\lt f(x)\le f(2n+2)$. That means $  \dfrac{x}{2\log(x)} \le \dfrac{2n+2}{2 \log(2n+2)}$ which implies the result  $\dfrac{x}{2\log(x)}\log(2) \le \dfrac{(n+1)}{\log(2n+2)}\log(2)$.
Comment: Thats really mean, it looks as if the result is almost trivial but then ... thx!


jQuery DOM selector issue

Question: I have a jQuery code as follows;
$("#"+iframeId).attr("src",url); //works perfect
$("a[target="+iframeId+"]").attr("href", url); //does not return anything. not sure why?

Here iframeId gets "swcontent"
Link

In Firebug inspector, if I write
document.getElementsByTagName("a")[0].getAttribute("target") it does find the target "swcontent"
Now in one of my included JS, I have;
jQuery.extend = jQuery.fn.extend = function() {
    // copy reference to target object
    var target = arguments[0],
        a = 1;

    // extend jQuery itself if only one argument is passed
    if ( arguments.length == 1 ) {
        target = this;
        a = 0;
    }
    var prop;
    while (prop = arguments[a++])
        // Extend the base object
        for ( var i in prop ) target[i] = prop[i];

    // Return the modified object
    return target;
};

Could this causes any issues and if yes, how do I fix this (I might have limited scope to change the code entirely)
Comment: Is `iframeId` definitely `swcontent`?
Answer: if your iframeId is 'swcontent' then it should work
i prepared a simple example doing the same you want to do
and the css class is actually added to the anchor tag
var iframeid = "swcontent";
$('a[target="' + iframeid + '"]').addClass('loadsInIframe');

check it out here:
http://jsfiddle.net/saelfaer/pWgWZ/1/
Answer: It works perfectly if you sorrounding the vararible with ' ;-)
$("a[target='"+iframeId+"']").attr("href", url);

Comment: Did you consider the jQuery.extend that I gave ?

jQuery DOM selector issue


How to measure correlation between multi-item likert scales?

Question: I recently conducted a online survey and are now having trouble deciding for the right analysis method.
For example: I wanted to see if there is a correlation between Factor A and Factor B.
However in my survey I did not ask the participants to directly rate Factor A and Factor B, but rather asked multiple subquestions for these two factors which were rated from 5(Strongly Agree) to 1 (Strongly Disagree). I created a sum score for item A and a sum score for item B by summing up the values of each subquestion and calculated the mean of the sumscores to measure them.
So my question ist: Which method would be best to use here? I want to test if e.g. people with a higher score in Factor A would be more likely to decide for Factor B.
I actually planned using Spearman or ANOVA depending on the number of independent variables, but I am not sure if that would really be the correct way to measure the correlation.
Comment: It's important to be clear whether you want to measure correlation or agreement. For example, if on one item everyone was 1 or 2 and on another item the same people were 2 or 4 respectively then the correlation is perfect but agreement is not. In practice cases like that are unlikely I would guess, but in principle correlation and agreement are different properties.
Answer: Since you have a 5-level Likert scale, rather than encoding them as:
$$1, \, 2, \, 3, \, 4, \, 5$$
You could encode them as:
$$-2, -1, -0, \; \; \, 1, \; \; \, 2 \; \; \,$$
That way, summing over a large number of questions will give you a number that is positive if someone tends to agree and negative if someone tends to disagree. More importantly, you can interpret this number the same, regardless of the number of questions summed over.
Then you could simply plot the average response on factor A against the average response on factor B per participant in a scatter plot. This will give you much more compelling evidence then just some measure of correlation or a $p$-value from an analysis.
You could add a measure of correlation to the plot. If the relationship is more or less linear, you can use the Pearson correlation. Otherwise, you can use rank correlation instead, like Spearman's rank correlation.
The question only mentions factors A and B, so I see no reason to use ANOVA (comparing any number of means) over a simple correlation coefficient.
Answer: As you computed a sum score you accepted that this is data suitable for buidling quasi-metric data as in a Likert scale.
The quasi-metric scale niveau gives you the option of computing either Pearson correlations or Spearman correlations.

people with a higher score in Factor A would be more likely to decide for Factor B

That is what Spearman correlations are made for. Pearson correlations are made for linear relationships. So choose Pearson if you expect a linear relationship and Spearman if you expect a "the more A, the more B" relationship indepent of linearity.
Should you have more then 2 scales and you want to investigate which of those "goes together" whith which other ones, you are probably looking for Factor analysis or Principal Componen Analysis rather then ANOVA.


Hiding a filter in a view with same filter in contextual filters

Question: I've a simple problem. In Views I've city filter(exposed) set that'll show jobs in a city. Now I've set the same City in contextual filters as well with the condition to show all values when no argument is supplied. So this view is "General Advanced Job Search"
Now I want to offer "Jobs in Citi1", "Jobs in Citi2". But I want to reuse the same View without duplicating it. I'd call it "Advanced Job Search given a city".
So I can pass the arguments as Citi1 etc and it'd show Jobs in Citi1 at the same time it'll show City filter as drop down in Filter Criteria. I want to hide this City in Filter criteria as it is of no use as cities are already being limited by the argument passed(Citi1).
I've tried searching here and there but nothing found.
In short if argument is passed to a view I want to hide an exposed field show in filter criteria.
Answer: The following code will help you to solve your issue.
/**
 * Implement hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  if($form_id == 'views_exposed_form') {
    if($form['#id'] == 'views-exposed-form-myview-page') {
       // argument 1 represent city1
      if(arg(1)) {
        // hide city field
        unset($form['#info']['filter-jobs_in_city']);
        hide($form['jobs_in_city']);
      }
    }
  }
}

Notes:

Replace form id views-exposed-form-myview-page with your own form id
Replace argument 1 with the right City1 argument index
Replace jobs_in_city field name with your own city field
Answer: You can use this module
https://www.drupal.org/project/filter_harmonizer
It fixed that problem for me. if you have the same exposed filter as a contextual filter this module helps you to avoid this problem. Read the instrucions in the module's page


Why does this not satisfy the conditions of a metric?

Question: Suppose we would like to define a metric on New York City, let t : NYC × NYC → R+ is
a function that measures the time it takes to travel between two points in New York City.
Why doesn't t satisfy the criteria of being a metric?
I know that a metric must satisfy triangle inequality, non-negativity, and symmetry. I feel like this satisfies all of these conditions. Why is it not a metric, though? Thanks for the help!
Comment: Do you mean travel by car?
Answer: First and most important, it's not well-defined: the time needed to get from one point in New York City to another depends on the time, date, and means of transportation. Secondly, it need not be symmetric even at a particular time and date using a particular means of transportation.


Fill in a group table with $4$ elements

Question:
There is exactly one group $G$ of four elements, say $G = \{e, a, b, c\}$ satisfying the
  additional property that $xx = e$ for every $x \in G$. Complete the following group table of $G$.
$$
\begin{array}{c|lcr}
 & e & a & b & c\\
\hline
e & e & a & b & c\\
a & a &  &  \\
b & b &  & \\
c & c &  &
\end{array}$$

Every $x$ in $G$ satisfies $xx = e,$ so $aa = e, bb = e, cc = e.$
first row: $ab \neq a$ because it's given that $b \neq e.$ Also, $ab \neq b$ since $a \neq e.$ So, $ab = c.$ Thus, $ac = b.$
second row: $ba \neq a$ since $b \neq e.$ So, $ba = c.$ Then, $bc = a.$
third row: $ca \neq a$ since $c \neq e.$ So, $ca = b$ and $cb = a.$
So,  $$
\begin{array}{c|lcr}
 & e & a & b & c\\
\hline
e & e & a & b & c\\
a & a & e & c & b\\
b & b & c & e & a\\
c & c & b & a & e
\end{array}$$
Please, check my work.
Comment: This is correct. You are calculating the Klein 4-group, Google that for further confirmation.
Comment: I wish more questions were like this on MSE. Nice work!
Answer: "Fortunately" there are only two choices for a finite group of order $4$.
One is $(\mathbb{Z}_4,+)$, which is not unipotent.
The second choice, $(\mathbb{Z}_2\times\mathbb{Z}_2,+)$ or Klein four-group, is indeed unipotent and, if you check this Cayley table of it, you'll have your solution confirmed with no even need of relabelling the elements.
Comment: I am trying to prove these two are the only groups on the set of $4$ elements. There are $3$ $x \neq e$ in Klein four group s.t. $xx = e.$ There's no group with $4$ elements where $4$ or more of its elements($x \neq e$) abide by $xx = e.$ So, we can have maximum $3$ groups with $4$ elements. My strategy is to rule out one of them by contradiction. We can use following theorems to do that: $(1.)$ If the order of $G$ is even, there is at least one $x \neq e \in G$ s.t. $x^2 = e.$ $(2.)$There is exactly one group G of four elements s.t. $\exists x \neq e (x^2 = e)$ and $\exists y(y^2 \neq e).$

Fill in a group table with $4$ elements


Calculate geometry created by "slicing" rectangle with lines

Question: Given a rectangle with a series lines intersecting it, how would you calculate the points of each individual shape created? In this particular application that we are working on, the user can "slice" a rectangle into sub-shapes, similar to how Adobe Illustrator's scissors tool works. Programmatically speaking, I can do the interaction part and drawing,  but I'm unsure how to calculate the shapes. The rectangle will always be a fixed size and users cannot plot a point that is not on the main rectangle's sides.

EDIT:
Not really looking to get the area of each of the shapes shown in the diagram (A, B, C, etc). What I would to solve is this: given the points that define each dotted line, I want to find the points that define each created shape. So (in the drawing) area is defined by A=(0,0),(0,1),(1,0); B=(0,1),(0,3),(1,3),(2,0),(1,0); and so on. I know the size of the rectangle is 5x4 and that will never change, only a series of lines that the user can create by tapping two points on the rect, thereby slicing a section in two for each line.
Comment: Apologies for the noob question in advance. I went to art school!
Answer: If you have the points you can use elementary calculation (triangle, trapezoid etc.) to calculate the area.
I would like to repeat myself:
The way you draw your picture it might be easier to slice all pieces in triangles because then you can read the lenght of sides and hight of the triangles right away and wouldn't have to calculate that much.
You could almost "see" the area of the triangles and just add them up - no equation to solve at all.
Answer: I'm not quite sure what you are really asking, but I can tell you a general way to solve it.
Letting $$A(0,0),B(a,0),C(a,b),D(0,b)$$ be the vertices of the rectangle where $a,b\gt0$. (you would know the values $a,b$.)
If you have a line represented as$$Ax+By+C=0,$$
you'll be able to find the coordinates of the intersection points.
Once you know the coordinates of the intersection points, then you can calculate the area of each individual shape. If the shape is a quadrilateral, you can divide it into two triangles. This will makes it easier for you to calculate its area.
EDIT : You can calculate the coordinates of the intersection points in the following way with a rectangle which I wrote in my comment.
If the line you have is represented as
$$y=x+1,$$
then consider $x=0, y=3$. (These are the lines included the edges of the rectangle.)
Then, you'll know that the line intersects at
$$(0,1),(2,3).$$
So, we know that the area of a triangle made by this line is
$$1\times 2\times \frac 12=1.$$
Comment: OK. If your rectangle $ABCD$ is $3\times 4$ for example, you can put it in $xy$-coordinates plane as I wrote in my answer : $A(0,0),B(4,0),C(4,3),D(0,3).$ Then, you can find the coordinates of the intersection points if you know the equation of the lines.
Comment: Ok, maybe the rectangle of your picture is $4\times 5$? If so, you can get some areas : for example, the area of $C$ is $2\times 4\times (1/2)=2.$ Is this what you want? But for example, we cannot get the area of $G$ because we don't know its height.
Comment: I am really asking how to get the x,y points of each point in a shape created, imagining if the rectangle was sliced up along the dotted lines. This is so I can redraw the square as multiple shapes in different colors.
Comment: The way you draw your picture it might be easier to slice all pieces in triangles because then you can read the lenght of sides and hight of the triangles right away and wouldn't have to calculate that much
Comment: @typeoneerror: I added at bit in my answer. Does this help?
Comment: I still wonder if the equations of the lines are given or the picture. If it's the picture I find it very complicated to use equations
Comment: If your short lines on the top of the rectangle (also at the left side of the rectangle) shows the same distances, then you can calculate their areas without any equation of lines.
Comment: If the rectangle of your picture is $5\times 4$ and if the points on the edges are $(0,0),(0,1),(1,4),(2,4),(4,4),(5,4),(5,1),(4,0),(2,0),(1,0)$, then we can find each area of the small shapes.
Comment: Not really looking to get the area. I get how I would do that. What I want is, given the points that define each dotted line (as you just listed above), I want to know the points that define each created shape. So (in the drawing) area A=(0,2),(1,3),(0,3); B=(0,0),(0,1),(2,3),(1,3),(0,2); and so on. I know the size of the rectangle is 5x4 and that will never change, only a series of lines that the user can create by tapping two points on the rect, thereby slicing a section in two for each line.
Comment: I don't understand your A=(0,2),(1,3),(0,3); B=(0,0),(0,1),(2,3),(1,3),(0,2). Are these the coordinates? If so, I don't understand them. Or something else?
Comment: Ah, sorry, I am thinking in Flash programming coordinates, and so I'm reversing the y-axis. Let me correct that: A=(0,0),(0,1),(1,0); B=(0,1),(0,3),(1,3),(2,0),(1,0);
Comment: @typeoneerror: Yes. They are what I thought. So, if you know a series of lines, then you'll know these points. How come we can know if we don't know what kinds of lines we are given? I want to ask you what the condition is? Or, how are we given a series of lines?
Comment: Assume we start with the 5x4 rectangle and then plot two points, one on top and one on bottom. The rectangle would be divided into two polygons. Trying to then get the points that define each of those two shapes. If we then split one of those, there would be then three shapes. Want to figure out a method or algorithm for this. I guess it's "splitting a polygon" by multiple lines, similar to http://stackoverflow.com/questions/3623703/how-can-i-split-a-polygon-by-a-line but with simple convex shapes.
Comment: Like in this program Maya, you can draw two control points across a face to split that face into two new shapes (and more if you like). I need to figure out a mathematical way of creating the new shapes. http://download.autodesk.com/global/docs/maya2014/en_us/index.html?url=files/Combining_separating_and_splitting_Split_polygon_faces.htm,topicNumber=d30e158490
Comment: Yeah, I understand how it works. But you are asking the points, right? so, mathematically, to know the points we need to know what the lines are. I mean, not about how it goes, what they are. Also, are you saying that first you can choose to draw lines?


Successive LEFT SQL joins back to original

Question: I need to redo sql statement in legacy Foxpro application and don't understand whether it is meaningful at all. Syntax is a bit specific -  it extracts data from temporary table  into the same temporary table ( overwriting)   with some joins.
SELECT aa.*,b.spa_date FROM (ALIAS()) aa INNER JOIN jobs ON aa.seq=jobs.seq ;
LEFT JOIN job2 ON jobs.job_no=job2.rucjob;
left join jobs b on b.job_no=job2.job_no;
WHERE jobs.qty1<>0 INTO CURSOR (ALIAS())

Since only one field is added from joined tables ( spa_date ) is there any point in 2 left joins or I am missing something. Isn't it equivalent to
SELECT aa.*,jobs.spa_date FROM (ALIAS()) aa INNER JOIN jobs ON aa.seq=jobs.seq ;
WHERE jobs.qty1<>0 INTO CURSOR (ALIAS())

Answer: They are different because b.spa_date come from the second left join. You may be missing filtered rows without both left joins.
You would need to know the intent of the original query and perhaps rewrite it to make more sense but I'd say the two queries are different.
Comment: Yes, they are different.  I was able to mimic the statement outside of application. The intent remains unclear.


Erro ao tentar somar tudo através de uma classe em Java

Question: Estou fazendo um projeto pequeno sobre controle de despesas,e estou tendo um problema para calcular o total das despesas.
Estou com um classe chamada Despesa que é uma classe abstrata,e outras classes chamadas Transporte,Alimentação e Diária irão herdar dela o valor total das despesas e outros dois métodos.
E tenho também uma classe separada chamada Gerenciador Despesas com um método que vai passar por parâmetro a classe Despesa e pegar o valor total de todas as outras classes,e somar o valor total dentro de uma variável chamada total despesas.
O problema é que quando eu calculo uma das três classes que estão herdando,o valor total da classe Despesa irá ir para todas,sendo que eu queria separado,o valor total de cada classe e depois a soma total das três classes.
Classe Gerenciador Despesas :
public class GerenciadorDespesas {

    private int qtdeAlimentacao;
    private int qtdeTransporte;
    private int qtdeDiaria;
    private double totalAlimentacao;
    private double totalTransporte;
    private double totalDiaria;
    private double totalDespesas;

    public int getQtdeAlimentacao() {
        return qtdeAlimentacao;
    }
    public void setQtdeAlimentacao(int qtdeAlimentacao) {
        this.qtdeAlimentacao = qtdeAlimentacao;
    }
    public int getQtdeTransporte() {
        return qtdeTransporte;
    }
    public void setQtdeTransporte(int qtdeTransporte) {
        this.qtdeTransporte = qtdeTransporte;
    }
    public int getQtdeDiaria() {
        return qtdeDiaria;
    }
    public void setQtdeDiaria(int qtdeDiaria) {
        this.qtdeDiaria = qtdeDiaria;
    }
    public double getTotalAlimentacao() {
        return totalAlimentacao;
    }
    public void setTotalAlimentacao(double totalAlimentacao) {
        this.totalAlimentacao = totalAlimentacao;
    }
    public double getTotalTransporte() {
        return totalTransporte;
    }
    public void setTotalTransporte(double totalTransporte) {
        this.totalTransporte = totalTransporte;
    }
    public double getTotalDiaria() {
        return totalDiaria;
    }
    public void setTotalDiaria(double totalDiaria) {
        this.totalDiaria = totalDiaria;
    }
    public double getTotalDespesas() {
        return totalDespesas;
    }
    public void setTotalDespesas(double totalDespesas) {
        this.totalDespesas = totalDespesas;
    }

    public void analisarDespesas(Despesa despesa) {
    setTotalAlimentacao(despesa.getValorTotal());
    setTotalTransporte(despesa.getValorTotal());
    setTotalDiaria(despesa.getValorTotal());
    setTotalDespesas(getTotalAlimentacao() + getTotalTransporte() +
            getTotalDiaria());

    }

}

Classe Despesa :
import javax.swing.JOptionPane;

public abstract class Despesa {

    private String descricao;
    private double valorTotal;

    public String getDescricao() {
        return descricao;
    }
    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }
    public double getValorTotal() {
        return valorTotal;
    }
    public void setValorTotal(double valorTotal) {
        this.valorTotal = valorTotal;
    }

    public void cadastrarDespesa() {
        setValorTotal(0);
        setDescricao(JOptionPane.showInputDialog("Digite a descrição da Despesa : "));
    }

    public abstract void calcularDespesa();
    public abstract void listarDespesa();

}

Me desculpem,se a explicação do problema ficou grande demais ou se o código ficou muito grande,por favor,se alguém puder me ajudar irei ficar muito grato.
Comment: Na verdade não dá para responder só com isto. Tem informação de menos. Mas alguma coisa me diz que não deveria estar usando herança.
Comment: Ah, sim se funciona em um projeto, vai funcionar em todos. Na verdade nem sei o significa funcionou. Quer dizer que compilou? OOP não é isto.
Comment: As outras três classes somente tem o cadastramento das variáveis e listamento delas e o cálculo nada a mais.Agora sobre a herança,funcionou em meu outro projeto,não sei por que neste não esta funcionando.
Comment: Quando eu disse isto eu quis dizer que funcionou praticamente com o mesmo código e com uma classe também que era gerenciadora que tinha como função a mesma desta.Se quiser levar pelo lado da ironia e do sarcasmo tudo bem,mas não te insultei de modo algum para vir fazer isto.
Answer: Você falou: "...Gerenciador Despesas com um método que vai passar por parâmetro a classe Despesa e pegar o valor total de todas as outras classes,e somar o valor total dentro de uma variável chamada total despesas. O problema é que quando eu calculo uma das três classes que estão herdando,o valor total da classe Despesa irá ir para todas,sendo que eu queria separado,o valor total de cada classe e depois a soma total das três classes."
A solução é criar uma ArrayList estática de Despesas dentro de Despesas
e toda vez que for criada um novo objeto "Despesa" adiciona-lo nessa Array.
Desse modo se salva todos os objetos criados dentro da própria classe
import java.util.ArrayList;

import javax.swing.JOptionPane;

public abstract class Despesa {

private static ArrayList<Despesa> despesa=new ArrayList<Despesa>();

private String descricao;
private double valorTotal;

public String getDescricao() {
    return descricao;
}

public void setDescricao(String descricao) {
    this.descricao = descricao;
}

public double getValorTotal() {
    return valorTotal;
}

public void setValorTotal(double valorTotal) {
    this.valorTotal = valorTotal;
}
   public void cadastrarDespesa() {
        setValorTotal(0);
        setDescricao(JOptionPane.showInputDialog("Digite a descrição da Despesa : "));
    }

    public abstract void calcularDespesa();
    public abstract void listarDespesa();

    public static ArrayList<Despesa> getDespesa() {
        return despesa;
    }

}

Para somar todas as Despesas no GerenciamentoDespesas
Se quiser somar só uma, aquele seu primeiro método funciona
PS:Só não entendi pq vc ta atribuindo o mesmo valor a alimentação, tranporte e diaria...Mas vlw
public void analisarDespesas(Despesa desp) {
    double ali = 0;
    double trans = 0;
    double dia = 0;
    double total = 0;

    for (Despesa despesa : Despesa.getDespesa()) {
        ali += despesa.getValorTotal();
        trans += despesa.getValorTotal();
        dia += despesa.getValorTotal();
        total += ali + trans + dia;
    }
    setTotalAlimentacao(ali);
    setTotalTransporte(trans);
    setTotalDiaria(dia);
    setTotalDespesas(total);
}

Agradeço de der aquele UP na resposta
:)
Comment: Na verdade todos iriam pegar o valor total da classe Despesa,já que nas três classes ambas pegam a variável valor total com getters e setters. Por isso estou atribuindo o mesmo valor.Em outro projeto que fiz uma coisa parecida,funcionou normalmente,mas agora deste jeito neste projeto não funcionou.
Comment: Tentei seu código,mas não foi,mas mesmo assim,obrigado amigo :)


Como manipular printf em linguagem C

Question: Olá!
Como faço para colocar algo após a variável em um printf.
Ex:
printf("Digite um valor para a posição: [%d", l); printf(" ,%d", c); printf(" ]");

estou usando o exemplo acima, mas eu queria saber se é possível fazer algo semelhante ao pseudocódigo:
Ex:
printf("Digite um valor para a posição: [%d", l, ",", c, " ]");

O resultado final seria algo do tipo:
Digite um valor para a posição [ x, y]:
Answer: int main()
{
    int x=5;
    int y=3;
    printf("Digite um valor para a posição [%d, %d]", x, y);
    return 0;
}

Como ficou:
Digite um valor para a posição [5, 3]
Answer: #include <stdio.h>

int main(void)
{
    int x, y;

    printf("Digite dois valores para definir a posição [x, y]\n");
    scanf("%d %d", &x, &y);
    printf("Posição escolhida [%d , %d].", x , y);

  return 0;
}

Como manipular printf em linguagem C


How to end a RDP session without locking in windows 2003 server

Question: When I use "C:\Windows\System32\tscon.exe RDP-Tcp#NNN /dest:console"
I get the following error:

Could not connect sessionID 1 to sessionname console, Error code
  Error [7041]:Disconnecting the console session is not supported.

I searched for a solution and found nothing.
maybe there is another tool, apart from tscon, to help me?
Answer: I don't have a 2003 box to test with, but maybe this will work:
Start your RDP session with mstsc /console /v:servername and then try the tscon command again.
If that doesn't work, try mstsc /admin /v:servername instead.


Why should i remove zero when handling data?

Question: I am trying to find out whether two variables X,Y are distributed as bivariate normal. Here is my procedure:

check whether X is normal
check whether Y is normal
check whether scatter plot is follow a ellipse

My tutor told me that I should remove the zeros of my data. I want to know, what is the point of doing that?
Comment: If you want to know why your tutor said to do something, why not ask your tutor?  But you should give more details. What do the data consist of? How do zeros occur? Why are you checking bivariate normality? How are you assessing normality? How are you assessing elliptical contours? It might give us some better idea. It's hard to say much with so little to go on.
Comment: Surely zero is a legal value for a normal which has its support on the whole real line? So I agree with @Glen_b you need to politely ask your tutor what his/her understanding of the normal distribution is.
Comment: @mdewey with continuous data the probability of an exact 0 is 0 (and if one actually occurred, would not need to be removed anyway); I believe the problem here is that the data are not truly continuous and that multiple zeros are in the data -- which is presumably why the tutor is saying to remove them, even though they're the biggest clue that the data are not drawn from a bivariate normal.
Answer: If you have exact zeros in your data, the distribution they were drawn from will not be normal. So rather than remove them, they're grounds for immediately rejecting the null of bivariate normality.
Elliptical contours imply an elliptical distribution. A bivariate normal is elliptical, but so (for example) is a bivariate $t$. However, elliptical contours with normal margins would imply bivariate normality. So that part would be fine, if you knew that information about the distributions from which the data were drawn.
However sample margins that aren't obviously non-normal and sample contours that are not obviously non-elliptical doesn't mean that the distribution is bivariate normal. Similarly failure to reject in some hypothesis test of such things doesn't tell us that the distribution
the data were drawn from is bivariate normal. Sometimes you can see
that you don't have bivariate normality and sometimes you can't tell
that you don't.


Is it possible to find $g^k(x)$?

Question: Given $g(x)=\frac{x}{2}+\frac{1}{x}$, is it possible to find an expression for $g^k(x)=(g\underbrace{\circ \cdots \circ}_k g)(x)$, where $k$ is some positive whole number?
For example, given $h(x)=\frac{x}{2}$, the expression for $h^k(x)$ is $h^k(x)=\frac{x}{2^k}$.
Comment: Trivially, $g^k(\pm\sqrt{2}) = \pm\sqrt{2}$, but I'm not sure what else to say about the function. I wish I knew more!
Comment: The only rational functions whose iterates I know a reasonable way of writing down are the fractional linear transformations $\frac{ax + b}{cx + d}$. Beyond that case I think things get quite complicated; see, for example, https://en.wikipedia.org/wiki/Complex_dynamics.
Answer: Looking at
$$
g(x)=\frac{x}{2}+\frac{1}{x} = \frac{x^2 + 2}{2x}
$$
and cranking some iterations through the Maxima CAS, I get
$$
g^2(x) =
{{x^4+12\,x^2+4}\over{4\,x^3+8\,x}} \\
g^3(x) =
{{x^8+56\,x^6+280\,x^4+224\,x^2+16}\over{8\,x^7+112\,x^5+224\,x^3+
 64\,x}} \\
g^4(x) =
{{x^{16}+240\,x^{14}+7280\,x^{12}+64064\,x^{10}+205920\,x^8+256256
 \,x^6+116480\,x^4+15360\,x^2+256}\over{16\,x^{15}+1120\,x^{13}+17472
 \,x^{11}+91520\,x^9+183040\,x^7+139776\,x^5+35840\,x^3+2048\,x}}
$$
This gives no simple pattern I am able to spot, just more or less
complicated rational functions with nominator degree $2^k$ and denominator degree $2^k - 1$, and the proper coefficients to go asymptotically to $h^k$.
Here are plots of $\text{id}, g, g^2, g^3, g^4, g^5$:

(Larger version)
This is slightly more interesting, as we see that for $x > 0$ the series $g^k$ seems to iterate against a constant function, at value of the positive fixed point $x_+^*$ of $g$. (Similar for the negative arguments against $x_-^*$).
Going for the fixed points:
$$
x = g(x) = \frac{x^2 + 2}{2x} \Rightarrow \\
2 x^2 = x^2  + 2 \Rightarrow \\
x^2 = 2 \Rightarrow \\
x = \pm \sqrt{2}
$$
Comment: I guess it's not really easy, maybe impossible, to find $g^k(x)$ because the formulas for $g^2,g^3,g^4...$ grow longer to write down...
Comment: $g^4(x)$ is simpler than $${{x^{16}+240\,x^{14}+7280\,x^{12}+64064\,x^{10}+205920\,x^8+256256
 \,x^6+116480\,x^4+15360\,x^2+256}\over{16\,x^{15}+1120\,x^{13}+17472
 \,x^{11}+91520\,x^9+183040\,x^7+139776\,x^5+35840\,x^3+2048\,x}}$$. Coming up with a formula or recurrence for the coefficients might be possible, but do I want it?

Is it possible to find $g^k(x)$?


Unique solution for IVP with $y''(x) + y(x)^2 = 0$?

Question: I'm supposed to show that the following initial value problem has a unique non-trivial solution.

$y''(x) + y(x)^2 = 0$
$y(0) = y(1) = 0$

My approach so far is:
$$y''(x) = -y(x)^2 \Rightarrow y^{-2}dy^2 = -dx^2 \Rightarrow (-y^{-1} + c_1)dy = -c_2 dx \Rightarrow \ln{|y|} + c_1 y = c_2 x + c_3$$
Here is the problem, if we say $y(0) = 0$ but I try to plug that in, I need to calculate $\ln{(0)}$ which is not defined. Did I mess this up?
Comment: No, your alchemy with differential quotients is not correct. The second order derivative is not the square of the first order derivative. Multiply with $2y'$ and integrate to get $y'^2+\frac23y^3=C$.
Comment: If we remain informal, the numerator of the second derivative is $d^2y=y(x+dx)-2y(x)+y(x-dx)$ while the square of the first derivative is in the numerator $(dy)^2=(y(x+dx)-y(x))^2$. Or did you mean $d(y^2)=y(x+dx)^2-y(x)^2$?
Comment: Yeah, it is correct. It is problem 1.26 on page 30 here (https://www.mat.univie.ac.at/~gerald/ftp/book-ode/ode.pdf). What do you mean? Is my approach not correct?
Comment: @Moo maybe there is a way to show there is a unique solution without explicitly solving it?
Comment: @LutzLehmann I'm not sure I understand what you are referring to as "alchemy". I know I wrote it as $dy^2$ and $dx^2$ but that was just so I could integrate twice. Which step exactly is wrong?
Comment: Okay, so if I'm more careful I can write:

$$d^2 y/ dx^2 = -y^2 \Rightarrow d^2 y = -y^2 dx^2 \Rightarrow d^2 y/y^2 = -dx^2 \Rightarrow \int{y^{-2}d^2y = -\int{dx^2}} \Rightarrow
 -y^{-1} dy = (-x + c)dx$$

My guess is that my error is in the last step?
Comment: Yes, the last step. Such an integration does not exist. Just like $\frac{dy}{dx}$ is a symbol with a suggestive structure and many rules for its correct use, so is $\int ... dx$ in the first place a suggestive symbol and associated rules. That the rules sometimes harmonize very well with the symbolic makes them easier to learn, but also easier to abuse.
Answer: The argument roughly goes as follows: Choose a unique solution $y$ such that $y(0)=0$ and $y'(0)=1$. This is possible because of Picard-Lindelöf theorem. Prove by differentiating the LHS (so it is constant) that the energy equation
$$
\frac{1}{2}(y')^2 + \frac{1}{3}y^3 = \frac{1}{2}
$$
holds. Because of $y$ increasing near zero, it must hold because of the above equation that $y'$ decreases and $y$ increases until $y'(\bar x) = 0$ for some $\bar x >0$ with positive value (according to the above equation).
Here, $y$ has a local maximum: Since a piecewise constant solution is impossible according to $y''+y^2=0$, $y$ can only decrease there: If it were to increase, then the energy equation is clearly violated. So in $\bar x$, $y'$ decreases again, gets negative and the energy equation states that $y'$ has to decrease further if $y$ decreases as well. This happens until $y(\hat{x})=0$ for some $0 < \bar x < \hat{x}$ (and even further). Then prove that the mapping
$$
v(x) := \hat{x}^2 y\left(\hat{x}\cdot x \right)
$$
is still a solution to the BVP. $v$ is of course non-trivial.


How do I compute the area of the surface where $z=x^2+y^2$ and $0\leq z\leq 1$?

Question:
Let me define the surface where $z=x^2+y^2$ and $0\leq z\leq 1$. I want to compute the area of this surface.

My idea was to parametrize the surface with the following parametrization $$\phi(r,\theta)=(r\cos(\theta), r\sin(\theta), r^2)$$ where $\theta\in [0, 2\pi]$ and $r\in (0,1)$. Then I compute the vector $$\frac{\partial \phi}{\partial(r,\theta)}=
  \begin{bmatrix}
    \cos(\theta)&-r\sin(\theta) \\
    \sin(\theta)&r\cos(\theta) \\
    2r &0
  \end{bmatrix}
$$
Now I denote $v=
\begin{bmatrix}
\cos(\theta)\\
\sin(\theta) \\
2r
\end{bmatrix}$, and $w=\begin{bmatrix}
-r\sin(\theta)\\
r\cos(\theta) \\
0
\end{bmatrix}$. Then I compute the Gram matrix $$G(v,w)=
\begin{bmatrix}
\langle v,v\rangle & \langle v,w \rangle \\
\langle w,v \rangle & \langle w,w \rangle
\end{bmatrix}=
\begin{bmatrix}
1+4r^2 & 0 \\
0 & r^2
\end{bmatrix}$$Then the gram determinant is $$g_\phi=\det(G(v,w))=(1+4r^2)r^2$$

Then from the lecture we know that the area of a parametrization $\phi(x)$ is given by $$A(\phi)=\int_Q \sqrt{g_\phi}~~ dx$$ where $Q$ is a square on which $\phi$ is defined.

So I would say in our case $$A(\phi)=\int_0^1 \int_{0}^{2\pi}r\sqrt{1+4r^2} ~~d\phi dr=...=\frac{1}{6}(5\sqrt{5}-1)$$
Now my question is, is this correct or am I wrong, because I'm not sure if my boundaries are correct. It would be helpful if someone could explicitly tell me where I did the mistakes if there are some.
Thanks for your help.
Comment: @JackD'Aurizio Oh sure it was $0\leq z\leq 1$. Sorry this is my mistake, but does then something change or is my result correct?
Comment: @JackD'Aurizio I edited my question and result now, is it correct like this?
Comment: It looks almost correct. There seems to be a factor of $\pi$ missing. I get $\frac\pi6\left(5^{3/2}-1\right)$.
Comment: I agree with robjohn: I think you forgot to include the $\pi$ from your upper limit for $\phi$.
Answer: Other than leaving out a factor of $\pi$ from the integration in $\phi$, your answer looks correct. I used a slightly different approach.

Start with the parameterization
$$
(x,y,z)=\left(r\cos(\theta),r\sin(\theta),r^2\right)\tag1
$$
Next, compute
$$
\begin{align}
\frac{\partial(x,y,z)}{\partial r}\times\frac{\partial(x,y,z)}{\partial\theta}
&=(\cos(\theta),\sin(\theta),2r)\times(-r\sin(\theta),r\cos(\theta),0)\tag{2a}\\
&=\left(2r^2\cos(\theta),-2r^2\sin(\theta),r\right)\tag{2b}
\end{align}
$$
The magnitude of $(2)$ is
$$
\left|\left(2r^2\cos(\theta),-2r^2\sin(\theta),r\right)\right|=r\sqrt{4r^2+1}\tag3
$$
Therefore, the surface area is
$$
\begin{align}
\int_0^{2\pi}\int_0^1r\sqrt{4r^2+1}\,\mathrm{d}r\,\mathrm{d}\theta
&=2\pi\int_0^1r\sqrt{4r^2+1}\,\mathrm{d}r\tag{4a}\\
&=\frac\pi4\int_0^4\sqrt{u+1}\,\mathrm{d}u\tag{4b}\\[3pt]
&=\left.\frac\pi6(u+1)^{3/2}\,\right|_0^4\tag{4c}\\[6pt]
&=\frac\pi6\left(5^{3/2}-1\right)\tag{4d}
\end{align}
$$
Explanation:
$\text{(4a):}$ integrate in $\theta$
$\text{(4b):}$ substitute $u=4r^2$
$\text{(4c):}$ integrate
$\text{(4d):}$ evaluate
Comment: Perfect thank you!


Como mudar background do ImageBrush?

Question: Segue código XAML:
<TextBox />
    <TextBox.Background>
        <ImageBrush x:Name="image_background" Stretch="Fill" TileMode="None" AlignmentX="Left" AlignmentY="Center" />
    </TextBox.Background>
</TextBox>

Segue código C#: (O código a seguir, tem um evento click, para mudar a imagem do textbox de cor preto)
image_background.ImageSource = CreateBitmapSource(System.Windows.Media.Color.FromArgb(255, 0, 0, 0)); // Black Color

O que funciona é só no evento Loaded:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
   // aqui consigo mudar a cor
   image_background.ImageSource = CreateBitmapSource(System.Windows.Media.Color.FromArgb(255, 0, 255, 0));
}

Alguma solução para mudar a cor ?
Answer: Pode setar uma cor para o fundo do TextBox utilizando a propriedade TextBox.Background:
textBox.Background = Brushes.Black; // a classe Brushes já tem cores pré definidas

Se quer uma imagem no fundo, faça:
var imageBrush = new ImageBrush();
imageBrush.ImageSource = new BitmapImage(new Uri("caminho/arquivo.jpg", UriKind.Relative));
textBox.Background = imageBrush;

O ImageBrush é para preencher uma área com uma imagem. Se não for para esse propósito, não faz muito sentido seu uso.

Como mudar background do ImageBrush?


Regex grouping issue

Question: I need a regex to grouping my strings, but I can't grouping properly.
String must be start "foo/", after end with "login" or "something" + "/" + (set|get).
    ^foo\/(login$|(.*)\/(set|get))

"login" or "something" must be group 1
"set" or "get"  must be group 2, if exist.
Test strings:
foo/
foo/login   -match
foo/login/get
foo/sadas/set   -match
foo/sadasf/asd
foo/blabla/get   -match

The grouping should be in the following format.
             Group1          Group2
foo      /   login
foo      /   sadasas     /    set
foo      /   blabla      /    get

Comment: It is not quite clear, try [`^foo\/(login$|[^\/]*(?:\/([sg]et))?)`](https://regex101.com/r/WlQGs9/1). Or [`^foo\/(login$|[^\/]+(?:\/([sg]et))?)$`](https://regex101.com/r/WlQGs9/2).
Answer: Try this Regex:
^foo\/(?(?=login)(login)|(.*?)(set|get))$

Click for Demo
Explanation:

^ - asserts the start of the line
foo\/ - matches foo/ literally
(?(?=login)(login)|(.*?)(set|get)) - If the current position is followed by login, match login and capture it as group 2, else match 0+ occurrences of any character(captured in group 1) followed by either set or get(captured in group 3)
$ - asserts the end of the string

Updated solution
^foo\/(login$|(?!login).*?(?=[gs]et))([gs]et)?$

Click for Demo
Just realised that this is very close to Wiktor's Comment
Comment: Its ok, but in "foo/sadas/set"; "sadas" in Group 2, "set" in Group 3. Is there a way start with group1?
Comment: Thank you for your help. Now, group 1 is "sadas/set", its must be only sadas.

Regex grouping issue


How can I sum up the totals of groupings in views?

Question: I am trying to sum up my sales in my Commerce store by month.
I have created a view of completed payment transactions that is grouped by payment year (first grouping) and then payment month (second grouping).  The config looks like this:

This gives output look like this:

Now what I'd like to do is sum up each month (the second grouping) to show the total sales for that month.  I think I can use aggregation for this but I'm not sure how to set it up.
Answer: Most of the links I found for this kind of thing point towards Views Aggregator Plus.  Apparently it allows you to "aggregate and group by column" (source).