D Language fails to display german Umlaute on Windows?

Question:
As you can see, D fails to output german Umlaute. At least on Windows. On Linux or BSD the same program outputs the string as I've saved it.
I already tried wstring or dstring, but the output is the same.
What am I doing wrong?
Answer: D will output UTF-8 regardless of the operating system. How the output will be interpreted depends on how it is displayed. In this particular case, it looks like your IDE is interpreting the output as if it was encoded in the Windows-1252 encoding.
For the standard Windows console, you could change the output encoding by calling SetConsoleOutputCP(65001), but note that this may have some undesired side effects (you should restore the codepage before your progam exits, and batch files may not run while the console output codepage is set to 65001).
Comment: `SetConsoleOutputCP` is not a global setting, it changes the setting for the current window.
Comment: Java's runtime most likely does check what is the underlying operating system and adjusts the output encoding... Perhaps Phobos should do the same.
Comment: I feel uncomfortable changing global settings of my console. Isn't there a cleaner solution? Why is C++- or Java-Ouput not affected by this problem?
Comment: C++ and Java probably do not output UTF-8.
Answer: CyberShadows post guided me to an acceptable answer. :-)
In Eclipse it is possible to change the output-encoding without changing global settings of the OS.
Go to Run --> Run-Configurations...

There select the Common-Tab and change the encoding to UTF-8. Now german Umlaute are displayed correctly. At least in Eclipse. :-)
Another possibility is to use https://babun.github.io/ . It is a Cygwin-based Shell that ouputs UTF-8:


What does tracert make NETBIOS work on Win7?

Question: This is really strange - I have a workaround for this (read on), but I'd love to know why it works.
I had a VPN setup working fine with a WinServer2003 server and a Vista client.
Then I setup a new Win7 box to access the same server.  The server is running WINS.
Both clients could get into the VPN fine, and ping machines on the server side by IP4 address.
But ONLY the Vista client could ping machines by NETBIOS address (machine name).  The Win7 client just returned "could not find host".
As far as I can tell, the clients are configured identically.
By chance, while fiddling, I discovered that if I run a tracert on the Win7 client - tracing the route to any machine on the server side - then AFTER THAT the NETBIOS works.
For example (this is from the cygwin command line on the Win7 box, with redacted passwords, etc.):
$ rasdial "vpnName" Dave passWord
Connecting to vpnName.
Verifying username and password...
Registering your computer on the network...
Successfully connected to vpnName. Command completed successfully.

Dave@QUIET ~
$ ping henshaw
Ping request could not find host henshaw. Please check the name and try again.

Dave@QUIET ~
$ tracert 10.1.10.1

Tracing route to www [10.1.10.1] over a maximum of 30 hops:

  1    39 ms    47 ms    49 ms  ASH [10.1.10.184]
  2    44 ms    31 ms    32 ms  www [10.1.10.1]

Trace complete.

$ ping henshaw

Pinging henshaw [10.1.10.92] with 32 bytes of data:
Reply from 10.1.10.92: bytes=32 time=36ms TTL=127
Reply from 10.1.10.92: bytes=32 time=46ms TTL=127
Reply from 10.1.10.92: bytes=32 time=35ms TTL=127
Reply from 10.1.10.92: bytes=32 time=41ms TTL=127

Ping statistics for 10.1.10.92:
   Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 35ms, Maximum = 46ms, Average = 39ms

(ASH is the Server2003 server box, 10.1.10.1 is the network gateway.)
What the heck is going on?  Why does the Win7 box act differently in the first place, and why does tracert fix it?
--Dave

Added:
Per suggestion of @Sane, here is the ipconfig all output from both clients:
Vista box:
Dave@Tower ~
$ ipconfig /all

Windows IP Configuration

   Host Name . . . . . . . . . . . . : Tower
   Primary Dns Suffix  . . . . . . . :
   Node Type . . . . . . . . . . . . : Hybrid
   IP Routing Enabled. . . . . . . . : No
   WINS Proxy Enabled. . . . . . . . : No
   DNS Suffix Search List. . . . . . : home

PPP adapter vpnName:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : vpnName
   Physical Address. . . . . . . . . :
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   IPv4 Address. . . . . . . . . . . : 10.1.10.80(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.255
   Default Gateway . . . . . . . . . :
   DNS Servers . . . . . . . . . . . : 10.1.10.1
   NetBIOS over Tcpip. . . . . . . . : Enabled

Ethernet adapter Local Area Connection:

   Connection-specific DNS Suffix  . : home
   Description . . . . . . . . . . . : NVIDIA nForce 10/100/1000 Mbps Ethernet
   Physical Address. . . . . . . . . : 6C-F0-49-D1-92-FC
   DHCP Enabled. . . . . . . . . . . : Yes
   Autoconfiguration Enabled . . . . : Yes
   Link-local IPv6 Address . . . . . : fe80::1d56:57b0:5c40:8ea2%10(Preferred)
   IPv4 Address. . . . . . . . . . . : 192.168.1.11(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Lease Obtained. . . . . . . . . . : Tuesday, November 20, 2012 12:52:51 PM
   Lease Expires . . . . . . . . . . : Wednesday, November 21, 2012 12:52:50 PM
   Default Gateway . . . . . . . . . : 192.168.1.1
   DHCP Server . . . . . . . . . . . : 192.168.1.1
   DHCPv6 IAID . . . . . . . . . . . : 258797641
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-14-7D-F7-96-6C-F0-49-D1-92-FC
   DNS Servers . . . . . . . . . . . : 192.168.1.1
   NetBIOS over Tcpip. . . . . . . . : Enabled

Tunnel adapter Local Area Connection* 6:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

Tunnel adapter Local Area Connection* 7:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Teredo Tunneling Pseudo-Interface
   Physical Address. . . . . . . . . : 02-00-54-55-4E-01
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   IPv6 Address. . . . . . . . . . . : 2001:0:9d38:6ab8:93:2ec:3f57:fef4(Preferred)
   Link-local IPv6 Address . . . . . : fe80::93:2ec:3f57:fef4%11(Preferred)
   Default Gateway . . . . . . . . . : ::
   NetBIOS over Tcpip. . . . . . . . : Disabled

Tunnel adapter Local Area Connection* 11:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . : home
   Description . . . . . . . . . . . : isatap.home
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

Win7 box:
Dave@QUIET ~
$ ipconfig /all

Windows IP Configuration

   Host Name . . . . . . . . . . . . : QUIET
   Primary Dns Suffix  . . . . . . . :
   Node Type . . . . . . . . . . . . : Hybrid
   IP Routing Enabled. . . . . . . . : No
   WINS Proxy Enabled. . . . . . . . : No

PPP adapter vpnName:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : vpnName
   Physical Address. . . . . . . . . :
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   IPv4 Address. . . . . . . . . . . : 10.1.10.108(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.255
   Default Gateway . . . . . . . . . :
   DNS Servers . . . . . . . . . . . : 10.1.10.1
   NetBIOS over Tcpip. . . . . . . . : Enabled

Ethernet adapter Local Area Connection:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Intel(R) 82578DC Gigabit Network Connection
   Physical Address. . . . . . . . . : 00-1C-C0-F7-54-2F
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   Link-local IPv6 Address . . . . . : fe80::3c6a:4873:97c:e773%10(Preferred)
   IPv4 Address. . . . . . . . . . . : 192.168.1.110(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.1.1
   DHCPv6 IAID . . . . . . . . . . . : 234888384
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-17-C6-DC-78-00-1C-C0-F7-54-2F
   DNS Servers . . . . . . . . . . . : 192.168.1.1
   NetBIOS over Tcpip. . . . . . . . : Enabled

Tunnel adapter isatap.{13A00E9E-CF57-4B02-B3F6-21929585E6FC}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

Tunnel adapter Teredo Tunneling Pseudo-Interface:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Teredo Tunneling Pseudo-Interface
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   IPv6 Address. . . . . . . . . . . : 2001:0:4137:9e76:400:32e2:9d91:5c30(Preferred)
   Link-local IPv6 Address . . . . . : fe80::400:32e2:9d91:5c30%12(Preferred)
   Default Gateway . . . . . . . . . : ::
   NetBIOS over Tcpip. . . . . . . . : Disabled

Tunnel adapter isatap.{B34461EA-B740-4553-A1A7-570852066611}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter #2
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

Comment: I don't have a solution for you, but why use WINS at all?  It's evil; kill it with fire at your earliest opportunity.
Comment: That doesn't really make much sense to me.  Have you considered firing up wireshark/tcpdump and performing a capture to see what else is going on while you run that that traceroute?
Comment: Check to see if the Win7 system has WINS set, it would probably also be helpful to have a ipconfig /all print out for both the Win7 and Vista systems.
Comment: @Sane See updated post.  Neither client has WINS set.
Comment: Seems to be some kind of routing issue, when you try pinging the first time it doesn't know how to route to the ASH box but after a trace route it "learns" the route to the ASH server. I'd check routes on both the Win7 box before and after the tracert and routes on the vista box (as a note trace routes send ICMP packets to each hop in the path where ping send an ICMP packet directly to the host)
Comment: @Sane Thanks for your thoughts; this is working well enough so I'm not going to put more time into it unless something breaks. I was just hoping somebody already knew what was going on here.  BTW - if I don't use NetBIOS for 15 minutes or so, it "forgets" about it and I have to do the tracert again.  Weird.
Comment: Going out on a limb here... I notice you have a single label DNS suffix. Changes were made to the DNS devolution mechanism in Windows 7. I'm wondering if this change in combination with the single label DNS suffix is the cause of the problem. Is your DNS zone a single label zone (home instead of home.local or some such)?
Comment: I've a question: does the name resolution also work after `ping 10.1.10.1`? Can you put the output of 'route print' _before_ and _after_ tracert?
Comment: Maybe you missed this out. If you just changed the Host Name, you need to restart the Win7 for the changes to take effect.
Comment: Here's what you should be doing - notice that your reverse lookup is resolving DNS:
Tracing route to www [10.1.10.1] over a maximum of 30 hops:

So, instead of using ping, use nslookup setting "d2". Since the reverse works, try the 126.96.36.199.in-addr.arpa address in nslookup.
Comment: What is the FQDN of www, ash and henshaw?
Comment: Did you allow use of netbios traffic on Windows Firewall in Win7 box for VPN connection?
Also double check that "Client for microsoft network" feature is enabled on VPN interface in Win7 box
Comment: Windows can be stubborn about local name resolving if a DNS Suffix isn't configured. It can be added manually for machines with static addresses via the GUI, as an option in DHCP responses (dnsmasq example: `domain=lan`) or even into IPv6 radvd messages (`DNSSL lan { FlushDNSSL on; };` goes into the `interface` block in radvd.conf).
Answer: I suspect that a side-effect of the tracert command is that it is populating the NetBIOS name cache. Run the command:
nbtstat /c

Both before and after the tracert command.  My guess is you'll see the entry for "henshaw" show up.
I forget the exact mechanism, it's something about being in an ad hoc NetBIOS network, there's no centralized name service so machines have to discover each other. Something tracert does while trying to do a reverse lookup of the IP address you supplied provokes a broadcast for NetBIOS names on the local LAN, and since your test box and "henshaw" are on the same network, your box can learn the name.
Try using "nbtstat /R" to flush the NetBIOS name cache, which should bring you back to the problem state. I think if you ping henshaw by its IP address, that will also populate the cache. Also, I suspect if you used "tracert /d" (don't resolve IP addresses into names) you won't get that beneficial effect.


add and remove an element to a mathematical set

Question: I'd like to write pseudo code with mathematical notation, I will write the code phrases in Python. I need to know if
first question:
aList = []
aList.empty() is not True

equals
$aList \neq \emptyset $
second question
a = 5
aList.append(a)

equals
$a \gets 5$
$aList \cup a$
third question
how to write to get the first element and remove it from the list i.e.:
curElement = aList[0]
aList.remove(0)

Thanks for any advice the Internet couldn't help me out.
Kind Regards
Comment: I don't understand your first question and your second.
Comment: I see. For second question, it should be $aList \cup \{a\}$. For the third one, it should be $aList - \{curlElement\}$.
Comment: We don't have "list" in math. We only have set.
Comment: Pardon me. 1) A list is often referred as a vector or a dynamic array i.e.: a container for multiple values. 2) I updated the question, the goal is to insert/append a new value to this list/array - I know $\cup$ usually stand for uniting two sets, however I'm not sure if that counts for a set and a sole value to as shown in the question
Comment: I guess $aList -\{ curElement \}$ stands for removing the element from the list, but how do I define which element from the set was chosen to assigne $curElement$ beforehand (i.e. how to retrieve an element from an arbitrary position in the set)?
Comment: I understand. That came unexpected though
Comment: @Misakov: We have tuples and functions :D
Answer: Notice that mathematicians and computer scientists of that field (type system and so on) do have their own shorter notation for these operations. However, they are not that common among the general public.
What are lists?
There are many list like constructs in math. For mathematician they are all functions. Basically, a list/tuple is a function $f$ from $\{1,\dotsc,n\}$ into a set, say $X$. So typically you define the set of lists with values in $X$ as its Kleene star:
$$ X^* = \{ f:\{1,\dotsc, n\} \to X \mid n \in\mathbb N \} = \bigcup_{n\in\mathbb N} X^n, $$
where $\mathbb N$ includes $0$.
Most computer scientists and mathematicians in that field use to work with partial functions. So you could also write
$$ X^* = \{ f:\mathbb N\to X \mid \operatorname{dom} f = \{1, \dotsc, |\operatorname{dom} f| \} \}. $$
They also identify $f$ with its graph, that is
$$ f = \{ (i,f(i)) \mid i\in\operatorname{dom} f \}. $$
Answer to your question:
Using partial functions you can express

"$f\in X^*$ is a empty list" by $f = \emptyset$,
"$g\in X^*$ is $f\in X^*$ appended with $a\in X$" by
$$ g = f \cup \{ (|\operatorname{dom} f| + 1, a) \}, $$
"$g\in X^*$ is $f\in X^*$ removed the first element" by
$$ g = \{ (i-1, f(i)) \mid i\in \operatorname{dom} f\setminus\{1\} \}. $$
Comment: @user3085931: Concerning pseudo code, some common concepts can be explained in text more easily :) There is no need to use formula with uncommon notations or concepts.
Comment: First of all thanks for your answer, it brought some light in here. However I guess it looks more complicated as it would make sense in this case. Since the goal of this pseudo code structure is to facilitate the understanding of rather complex text phrase - at this point of the paper for people barely dealing with mathematical expressions.
Comment: Not when considering that programmers tend to be lazy guys, skipping text and rather used to read code ;) I'm thinking about a way inbetween atm


How to read values from a file and then use them to initialize a 2D array C++

Question: I wish to read a text file such as
4
2
3
4 3
2 1
5 4
8 4

The first line being the first dimension of a 2D array and the second line being the second dimension of a 2D array and the third line being a value. Upon reading and storing the first three values into the variables n,m,k i would like to initialize the 2D int array int x[n][m].
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>

using namespace std;

int n,m,k;

int main()
{
    ifstream File;
    File.open("text.txt");

    if (File.fail()) {
        cout << "error opening file";
    }

    while (!File.eof())
    {
            File >> n;
            File >> m;
            File >> k;

            int x[n][m];

            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 5; j++) {
                    File >> x[i][j];
                }
            }

    }
    return 0;
}

However, I cannot initialize the array as it appears the expression n and m do not have constant values. If i were to set the variables to const int n,m,k, i would not be able to read them from the file using >>. How can i read the array sizing values, use them to create the array, and then store the values in them?
edit:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <math.h>

using namespace std;
std::vector < std::vector <int>> x;

int n,m,k;

int main()
{
    ifstream File;
    File.open("test.txt");

    if (File.fail()) {
        cout << "error opening file";
    }

    while (!File.eof())
    {
            File >> n;
            File >> m;
            File >> k;

            for (int i = 0; i < n; i++) {
                vector <int> row;
                for (int j = 0; j < m; j++) {
                    int readFromFile = 0;
                    File >> readFromFile;
                    row.push_back(readFromFile);
                }
                x.push_back(row);
            }

    }

    cout << n;
    cout << "\n";
    cout << m;
    cout << "\n";
    cout << k;
    cout << "\n";

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cout << x[i][j];
            cout << " ";
        }
        cout << "\n";
    }
    return 0;

}

Comment: "`int x[n][m];`" there is no such thing as variable length arrays in C++. Use `std::vector`! Also: [Why is "while ( !feof (file) )" always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong)
Comment: Also keep in mind that the scope of your array x is limited to the while loop - x doesn't exist outside the while.
Comment: Ah i see. I was also wondering, do you know if its possible to read the value directly into the array instead of storing them into a variable and then assigning the variables in the array declaration? Thanks for the good link too.
Comment: Also good point atru.
Comment: As @Swordfish wrote, you may want to consider switching to `std::vector` instead of using plain (C) arrays. There are many reasons to do so, including that you can determine the size of the container at runtime in a straightforward way. If you switch, [this post](https://stackoverflow.com/a/32177226/2763915) is an example of how to read a two column file into a "2D" vector - i.e. vector of vectors of doubles - ints in your case.
Answer: #include <cstdlib>  // EXIT_FAILURE
#include <vector>
#include <fstream>
#include <iostream>

int main()
{
    char const * file_name{ "test.txt" };
    std::ifstream is{ file_name };

    if (!is.is_open()) {  // exit if the file couldn't be opened.
        std::cerr << "Couldn't open \"" << file_name << "\" for reading!\n\n";
        return EXIT_FAILURE;
    }

    int m, n, k;
    if (!(is >> m >> n >> k)) {  // whatever k might be.
        std::cerr << "Data error!\n\n";
        return EXIT_FAILURE;
    }

    std::vector<std::vector<int>> data(m, std::vector<int>(n)); // m rows, n cols

    for (int row = 0; row < m; ++row) {
        for (int col = 0; col < n; ++col) {
            if (!(is >> data[row][col])) {  // try to extract an integer
                std::cerr << "Data error!\n\n";  // give an error message and
                return EXIT_FAILURE;             // exit if it fails
            }
        }
    }

    for (auto const &row : data) {
        for (auto const &col : row) {
            std::cout << col << ' ';
        }
        std::cout.put('\n');
    }
}

Output:
4 3
2 1
5 4
8 4

Comment: Thank you kind soul, I fixed my original code by switching to std vector. I will definitely make use of some things you have provided, including a fix to !File.eof().
Comment: Potential tweak: `std::vector> data(m, std::vector(n));`. Eliminates the need for `data[row].resize(n);` Maybe there's some room for optimization in there, maybe not.
Comment: @user4581301 Memory allocation vs. file-io? I don't wanna bet. Changed anyway.


Need To Authonticate User Via Facebook & Twitter(PhonegapAndroid)

Question: new to phonegap programing development.having one issue that i need to authonticate user via facebook/twitter & if authontication goes true on basis of that need to upload some image to server..i have stuck on this issue..i could found this one facebook sdk for phonegap android.i have downloaded this one plugin https://github.com/davejohnson/phonegap-plugin-facebook-connect  but when implemented it just redirects to facebook page to browser,it dosen't opening popup of facebook login page as we can see in native android application...so any guide for that?
Thanks in advance
Aamirkhan i.
Answer: We've recently developed an iOS phonegap app.  We had to pull a feed from Twitter (to our Grails server component) and elected to use Twitter4J as it simplified the process.  Here's a code example on the Twitter4J site focussed particularly on authentication.  Hope it helps.  Good luck!
Comment: entire Code is looiking like java class,can u tell me how can i apply it on phonegap?,& it will be better if u can give me sample code u have built..
Comment: Does your phonegap app have a server component i.e. an app server that it pulls content down from?  That's normally how you set a phonegap app up AFAIK.  Then, when the end user logs in using their Twitter credentials, you post them to your server and authenticate them using the API.  If your server component is done in some other technology, there is likely a client library for it.  See here, https://dev.twitter.com/docs/twitter-libraries.
Answer: When you get redirected to the web page instead of the popup it means that the facebook app is not installed on your phone. This is unfortunately necessary now with the new FB jar.


Sum of reciprocal of evil/odious numbers

Question: A positive integer $n$ is said to be evil if the sum of $1$s in its binary expansion is even, odious otherwise. Is anything known about the sum of reciprocals of evil numbers?
Comment: You asked a very similar question about $4$ hours earlier at [What is known about evil primes?](https://math.stackexchange.com/questions/3143620/what-is-known-about-evil-primes). A comment by Barry Cipra gave a link to MO [Odd-bit primes ratio](https://mathoverflow.net/questions/44561/odd-bit-primes-ratio) which was useful there, & could also be useful here for anybody reading this question. I believe the general policy on this site is you should try to avoid asking such similar questions or, at the least, provide a link if you do. Thanks.
Answer: For every $n$, one of $2n$ and $2n+1$ is evil and the other is odious.
So you can get upper and lower bounds of the sum of reciprocals of the evil numbers up to $N$ in terms of the sums of reciprocals of the even and odd numbers up to $N$, for which good asymptotics are known.


Use of partner for better jump smash in badminton

Question: Is it  allowed, in badminton (mix) doubles, to use your partner to gain more height in order to perform a jump smash for example?
Answer: Presumably you mean by, say lifting your partner in the air.
I don't think there's any rule which would ban this.
However, I doubt that it would be effective in practice as the game is so fast and you'd only know where the shuttle is going at the last second. Also, as there are only two of you on the court, you may struggle to lift your partner without dropping your racket.
Contrast this with a Rugby Lineout, where a lighter player may be surrounded by several stronger players with their hands free.
Comment: "[L]ifting your partner in the air like they do in volleyball" actually happens in volleyball?
Comment: I was wrong. It's illegal in volleyball, but allowed in Rugby - see edit.
Comment: I could be wrong. I don't know much about volleyball!


Legato and staccato in Mozart?

Question: I'm not sure what this means in Mozart's K 545 but it is that same movement in which the left hand is almost 100% Alberti bass, that is the second movement.
I see twice a passage of 8 16th notes marked with staccato and a slur. I have listened to it and I can hear a clear separation between notes in that passage just like I would with staccato. But I also see a legato marking(implicit in my case but I have seen it explicitly put in by editors) for the whole movement. In other words if I don't see a slur or a staccato, especially if it is in the left hand, it is still legato.
So what does this mean when I have a passage marked both legato and staccato? Does this mean that I should play legato but with clear separation like what I hear(so in other words smoothly transition from 1 staccato to the next)? Or does this mean portato or mezzo-staccato(which essentially is just nonlegato because that is what is in between legato and staccato)?
Answer: The slur in the notation you encountered does not mean legato it's a phrase mark. It's an indication of the composer or the editor that this set of notes should be played staccato but also as a significant whole, for example by varying the volume of the notes in the phrase or by playing (some of) the notes more tenuto.
In Romantic repertoire (where this kind of notation is more frequent) some interpreters use dabs of pedal and some even use the pedal over the whole passage making the staccato inaudible, while still keeping the idea of staccato. Ofcourse using the pedal this way is not the way to go in this Mozart.
In general I think it's clearer to think of a slur as a phrase mark and less of an indication of the articulation to be used, even in the case without the staccato dots. It makes you more creative when you are thinking more of the actual intention of the composer, even when in 95% of the time it means the use of legato.
Answer: From your description, these markings were almost certainly added by the editor of whatever edition you are using, and mean whatever the editor thought they meant. (Without knowing the editor and the date of the edition, guessing what he meant is just that - guessing).
When you listened to "it", of course you are just hearing what the performer did (and you didn't tell us whether that was someone with a good reputation as a Mozart interpreter, or "some random guy with a YouTube account," but either way it isn't a definitive guide to anything.
The best option is to look at what Mozart actually wrote, not what some editor thought he ought to have written (from the Neue Mozart-Ausgabe at https://imslp.org/wiki/Special:ImagefromIndex/456602/torat). The dotted slurs and notes in small type are editorial additions.

Note that Mozart (and his contemporaries like Haydn, and even early Beethoven) wrote two different marks for "staccato". The staccato dots mean the notes have about half the written duration, which some people might call "non legato" rather than "staccato" in a slow tempo. The dashes mean "play the note as short as you can". The slow movement of K545 contains both markings.
There is one feature of the original slur marks which isn't the obvious (or for "obvious" read "lazy"?) way to play it: the second beat of the bar is usually separated from the first beat by the slurs (e.g. in bar 2, 4, 5, 6, 8 etc).
Comment: In my opinion, one shouldn't play Mozart at a serious level without hearing and taking into consideration the capabilities of the pianos of Mozart's time.  (Recordings on instruments from the time, or modern replicas, are not too hard to find.)  They have (relative to their total volume) a stronger attack and faster decay than modern pianos, making it much easier to play non-legato.
Answer: Legato for the movement doesn't mean every single note has to be legato. It could mean that you might wish to play the staccato notes slightly less staccato than you would in a movement not marked legato. It's really up to you. I personally think that movement sounds better if the staccato notes are "mezzo-staccato." And most recordings of those notes are mezzo-staccato as well. I used to play that sonata, and sometimes I would do the staccato very soft and light and quick. Other times, I would play it only slightly less smoothly than the rest of the movement. Ultimately, you need to make the artistic choice for yourself.

Legato and staccato in Mozart?


Network issues kubernetes cluster

Question: I have a Kubernetes cluster of one master and three nodes inside a VPN, it shows ready status. It was built using kubeadm and flannel. The VPN network has the range 192.168.1.0/16.
$ kubectl get nodes -o wide
NAME        STATUS   ROLES    AGE    VERSION   INTERNAL-IP     EXTERNAL-IP   OS-IMAGE             KERNEL-VERSION      CONTAINER-RUNTIME
k8-master   Ready    master   144d   v1.17.0   192.168.1.132   <none>        Ubuntu 18.04.3 LTS   4.15.0-72-generic   docker://18.9.7
k8-n1       Ready    <none>   144d   v1.17.0   192.168.1.133   <none>        Ubuntu 18.04.3 LTS   4.15.0-72-generic   docker://18.9.7
k8-n2       Ready    <none>   144d   v1.17.0   192.168.1.134   <none>        Ubuntu 18.04.3 LTS   4.15.0-72-generic   docker://18.9.7
k8-n3       Ready    <none>   144d   v1.17.0   192.168.1.135   <none>        Ubuntu 18.04.3 LTS   4.15.0-72-generic   docker://18.9.7

I can reach the nodes.
$ ping 192.168.1.133
PING 192.168.1.133 (192.168.1.133) 56(84) bytes of data.
64 bytes from 192.168.1.133: icmp_seq=1 ttl=64 time=0.219 ms
64 bytes from 192.168.1.133: icmp_seq=2 ttl=64 time=0.246 ms
64 bytes from 192.168.1.133: icmp_seq=3 ttl=64 time=0.199 ms
64 bytes from 192.168.1.133: icmp_seq=4 ttl=64 time=0.209 ms
^X^C
--- 192.168.1.133 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3071ms
rtt min/avg/max/mdev = 0.199/0.218/0.246/0.020 ms

$ ping 192.168.1.134
PING 192.168.1.134 (192.168.1.134) 56(84) bytes of data.
64 bytes from 192.168.1.134: icmp_seq=1 ttl=64 time=0.288 ms
64 bytes from 192.168.1.134: icmp_seq=2 ttl=64 time=0.272 ms
64 bytes from 192.168.1.134: icmp_seq=3 ttl=64 time=0.268 ms
^C
--- 192.168.1.134 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2032ms
rtt min/avg/max/mdev = 0.268/0.276/0.288/0.008 ms

$ ping 192.168.1.135
PING 192.168.1.135 (192.168.1.135) 56(84) bytes of data.
64 bytes from 192.168.1.135: icmp_seq=1 ttl=64 time=0.278 ms
64 bytes from 192.168.1.135: icmp_seq=2 ttl=64 time=0.221 ms
64 bytes from 192.168.1.135: icmp_seq=3 ttl=64 time=0.181 ms
^C
--- 192.168.1.135 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2030ms

But I set a nginx 2 pods deployment to test if it worked
nginx-deployment-574b87c764-2gz8t   1/1     Running   0          25m     192.168.2.12   k8-n2   <none>           <none>
nginx-deployment-574b87c764-rst8x   1/1     Running   0          25m     192.168.1.17   k8-n1   <none>           <none>

$ kubectl get svc
NAME               TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
kubernetes         ClusterIP   10.96.0.1       <none>        443/TCP        3d17h
nginx-deployment   NodePort    10.96.211.211   <none>        80:31577/TCP   13s

And I can't connect to it.
$ curl k8-n1:31577
curl: (7) Failed to connect to k8-n1 port 31577: Connection refused
$ curl k8-n2:31577
curl: (7) Failed to connect to k8-n2 port 31577: Connection refused
$ curl k8-n3:31577
curl: (7) Failed to connect to k8-n3 port 31577: Connection refused
$ curl 10.96.211.211:80
curl: (7) Failed to connect to 10.96.211.211 port 80: Connection refused
$ curl 192.168.1.17:80
curl: (7) Failed to connect to 192.168.1.17 port 80: No route to host
$ curl 192.168.1.17:31577
curl: (7) Failed to connect to 192.168.1.17 port 31577: No route to host
$ curl 192.168.1.133:31577
curl: (7) Failed to connect to 192.168.1.133 port 31577: Connection refused
$ curl 192.168.1.133:6443
curl: (7) Failed to connect to 192.168.1.133 port 6443: Connection refused

I changed:
sudo kubeadm init --pod-network-cidr=192.168.1.0/16 --apiserver-advertise-address=192.168.1.132

And I changed flannel.yaml network to 192.168.1.0/16 with
kubectl edit cm -n kube-system kube-flannel-cfg

The core-dns pod description after restart:
  Normal   Scheduled  109s                default-scheduler  Successfully assigned kube-system/coredns-6955765f44-vwqgm to k8-n1
  Normal   Pulled     106s                kubelet, k8-n1     Container image "k8s.gcr.io/coredns:1.6.5" already present on machine
  Normal   Created    105s                kubelet, k8-n1     Created container coredns
  Normal   Started    105s                kubelet, k8-n1     Started container coredns
  Warning  Unhealthy  3s (x11 over 103s)  kubelet, k8-n1     Readiness probe failed: Get http://192.168.1.19:8181/ready: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)
  Warning  Unhealthy  1s (x5 over 41s)    kubelet, k8-n1     Liveness probe failed: Get http://192.168.1.19:8080/health: dial tcp 192.168.1.19:8080: connect: no route to host
  Normal   Killing    1s                  kubelet, k8-n1     Container coredns failed liveness probe, will be restarted

I would appreciate any help or ask for more information.
Comment: Yes, that was the solution I reset everything and connect it again with kubeadm init in another network and it solved. Sorry, I don't know the reason, I received that configuration. I don't know how to end the question or take yours as the good one, you were right.
Comment: I think you overlapped your pod ip addresses with the your node ip's. What was the reason behind changing the pod CIDR?
Comment: Great news, glad that I helped! I`ll place some short answer then.
Answer: While check the question I noticed that OP initialized cluster with CIDR 192.168.1.0/16 which overlapped with this node
IP addresses and then cause problem with coreDNS pods.
Initializing cluster with the new different CIDR solved the issue.

Network issues kubernetes cluster


VS2012 compiles to x86 with "Any CPU" in a x64 OS

Question: I have a solution with a C# project and a C DLL. The solution is set to "Mixed Platforms" and the C# project to "Any CPU".
When the DLL is set to compile for x64, I get a crash. But when the DLL is set to compile for x86, everything works fine.
The OS is Windows7 x64.
Environment.Is64BitProcess gives false no matter which I try.
My understanding is that "Any CPU" would compile to x64 by default since the OS is x64. Clearly, I am wrong.
Thank you guys.
Comment: This is a usability nightmare in Visual Studio, VS2010 really screwed this up.  The solution's Platform name is irrelevant to C# projects, it only matters to C++ projects.  There's only one setting you care about, right-click your *EXE Project*, Properties, Build tab, Platform target/Prefer 32-bit.  Set it both for the Debug and Release configurations.  You want x86 here to keep the C code happy.
Comment: Yes, the "Prefer 32-bit" flag was set. After messing around a bit with those options, I got it to work for x64 and Any CPU. Thanks.
Answer:
My understanding is that "Any CPU" would compile to x64 by default

Nope, it'll compile to "Any CPU". What it runs as depends on what machine is executing it. So if you are running it on a 64-bit CPU, then yes, it will run as 64-bit. However, from the crash, it sounds like your C dll is 32-bit, or you are using 32-bit API calls. In which case you will need to compile it for 32-bit. Note that in VS2013 there is also a "Prefer 32-bit" option for "Any CPU", which will run as 32-bit unless 32-bit simply isn't available. Most people want to turn this off ;p
Note also that if this is a library (from the dll tag), it will also depend on whether the process is 32-bit vs 64-bit.
Answer: First we should now what is  Platform target:
anycpu (default) compiles your assembly to run on any platform. Your application runs as a 64-bit process whenever possible and falls back to 32-bit when only that mode is available.
anycpu32bitpreferred compiles your assembly to run on any platform. Your application runs in 32-bit mode on systems that support both 64-bit and 32-bit applications. You can specify this option only for projects that target the .NET Framework 4.5.
ARM compiles your assembly to run on a computer that has an Advanced RISC Machine (ARM) processor.
x64 compiles your assembly to be run by the 64-bit common language runtime on a computer that supports the AMD64 or EM64T instruction set.
x86 compiles your assembly to be run by the 32-bit, x86-compatible common language runtime.
Itanium compiles your assembly to be run by the 64-bit common language runtime on a computer with an Itanium processor.
So anyCpu means run 32bit and 64bit depend on your cpu.I think your dll is 32bit so yo can use x86 or anycpu.


Giving default values for columns in join condition in oracle SQL Query

Question: I have 3 tables
users(userid,UserName)
1,Ram
2,Krishna
3,Madhu
4,Deepak

roles(roleid,roleName)
101,Agent
102,User
103,Manager

user_role_map(userId,roleId)
1,102
2,103
3,101

I need to get following details in my query. If there is no record in user_role_map for a user i need to get RoleName as NONE
UserID, UserName, RoleName
1,Ram,User
2,Krishna,Manager
4,Deepak,NONE

Below query is not returning UserID 4
SELECT  u.UserID
    ,   u.UserName
    ,   r.RoleName
FROM users u, roles r, user_role_map ur
WHERE u.UserID = ur.UserID
    AND r.roleid = ur.roleid

Comment: thats because UserId 4 not exists in user_role_map..
Comment: You should really state which database we are talking about
Answer: try this - not tested but it looks right to me
select
  u.UserID, u.UserName, IsNull(r.roleName, 'NONE')
from
  users u
  left join user_role_map ur on
    ur.UserId = u.UserId
  left join roles r on
    r.roleid=ur.roleid

Comment: I would recommend you familiarise yourself with the syntax of `JOIN` and `LEFT JOIN`.  Joins in the `WHERE` clause are old-fashioned.


How do I override the vocabulary template but only on a specific content type

Question: I have a vocabulary called "Sectors" and a content type called "News". Basically the vocab displays which sector the blog article is related to and links to the corresponding CMS page about that sector.
How do I customise the template that shows that vocabulary on my pages of that content type?
Many thanks.
Answer: I think you can make that with views :)
You have to create your views with the fields  you need. After that you will be able to theme them globally and locally.
check views's theme suggestion
i hope it helped you


Começar exibição da div pelo final do Scroll

Question: E ae pessoal, blz? Pessoal, parece até uma dúvida besta a priore, mas procurei e não encontrei algo relacionado, tenho uma div com listas dentro
etc...
li.intem3
li.intem2
li.intem1

Quando eu carrego a página, ele inicia a exibição pelo TOP da Div, e eu queria que ele iniciasse a exibição pelo BOTTOM, pronto, o chat do facebook, ele inicia a exibição das mensagens pelo final, aí a pessoa vai subindo o scroll pra ver as mais antigas, quero dessa forma vllw pessoal... E perdão pelas Tag's, Nn sei em qual isso se encaixa.
Comment: Cara nessa resposta tem alguns exemplos, inclusive acabei de colocar lá um que é feito apenas com CSS caso te interesse. Se resolver vc pode marcar como duplicada se for o caso... Se não for o que vc precisa é só dar mais detalhes.
Comment: Veja esse link aqui: https://stackoverflow.com/questions/270612/scroll-to-bottom-of-div ou esse:
https://stackoverflow.com/questions/11715646/scroll-automatically-to-the-bottom-of-the-page
Comment: O seu com Css era oq eu queria, mas da forma que colocou, Nn consegui encaixar em meu código
Comment: Cara te dei uma nova opção apenas com CSS diferente da da outra resposta. As vezes agora te atende...
Answer: Vou colocar aqui um exemplo usando Jquery e animação, que mostra o conteúdo "rolando" como se alguém estivesse mesmo rodando o scroll do mouse.
A mágica fica por parte do jquery, e a chamada é :
$('#divQueQueroScrollar').stop().animate({
  scrollTop: $('#divQueQueroScrollar')[0].scrollHeight
}, 1500);

O 1500 é a velocidade da animação, sendo em milissegundos, ou seja, um segundo e meio.
Segue o snippet executável para ver como fica:

$('#divQueQueroScrollar').stop().animate({
  scrollTop: $('#divQueQueroScrollar')[0].scrollHeight
}, 1500);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

Answer: Como vc falou que as outras resposta não te atenderam vou te dar uma outra opção apenas com CSS usando flexbox.
A técnica consiste em inverter a direção do conteúdo da div usando flex-direction: column-reverse então o conteúdo sempre começa embaixo e vai sendo empurrado pra cima.
Veja o exemplo para entender melhor:

.container {
  height: 100px;
  overflow: auto;
  display: flex;
  flex-direction: column-reverse;
  border: 1px solid;
}

 /* essa div na verdade começa de baixo pra cima */

Primeira mensagem

oi

oi

oi

oi

oi

oi

oi

oi

oi

oi

Última menssagem

OBS: Essa solução pode não ser totalmente crossbrowser, seria interessante vc testar no Safari, no IE não funciona...


How do I get index of an string array on php?

Question: Lets say I have an multidimensional string array:
.food = array(
            'vegetable' => array(
                               'carrot' => 'blablue',
                               'potato' => 'bluebla',
                               'cauliflower' => 'blabla'
                           ),
            'Fruit' => array(
                               'apple' => 'chicken65',
                               'orange' => 'salsafood',
                               'pear' => 'lokkulakka'
            )
);

is it possible to access the array by using index as numbers, instead of using the name of the key?
So for accessing chicken65 , I will type echo $food[1][0]; I don't want to use numbers as key, because its a big array and its more user-friendly if I use string as key and it will let me do for-loops on advanced level.
Comment: If you don't want to use the number as the key, why are you asking how to do that?
Comment: Why not use foreach, instead of a for loop.
Answer: You can do foreach loops to achieve much the same thing as a typical for-loop.
foreach ($foods as $key => $value) {
    //For the first iteration, $key will equal 'vegetable' and $value will be the array
}

Answer: $food[1][0] != $food[1]['apple'], so you cannot use numeric keys in this case.
Answer: try
$new_array = array_values($food);

however, variable can't start with .. It should start with $
Comment: array_values thats what i need :D
Comment: English isn't my native language
Answer: You can use array_keys() on the array. The resulting array can be traversed via a for-loop and gives you the associative key.
I will show it to you for the first dimension:
$aTest = array('lol' => 'lolval', 'rofl' => 'roflval');
$aKeys = array_keys($aTest);
$iCnt = count($aKeys);

for($i = 0; $i < $iCnt; ++$i)
{
  var_dump($aTest[$aKeys[$i]]);
}

You would need to do this for two dimensions but I would not recommend this. It is actually more obstrusive and slower than most other solutions.
Comment: _I_ would not do this, _I_ would use foreach. I think this solution comes closer to what the OP _asked for_ (no pun intended).
Comment: Why would you do this when you can simply use a foreach without it?
Answer: you may want to try the function array_values but since you are dealing with multidemsional arrays, here is a solution posted by a php programmer
http://www.php.net/manual/en/function.array-values.php#103905
but it would be easier to use foreach instead of for.
Comment: array_values thats what i need :D
Answer: I don't think there is something native to go this route.
And it does seem like you are trying to stretch array use a bit.
You should go OOP on this one.
Create a FoodFamilly object and a Food object in which you can store arrays if necessary and you'll be able to write a nice user-friendly code and add indices if needed.
OOP is almost always the answer :)


What tape backup device can read a DC 2120 XL cartridge?

Question: While preparing to move to a new house, I came across two forgotten tape backup mini cartridges from 1996. I know they hold the only backup I made of my original Remote Access BBS, with all my original Star Trek themed ANSI art, DOS/OS2 shareware, and 1000+ users.
I'd love to be able to resurrect this time-capsule, but what hardware device can actually read this?
I think I originally used a 50pin Wide-SCSI external backup, narrower & longer than an external CD-Rom drive (caddy-style). Backup restoration software I'm not worried about as I'm certain I can find something on Linux to suffice, I just need to find the hardware ;)
Here is the mystery cartridge in question:

The cartridge size is:

3 3/16"(w) x 2 3/8"(h) x 5/8"(d), or
8cm(w) x 6cm(h) x 1.5cm(d)

Thanks!
Comment: Can't be everything, it's also labeled "1/2". :)
Comment: Great labeling scheme! "everything"
Answer: That looks like a 1/4" QIC minicartridge. This particular form factor was apparently common in desktop computers.
Look for a QIC tape reader which was pulled out of somebody's desktop machine, and you may get lucky. I see several of them on eBay under $20.
Comment: Thanks for the lead, this sounds like what i'm looking for... Although you said "I see several of them on eBay under $20" would you mind posting a link? .. I don't see anything under $60, maybe I'm searching for the wrong term.
Comment: [1](http://www.ebay.com/itm/Iomega-640MB-QIC-Tape-Drive-IO3010-/200790632960) [2](http://www.ebay.com/itm/Colorado-250MB-QIC80-internal-tape-drive-/330763366279) Try searching for `QIC tape drive`.
Comment: Ah, there's different search results from your ebay.com and my ebay.ca :) .. thx!
Answer: I was also the "SysOp" of a dial-up BBS, and a member of the RelayNet International Message Exchange from 1970 until 1977. The "Colorado Jumbo 250" and the "Conner Micro 250" were two of the tape drives that could/can read and write to the DC2120 mini tape cartages that were manufactured by 3M, Maxwell, and possibly other companies. The Colorado Jumbo 250's made a unique whirring sound when accessing the tape that I found fascinating; I was disappointed when the Conner tape drive did not make the same sound. If you do a Google search for "dc2120 tape drive", you may find that there are still several available for under $100.00.


Como configurar o pygame em português?

Question: Estou fazendo um jogo com pygame. Eu quero mostrar um texto em português na tela, mas o mesmo troca "ç", "ã", "[", e "<" por "?" (ponto de interrogação).
import pygame
class TelaInicial():
    def __init__(self, logoTipo = None, lagura_do_logo_tipo = None, altura_do_logo_tipo = None, posicao_x_do_logo_tipo = None, posicao_y_do_logo_tipo = None):
        self.altura_do_logo_tipo = 350
        self.lagura_do_logo_tipo = 250
        self.posicao_x_do_logo_tipo = pygame.display.Info().current_w - 700
        self.posicao_y_do_logo_tipo = pygame.display.Info().current_h - 450
        self.logoTipo = pygame.transform.scale(pygame.image.load('./imagens/logo-tipo.png'), (self.lagura_do_logo_tipo, self.altura_do_logo_tipo))

    def logo_tipo(self, tela):
        tela.blit(self.logoTipo, (self.posicao_x_do_logo_tipo, self.posicao_y_do_logo_tipo))

    def aperteEspaco(self, tela):
        font = pygame.font.Font("./fonts/smbfont.ttf", 45)
        texto = font.render("APERTE ESPAÇO", True, (255, 255, 255))
        tela.blit(texto, (pygame.display.Info().current_w - 700, pygame.display.Info().current_h - 80))

    def background(self):
        pass

Comment: Coloque realmente o seu código e não um print do mesmo, explique melhor a sua pergunta já que ela esta muito ampla, e deixe explicito o ponto ao qual você teve dificuldade.
Answer: Se os símbolos aparecem como ? isso simplesmente significa que o arquivo de fontes que você está usando - smbfont.ttf não inclui esses símbolos  -e eles são substituídos por "?".
Esse é um problema muito comum com fontes de baixa qualidade, como as que eram distribuidas aos milhares em CD-ROMs em bancas de revista nas décadas de 90 e 2000.
Quando se usa uma fonte num aplicativo "normal" do sistema operacional, o próprio sistema se encarrega de fazer essa substituição, quando é assim. No Pygame, o controle é mais manual - tem-se que fazer tudo na mão. Infelizmente, a API que o Pygame apresenta não permite introspecção nas fontes carregadas para saber se um símbolo existe ou não.
Esse tipo de erro de acentuação e etc... é comum em aplicações que usam o terminal (cmd) no Windows, ou aplicações em Pygame usando Python 2, por conta de codificações de texto diferentes (ex. "utf-8", "CP1252", etc...) - mas em Python3, em que o texto do programa é todo tratado como Unicode, esse problema não existe mais - usando Pygame, se um caractere existe na fonte que você está usando, ele será desenhado corretamente.
Resumindo: o que vai arrumar a coisa pra você é usar uma fonte que inclua os caracteres acentuados e símbolos, além de só as letras maiúsculas. Eu recomendo que você olhe as fontes que o Google disponibiliza em https://fonts.google.com/ : são todas de uso permitido e de altíssima qualidade (só é um pouco chato navegar até conseguir baixar as mesmas como um arquivo TTF, mas é possível)
Answer: Tente especificar uma fonte, em vez da que você está usando (você está usando o padrão?) - é mais provável que seja um problema na fonte.
Palavras do autor original

Funcionou para mim com todas as fontes que eu tentei no meu sistema.

Para jogos completos, uma solução ideal é distribuir o arquivo de fonte ao lado do seu projeto - já que as fontes abertas do Pygame recebem o nome de arquivo ".ttf".
Para usar uma fonte do sistema, você tem que encadear chamadas pygame.font.get_fonts()  para obter nomes de fontes, para pygame.font.match_font para obter o caminho para o arquivo de fonte dado o nome da fonte e, finalmente, pygame.font. Fonte passando esse caminho e um tamanho de ponto para obter um objeto de fonte utilizável (com o método de renderização)
Fonte
Problemas semelhantes
Rendering unicode in pygame
Rendering unicode font with pygame
Comment: Obrigaod por citar minha resposta lá - mas infelizmente o problema aque é outro - o A.P. já não está usando a fonte original.
Answer: Olhei em um código que eu tenho e simplesmente adicionando no Unicode no início do código e iniciando a fonte ela apresenta os caracteres normalmente.
# -*- coding: UTF-8 -*-

#Init the font module
        pygame.font.init()
        #Instance of Font
        font = pygame.font.SysFont('Arial', 25)

Comment: Essa declaração não é necessária em Python 3. Mas ela nunca fez nenhuma mágica - ela só avisa o complador do Python sobre a codificação de acentuação usada no próprio arqiuvo em que ela aparece. Se estivesse faltando isso, (em Python 2), o autor do código teria tido um erro de sintaxe, não caracteres incorretos.

Como configurar o pygame em português?


How to fix: npm ERR! Cannot find module 'read-package-json'

Question: I made a horrible mistake and run this command:
sudo npm update -g npm

As a result npm was rendered useless, any attemps to install anything results in the following error :
npm ERR! Darwin 15.0.0
npm ERR! argv "/Users/michaelb/.nvm/versions/node/v5.3.0/bin/node" "/Users/michaelb/.nvm/versions/node/v5.3.0/bin/npm" "install"
npm ERR! node v5.3.0
npm ERR! npm  v3.7.4
npm ERR! code MODULE_NOT_FOUND

npm ERR! Cannot find module 'read-package-json'
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

Can anyone speculate what is the problem and how to fix it ?
Im using OS X El Capitan (10.11)
node -v
v5.3.0

npm -v
3.7.4

nvm ls
->       v5.3.0
default -> stable (-> v5.3.0)
node -> stable (-> v5.3.0) (default)
stable -> 5.3 (-> v5.3.0) (default)
iojs -> N/A (default)

Comment: Have you tried to run it with sudo?
Comment: yes, i get the same error using "sudo npm install"
Answer: Just found in their GitHub issues
Reference:

Solution: Reinstall npm
Comment: I ended up doing just that,
my npm was installed through nvm

mv ~/.nvm/ ~/.nvm-bkp;
nvm install 5.3.0
Answer: In my case, my node was installed by the .pkg file. And I reinstall npm didn't work.
I solved this problem by uninstall the node totally follow this gist:
https://gist.github.com/TonyMtz/d75101d9bdf764c890ef
Answer: All npm issues such as :

Error: Cannot find module 'interpret'
Error: Cannot find module 'read-pkg-up'
Error: Cannot find module 'lru-cache'

Solution

Delete file :

package-lock.json

Run in the terminal

$npm upgrade


How do I make this python command line an alias in bash?

Question: I want a quick an easy way to check my ip address after reading a recent question that had been answered on SO. For future reference, is there a way to make the following alias work?
alias myip='python -c "from urllib import urlopen; print urlopen("http://whatismyip.appjet.net").read()[:-1]"'

Answer: alias myip="python -c 'from urllib import urlopen; print urlopen(\"http://whatismyip.appjet.net\").read()[:-1]'"

You need to use single quotes inside the alias to stop bash trying to interpret parts of your code inside them. The escapes on the double quotes get stripped out while processing what the alias itself is.
Comment: Scratch that, monoxide got in first!
Answer: Quote the inside double-quotes:
alias myip='python -c "from urllib import urlopen; print urlopen(\"http://whatismyip.appjet.net\").read()[:-1]"'

Comment: You two answered at the same time, but kevinbutler has less rep. Answer goes to the little guy. Thanks to the both of you.
Answer: could also be done with curl:
alias myip='curl "http://whatismyip.appjet.net"'

or using wget:
alias myip='wget -O - "http://whatismyip.appjet.net" 2>/dev/null'


matrix trigger mode in extendedEmail - Jenkins job DSL

Question: I've a multi configuration project on Jenkins(ver. 2.222.1) We use JenkinsDSL(v1.77) to create the free-style jobs from the groovy scripts. Email notifications is with extendedEmail(v2.69)
It seems like trigger mode for notifications cannot be specified in the groovy script but it could be done via the UI as below(ONLY_PARENT or ONLY_CONFIGURATIONS or BOTH)
As I see here, below are the configurations we could specify for extendedEmail in groovy for DSL plugin
job('example') {
    publishers {
        extendedEmail {
            recipientList('firstname.lastname@example.com')
            defaultSubject('Oops')
            defaultContent('Something broken')
            contentType('text/html')
            triggers {
                beforeBuild()
                stillUnstable {
                    subject('Subject')
                    content('Body')
                    sendTo {
                        developers()
                        requester()
                        culprits()
                    }
                }
            }
        }
    }
}

It does not say anything in case of multi configuration project where I need the notifications to be sent only if parent job fails
I believe it exists on hipChatNotifier where we could specify as matrixTriggerMode

Is there a way to do this via extendedEmail publisher as we could do it on the UI?
Answer: Seems that this isn't supported by the Job DSL plugin, yet.
You can work around by using a custom configure block. For example
    publishers {
        extendedEmail {
...
        }
    }
configure { project -> project / 'publishers' / 'hudson.plugins.emailext.ExtendedEmailPublisher' << {
            matrixTriggerMode('ONLY_PARENT')
        }
    }

Note the << to append a node to the publisher configuration instead of overwriting it.


$h\mid (3a + 5b)$, prove $h\mid a$ and $h\mid b$

Question: I have this homework question.
"For any integer $a$ and $b$, prove that $\gcd(a,b) = \gcd(3a+5b,11a+18b)$."
I know that if $ g = \gcd(a,b)$
and
$h = \gcd(3a+5b,11a+18b)$
then
$g = h$
iff $g \leq h $ and $h \leq g$.
I successfully proved that $g \leq h$.
Now, to prove that $h \leq g$,
I need to prove that $h\mid (a,b)$, but I can't seem to find how I should prove this.
$\because h = gcd(3a+5b,11a+18b) \Rightarrow h \mid (3a+5b)$
From here I'm stuck on how to get $a$ and $b$ seperate.
Any hint would be very helpful.
Edit:
Since this question was marked duplicate and I was given these 1,2,3 links to check, I did check them and didn't find my answer because all of these questions have given that $gcd = 1$, whereas my question doesn't tell if $gcd = 1$ and furthermore these questions are a bit complex for me to understand since I'm a new learner of number theory.
Comment: See also [here](https://math.stackexchange.com/q/1159468/242) and [here.](https://math.stackexchange.com/questions/1987689/show-that-gcd3k2-5k3-1/1987826#1987826)
Comment: I edited my question after checking other answers and they didn't give me my answer.
Comment: You question is a special case of the linked dupesince  $\,5\cdot 11-3\cdot 18 = 1$. Most of the ideas in the other linked answers will also work here even though they deal only with the coprime case. Indeed, we can reduce to the coprime case by cancelling the gcd from both sides.
Answer: Since $$ h\mid 3a+5b\;\;\;{\rm and} \;\;\;h\mid 11a+18b$$ we have $$h\mid 4(3a+5b)-(11a+18b)= a+2b$$
Now $$h\mid 3(a+2b)-(3a+5b)=b$$
so $$h\mid (a+b)-2b = a$$
so $h\mid \gcd(a,b)$.


regex search von Bibtex file to extract cite key and title in capture groups

Question: The problem I have is that i would like to extract only the cite key and the Title of an Bibtex library file using capture group.
My Data file looks like this.
@article{Wang2017,
author = {Wang, Yunsen and Kogan, Alexander},
file = {:/2017/2017{_}Designing Privacy-Preserving Blockchain based Accounting Information Systems.pdf:pdf},
keywords = {accounting information systems,blockchain,continuous auditing},
title = {{Designing Privacy-Preserving Blockchain based Accounting Information Systems}},
year = {2017}
}
For the extraction of the cite key I used the following regex:
@\w+{([\w:-]+)
For the extraction of the title I used the following regex:
title = {{(.*?)}}
Both work. But I'm not able to combine both into one regex command so that cite key is capture group 1 and title is capture group 2
You can find the example file and the already used regex command using the following link.
https://regex101.com/r/v4cIe6/1
My expected result would be one command to extract cite key and title at once and have it in different capture groups.
Answer: If a negative lookahead is supported, you could repeat all the lines that do not start with title. If the line does, match it followed by space, =, space and {{ and capture the title in capturing group 2
@\w+{([\w:-]+).*(?:\r?\n(?!title\b).*)*\ntitle = {{(.*?)}}

Explanation

@\w+{([\w:-]+) The pattern to match the cite key
.* Match any char except a newline non greedy
(?: Non capturing group

\r?\n(?!title\b).* Match a newline asserting the string does not start with title

)* Close Non capturing group and repeat 0+ times
\r?\ntitle = Match a newline, then title =
{{(.*?)}} The pattern to match the title, capture in group 2 matching between {{ and }}

Regex demo


Efficiently converting data.table columns from numerical to character

Question: I'm looking through some legacy R code, which loads a text file into an R data.table, and then converts the column type from type numeric to character.
Here is how the author did this:
library(data.table)
dtable = read.table("path/filename.txt",header=TRUE,sep="\t",check.names=FALSE)

for(i in c(1,2,3,8:18))
{
dtable[,i] <- as.character(as.vector(dtable[,i]))
}

This looks highly inefficient for the data.table package, as we are using a for loop.
What is the most efficient "data.table" way to convert the data type several columns in this fashion, without a for-loop?
Comment: set(dtable, j = i, value = as.character(dtable[[i]])) inside the loop should make it efficient. Alternatively, use lapply(.SD, as.character) together with .SDcols. The person who wrote that legacy code didn't really know what they were doing. They didn't even know the basics of subsetting such as [[.
Comment: Use colClasses when reading in
Answer: You don't need a loop. Here is an example
data <- mtcars
str(data)
library(data.table)
id.col <- c(1,2,3,8:11)
setDT(data)[, (id.col) := lapply(.SD, as.character), .SDcols = id.col]
str(data)

Comment: Why would you need `str(data)` given `lapply(.SD, as.character), .SDcols = id.col`?
Comment: I used `str(data)` just to see the number of variables to set `id.col` well.
Comment: Ah, I understand now


Xenserver 6.5 Passtrough from HASP [USB] to Windows Server 8 SP2

Question: Due to an accidental update on VM with Windows Server 2008 SP2, the HASP USB key is no longer recognised. The key works on my laptop, so it looks fine. I have a pool of VMs built on XenServer 6.5. The Windows Server sits on one of the nodes. So I need to make a pass through for a specific USB port on a specific VM. Since the HASP key is not a storage device, I am not sure if  method described here really works, plus the version of Xen is a bit different:
https://discussions.citrix.com/topic/351605-xenserver-62-passtrough-from-usb-to-windows-7-vm/
Also, typing lspci | grep USB on XenServer command line, does not give me the device. How can I list connected devices from all the VMs USB ports, not just the one where Xen is installed?
Basically, the question is, how to make the HASP key visible to the mentioned VM?
Answer: My customers mostly use USB over IP device for such need. Like; https://www.digi.com/products/usb-and-serial-connectivity/usb-over-ip-hubs/anywhereusb
It work for dongle. It's especially good if you have more than one host, as even in HA or load balancing mode the VM will always be able to read the dongle.
Answer: Thanks for an offer. I managed to resolve the issue by following this guide
https://email@example.com/%D0%BF%D1%80%D0%BE%D0%B1%D1%80%D0%BE%D1%81-usb-%D1%83%D1%81%D1%82%D1%80%D0%BE%D0%B9%D1%81%D1%82%D0%B2-%D0%B2-xenserver-50a9b4e8a80a
Basically, you can follow the commands on XenServer:
lspci | grep USB

you get a list of USB controllers with their IDs like 00:1d.0
then you check which of the controllers are used for the dongle by:
lsusb

note, that you might need to install the usb utilities, by:
yum install --enablerepo=base usbutils

after that list the virtual machines, where test is the name of the machine
xe vm-list name-label=test

this will show you the uuid of the machine. then use all info to pass it through
xe vm-param-set other-config:pci=0/000:00:1d.0 uuid=cd9c4255-d28a-c086–113c-c1716293449d

thats all. you can check if its successful by
xe vm-param-list uuid=cd9c4255-d28a-c086–113c-c1716293449d | grep other-config


Showing that, for all polynomial $p(x)$ with $\deg(p)>1$ the series $\sum 1/p(n)$ converges.

Question: How can I show that, for all polynomial $p(x)$ with $\deg(p)>1$, the series $\sum 1/p(n)$ converges? I tried comparison, but it works only for polynomials in $\mathbb{N}[x]$.
Comment: Of course, you are making the assumption that the denominator never gets zero for any $n$...
Answer: Let $\deg p = \alpha$. There exists an $N,C>0$ such that for all $n\geq N$, $p(n) \geq Cn^\alpha$. (If this is not obvious, try to prove it for yourself!) Then try the comparison test again.
Comment: Okay, it works! Thanks.


Find all points where $f(x)$ is continuous

Question: Let $f:\mathbb{R} \rightarrow \mathbb{R}$ a function. If $x$ is irrational $f(x)=0$, otherwise if $x=\frac{p}{q}$ ($p$,$q$ are integers, $q>0$ and $\gcd(p,q)=1$) then $f(x)=\frac{1}{q}$. Find all points where $f(x)$ is continuous.
Comment: Possible duplicate of [Proof of continuity of Thomae Function at irrationals.](https://math.stackexchange.com/questions/530097/proof-of-continuity-of-thomae-function-at-irrationals)
Comment: If $x_0$ is irrational and $\epsilon>0$ then there are only finitely many $q$ such that $1/q>\epsilon$. Therefore in a small neighborhood around $x_0$ we have $0\leq f(x)<\epsilon$. So, it is continuous at irrationals $x_0$. If $x_0$ is rational then $f(x_0)=1/q>0$ for some $q$. If $\epsilon = 1/(2q)$ then there are irrationals $x$ arbitrarily close to $x_0$ and we would have $|f(x_0)-f(x)|=1/q>1/(2q)$. Therefore it is discontinuous at $x_0$ rational.
Comment: It is the very standard result. It is continuous on every irrational points. Proof is found in elementary real analysis books.
Comment: See also: https://math.stackexchange.com/questions/2128197/prob-18-chap-4-in-baby-rudin-fx-0-for-x-irrational-and-fx-1-n-for
Answer: If $x\in\mathbb Q$, then $f(x)>0$. But any interval $(x-\varepsilon,x+\varepsilon)$ contains irrational points and at those points the value of $f$ is $0$. Therefore, $f$ is not continuous at $x$.
On the other hand, is $x\in\mathbb{R}\setminus\mathbb{Q}$, then $f(x)=0$. Take $\varepsilon>0$. The open interval of length $1$ centered at $x$ contains only finitely many numbers $y$ such that $f(y)\geqslant\varepsilon$. Pick $\delta>0$ such that $(x-\delta,x+\delta)$ contains no such point. Then$$|y-x|<\delta\Longrightarrow\bigl|f(y)-f(x)\bigr|<\varepsilon.$$
Comment: why does the first statement prove that f(x) is discontinuous at x?
Comment: @Hugh If $f$ was continuous at $x$, then, since $f(x)\neq0$, there would be a $\varepsilon>0$ such that $|y-x|<\varepsilon\implies\bigl|f(y)-f(x)\bigr|<\bigl|f(x)\bigr|\implies f(y)\neq0$.
Comment: I am not good at these topics but I found them interesting. So I guess what you stated above is the definition of what a continuous function is?
Comment: @Hugh Almost. A function $f$ is continuous at $a$ if, for every $\varepsilon>0$, there is a $\delta>0$ such that $|x-a|<\delta\implies\bigl|f(x)-f(a)\bigr|<\varepsilon$.
Comment: I understand that. But above when you say f(y) is not equal to zero implying that the function is not continuous. Why is that? Thank you!
Comment: @Hugh That's what my answer to your first comment was about.
Answer: Let $\theta \in \mathbb{R} \setminus \mathbb{Q} $. Given $\epsilon > 0
$  choose $ \frac{1}{N_{\epsilon}} < \epsilon$
Note that $ {N_{\epsilon}}$ is being a finite number, the number of rationals of the form $\frac{1}{q} > \frac{1}{{N_{\epsilon}}} $is finite.
Congest  interval $(\theta−1,\theta+1)$ down to $ (\theta−q,\theta+q)$ such that all these $1/q$ are tossed out, leaving only rationals $\frac{1}{q} < \frac{1}{{N_{\epsilon}}} < \epsilon$.
It follows that if $|x -b| < \delta$ then $ |f(x) - f(b) | = |f(x)| \leq \frac{1}{{N_{\epsilon}}} < \epsilon$.


Application Pool in TomCat?

Question: IIS has concept of "Application Pool" which can isolate the applications to a specific pool. Does  Tomcat have the similiar one?
Answer: If I understand the IIS concept correctly then all Tomcat applications effectively run in their own application pool and cannot access other applications.

Application Pool in TomCat?


How to generate a random number/String based on a pattern in java?

Question: I want to generate a random number based on a pattern like:
random.int= pattern="[0-9]{%len%}"
random.big_integer= pattern="[0-9]{%len%}"
random.long= pattern="[0-9]{%len%}"
random.string= pattern="[A-Z][a-z]{0,%len%}"
random.char= pattern="[A-Z]{1}"
random.byte= pattern="[A-Z][0-9]{1}"
random.short= pattern="[0-9]{%len%}"
random.float= pattern="[0-9]{%len%}\\.[0-9]{%scl%}"
random.double= pattern="[0-9]{%len%}\\.[0-9]{%scl%}"
random.big_decimal= pattern="[0-9]{%len%}\\.[0-9]{%scl%}"

So, my inputs will be "len","scl" and the datatype. And based on these inputs,
I will have to read the corresponding pattern and generate the output. This output should
be random for every call during a single run. Output should be same if I rerun the program.
What is the best approach I can take to achieve this in JAVA ?
For example, if I call generateRandomOutput("float",5,2) [datatype,length,scale] my output
should have a random float number like for example: 21453.67 (This is based on the pattern "random.float" described above)
Comment: Step 1. Post code that shows your efforts so far. The question with no code to back it is not clear enough.
Comment: Giving a concrete example of input and output would go a long way.
Comment: Hi Marko, I am working on the best approach to this problem, like what kind of library can I use to achieve this. so, haven't started on the code yet...
Comment: Nothing in your questions sounds like it will need a library, all the ingredients are in the JDK. But I don't understand your problem fully.
Comment: Basically i need to generate a random String/number based on the datatype,length and scale passed... I am having the patterns customizable because I can add custom datatypes...
Comment: For example, if I call generateRandomOutput("float",5,2) [datatype,length,scale] my output should have a random float number like for example: 21453.67 (This is based on the pattern "random.float" described above)
Comment: If you do not share a single line of code... what do you expect... ? You generate random numbers with Math.random() and then interpret them as you wish...
Answer: Putting it simply, it is a change of base. You can generate a random char by getting a Math.random and multiplying by 26, the result tells you the position of the random letter in your alphabet([A-Z]).
Getting a String with two random characters needs you multiplying by 26^2 and changing the number to base 26(or alternatively, getting a random number multiplied by 26 two times).
Comment: Then ** PROGRAM IT ** We are not here to do your job. I helped with some pointers in case you do not need where to start the program that ** YOU ** need. If you have a specific issue you will get a specific answer. If you have a vague, generic question you will get a vague, generic answer. If you just want the code, don't bother asking here.
Comment: Hmm but how do I generate it based on the pattern?
Comment: `if (pattern.equals("char")) then ....`. If you use Java 7 I believe you can use switch with strings, too :-D.
Comment: but i need a generic parsing technique which can decode any pattern ...
Comment: i was just asking for an idea or an approach to start with.. like is there any readymade API availabe to do this ? Anyways thanks for your help ..
Answer: Try out QuickCheck
It provides great primitive generators for you.
Answer: First, you need a random number generator that you can "seed", so you can supply the same seed each run so that runs are reproducible.  You can seed java.util.Random.
Next, I'd suggest you write a standard routine that, given a length and an alphabet, will supply a string of that many random characters.  Then write routines for each of your data types to call the common routine to get the character strings, and convert them into the desired type.
The standard routine is fairly simple:

Receive length and alphabet parms.
Get the next random integer from your RNG.
Take the random integer and calculate the modulus of the length of the alphabet.
Use the modulus to select the next character from your alphabet -- shove that into the result string.
Repeat until you've accumulated the specified number of characters.

In the type-specific routines you call the above common function with the proper parms (twice, with inserted ".", for float/double/big decimal), then use Datatype.getDatatype (substituting the appropriate data type name) to convert the resulting string to the proper type.  The type-specific routines are thus mostly "boilerplate".
The "alphabet" passed to the common routine is "0123456789" the numeric types, "ABCD..WXYZ" for your "char" type, "ABCD..WXYZ0123..789" for your "byte" type (or did you intend for it to be "0123456789ABCDEF"?).
Comment: Actually I came across this API and looks to do exactly what I need ... http://code.google.com/p/xeger/
Answer: it's not possible to determine all the possible strings which conform to a regular expression, only some simple regular expression such as you have. As such I doubt there is a library which will help you.
I suggest you use a simpler format of your own such as A => A-Z, a => a-z, d => 0-9, nnn as repeat and any other character as itself.
e.f. instead of
random.byte= pattern="[A-Z][0-9]{1}"

I would have
random.byte.pattern=Ad

which would be much simpler to parse.
Answer:
Output should be same if I rerun the program.

Doesn't sound like you actually want it to be random?
Look at one way hashing functions like MD5, SHA, etc.


How to make a block visible only to one page

Question: I have made a custom block and i want to make it visible only to pages that follow this pattern: user/[user-id]/galleries.
Is there a way to do it?
Answer: There are Visibility settings for blocks in Drupal. One of options is "Show block on specific pages". Select "Only the listed pages" and input user/*/galleries
Comment: Good point. No need to use PHP.
Answer: In the Page specific visibility settings, select Show if the following PHP code returns TRUE (PHP-mode, experts only) and enter
return arg(0) === 'user'
    && is_numeric(arg(1))
    && arg(2) === 'galleries'
    && arg(3) === null;

in the Pages text input field. Skip the && arg(3) === null part if you also want to display the block on pages further down in the hierarchy (e.g. on user/[user-id]/galleries/private).
Comment: Although not the best answer for *this* situation, this is actually a very good tip. Thanks friend!


How to create a filter in views which only shows contents that current user can edit?

Question: I set content access permission using nodeaccess_userreference module, I need a view to shows contents that user can change.
Answer: It's probably not a very well-elaborated patch/module but it might solve your problem: https://www.drupal.org/node/620392 I've just found it...


How do I preserve the order of associations in Rails3?

Question: I have an array of locations
locations = ["california", "new york", "florida"]

I have a model called foobar that has_many :places.
the Place model belongs_to :foobar and has one relevant column - name:string.
I have a nested form that allows me to select locations applicable for the foobar.
To offer the options, I build the places based on my locations list in my controller:
class FoobarController < ApplicationController
  def edit
    @foobar = Foobar.find(params[:id])
    APP_CONFIG['locations'].each do |location|
       @foobar.places.find_by_name(location) || @foobar.places.build(:name => location)
    end
  end
end

This works almost without a problem. The reason I'm including the edit method is because that's the problematic one. The list of places DOES get populated, but the Foobar places that already existed appear on the top.

Example time! :)

I create a new Foobar. In my form
I scroll down to places and I see
the options "california", "new york"
and "florida". I check "california"
and "florida" and create Foobar.
Next I go to edit Foobar. Again, I
scroll down to the places and I see
that I checked two options. That's
great, except that the order in
which the options appear is
"california", "florida", "new york" - checked places are on the top.

How can I preserve the order of the locations from my original array?
Thanks!

Update: the view code:
<%= f.fields_for :places do |place| %>

        <%= place.hidden_field :name %>
        <%= place.check_box :checked %>
        <%= place.label :checked, place.object.name %>

<% end %>

Answer: You can't... At least not the way you are doing it. Think about what rails does. It automatically orders by the id (PK) column of a table. Since the records you are BUILDING wont have an id, they will be placed at the end - every time. You COULD finagle and use CREATE and fudge ids, but that's messy and could run into serious problems.
In order to maintain order (pun), you'll need some kind of array-pointer system:
class FoobarController < ApplicationController
  def edit
    @foobar = Foobar.find(params[:id])
    @places = Array.new
    APP_CONFIG['locations'].each do |location|
      @places << @foobar.places.build(:name => location)
    end
  end
end

Then, in your view you'll need to loop over the array and manually build the form. I recommend viewing the source and seeing how the nested form appears first.
Here's how I would approach it - build every time (no find_by_name). Then, in your model you want:
class Foo < ActiveRecord
  has_many :places

  accepts_nested_attributes_for :places, :reject_if => { |a| !APP_CONFIG['locations'].include?(a) || Place.find_by_name(a).nil? || !Place.find_by_name_and_foo_id(a, self.id).nil? }
end

Now, I haven't actually tested that code exactly for your case, so I'll break it down;
1.) Reject if the submitted attribute isn't in the global array (more of a security concern)
2.) Reject if the name isn't a valid place (again, security)
3.) Reject if the place ALREADY exists for that foo (your class that has_many :places)
Comment: inconvenient, but it works. You mentioned "at least not the way [I am] doing it." Am I going about doing something wrong in the first place? Thanks!!
Answer: Check out acts_as_list >> https://github.com/rails/acts_as_list,  It explicitly stores the order of items in a has_many collection in a column called "position".


Marshal.StructureToPtr throws "Typelib export: Type library in not registered" exception when executed

Question: Plugin Data is defined as:
[StructLayout(LayoutKind.Sequential)]
public struct PLUGIN_DATA
{
    public int paramterDataLength;
    public PLUGIN_PARAMETER_DATA[] pluginParameterData;
}

[StructLayout(LayoutKind.Sequential)]
public struct PLUGIN_PARAMETER_DATA
{
    public string version;
    public string name;
    public string data;
}

WindowHelper.PLUGIN_DATA pluginData = new WindowHelper.PLUGIN_DATA()
      {
          ParameterDataLength = 3,
          PluginParameterData = new[]
          {
              new WindowHelper.PLUGIN_PARAMETER_DATA { Name = "StartingPlugin", Version = "1", Data = "BD9B5012-4B81-4DBA-876E-DD6829208F3A" },
              new WindowHelper.PLUGIN_PARAMETER_DATA { Name = "StartingPluginParameter", Version = "1", Data = "{ \"parameterModelVersion\":1,\"parameterModelJson\":\"{\"parameterData\":{\"star-rating\":5}}\"}"},
              new WindowHelper.PLUGIN_PARAMETER_DATA { Name = "StartingPluginPriority", Version = "1", Data = "1" }
          }
      };

var pluginDataSize = Marshal.SizeOf(pluginData);
pluginDataBuff = Marshal.AllocHGlobal(pluginDataSize);

When I execute the following line:
Marshal.StructureToPtr(pluginData, pluginDataBuff, false);

I get the exception

Typelib export: Type library is not registered (Ox80131165)

and the ex.Source is System.Private.CoreLib
Any help with how to remedy this exception is very much appreciated.
public static int SendMessageToWindow(IntPtr hWnd, uint wParam, PLUGIN_DATA pluginData, bool throwExceptions = false)
{
    var result = 0;
    var copyData = new COPYDATASTRUCT();
    var copyDataBuff = IntPtr.Zero;
    var pluginDataBuff = IntPtr.Zero;

    try
    {
        var pluginDataSize = Marshal.SizeOf(pluginData);
        pluginDataBuff = Marshal.AllocHGlobal(pluginDataSize);
        Marshal.StructureToPtr(pluginData, pluginDataBuff, false);

Comment: This issue happens when the structure being dealt with itself contains a structure.  The PLUGIN_DATA structure above contains a member, pluginParameterData, that is an array of PLUGIN_PARAMETER_DATA structures.  If I don't initialize pluginParameterData, then Marshal.StructureToPtr will work with no issues.  I will post the fix for this issue when I verify it.
Comment: Maybe include the full call stack when you get this?
Comment: call stack is: System.StubHelpers.MngdSafeArrayMarshaler.ConvertSpaceToNative(IntPtr pMarshalState, Object& pManagedHome, IntPtr pNativeHome)
--- End of stack trace from previous location ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.InteropServices.Marshal.StructureToPtr(Object structure, IntPtr ptr, Boolean fDeleteOld)
   at Dell.Client.Framework.UX.WPF.WindowHelper.SendMessageToWindow(IntPtr hWnd, UInt32 wParam, PLUGIN_DATA pluginData, Boolean throwExceptions) in D:\DUCA294EV1.1\src\Dell.Client.Framework.UX.WPF\WindowHelper.cs:line 512
Comment: Line 512 is the call to  Marshal.StructureToPtr(pluginData, pluginDataBuff, false);
Answer: When dealing with nested structures (structures that contain structures), the PLUGIN_DATA structure detailed above contains a member public PLUGIN_PARAMETER_DATA[] pluginParameterData; which is a variable length array.
Marshal is not able to deal with a variable length array. I was able to better deal with this by not using the PLUGIN_DATA structure at all, and just creating an array of PLUGIN_PARAMETER_DATA. NOTE that the PLUGIN_PARAMETER_DATA structure contains three variable length strings.  I was only able to deal with these strings if I declared a MarshalAs with a SizeConst value ... i.e. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 50)] . I tried other notations but they did not provide a successful outcome.
I did find the URL https://www.pinvoke.net/default.aspx/Structures/COPYDATASTRUCT.html quite useful.  Hopefully others will as well.


SendGrid setup trouble

Question: I just got my SendGrid account provisioned and the zip file uploaded to my server and now I'm trying to integrate it with my Zend Framework project. I tried to integrate slowly so I would only get a few errors at a time, starting off with just creating an email before trying to send it. This is all I have so far:
require_once(BASE_PATH . "/library/sendgrid-php/SendGrid.php");
require_once(BASE_PATH . "/library/sendgrid-php/SendGrid_loader.php");
$sendgrid = new SendGrid($username, $password);
        $mail = new SendGrid/Mail();
        $mail->addTo($email)
             ->setSubject('Subject')
             ->setText('');
        //$sendgrid->smtp->send($mail);

By the way, the first require is in there because SendGrid loader threw an error because it couldn't find SendGrid.php. Anyway, just these few lines of code produce all of these errors:
Warning: Missing argument 1 for SendGrid::__construct(), called in
...InviteController.php on line 51 and defined in
...library/sendgrid-php/SendGrid.php on line 13

Warning: Missing argument 2 for SendGrid::__construct(), called in
...InviteController.php on line 51 and defined in
...library/sendgrid-php/SendGrid.php on line 13

Warning: mail() expects at least 3 parameters, 0 given in
...InviteController.php on line 51

Warning: Division by zero in ...InviteController.php on line 51

Fatal error: Call to a member function addTo() on a non-object in
...InviteController.php on line 52

SendGrid's own guide, http://docs.sendgrid.com/documentation/get-started/integrate/examples/php-email-example-using-smtp/, basically just says upload the files to your server and include the loader and you're ready to go. I absolutely do not understand why I would be getting all of these errors. Did I miss a step in setting it up or something?
Comment: What version of PHP are you using? The \ is a namespace separator which means SendGrid requires 5.3.
Comment: `new SendGrid/Mail();` should be `new SendGrid\Mail();`, not sure if that was just a typo in your question
Comment: With the backslash I get an unexpected input and parse errors. That did clear up the rest of them, but probably because it's just not making it past the parse error to actually execute.
Comment: 5.2.17 apparently. I'll bet that's the entire problem.
Answer: It was just an outdated version of PHP. Sendgrid requires at least 5.3 for its namespace feature (the slash in the class name), to work correctly. My code couldn't evaluate the namespace and so it couldn't find the class it needed.

SendGrid setup trouble


Derivation of $\frac{\sum (x - \bar{x})^2}{N} = \frac{\sum x^2 - \frac{(\sum x)^2}{N}}{N}$

Question: I saw the above equation in an introductory statistics textbook, as a shortcut for evaluating the variance of a population.
I tried to prove it myself:

$$\sigma^2 = \frac{\sum (x - \bar{x})^2}{N} \tag{1}$$
$$\sigma^2 = \frac{\sum x^2 - \frac{(\sum x)^2}{N}}{N} \tag{2}$$
We are given that $(1) = (2)$:
$$\frac{\sum (x - \bar{x})^2}{N} = \frac{\sum x^2 - \frac{(\sum x)^2}{N}}{N} \tag{3}$$
Multiply $(3)$ through by $N$:
$$\sum(x - \bar{x})^2 = \sum x^2 - \frac{(\sum x)^2}{N} \tag{4}$$
Expand the LHS in $(4)$:
$$\sum\left(x^2 - 2x\bar{x} + \bar{x}^2\right) = {\sum x^2 - \frac{(\sum x)^2}{N}} \tag{5}$$
Expanding both sides in $(5)$:
$$\sum x^2 - 2x\sum\bar{x} + \sum\bar{x}^2 = \sum x^2 - \frac{\sum x\sum x}{N} \tag{6}$$
From $(6)$:
$$\sum\bar{x}^2 - 2\bar{x}\sum{x} = -\bar{x}\sum{x} \tag{7}$$
From $(7)$:
$$\sum\bar{x}^2 = \bar{x}\sum{x} \tag{8}$$
I don't know how to make the LHS equal RHS in $(8)$.
Comment: A clear way to write the expression in the question might be $\dfrac{\sum x^2 }{N} -\bar{x}^2$, asking why this is equal to $ \dfrac{\sum (x-\bar{x})^2}{N}$
Comment: I'll edit the question then.
Answer: First of all, in order to prove $A = B$ in general, start with either A or B, and show that it equals the other. Working with both of them together, is not the "proper" way of proving something, since in each step you are already assuming that they are equal.
Regardless, note that $\sum \bar{x}^2$ = $N\bar{x}^2$. This is because $\bar{x}^2$ doesn't depend on the index. That is,
$$\sum \bar{x}^2 = \sum_{i=1}^{N} \bar{x}^2  = \bar{x}^2 \sum_{i}^{N} 1 = N\bar{x}^2\,.$$
So now in (8)
\begin{align*}
\sum \bar{x}^2 & = N\bar{x}^2\\
& = N \bar{x} \bar{x}\\
& = N\bar{x} \sum \dfrac{x}{N}\\
& = \bar{x} \sum x\,.
\end{align*}
Thus the LHS and RHS of (8) are equal.
Answer: Starting from what you know:
$\sigma^2 =\dfrac{\sum (x - \bar{x})^2}{N} $
$= \dfrac{ \sum\left(x^2 - 2x\bar{x} +\bar{x}^2 \right)}{N}$
$= \dfrac{\sum x^2}N  - \dfrac{2\sum x\bar{x}}N  +\dfrac{\sum\bar{x}^2}N  $
$=\dfrac{\sum x^2}N - 2\bar{x}\dfrac{\sum x}{N} + \bar{x}^2 $
$=\dfrac{\sum x^2}N - {2\bar{x}^2} + \bar{x}^2 $
$= \dfrac{\sum x^2}N - {\bar{x}^2} $
$= \dfrac{\sum x^2}N - \dfrac {\sum{\bar{x}^2}}N $
$= \dfrac{\sum (x^2 - \bar{x}^2) }N $


How to set up this view of commerce orders...?

Question: Really hope someone can help me with this as am completely stuck, sorry it's a bit long but I don't know what else to do...
I'm working on a commerce site for a client that offers blocks of pilates classes. Users will purchase blocks of 6 classes in order to book onto them.
I have one product in the store called 'standard-6-block' at a price of £45.
I then have a product display called 'Class (Block)'.
The Class (Block) nodes will list 6 dates using just a text field with an unlimited number allowed (although each block will just have 6 classes added)
Blocks of classes run for 6 weeks, hence the 6 dates in each node, and will be added every week.
For example there may be one Class (Block) node with 11/01/2017, 18/01/2017, 25/01/2017, 1/02/2017, 8/02/2017, 15/02/2017 dates.
There will then be another node added a week later with 18/01/2017, 25/01/2017, 1/02/2017, 8/02/2017, 15/02/2017, 22/02/2017 dates.
This is because users may start blocks of classes at different times so we've agreed blocks will be added each week.
I now need my client to be able to run reports using a views page to show who has booked on to each class. (Not each block of classes (node) but individual classes in blocks (dates in the 'Class Dates' field in the node).
I've created one test order in my store which has purchased just one block of classes. There are currently 4 blocks of classes available to purchase on the website.
My view settings are:
View of: Commerce Orders
Relationships:
Commerce Order: Line items, (Line items referenced by commerce_line_items) Commerce Line item: Product, Commerce Order: Owner, (Products referenced by commerce_product) Commerce Product: Referencing Node, Commerce Order: Payment Transaction
Filters:
(Node referencing products from field_product_type) Content: Class Dates (exposed) and is REQUIRED!
Now when I run the report and enter a date for example 18/01/2017, the view doesn't just show the ONE order in the store IE this user has registered and paid for this class, it shows all 4 of the nodes that have been added.
Really hope that makes sense...? Thank you so much for taking the time to help me
Answer: Turns out I need to make every block of classes individual products in the store and use 'Auto product display' module to automatically create the node displays.  Then have to create a view that lists the commerce products rather than node displays


How can import a database which is not exist yet in bash shell?

Question: Export database named english in bash command:
pg_dump --no-owner --dbname=postgresql://postgres:password@localhost/english  > /tmp/database.sql

Now i enter into psql and drop the database english:
psql -U postgres
drop database english;

And exit.
Now i want to import the database english which is not exist.
psql -U postgres -d english  < /tmp/database.sql
#it can't work,error
psql: error: FATAL:  database "english" does not exist

It can work to import the whole database after creating english database first:
psql -U postgres
create database english;
press ctrl+d to exit
#execute in bash shell command
psql -U postgres -d english  < /tmp/database.sql

How can import a database which is not exist yet in bash shell?
Answer: If you are using a plain format dump like you do, you'd have to create the dump with the --create option, so that it contains a CREATE DATABASE statement:
pg_dump --create ... -f database.sql english

To restore such a dump, connect to database postgres:
psql -d postgres database.sql

If you were using a custom format dump (which I recommend), you could specify --create when you restore the dump.


Calculate $E(X\mid Y=y)$ and $E[YE(X\mid Y)]$ for $g(x,y)=6xy$

Question: We know that (X,Y) have density $g(x,y)=6xy$ for $x,y \in T$ where $T=((x,y); 0 \leq x \leq 1, 0 \leq y\leq \sqrt x )$.
The task is to calculate $E(X|Y=y)$ and $E[YE(X|Y)]$.
Now I find joint density of x and y
$g(x|y)=\frac{6xy}{\int_{0}^{1} 6xy dx}=\frac{6xy}{3y}=2x$
And $E(X|Y=y)=\int_{0}^{1} 2x^2 dx=\frac{2}{3}$
Is this solution corect? What can be done with the $E[YE(X|Y)]$?
Comment: Note that $E [Y E [X\vert Y]] = E[E[XY\vert Y]] = E[XY]$
Comment: Besides, your calcluation of $g(x\vert y)$ is not right. You have to divide by $\int_{y^2}^1 6xy \text d x$.
Answer: Your answer is not correct. The mistake occurs when you compute the marginal distribution of $x$.
This needs to be $\int_0^1 g(x,y) \text{d}x = \int_{y^2}^1 6xy \text{dx} = 3y - 3y^5$, because $g(x,y)$ is zero when $\sqrt{x} \leq y \iff x \leq y^2$.
Answer:
Let's write $g(x,y) $ in a better way:

$$g_{XY}(x,y)=6xy\mathbb{1}_{(0;1)}(y)\mathbb{1}_{(y^2;1)}(x)$$
then the marginal
$$g_Y(y)=3y\int_{y^2}^1 2x dx=3y(1-y^4)$$
And the conditional distrbution is
$g(x|y)=\frac{2x}{1-y^4}\mathbb{1}_{(y^2;1)}(x)$;
$0<y<1$

using the fact that

$\mathbb{E}[XY]=\mathbb{E}[\mathbb{E}(XY|Y)]$
$$\mathbb{E}[Y\mathbb{E}(X|Y)]=\int_0^1 6x^2dx\int_0^{\sqrt{x}} y^2dy$$
Answer: First we have for $y\in (0,1)$
$$g(x\vert y) = 1_{\{y^2 \leq x \leq 1\}}\frac{6xy}{\int_{y^2}^1 6xydx} = 1_{\{y^2 \leq x \leq 1\}}\frac{6xy}{3y - 3y^5} = 1_{\{y^2 \leq x \leq 1\}}\frac{2x}{1 - y^4}$$
resulting in
$$E[X\vert Y= y] =  \frac 1 {1-y^4} \int_{y^2}^1 x 2x  dx = \frac{2(1 - y^6)}{3(1 - y^4)}$$
Further
$$E[YE[X\vert Y]] = E[XY] = 6 \int_0^1 y^2 \int_{y^2}^1 x^2 dx dy = 2 \int_0^1 y^2 (1 - y^6) dy \\= 2\int_0^1 y^2dy - 2 \int_0^1y^8dy
= \frac 2 3 - \frac2 9 = \frac 4 9$$


How can I determine if a $form (or $form_state) is an entity create/edit form

Question: When in a function (e.g. a hook_form_alter) is there a reliable way to determine if the form is an entity form and if so, what type of entity?
Answer: You can check if the form is an instance of EntityForm and then get the entity to check the entity type:
<code>if ($form_state->getFormObject() instanceof \Drupal\Core\Entity\EntityFormInterface) {
  $entity_type = $form_state->getFormObject()->getEntity()->getEntityTypeId();
}
</code>


How to pass form control error messages from component to child component that implements ControlValueAccessor in Angular?

Question: For now I am using @Input() to pass error messages from parent to child component that implements ControlValueAccessor. I would like to know is there better way of passing error messages. Please guide me. Thank you
<code><mat-form-field class="increment">
    <input
        matInput
        [formControl]="_control.control"
        type="text"
        [disabled]="disabled"
        [max]="max"
        [min]="min"
        [errorMessage]="errorMessage"
        [(ngModel)]="value"/>

</mat-form-field>
</code>
Let me know if you know how it can be done
Answer: Try using setError() provided by the ControlValueAccessor interface. Refer this link to understand the concept behind this: https://indepth.dev/posts/1143/a-thorough-exploration-of-angular-forms


How do I know which position to use when I'm playing by ear

Question: I come from a piano background ( and I know enough theory to read intermediate piano sheet music) and I want to learn fingerstyle guitar. but It's so difficult because there is more than one way to play each note. and the notes on the guitar is just too much.
Even though I know the melody or figure it out and when I try to transpose what I know to the guitar it I either play the whole melody on the one string or two strings and sometimes I have to stretch to reach a note. Now this is only the melody. there are still Bass and harmony in which I have to account for.
take a look at this for example

 its in dadgad tuning lets say at 1:20 he plays a V chord in 6th position then resolves to one and moves to 2nd position. and sometimes he move from low to high fretboard. of course there are multiple ways to play the song but maybe because the intonations are different so you play this note instead or it's voice leading to make it sound better and smoother. I don't know the thought progress I mean this person is a professional so the fingerings must be good but what is their thought process? why play it like this? Are there just some general go to shapes in advanced voice leading?
Please help. I'm looking to be more efficient and effective at arranging fingerstyle songs
EDIT  oh and most of the time I see sungha or any other guitarist they can play the melody and somehow know which chord shapes to use
Comment: I know Rachmaninov's C# minor on the piano. My guitar interpretation reflects what I prefer aesthetically. Consider personalizing the Canon on the piano, and find that familiar feeling on the guitar.
Answer:
It's so difficult because there is more than one way to play each note.

I would look at it from another angle: it's so easy because there is more than one way to play each note! Whenever one way to play a note turns out to be unwieldy, you have several alterative options that may be easier.
As a beginner, you'll want to stick to a few default positions. Practise the C-major and E-major scales thoroughly in first position and fifth position (without any position changes), that will give you a good basis that works well for many melody runs. Also practise the simple standard chords, i.e. the open G- C- D- A- and E-major chords, e-minor, a-minor and d-minor. When all of that works quite automatically, you can start combining both – play those open chords and add some melody by putting some scale runs in first position between the chords.
Later, practise bar chords in some position and combine these with melodies in that position.
At this point you'll be able to play quite a lot of nice stuff, without actually using any position changes at all. Only then should you start accustoming yourself to such changes. By then you'll know the advantages and problems of each position and can therefore judge when some position change is appropriate.
Answer: The position that works best for you to reproduce the music is the one you should use. Most of the time that will be the same position the player on the recording used, but since everyone's hands are different, you may end up using a different position and prefer it to the original.
Initially, one uses trial and error - trying different positions and deciding on the one that works the best and feels most comfortable. With experience, one draws on that experience to more quickly arrive at the ideal positions to use in a piece.
Answer: If you learn classical guitar from scratch, at least the way I did, was like this:

Play a lot on 1st fret to get the muscle memory of actually just using both hands together. Including chords around there (which, note, are different than anywhere else due to the open strings, obviously).
With sheet music, slowly progress down the board over time. I.e., there might be an occasional occasion where your left hand moves down to III or V or whatever.
Eventually, know all the frets pretty much by heart. They "feel" differently after a while, i.e. for me V feels quite different from, say, IIX due to the different spacing.

In the blues/jazz/improvisation world, it's all based on scales. That means you have a set of finger positions where the left hand does not move (at least not more than a fret or two, if at all). You don't care much about what actual tones you are playing, but that it makes sense in a relative way (i.e., minor, major, blues scale etc.). After you get a few of those scales internalized, it gets really easy (just like transposing a chord).
I would encourage you to look at both of those methods and see what suits your style of music best. If you wish to improvise and play by ear, scales are great.
I would actively avoid playing on only one or two strings, that does not have a real future, really...
Oh. And practice, practice, practice.
Answer: I would highly urge you to stick to standard tuning EADGBE. There a many good references to use. Give up any other tunings.
Comment: This does not answer the question, which is about playing position, not alternate tunings.