Hearing Chord Progressions

Question: Are chords divided amongst instruments or are they played on one instrument? I read an article online when searching for tips on hearing chords changes that read:
" The most direct way to figure out a chord progression is to focus on the roots of all the chords. In other words, listening to what the bass player is doing. Often, for horn players like myself, when we listen to chord progressions, our ears go straight to the upper structures because that is what we're accustomed to playing. By making yourself focus on the root of each chord, it will be much easier to identify the movement between chords."
This left me under the impression that a each note of a chord is played on a different instrument and that I should focus the most on the bass notes (bass line) because they're the root notes of the chord except in the case of inversions
Answer: "Are chords divided amongst instruments or are they played on one instrument?"
Either and both, depending on what they ARE being played on!    If there's only a piano or only a guitar, it plays everything.   If there's a string quartet, the chord is the sum of the single notes cello, viola and the two violins are each playing (let's not quibble over double-stops for now).
In some styles of music there's a 'rhythm section' that largely takes care of the bass line and chords.  And yes, if you need to work out the chord sequence, the bass is a very useful place to start.
Answer: With simple harmony - triad chords, for example, when there's an instrument there to play chords on, that's usually its job. Guitar piano/kbd comes to mind. Other instruments which generally play single notes will play notes from the underlying chord, often.
In most cases, the bass is expected to represent the bottom, with the root note. Although it will also play any of the other notes from the chord, and always the note after the slash in 'slash chords'.
So, listening to what's happening in the bass line is a good place to start. It often won't say major or minor, that's where the other instruments will help.
Be aware that in big band music, often there are complex chords, containing 5,6,7 or more different notes, making the job of recognising particular chords, especially those with changed notes (b5, #9, et al) very difficult.
Answer: I would expect in an orchestra, chordal harmony would be accomplished by separate instruments except when there are pianos, organs, guitars or other instruments which are able to play harmony by themselves. This is not so much the case in most basic rock, country, bluegrass, and other types of music that employ instruments that can play chords. Even so, lead parts, horn parts, bass and others combine to become harmony in some fashion and that's what chords are.
Ear training and being able to recognize intervals has been what helps me recognize which chords are part of a progression.
Answer: The notes of a chord are distributed among voices. More than one voice is able to played simultaneously on piano or guitar (and occasionally on string instruments.) Piano and guitar are able to play all the notes of the chord. The chord needs to be heard as a whole among all the voices. The bass often plays the root of the chord, but chords are so often in inversion that relying on the bass to determine the root of the chord is too simplistic. In a walking bass line in a jazz piece, for example, the bass is all over the place and does not always hit the root note on beat one, even if outlining a chord completely.
If you want to get better at hearing chord progressions, I suggest you learn how to form chords on the piano. I don't mean that you have to get good at playing them if you are not already a pianist. Learn how to identify the notes of the chord and play them in root position and all the inversions and then sing the root note.  This will help you to hear where the root note is, even if the chord is in inversion. The root note will help you hear the movement between the chords.  Ideally, you want to be able to hear it no matter in which voice it is located.
Comment: "Piano and guitar are able to play all the notes of the chord." -- One is often required to leave some notes out of a chord on guitar, since most of us only have four fingers.
Comment: What I say is true for basic triads and 7th chords. Any more than that is not really pertinent to this discussion.
Comment: I don't see how you get that "any more than that is not really pertinent to this discussion." There is nothing in the question to suggest that only triads and seventh chords be considered. In fact, the quote in the question mentions upper structures. Not the end of the world, but your statement was a little bit wrong, hence the comment.
Comment: It is true that past 7ths a guitarist has to leave out some notes. I would say that listening to inversions of triads and 7ths is the way to start being able to identify the root of a chord. After that is mastered, go on to more complex chords. But since the first poster was asking about being able to hear the root, I didn't see the need to get into more complex chords.
Comment: "past 7ths a guitarist has to leave out some notes" -- not always. Off the top of my head, there are some common 9th chord voicings that don't require any omissions. For voicings with more than four notes one can use the thumb to fret a bass note, or use a barre, or use open strings, or use the side of the first finger to add extra notes.
Comment: Good to know. That is not something that I have ever discussed with my guitarist husband. I clearly should have said in my first answer that I was only referring to triads and 7ths when I was giving my suggestion on how to learn how to identify the roots of chords by ear.

Hearing Chord Progressions


What is the broadcast etiquette when a pitcher has a perfect game?

Question: When a pitcher has a no-hitter or perfect game going there is a lot of superstition and etiquette surrounding what goes on in the field of play and in the dugout. The pitcher is expected to always sit in the same spot in the dugout between innings, the opposing team is expected not to try to bunt for a base hit in the late innings, etc.
What amount of this etiquette/superstition does, or should, apply to the broadcasters or others who report on the game? Where does the duty to the fans and effectively communicating what is going on in the game (especially in radio where what you say is all you communicate) end?
Answer: Being a "should" question makes this difficult to answer, but I'll try.
The superstition by the players actually has some basis in reality.  The idea is to not inflate the event in the pitchers mind.  It's doubtful, but at many points throughout the game the pitcher may not even be aware of a perfect game or no hitter is in progress.  In any event, the idea that you could jinx it actually helps keep an atmosphere of normality around a pitcher who simply has a job to do.
Announcers and fans have no reason to abide by this superstition because the pitcher and other players should be largely unaware of what they are saying.  In practice, many fans will openly talk about a no-hitter or perfect game while it's in progress (I've witnessed both at Kenny Rogers perfect game against the Angels in Arlington) and networks will often "cut in" to a game in progress while a perfect game is alive in the late innings.  I've yet to see any restrictive etiquette around a broadcasters ability to talk about a perfect game/no hitter while in process.
Knowing that baseball fans can often be as superstitious as the players themselves, some may have a problem with this.  You can't please everyone though, especially not those who don't live in reality.
Comment: +1, my understanding of no-hitter etiquette has extended primarily to the teams themselves - don't bother the starter, don't bunt for cheap hits late, etc. However, many broadcasters are ex-players, so they may choose to follow the same rules, particularly if they're the broadcast crew for the team with the no-hitter going.


Automatic connection between 2 IOS Apps

Question: I have written a Solution that contains two Apps,
the first app acts like a remote control app and the second app display some stuff depending on the selection of the first app.
State Now:
Currently, both apps communicate over a Bluetooth connection using the MultipeerConnectivity.framework.
Problem:
I have always to pair both apps manually starting the apps.
Solution:
Starting both apps, they should detect each other and be paired automatically.
How could I solve my Problem, is there any alternative to the Bluetooth connection or can I set up the connection to have trusted devices or something like that?
Comment: You could use Core Bluetooth directly; have one app acts as a peripheral and the other as the central.
Comment: Your central would scan for peripherals advertising your service. Your peripheral app would advertise that service. Your central app could automatically connect to any peripheral advertising that service or you could show the initial discovered peripheral to the user and once they have selected it, store the identifier in user defaults and automatically connect to that in future.
Comment: @Paulw11 would this way solve the problem with manual pairing ? How would both apps establish the connection ?
Comment: Could you provide a simple sample code, maybe on github hosted sample or any tutorial ? Just to see how it works
Comment: https://developer.apple.com/library/content/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/BestPracticesForInteractingWithARemotePeripheralDevice/BestPracticesForInteractingWithARemotePeripheralDevice.html thats exactly what I was looking for
Answer: It's up to you as the developer how the pairing is implemented. You could even code a solution which requires no approval from the user; the app could pair automatically with any device looking for other peers (although this probably wouldn't be a good idea for a variety of reasons).
One possible solution for your problem:
The first time your devices pair, you generate a random UUID and save it on both devices for later use.
The next time your devices discover one another, they check to see if they have any matching UUIDs stored; if they do find a matching pair then you can let them connect automatically.

Automatic connection between 2 IOS Apps


network service failing on boot in SLES 10.2, possibly leading to NFS client problems

Question: On a box recently upgraded from SLES 9.3 to 10.2, I'm seeing the following issue:
Prior to the upgrade, an NFS mount (defined via yast, i.e., it appeared in /etc/fstab) worked correctly. Following the upgrade, however, it is failing. A network trace shows that it is making the initial connection to the NFS server over TCP (for the portmapper RPC), but then it switches to UDP for the subsequent MOUNT call; since the NFS server doesn't allow UDP (with good reason, due to the possible issues with data corruption, as in nfs(5)), the connection will not go through.
Adding the TCP option (whether in fstab, or at the command line, etc.) has no effect.
In the course of troubleshooting this, I've found that /var/adm/messages is reporting the following as occurring during boot:
Failed services in runlevel 3: network

(I should note that despite this error message, apparently at least some network services are started, since the box is accessible via SSH.)
My questions, then:

What should I be looking at to determine the cause of the service startup failure?
Would this indeed be likely to cause the problem with NFS described above?
If the answer to (2) is no, then any suggestions on what to look for?

Editing to add some information relating to the answers below.
It turns out that the network service is failing on bootup because one of the interfaces (there are two on this box) uses DHCP, and that's not available yet at this time. So I've disabled it for now, stopped/restarted the network service and the NFS client services, but still get the same results.
There's no firewall on the client side. Also, iptables -L on the client side shows that everything is accepted; and there are no entries in /etc/hosts.allow or /etc/hosts.deny.
On the NFS server side, nothing has changed. The remote nfsserver is indeed advertising that it allows both TCP and UDP for all of the NFS services (though there is an iptables rule blocking UDP).
/etc/fstab entry is pretty basic - what you'd get from setting it up in yast:
x.x.x.x:/volume      /localdir   nfs     defaults 0 0

rpcinfo -p for the client box shows only portmapper v2 running, advertising both TCP and UDP. For the server, it shows all of the usual services:
   program vers proto   port
    100000    2   tcp    111  portmapper
    100000    2   udp    111  portmapper
    100024    1   udp   4047  status
    100024    1   tcp   4047  status
    100011    1   udp   4049  rquotad
    100021    1   udp   4045  nlockmgr
    100021    3   udp   4045  nlockmgr
    100021    4   udp   4045  nlockmgr
    100021    1   tcp   4045  nlockmgr
    100021    3   tcp   4045  nlockmgr
    100021    4   tcp   4045  nlockmgr
    100005    1   udp   4046  mountd
    100005    1   tcp   4046  mountd
    100005    2   udp   4046  mountd
    100005    2   tcp   4046  mountd
    100005    3   udp   4046  mountd
    100005    3   tcp   4046  mountd
    100003    2   udp   2049  nfs
    100003    3   udp   2049  nfs
    100003    2   tcp   2049  nfs
    100003    3   tcp   2049  nfs

The mount call, with the /etc/fstab entry above, is simply:
mount /localdir

although I've also tried it with various options such as tcp, v3, etc.
Both the /etc/fstab entry (hence the mount) and the rpcinfo -p call are using the IP address, so there are no DNS resolution issues involved.
Answer: Check to make sure /etc/hosts.deny does not contain an entry for mountd, and check hosts.allow, for similar reasons. For what it's worth, I usually clear out hosts.deny and use iptables to control access.
Use rpcinfo -p nfsserver to ensure that mountd is indeed advertising TCP — there's an option -n to disable TCP-listening, which (IIRC on SuSE) would likely be set in /etc/sysconfig/nfs or thereabouts.
Answer: as i understand your question, you can do the following:

ssh to your nfs client system
"connect" with rpcinfo from the client to the server
you have disbaled the dhcp interface, so every traffic is going over one interface and there are no other routes

but you can't mount a filesystem from the nfs server on the nfs client and you do not get any error message.
what is the difference between your rpcinfo and mount calls? do you use ip adress in one and fqdn in the other? could you please post both commands with output and returncode?
Answer: A couple things.  First off, you state at the start that since the NFS server doesn't allow UDP, and then in your edit mention The remote nfsserver is indeed advertising that it allows both TCP and UDP for all of the NFS services.  This seems a little odd.  Why does the server advertise something that it doesn't allow?
Secondly, are you attempting to use NFS version 2 or version 3?  Version 2 supports UDP only, whereas you need version 3 for TCP.  Perhaps manually specifying version 3 in the mount options will help?  (vers=3)  If it's defaulting to 2, then even specifying TCP won't do you any good.
I've also had issues with newer clients attempting to use version 4, when the server didn't quite support it.  Your SLES upgrade may have resulted in a different default version.  All the more reason to specify it explicitly.
Why don't you post the entry in /etc/fstab as well?
Comment: The mountd only allows one to disable TCP service, not UDP (Probably because NFS was originally designed around UDP).
Comment: When you try UDP for the mount, it doesn't get through (verified this using tcpdump). As Pi pointed out, there's no way to disable UDP within nfsd itself; it is being blocked using an iptables rule. The client is using NFSv3 - verified that as well with tcpdump. Have also tried specifying it explicitly.
Answer:
Try starting the service manually with service network restart and see what messages you get. There should be some information there.
Possibly...
Check to see if there is any firewall enabled by default on your system, this may be causing problems. Especially if the failed networking start doesn't correctly load the firewall rules.
Answer: Try setting things explicitly and see where that gets you. For instance, in /etc/fstab:
x.x.x.x:/vol /local nfs proto=tcp,port=2049,mountport=4046,nfsvers=3 0 0

This should at least bypass the portmapper and explicitly try connecting to the TCP ports that you list above and make it easier to tcpdump trace each channel during your debugging.
Comment: Same results, unfortunately. Looks like it still first connects to portmapper anyway (via TCP), and then continues in UDP.
Answer: For reference, in case anyone else comes across this question and wants an answer:
I finally opened a ticket with Novell on this. It turns out that this is a known bug in SLES 10.2 (491140: mount ignores "proto=" for "nfs"), and there is a patch for it (util-linux-2.12r-35.35.2.x86_64.rpm). With that installed, the mount works as expected, and all requests are made over TCP. (Novell support also informed me that this is merged in SLES 10.3.)


Do we have to empty SecurityContextHolder after request is finished with JWT

Question: I'm working on an implementation of JWT with Spring boot based on some open source projects and some of the documentations found on the net.
What's working?
I'm able to generate my tokens and in the first hit when I try to call some secured methods I'm revoked which is good.
What's the problem?
Once I generate my token, seems like I'm able to call my secured methods without the need to add my Authorization header.
I was debugging my code and found out that I set the authentication in the SecurityContextHolder but I don't empty this variable once the request is finished. In every implementation found no one does this, so my question is do I have to do this to get my code work as supposed, retrieving secured paths just when there's an authorization header with a valid token?
My code:
WebSecurityConfig class:
<code>@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserSecurityService userSecurityService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/public").permitAll()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated();

        // And filter other requests to check the presence of JWT in header
        http.addFilterBefore(jwtAuthenticationFilterBean(),
                UsernamePasswordAuthenticationFilter.class);

        // Disable page caching
        http.headers().cacheControl();
    }

    @Bean
    public JWTAuthenticationFilter jwtAuthenticationFilterBean() {
        return new JWTAuthenticationFilter();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService(userSecurityService);
    }
}
</code>
JWTAuthenticationFiler class
<code>public class JWTAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Value("${jwt.token.header}")
    private String tokenHeader;

    @Autowired
    TokenAuthenticationService tokenAuthenticationService;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String token = httpServletRequest.getHeader(tokenHeader);

        String username = tokenAuthenticationService.getUsernameFromToken(token);

        if(username != null && SecurityContextHolder.getContext().getAuthentication() != null){
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
            if (tokenAuthenticationService.validateToken(token, userDetails)) {
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);

    }

}
</code>
TokenAuthenticationService class
<code>@Service
public class TokenAuthenticationService implements Serializable {

    static final String CLAIM_KEY_USERNAME = "sub";
    static final String CLAIM_KEY_AUDIENCE = "audience";
    static final String CLAIM_KEY_CREATED = "created";
    static final String CLAIM_KEY_EXPIRED = "exp";

    static final long EXPIRATIONTIME = 864_000_000; // 10 days
    static final String SECRET = "ThisIsASecret";
    static final String TOKEN_PREFIX = "Bearer";
    static final String HEADER_STRING = "Authorization";

    @Value("${jwt.token.expiration}")
    private Long expiration;

    @Value("${jwt.token.secret}")
    private String secret;

    public String generateToken(UserDetails user) {

        Map<String, Object> claims = new HashMap<>();

        claims.put(CLAIM_KEY_USERNAME, user.getUsername());

        final Date createdDate = new Date();
        claims.put(CLAIM_KEY_CREATED, createdDate);

        final Date expirationDate = new Date(createdDate.getTime() + expiration * 1000);

        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public String getUsernameFromToken(String token) {
        String username;
        try{
            final Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        }catch (Exception e){
            username = null;
        }
        return username;
    }

    private Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            claims = null;
        }
        return claims;
    }

    public boolean validateToken(String token, UserDetails userDetails) {

        final String username = getUsernameFromToken(token);
        final Date created = getCreatedDateFromToken(token);

        if(userDetails.getUsername().equals(username) && !isTokenExpired(token)){
            return true;
        }
        return false;
    }

    private boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    private Date getExpirationDateFromToken(String token) {
        Date expiration;
        try {
            final Claims claims = getClaimsFromToken(token);
            expiration = claims.getExpiration();
        }catch (Exception e){
            expiration = null;
        }
        return expiration;
    }

    private Date getCreatedDateFromToken(String token) {
        Date createdDate;
        try{
            final Claims claims = getClaimsFromToken(token);
            createdDate = new Date((Long) claims.get(CLAIM_KEY_CREATED));
        }catch (Exception e){
            createdDate = null;
        }
        return createdDate;

    }
}
</code>
and this my controller test class
<code>@RestController
public class TestController {

    @GetMapping("/public")
    public String testPublic(){
        return "Welcom to the public place";
    }

    @GetMapping("/private")
    @PreAuthorize("hasRole('USER')")
    public String testPrivate(){
        return "Welcome to the private place";
    }

    @GetMapping("/admin")
    @PreAuthorize("hasRole('ADMIN')")
    public String testAdmin(){
        return "Welcome to the admin place";
    }

}
</code>
Thank you
Answer: So the answer to my question needs two modifications:

We need to have a stateless session management policy by adding this to our WebSecurityConfig

.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)

The second thing is a typo in my code, we have to be sure that the authentication is null in the condition of our filter:

if(username != null &&
  SecurityContextHolder.getContext().getAuthentication() == null)


AttributeError: probability estimates are not available for loss='hinge'

Question: text_clf = Pipeline([('vect',CountVectorizer(decode_error='ignore')),
                      ('tfidf',TfidfTransformer()),
                      ('clf',SGDClassifier(loss = 'hinge',penalty = 'elasticnet',alpha = 1e-3,n_iter = 10, random_state = 40))])

text_clf = text_clf.fit(trainDocs+valDocs,np.array(trainLabels+valLabels))
predicted = text_clf.predict_proba(testDocs)

How can I get the predicted probability of every test sample? Thanks!
Comment: As the error message says, you can't get probabilities if you use the hinge loss function.  Use a different one instead.
Comment: I don't know the mathematical details of why one model can get the probability and one can't, but it's not super surprising since SVM and SGD are totally different algorithms.  You could try asking the scikit people (e.g., in a github issue or on their mailing list) how to get SGD probabilities with hinge loss, but (assuming it is possible at all), it's unlikely to be a simple task, or they would have already done it.
Comment: Thanks for your reply. However, why can svm.svc(probability = True)) get the probability? I know that the loss of svm is hinge. In my imbalance task, SGDClassifier with hinge loss is the best. Therefore, I want to get the probability of this model. If possible, would you tell me how to modify some code to get the probability? Thanks very much.
Answer: SGDClassifier(loss = 'hinge') does not have probability by default.
You have to pass SGDclassifier(loss = 'hinge') to CalibratedClassifierCV() which will calculate the probability values of SGDclassifier(loss = 'hinge').
lr = SGDClassifier(loss='hinge',alpha=best_alpha,class_weight='balanced')
clf =lr.fit(X_tr, y_train)
calibrator = CalibratedClassifierCV(clf, cv='prefit')
model=calibrator.fit(X_tr, y_train)

y_train_pred = model.predict_proba(X_tr)
y_test_pred = model.predict_proba(X_te)

Answer: You can use decision_function instead of predict_proba to get the predicted values.


Intonation exercises for string players

Question: I am looking for intonation exercises for bowed strings.
I use techniques mentioned by Simon Fischer in his books and those have served me well I think. However I am now able to match pitches well but only while hearing them. If I'm playing along with an ensemble I can match their pitch fairly well.
My problem is that when I am alone my intonation is rather inconsistent.
I practice playing with an electronic tuner for hours and hours but this doesn't seem to help at all. After hours of practicing this way my intonational problems have not improved much. Teachers just say "practice scales" Which is an instruction which frustrates me to no end since I can't tell when my scales are truly in tune. That isn't to say I am completely inept, I am just not satisfied with my intonation for my playing level and I would like to improve.
I understand that intonation on bowed string is a combination of mechanical skill and internal audiation. I would like some exercises that can help with both.
Comment: Can you sing in tune?
Comment: I can. I'm not sure how precise I should be by myself but I have sung as part of a choir. I don't think I am any more or less precise with singing than I am on on violin/cello.
Comment: You say that you cannot tell when your scales are truly in tune.  If you cannot tell why do you think that they are not in tune?  I'm trying to understand what exactly the problem is hre.
Comment: @JimM I have a sense of the structure of scales. I know the notes. I can play them. But I am not confident. When I listen to recordings of myself my scales are never as in tune as I thought they were. When I sing or play with an electric tuner I never get it exactly. I am usually within 10 cents but that is hardly in tune
Answer: I have never used an electronic tuner and I don't really know how they work, but I am guessing that they do not adapt for temperament.
On a stringed instrument such as the violin or cello (I play the cello) as well as in singing you naturally veer towards mean temperament, so for example you will tend to play mediants sharp and leading notes very sharp. So the f# you play in a scale of G major will be slightly higher than the one you play in the scale of D major. If your tuner does not accommodate this then I am not surprised that you do not agree with it.
This would be consistent with your statement that you seem to play more in tune with an instrumental ensemble (where I assume you do not employ the tuner) but seem to struggle when playing alone using the tuner.
I hesitate to suggest this but I think that you should try practicing without the tuner.  Use the tuner to tune your A string and tune all the others by ear.  Give it a week or so and see how it goes.  Use your natural aural ability rather than rely on an external source all the time.  This is, after all, how everyone did it until a relatively few years ago.
Good luck.
Comment: Hey. I am actually doing this now, based on your advice. It seems that throwing the tuner in the mix has just served to make me insecure. I am now using it at the start of practice with the cello to practice finger placement with less guesswork. After I'm going without the tuner and I seem to be improving a lot. My instrument is a lot more resonant and my corrections are more confident. So I'll mark this one as right.
Comment: @xerotolerant  Happy to have helped.
Answer: I would allow me to start with a question: do you play in tune while you stay in one position? If not, I would start working on improving the intonation without changing the position. For me always works looking in a mirror - just watch your hand if it does not do some inappropriate movements and check with your ear if you are correct. If you think your ear is not enough precise, practice veeeery long notes and download some app which can show you exactly where you are (I am using the legendary Pitch Primer for iPhone, but I am sure there much less expensive apps).
That is the basic I think - to find a nice shape for your hand.
Every hand is different so you need to find yours.
Of course most of the intonation problems come with changing the positions. Then I would do the next step and concentrate on that (after you master separately each).
My favourite - not only because I am Czech - is Ševčík, which you can find on IMSLP. You can start with Op. 1: http://imslp.org/wiki/School_of_Violin_Technique,Op.1(Ševč%C3%ADk,_Otakar)
P.S.: I am a cellist, but I guess that makes no difference :)
P.P.S.: The most finest intonation is not felt just by ears but also by your fingertips. Just try to concentrate while you play on this fingertip sensation. It will be different when you play out of tune and in tune. Another "yoga" exercise is to look at your strings how they vibrate. Again - if you play in tune you can see that they move more (esp. lower strings).
Comment: I'm sceptical about the very last part - unless you are playing with others.
Comment: I do not understand. Intonation is definitely something you need to practice just by yourself. It is a basic ability to hit the note you wish. No one can help you with that :) Different category is e.g. quartet, where you have to find specific intonation of the ensemble, but I guess that is not the case of xerotolerant....
Comment: @Tim I think jamnik is talking about sympathetic resonance. Which I do know about. I find relying on it to be mostly ineffective since I am I don't place my fingers reliably, and sometimes I am always really sure whether or not I am getting the maximum amount
Comment: @jamnik I started cello a few months ago. I would be nice if you share your cello exercises as well. I said "strings" in the original post since I play cello and voilin
Comment: @xerotolerant - sympathetic vibration only occurs when something else has the same basic frequency, as I'm sure you're aware. It will only happen on a cello/violin etc., with any of the three unplayed strings, so if one plays a different note or even a not-in-tune note (in the cracks, we say!) then that wouldn't resonate any more or less than an in-tune note that wasn't the same as another open string, if that makes sense. So it won't help with intonation.
Comment: @xerotolerant - nice choice :) It is really hard to tell which kind of exercise you need, I do not know how do you play. For advanced players, there are very nice Feuillard etudes for changing the positions, also online at the IMSLP... But Ševčík is really great, there are thousands of combinations, concentrated on practicing separately left and right hand.
Comment: I looked at sevcik on imslp but I only see violin exercises. Are you recommending that I play the violin exercises on cello?
Comment: There are some editions also for cello, especially right hand, but left hand also. For the left hand on cello try few of the Feuillard's Daily Exercises for Cello. My favorite one is No. 16
Answer: Suppose you are playing tonal music:
As you said, you perform better when there are reference pitches (e.g. play in ensemble). To play solo violin, a method I use to maintain consistent intonation is always compare with open string or natural harmonics when possible. Do some ear training to get familar with basic intervals. Your ear will tell you the interval is weird if you played off-pitch, compared with open string or harmonics.
Of course in some piece you do not have the chance to use many open string or natural harmonics. Then play the piece in segement, and record it. Analyse what is not in tune, and fix it. This process is relatively slow, but it will train your for better intonation and muscle memory in the long run. So it worthes the investment.

Intonation exercises for string players


Usar str_replace substitur tag  por

Question: Pessoal preciso substituir as tags br por p no meu construtor xml e para isso estou utilizando o método str_replace mas ele não está fazendo essa substituição.
Segue o código:
$i=1;
foreach ($xml->channel->item as $item){
   if($i <= 30){
       if(substr($item->link, 0, 23) == 'https://www.site.com.br'){
    $imagem = '';
    if($item->images->image != ''){
        $imagem = '
 ','',$item->images->image))))).'"/>
';
    }
    $newItem = $newXML->addChild('item');
    $newItem->addChild('title', $item->title);
    $newItem->addChild('link', $item->link);
    $newItem->addChild('guid', $item->guid);
    $newItem->addChild('pubDate', $item->pubDate);
    $newItem->addChild('content', '
    <![CDATA[

          <meta charset="utf-8">
          <link rel="canonical" href="'. $item->link .'">

'.$item->title.'

            '.str_replace('

','','
'.$item->summary.'
').'
            '.$imagem.'

            '.str_replace('

','

',$item->content).'

                link .'" hidden>

    ]]> ');
$i +=1;
}}
}
print($newXML->asXML('teste.xml'));

Answer: Observe que para você conseguir fazer esse tipo de substituição, o código retornado em $item->contentpor exemplo, precisa ser exatamente

 sem nenhum caracter entre eles. Se for
, não vai funcionar ou se for apenas um
 também não.
Compartilhe um trecho do código do seu xml (se for possível). Assim chegaremos a uma solução mais adequada.

Usar str_replace substitur tag  por


How customize update interval of aggregator module

Question: By default   update inteval of RSS aggregator in Core aggregator module start form 15 min, I mean 15 min is minimum value,

But I need update RSS aggregator shorter than 15 min,and update my feed each 2,5,10 minute too,
How can I set Update interval to what I required?
one solution is using alternative module like feeds module but it is not stable yet.
Answer: The update interval values for an Aggregator Feed is hardcoded into the Entity definition for the refresh field. You'll need to alter the definition to allow different values.
In a custom module, you can evoke hook_entity_base_field_info_alter() to alter the Feed definition to accept shorter intervals:
function MYMODULE_entity_base_field_info_alter(&$fields, $entity_type) {
  if ($entity_type->get('id') == 'aggregator_feed') {
    $definition = $fields['refresh']->getItemDefinition();
    $intervals = $definition->getSetting('allowed_values');
    $intervals = array(
      120 => '2 min',
      300 => '5 min',
      600 => '10 min',
    ) + $intervals;
    $intervals = $definition->setSetting('allowed_values', $intervals);
    $fields['refresh']->setItemDefinition($definition);
  }
}


Custom ckeditor.styles.js possible to specify for any/all elements?

Question: In the ckeditor.styles.js can you leave the element blank or specify multiple elements in a single line? Ex. if the class .red could apply to any element, do I actually have to write out a line for every possible element?
<code>{ name : 'Red' , element : 'p', attributes  : { 'class' : 'red' } },
{ name : 'Red' , element : 'h1', attributes  : { 'class' : 'red' } },
{ name : 'Red' , element : 'h2', attributes  : { 'class' : 'red' } },
</code>
etc...
Or is there an easier way?
Answer: I also searched for a way to specify multiple elements for one style - and it doesn't seem to be documented anywhere. I was successful with specifying multiple elements as an array:
<code>{ name: 'Red', element : ['h1', 'h2', 'p'], attributes: { 'class': 'red' } }
</code>
This works for me in CKEditor 4.2.1.
Comment: Although, this seems to work, it breaks the active state of the select.  When you choose an option, it doesn't show as active.  I had to separate the elements into their own hash.  In addition, I couldn't use the same name for multiple styles, I had to add an extra space to the names to make them unique.


Is it possible to calculate with an undefined variable value?

Question: I am subtracting two variables from each other but i sometimes need to subtract an undefined value. But then the output of the subtraction is Nan.
var margeproject= omzetproject - kostenproject;

when they are both set it works fine but when one value is undefined i get NaN returned. For example:
3=6-3;
Nan=6-undefined;

Comment: what do u need when undefined ?
Comment: try : var margeproject = Number(omzetproject - kostenproject); should return the value of zero if either is undefined.
Comment: The result *has* to be NaN. How can it *not* be NaN? What do you expect the result to be?
Comment: better to assure the variables have some numeric value; either preset (with 0?) or add || 0 on the (potentially undefined) assignment.
Answer: Try this:
var margeproject = (omzetproject || 0) - (kostenproject || 0);

This will use 0 instead of undefined, if either of the variables is undefined.
In case your variabled might contain strings, you could catch that like this:
var margeproject = ((omzetproject || 0) - (kostenproject || 0)) || 0;

Comment: @KooiInc: OP: _"My variables may be undefined, what should I do?"_ Solution: _"Better check if these variables are strings, booleans, objects, arrays, or maybe even functions!"_. While you raise a valid concern in that this function breaks when using strings, I don't think these variables (`projectTurnover` & `projectCosts`) will contain strings.
Comment: @Cerbrus Escpecially in programming statements like *"I don't think these variables will contain strings"* are instantly candidate for the activation of Murphy's law.
Comment: Assuming that `omzetproject` and `kostenproject` are declared (as they should be) this will work.
Comment: pasted into console gives: ReferenceError: omzetproject is not defined
Comment: @MBottens: _"but i sometimes need to subtract an undefined value. But then the output of the subtraction is `NaN`."_ --> OP wouldn't have gotten to `NaN` if the variables weren't declared.
Comment: In the first solution, what happens if `omzetproject` is `'a'`? I'd remove that one from the answer.
Comment: @pmandell: Oh whoops, that's completely broken (returning `0` whenever a variable is undefined). removed.
Comment: @KooiInc: Then I suggest you add a answer that handles all possible contents of these variables... I believe such thorough error checking is out of the scope of this question.
Comment: @Cerbrus: it's pretty simple. The answer you now removed did that. See http://jsfiddle.net/r8zxa/
Comment: @KooiInc: The answer I removed also returned `undefined - 5 === 0`, where `-5` might be desired. I could add a `( ) || 0` around the whole thing.
Comment: @Cerbrus `(undefined) || 0 - -5` would be `5`. But anyway, `parseInt` may come to the rescue. http://jsfiddle.net/4Ztsk/. I'm leaving the discussion now, time to move on.
Answer: You should test the validity of the variable. You can't use it while it's undefined :
if (typeof kostenproject === 'undefined')
   kostenproject = defaultValue;


How does regularization reduce overfitting for a linear decision boundary (logistic regression)?

Question: I understand that for higher-order polynomials, reducing the weights of individual features can help to avoid complex functions that are overfit to the training data in a logistic regression classifier.
But I'm not entirely sure how this is the case for non-polynomial features (e.g. there are no $x_1^2$, $x_1\cdot x_2$, etc. terms where $x_1$, $x_2$, etc. are features inherent to some original dataset). In other words, why is it that when I lower or completely remove the regularization term $\sum_j\theta_j^2$, my classifier will be more sensitive to outliers?
For instance, decision boundary of an SVM with $C = 1000$ (more regularization):

And an SVM with $C = 1$ (less regularization):

I think the reason for my confusion is that I can fully imagine a dataset that would be well fit by something like a quadratic function but where the feature space is very large and so it can be easy to overfit the dataset with a complex higher order function. I can't visualize anything of the sort for the linear case.
Comment: I know what you mean about explanations about regularization tending to use polynomial examples. However, consider it like this: unconstrained, the parameter estimates can latch onto whatever coincidence they see, but the constraints prevent them from being able to latch on too hard and overfit.
Comment: See also https://stats.stackexchange.com/q/500360/232706
Answer: The idea of regularization is related to the Bayesian idea of shrinkage: you are biasing your model towards a constant fit (hence the penalty on non-zero coefficients). The regularization factor defines the "price" your model must pay to use that coefficient (i.e., make non-zero).
Therefore, if you have noisy data, the noise terms will tend to not give much reduction in RMS or whatever loss metric you have, so the model will think its better off not including them (to save on the "price" of using that coefficient).
That is how regularization reduces overfitting -- in logistic or any other linear model.
Comment: @khajiit the C here is a bit misleading as a "regularization". This answer gives a nice overview: https://datascience.stackexchange.com/questions/4943/intuition-for-the-regularization-parameter-in-svm
Comment: This answer and the comments are all reasonable explanations, thanks all. I think it's starting to click, but I'm still not entirely sure how this explains a linear model's weights. For a polynomial model, I can see the effect of lowering all weights to be simplifying say, a cubic function to a quadratic or linear one because for instance the $x^2$ or $x^3$ is not as easily able to dominate. If the model is already linear, noisy data/outliers would be fit by weight vectors that are different but not necessarily smaller (in norm / length). So what is the effect of a regularization term?
Comment: @khajiit regularization  is not just about the form of the model but about how many dimensions to include. The simplest model would fit $y_i=\bar{y}$ or something like that. A linear model with 1000 features is more prone to overfit than one with just 10 feature since there are fewer levers to tweak to reduce the error.
Comment: Thanks for the clarification. In the case of a dataset with only two features $x_1$ and $x_2$ (I added pictures to my post above for clarity), how does this lever-tweaking analogy hold? Two features seems like a relatively small amount with or without regularization in terms of addressing that outlier. Apologies for the extra requests for clarification, this has already been helpful in any event.


DPDK sample application aborts after EAL: Couldn't get fd on hugepage file

Question: After cloning the dpdk git repository and building the helloworld application, I get the following error:
$ ./examples/helloworld/build/helloworld
EAL: Detected 4 lcore(s)
EAL: Detected 1 NUMA nodes
EAL: Multi-process socket /run/user/1000/dpdk/rte/mp_socket
EAL: Selected IOVA mode 'VA'
EAL: No available hugepages reported in hugepages-1048576kB
EAL: Probing VFIO support...
EAL: VFIO support initialized
EAL: Couldn't get fd on hugepage file
EAL: error allocating rte services array
EAL: FATAL: rte_service_init() failed
EAL: rte_service_init() failed
PANIC in main():
Cannot init EAL
5: [./examples/helloworld/build/helloworld(+0x11de) [0x56175faac1de]]
4: [/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf3) [0x7f31f60fe0b3]]
3: [./examples/helloworld/build/helloworld(+0x111c) [0x56175faac11c]]
2: [/lib/x86_64-linux-gnu/librte_eal.so.20.0(__rte_panic+0xc5) [0x7f31f62d537e]]
1: [/lib/x86_64-linux-gnu/librte_eal.so.20.0(rte_dump_stack+0x32) [0x7f31f62ecc52]]
Aborted (core dumped)

Checked hugepage support and it seems fine:
$ cat /proc/meminfo | grep -i huge
AnonHugePages:         0 kB
ShmemHugePages:        0 kB
FileHugePages:         0 kB
HugePages_Total:     256
HugePages_Free:      255
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
Hugetlb:          524288 kB

$ mount | grep huge
cgroup on /sys/fs/cgroup/hugetlb type cgroup (rw,nosuid,nodev,noexec,relatime,hugetlb)
hugetlbfs on /dev/hugepages type hugetlbfs (rw,relatime,pagesize=2M)

$ cat /proc/filesystems | grep huge
nodev   hugetlbfs

$ cat /proc/sys/vm/nr_hugepages
256

I saw a workaround in a related question; run it with the --no-huge option, which works:
$ ./examples/helloworld/build/helloworld --no-huge
EAL: Detected 4 lcore(s)
EAL: Detected 1 NUMA nodes
EAL: Static memory layout is selected, amount of reserved memory can be adjusted with -m or --socket-mem
EAL: Multi-process socket /run/user/1000/dpdk/rte/mp_socket
EAL: Selected IOVA mode 'VA'
EAL: Probing VFIO support...
EAL: VFIO support initialized
EAL: PCI device 0000:02:01.0 on NUMA socket -1
EAL:   Invalid NUMA socket, default to 0
EAL:   probe driver: 8086:100f net_e1000_em
EAL: PCI device 0000:03:00.0 on NUMA socket -1
EAL:   Invalid NUMA socket, default to 0
EAL:   probe driver: 15ad:7b0 net_vmxnet3
hello from core 1
hello from core 2
hello from core 3
hello from core 0

But this is a limiting solution.
Answer: TL;DR Use sudo
Running with --log-level=eal,8 as suggested by @VipinVarghese revealed that this was a permissions issue:
$ ./examples/helloworld/build/helloworld --log-level=eal,8
EAL: Detected lcore 0 as core 0 on socket 0
EAL: Detected lcore 1 as core 0 on socket 0
EAL: Detected lcore 2 as core 0 on socket 0
EAL: Detected lcore 3 as core 0 on socket 0
EAL: Support maximum 128 logical core(s) by configuration.
EAL: Detected 4 lcore(s)
EAL: Detected 1 NUMA nodes
EAL: open shared lib /usr/lib/x86_64-linux-gnu/dpdk/pmds-20.0/librte_pmd_qede.so
EAL: Registered [vdev] bus.
EAL: Registered [pci] bus.
EAL: Registered [eth] device class.
EAL: open shared lib /usr/lib/x86_64-linux-gnu/dpdk/pmds-20.0/librte_pmd_aesni_mb.so
...
EAL: Ask a virtual area of 0x61000 bytes
EAL: Virtual area found at 0xd00600000 (size = 0x61000)
EAL: Memseg list allocated: 0x800kB at socket 0
EAL: Ask a virtual area of 0x400000000 bytes
EAL: Virtual area found at 0xd00800000 (size = 0x400000000)
EAL: TSC frequency is ~2590000 KHz
EAL: Master lcore 0 is ready (tid=7fc11ed01d00;cpuset=[0])
EAL: lcore 2 is ready (tid=7fc116ffd700;cpuset=[2])
EAL: lcore 3 is ready (tid=7fc1167fc700;cpuset=[3])
EAL: lcore 1 is ready (tid=7fc1177fe700;cpuset=[1])
EAL: Trying to obtain current memory policy.
EAL: Setting policy MPOL_PREFERRED for socket 0
EAL: get_seg_fd(): open failed: Permission denied
EAL: Couldn't get fd on hugepage file
EAL: attempted to allocate 1 segments, but only 0 were allocated
EAL: Restoring previous memory policy: 0
EAL: error allocating rte services array
EAL: FATAL: rte_service_init() failed
EAL: rte_service_init() failed
PANIC in main():
Cannot init EAL
5: [./examples/helloworld/build/helloworld(+0x11de) [0x56459e5391de]]
4: [/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf3) [0x7fc11eed00b3]]
3: [./examples/helloworld/build/helloworld(+0x111c) [0x56459e53911c]]
2: [/lib/x86_64-linux-gnu/librte_eal.so.20.0(__rte_panic+0xc5) [0x7fc11f0a737e]]
1: [/lib/x86_64-linux-gnu/librte_eal.so.20.0(rte_dump_stack+0x32) [0x7fc11f0bec52]]
Aborted (core dumped)

Tried solving the permissions problem (EAL: get_seg_fd(): open failed: Permission denied), but it only worked when I ran it as root:
$ sudo ./examples/helloworld/build/helloworld
EAL: Detected 4 lcore(s)
EAL: Detected 1 NUMA nodes
EAL: Multi-process socket /var/run/dpdk/rte/mp_socket
EAL: Selected IOVA mode 'PA'
EAL: No available hugepages reported in hugepages-1048576kB
EAL: Probing VFIO support...
EAL: VFIO support initialized
EAL: PCI device 0000:02:01.0 on NUMA socket -1
EAL:   Invalid NUMA socket, default to 0
EAL:   probe driver: 8086:100f net_e1000_em
EAL: PCI device 0000:03:00.0 on NUMA socket -1
EAL:   Invalid NUMA socket, default to 0
EAL:   probe driver: 15ad:7b0 net_vmxnet3
hello from core 1
hello from core 2
hello from core 3
hello from core 0

As it turns out, this is the correct approach, even though the documentation appears to assume that this is obvious. There is no mention of root privileges required on section "6.2. Running a Sample Application", excerpt below:

Copy the DPDK application binary to your target, then run the
application as follows (assuming the platform has four memory channels
per processor socket, and that cores 0-3 are present and are to be
used for running the application):
./dpdk-helloworld -l 0-3 -n 4

However, this point is mentioned later in the documentation, see "8.2. Running DPDK Applications Without Root Privileges" where there's a clear note:

The instructions below will allow running DPDK as non-root with older
Linux kernel versions. However, since version 4.0, the kernel does not
allow unprivileged processes to read the physical address information
from the pagemaps file, making it impossible for those processes to
use HW devices which require physical addresses

There is also a hint in the FAQ:

What does "EAL: map_all_hugepages(): open failed: Permission denied Cannot init memory" mean? This is most likely due to the test
application not being run with sudo to promote the user to a
superuser. Alternatively, applications can also be run as regular
user. For more information, please refer to DPDK Getting Started
Guide.

And an email touching on this topic:
2016-07-07 16:47, Jez Higgins:
> Is it possible to get DPDK up and running as non-root - if so, can
> anyone guide me to what I'm missing? Or should I be giving this up as a
> bad job?

You can try the --no-huge option.
But most of drivers won't work without hugepage currently.
A rework of the memory allocation is needed to make it work better.

That was four years ago. Perhaps there is already a solution which does not require sudo or --no-huge? If so, other answers are most welcome. For now, I'm going with this.
Comment: this_still_works. Great answer!
Answer: @Nagev I request you to check dpdk as non root stack overflow question in Nov 2020
[EDIT-1] Noticed the above question is removed, hence access to the details are limited, updating with the answer how to run without sudo or root privellege section
Note: I have been running DPDK application as non root with 18.11.5 LTS and 19.11.3 LTS
Comment: Thanks. The content no longer exists at the link you posted.
Comment: I can acees the link and post the answer back, but it looks like you already have posted the answer based on the comments shared. So do you still need the content?
Comment: I don't need it.


quantile regression question

Question: How can  we guess which one of a quantile regression equation between several quantile is better and we can choose that.for example if we have 2 equation :
<code>r1 = -2.8037 + 0.2433 * r2 + 0.4387 * r3 + 0.2011 * r4 + 1.1313 * r5     q=0.05   (1)
r1 = 2.663 + 0.2364 * r2 + 0.8739 * r3 - 0.0188 * r4 + 0.9471 * r5       q=0.95   (2)

sum coefficient of equation (1) = -0.7893
sum coefficient of equation (2) = 4.7022
</code>
can we say  when sum of coefficient a equation between several quantile regression are minimum  is suitable?
Comment: I improved formatting of your question - check if it is ok. Also it is not clear what you are asking so consider editing your question to describe it more precisely.
Answer: I suspect you used quantile regression to estimate the effects on the 5th and 95th quantile and want to know which is better.
The answer is that these two equations answer different questions and thus give different answers. So neither is better, they are just different.

quantile regression question


Regex matching area in PHP

Question: So I am doing a bit of scraping on a site, and everything is working just fine. The results I get back from the page have some span tags like such:
Assigned

There are actually a possible 5 span tags that could be returned. From 0-4. I'd like to be able to get the status dug out between the opening and closing span tags. I can't seem to find something on SO that works for what I need.
Comment: maybe better use an xpath instead of regex
Comment: Nope, don't go with regex , use a **DOMDocument** class ,  `foreach ($dom->getElementsByTagName('span') as $tag) {
               echo $tag->nodeValue;
    }`
Comment: so what about using preg_match_all?
Comment: Are you looking to scrape content_drptrResults_lbl`Status_0` from the id atrib?
Comment: yes, there are 5 possibilities from "Status_0" to "Status_4"
Answer: Don't use regex. But if you have to, this is far from perfect.
Its especially bad if nesting occurs.
 #  '/]*id\s*=\s*"[^"]*Status_([0-4])[^"]*"[^>]*>([^<>]*)<\/span\s*>/'

 ]*
 id \s* = \s*
 " [^"]*
 Status_
 ( [0-4] )        # (1)
 [^"]*
 "
 [^>]*
 >
 ( [^<>]* )       # (2)

Perl test case
$str = 'Assigned';

if ($str  =~ /]*id\s*=\s*"[^"]*Status_([0-4])[^"]*"[^>]*>([^<>]*)<\/span\s*>/)
{
    print "Matched '$1' = '$2'\n";
}

Output >>
Matched '0' = 'Assigned'

Comment: grrr - I can't get this to work.
Comment: @MrTechie - Should work. I changed the delimiter and added a test case in Perl (don't have php), same as PCRE.
Comment: I got it working after a little tweaking but you put me on the right path! :) Thanks

Regex matching area in PHP


Definition of Parabola

Question: Question
Every point on the parabola $y=\sqrt{2x-1}$ is equidistant from the $y$-axis and which of the following points?
(A) $(\frac{1}{2},0)$
(B) $(1,0)$
(C) $(\frac{3}{2},0)$
(D) $(2,0)$
(E) $(\frac{5}{2},0)$
I found the domain of the function to be $x$ is greater than or equal to $\frac{1}{2} (x\geq \frac{1}{2})$. Hence I guessed the shortest distance from the $y$-axis would be $(\frac{1}{2},0)$. However, the answer in the textbook is $(1,0)$. I don't really understand how they arrived at that.
Comment: Here's the [MathJax tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) $\ddot\smile$
Answer: It's not about the shortest distance at all. It's about the geometrical definition of a parabola. You need to read the definition of the directrix and the focus of a parabola and how to find them from an equation of a parabola. The question essentially tells you that the $y$-axis is the directrix of this parabola and asks you to find its focus.
Hint: the equation of this parabola (or rather, half of a parabola, because of the square root) can be rewritten as $y^2=2x-1$ (along with the condition that $y\ge0$). You know where the vertex is, you're given the directrix, and now find the focus.
Comment: Now I see. I don't know what I was thinking about earlier. Thanks
Answer: A parabola is the locus of points equidistant from a fixed point (the focus) and a fixed line not passing through this point (the directrix).  You are basically given the directrix, which never intersects the parabola, is the $y$ axis.  So you need to find the focus.
The parabola is clearly symmetric about the $x$ axis passing through $(1/2,0)$ on this axis, which is the vertex.  Then the line segment from this vertex to the focus and the segment perpendicular to the directrix merge into a single longer line segment where the vertex is the midpoint from the directrix to the focus.  You see that this segment meets the directrix at $(0,0)$ and the vertex/midpoint is $(1/2,0)$ so the focus must be $(1,0)$ = choice B.
Comment: Thanks. Now I see where I mixed things up

Definition of Parabola


Aggregate and group with case when statement

Question: I am trying to write a query against a table that contains daily payroll data for employees at different locations.  I need to be able to get a count of employee ids that have greater than 30 paid hours in a week and a count of employee ids that have less than 20 for the same week.  I've tried this with no luck:
select
[WEEKENDING],
[LOCATION],
sum(case when [PAID_HOURS] > 30 then 1 else 0 end) as [COUNT_OVER_30],
sum(case when [PAID_HOURS] < 20 then 1 else 0 end) as [COUNT_UNDER_20]
from mydb.payroll
group by [WEEKENDING],[LOCATION]

This is the source table:

Here is the desired result:

Thank you so much in advance!!!
Comment: Please don't use images, use table markdown text
Comment: As the source data doesn't have columns named `weekending` or `location`, seems like you have an obvious place to start.
Comment: Do your weeks really end on a Tuesday? The first thing you need to do is map your dates to weeks and week-ending dates - possibly using a combination of `DATE_BUCKET()` and `DATEADD()`. You then need to sum the hours, grouped by date, location, and employee. That can all be wrapped up in a subquery or CTE and fed into your final query to calculate your counts.
Comment: Case is an expression **not** a statement
Comment: What isn't working with your current query?
Comment: @T N, your suggestion did the trick, I ended up using a CTE to sum the daily hours into a week and then referencing that CTE in my case expression to get the counts!  Thanks!  Can you submit as an answer so I can select it?
Comment: Please use this [VBA code](https://davetallett26.github.io/excel-markdown.html) to create a Markdown table from your data and edit it into your question.
Comment: And yes, unfortunately it does run TU-MO.  HAHA
Comment: @ZRaptor - Glad you got your answer. However, without usable schema and data (text or markdown table that I can cut and paste into a fiddle - not an image), it is not worth my time to manually transcribe the data and prepare a formal answer.
Answer: You seem to have the right idea, but maybe in the wrong order.
First group by EMPID, WEEKENDING, FACILITY to sum the number of hours per employee, then count the EMPIDs for each case.
So, something like:
SELECT WEEKENDING, FACILITY,
    SUM( CASE WHEN WORKED_HOURS > 30 THEN 1 ELSE 0 END ) AS WH30,
    SUM( CASE WHEN WORKED_HOURS < 20 THEN 1 ELSE 0 END ) AS WH20,
SELECT W, EMPID, FACILITY, SUM(WORKED_HOURS) AS WH
FROM (
    SELECT EMPID, WEEKENDING, FACILITY,
        SUM(WORKED_HOURS) AS WORKED_HOURS
    FROM Wherever
    GROUP BY EMPID, WEEKENDING, FACILITY
) T
GROUP BY W, FACILITY

Comment: Looks like the above needs a syntax check.


Renaming the field label from "author" to "created by"

Question: How can I implement a hook in my template file that will change the label of a field for the "group" content type from "author" to "created by"?

Comment: Are you using drupal 6 or drupal 7. Did you create this field for the "group" content type. Or is this specific to a module you are using. Please provide more  information.
Answer: To rename the label of a field add the preprocess function template_preprocess_node to your template.php file:
function *YOUR THEME*_preprocess_node(&$vars){
  //Supposing that your content type name is "group"
  if($vars['type'] == 'group'){
    //Supposing that your field name is "field_txt_group"
    $vars['content']['field_txt_author']['#title'] = 'created by';
  }
}

Answer: I'll take a guess that there are a few different ways you can do this.

Use jQuery to target the element and use text replacement. You could so something like:
$("#my-element").each(function () {
  var s=$(this).text(); //get text
  $(this).text(s.replace('Author', 'created by')); //set the text to the replaced version
});

Of course you will need to add on Drupal specific jQuery code depending on what version of Drupal you are using (6 or 7). See: JavaScript in Drupal 5 and Drupal 6 and Managing JavaScript in Drupal 7.

Try the String Overrides module
Write a template pre-process function (template.php in your theme folder) to replace that text.
Comment: String Overrides would surely affect any usage of the word "author" which is probably not what's wanted here. jQuery is not an ideal way of changing this. The best approach would be to investigate some preprocess functions and change it only for the required content types.
Answer: You can also change the label from a field preprocess
function THEMENAME_preprocess_field(&$variables, $hook) {
  $field_name = $variables['element']['#field_name'];
  $view_mode = $variables['element']['#view_mode'];

  switch ($field_name) {
    case 'YOUR_FIELD_NAME':
      $variables['label'] = t('FIELD LABEL EVERYWHERE');
      // Possible to restrict by view mode
      if ($view_mode == 'teaser') {
        $variables['label'] = t('TEASER LABEL HERE');
      }
      break;

    // Duplicate for other fields
    case 'OTHER_FIELD_MACHINE_NAMES':
      // ...code
      break;
  }

}


Eight-ball or black ball pool rules

Question: In 8 ball pool, what is the penalty if I play my group ball and another one of my group balls falls into the pocket without being touched?
Comment: More information is needed to answer your question.  Are you talking of EPA black-ball rules? Black-ball world rules?...
Answer: The rules as defined at UPA are:

11.5 Hanging Ball
  If an object ball hangs in a pocket and drops in 5 seconds or less after coming to complete rest by the hole, the ball is considered to be pocketed. If a hanging ball drops in the pocket after being at rest for more than 5 seconds, the ball is returned to the original position on the edge, and the incoming player may begin his/her inning. Both players will have the opportunity to argue their case. The referee's decision is final.

11.6 Suspended Balls
  If one or more balls become suspended in a pocket beyond the edge of the slate because it is partially supported by other pocketed balls, it is considered pocketed if the removal of the supporting ball(s) would cause the supported/suspended ball(s) to fall into the pocket. Tournament officials are the sole judges of whether this rule applies to any situation.

11.7 Settling Into Place
  A ball may settle slightly after it appears to have stopped, possibly due to slight imperfections in the cloth or table slate. Unless this causes a ball to fall into a pocket, it is considered a normal hazard of play and will not be moved back. If a ball falls into a pocket as a result of such settling, it is replaced as close as possible to its original position on the lip of the pocket. If a ball falls into a pocket during or just prior to a shot and it has an effect on the shot, the referee will restore the ball to its original position and the shot will be replayed. Players are not penalized for shooting while a ball is settling.

So no foul is committed.

Eight-ball or black ball pool rules


Show list of items not at the show page but at the index page

Question: May you help me please..
I have three models:
Day, Course, Dish
class Day < ApplicationRecord

  has_many :courses

  has_many :dishes, through: :courses

end

class Course < ApplicationRecord

  belongs_to :day

  belongs_to :dish

end

class Dish < ApplicationRecord

  has_many :courses

  has_many :days, through: :courses

end

class DaysController < ApplicationController

  before_action :require_user

  def index

    @days = Day.all

  end

  def show

    @day = Day.find(params[:id])

    @dishes = @day.dishes

  end

end

View index.html.erb:

    <% @days.each do |day| %>

      <button>

        <%=day.weekday %>

        <%= link_to "Show menu", day_path(day) %>

      </button>

      <% end %>

    <%= link_to "Back to Profile", profile_dir_path(@user), method: "get" %>

View show.html.erb:

Menu

    <% @dishes.each do |dish| %>

<%= dish.name%>

<%= dish.description%>

    <% end %>

What do I really need:
I need to display a list of dishes on the index page by clicking on the day button. (When user click on the weekday button he need to see menu list of items (in my implementation dishes))
But as you see I made display dishes on the show page.... May you give a couple of advise how can i realize it?
Comment: You can add a "view dishes" button on the index, next to each day, and a div underneath to load show via ajax. Look up ajax requests in Rails, if you spend some time reading you'll figure it out.
Comment: Thank you very much, I'll try. Is it possible not to make an additional button opposite each day, but use an existing button that I added to the index.html.erb?
Answer: You can try with AJAX request. Here I have added one AJAX request with day button.
# app/views/days/index.html.erb

    <% @days.each do |day| %>

      <%= button_to day.weekday, day_path(day), data: { remote: true } %>

    <% end %>

    <%= link_to "Back to Profile", profile_dir_path(@user), method: "get" %>

Here I am adding one view file for JS request.
# app/views/days/show.js.erb

$('.days').find('#menuList').html('<%= j (render "dishes", dishes: @dishes) %>');

Here I am adding _dishes.html.erb partial for rendering dishes.
# app/views/days/_dishes.html.erb

Menu

<%= link_to "Close", "#", id: "closeLink" %>

<% dishes.each do |dish| %>

<%= dish.name %>

<%= dish.description %>

<% end %>

Enjoy :-)
Comment: Thank you for your example! I try to write, and write but with some bugs.
And it work fine when i add
`<%= button_to day.weekday, day_path(day), remote: true, method: "get" %>`
instead of your code
`<%= button_to day.weekday, day_path(day), data: { remote: true } %>`
Otherwise I'm going to another page (like {somename/1}) - asynchronous doesn't work
And I don't understand why your script(closeLink) in _dishes.html.erb doesn't work properly. When I click Close link I see only white space. I edit it:
`$('#menuList, a').html("<%= j (render "dishes", dishes: @dishes) %>");`
Comment: You can use like: `$(this).parent().fadeOut('slow');`. I think this should work.
Sorry for the inconvenience. I forgot to add `method: "get"`. Use can use like `method: :get`. Thanks. :)


How can I add an image field to a block?

Question: I want to add a block containing an image field to Drupal to add it to the page layout.
I can see the image gets uploaded (because it appears in my file system), but the block forgets the image; next time I configure the block, the image I just uploaded has disappeared.
What I've got so far is the following code.
<code>/**
 * {@inheritdoc}
 */
public function build() {
  $build = [];
  $build['image']['#markup'] = '';

  return $build;
}

/**
 * {@inheritdoc}
 */
public function blockForm($form, FormStateInterface $form_state) {
  $form['image'] = array(
    '#type' => 'managed_file',
    '#upload_location' => 'public://images/',
    '#title' => $this->t('Image'),
    '#description' => t("Image to show on the contact form"),
    '#default_value' => $this->configuration['image']['value'],
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg'),
      'file_validate_size' => array(25600000),
    ),
    '#states' => array(
      'visible' => array(
        ':input[name="image_type"]' => array('value' => t('Upload New Image(s)')),
      )
    )
  );

  return $form;
}

public function blockValidate($form, FormStateInterface $form_state) {}

/**
 * {@inheritdoc}
 */
public function blockSubmit($form, FormStateInterface $form_state) {
  $image = $form_state->getValue('image');
  $this->configuration['image'] = $image;
  $file = \Drupal\file\Entity\File::load($image[0]);
  $file->setPermanent();
  $file->save();
}
</code>
How do I display a user-uploaded image?
How do I make the block remember this picture?
Answer: With help from "Ambidex" on Drupal Slack, I post here the complete plugin-file.
I could not find an example for this use case, and I believe it might benefit others:
file: [drupalroot]/modules/custom/ourcustomername_tweaks/src/Plugin/Block
/ContactBlock.php
.
<code><?php

namespace Drupal\ourcustomername_tweaks\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;

/**
 * Provides a 'Contact' Block.
 *
 * @Block(
 *   id = "contact_block",
 *   admin_label = @Translation("Image Contact block"),
 * )
 */
class ContactBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [

        'image' => [
          'value' => ''
        ],

        'label_display' => FALSE,
      ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function build(){
    $build = [];

    if (  isset($this->configuration['image']) && !empty( $this->configuration['image'] )  ) {

      $image_field = $this->configuration['image'];
      $image_uri = File::load($image_field[0]);

      $build['image'] = [
        '#theme' => 'image_style',
        '#style_name' => 'ourcustomername',
        '#uri' => $image_uri->uri->value
      ];
    } else {
      $build['image']['#markup'] = '['.t('Picture').']';
    }

    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {

    $form['image'] = array(
      '#type' => 'managed_file',
      '#upload_location' => 'public://images/',
      '#title' => $this->t('Image'),
      '#description' => t("Image to show on the contact form"),
      '#default_value' => $this->configuration['image'],
      '#upload_validators' => array(
        'file_validate_extensions' => array('gif png jpg jpeg'),
        'file_validate_size' => array(25600000),
      ),
      '#states'        => array(
        'visible'      => array(
          ':input[name="image_type"]' => array('value' => t('Upload New Image(s)')),
        )
      )
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {

    /* Fetch the array of the file stored temporarily in database */
    $image = $form_state->getValue('image');

    $this->configuration['image'] = $image;

    /* Load the object of the file by it's fid */
    $file = \Drupal\file\Entity\File::load( $image[0] );

    /* Set the status flag permanent of the file object */
    $file->setPermanent();

    /* Save the file in database */
    $file->save();
  }
}
</code>


How do i sum consecutively the 4th element of a list of lists (python)

Question: I have this:
lst=[['Lisboa', 36.751510873830824, 204.31859739607566, '3'],
    ['Madrid', 520.8624708804804, 392.9722807116641, '2'],
    ['Copenhaga', 1971.3230985689115, 2086.416520356296, '5'],
    ['Berlin', 2046.6589661942558, 1735.7426148990855, '4']]

and want to receive this:
[['Lisboa', 36.751510873830824, 204.31859739607566, '3'],
['Madrid', 520.8624708804804, 392.9722807116641, '5'],
['Copenhaga', 1971.3230985689115, 2086.416520356296, '10'],
['Berlin', 2046.6589661942558, 1735.7426148990855, '14']]

Hope to get some help here!!
Comment: Please show us what you've tried.
Comment: Welcome to StackOverflow.  Your question is attracting downvotes, and close votes, because it doesn't meet the guidelines at [ask].
Answer: This is a questionable pattern probably, but:
 summed = 0
 for inner_list in outer_list:
      summed += inner_list[3]
      inner_list[3] = summed

If you want to keep the strings for some reason:
 summed = 0
 for inner_list in outer_list:
      summed += int(inner_list[3])
      inner_list[3] = str(summed)

Comment: Sorry, why the down vote?
Comment: I'm only guessing, but this question is in the close vote queue, because it doesn't meet the guidelines (That's how I came across it).   The "accepted" thing to do with questions that don't meet the guidelines is flag them, not answer them.  This seems unhelpful to me, but it's how it works - you may not know that.   Irritated close vote queue reviewers may downvote your answer because it encourages bad questions.    That's not officially accepted either, but it happens. You can read the controversy about this at meta.stackoverflow.com if you're interested.   HTH you understand.
Answer: It is not clear whether or not you need *** around the initial value of 3.  If these were a failed attempt to bold the numbers, and you need the number in string format, then try:
cumsum = 0
for i in lst:
    cumsum += int(i[3])
    i[3] = str(cumsum)

>>> lst
[['Lisboa', 36.751510873830824, 204.31859739607566, '3'],
 ['Madrid', 520.8624708804804, 392.9722807116641, '5'],
 ['Copenhaga', 1971.3230985689115, 2086.416520356296, '10'],
 ['Berlin', 2046.6589661942558, 1735.7426148990855, '14']]

Comment: Pretty sure the asterisks were a failed attempt to make the font within the code bold.
Comment: Other than spite, not sure for the reason for the down vote since it answered the OP's question.


Erro ao enviar app para a apple store - Invalid Image Path

Question: Ao tentar fazer o upload da aplicação para a apple store esta me apresentando o seguinte erro e não consegui identificar como resolver esse erro.
Nessa aplicação estou usando o ionic, anteriormente eu já havia enviado essa mesma aplicação para a loja sem problemas, mais após um update está me apresentando o erro abaixo!!! Alguma dica?? Obrigado
Comment: Já tentou esta resposta (Ingles): http://stackoverflow.com/questions/28165916/error-itms-90032invalid-image-path-no-image-found-at-the-path-referenced-und
Comment: Acabei encontrando como resolver esse problema... https://github.com/apache/cordova-ios/commit/4ca3f28bae30b0974da7a7a4033d158b08303c4c?diff=unified
Comment: Para ajudar outras pessoas, recomendo que responda sua própria pergunta com esta solução, procure detalhar a resposta, não utilize somente link para justificar.
Answer: No arquivo 'PROJECT_NAME-Info.plist' Identifique e remova as seguintes linhas;
<code><key>CFBundleIconFile</key>
<string>icon.png</string>
</code>
Isso corrige o erro submissão ITC que este arquivo está faltando.
https://github.com/apache/cordova-ios/commit/4ca3f28bae30b0974da7a7a4033d158b08303c4c?diff=unified


how to execute ftp command " put 'FILE_NAME' " using python script

Question: how do I execute ftp command " put 'FILE_NAME' " using python script?
I want to transfer a file to the processor connected using FTP.
Command is ftp> put "C:\filename"
I want this to be executed using python script. Please help in this.
Answer: <code>from subprocess import call

call(['echo "put C:\filename" | ftp'])
</code>
this should call "ftp" command and pass input string "put C:\filename"


Suppose $(X, \mathcal{A})$ is a measurable space, $f$ is a real valued function, and $\{x : f(x) > r\} \in \mathcal{A} $ for each rational number $r$.

Question: Suppose $(X, \mathcal{A})$ is a measurable space, $f$ is a real valued function, and $\{x : f(x) > r\} \in \mathcal{A} $ for each rational number $r$. Prove that $f$ is measurable.
A function is measurable if $\{ x : f(x) > a \} \in \mathcal{A}$ for all $a \in \mathbb{R}$. For all $a \in \mathbb{R} $, there exists a sequence of rational numbers that converge to $a$, $r_k$, where $r_k > r_{k+1}$. We then have
$$\cup_{k =1}^{\infty}\{x : f(x) > r_k\} = \{ x : f(x) > a \} $$ Since $ \cup_{k =1}^{\infty}\{x : f(x) > r_k\} $ is the union of sets in $\mathcal{A}$, then it is also in $\mathcal{A}$ and by definition is measurable.
I want to show that this is true $$\cup_{k =1}^{\infty}\{x : f(x) > r_k\} = \{ x : f(x) > a \} $$
My approach is a double containment.
First show that $$\cup_{k =1}^{\infty}\{x : f(x) > r_k\} \subseteq \{ x : f(x) > a \} $$ Which is trivial, since every $r_k$ is larger than $a$. Any value larger than $r_k$ is always larger than $a$.
My trouble is going the other direction. $$\cup_{k =1}^{\infty}\{x : f(x) > r_k\} \supseteq \{ x : f(x) > a \} $$
Is there a way I can rewrite the RHS to be subsets of what is on the LHS?
Comment: If $y>a,$ $r_{k}\searrow a,$ so once $k$ is large enough, $y>r_{k}>a.$ This lets you prove the second containment in the usual way, i.e., $A\subseteq B$ if and only if every point in $A$ is a point in $B$.
Answer: One consequence of convergence of $r_k$ to $a$ from above is:

For each $y$ such that $y>a$, there exists $k$ such that $y>r_k$

which implies

For each $x$ such that $f(x)>a$, there exists $k$ such that $f(x)>r_k$

which is equivalent to the set containment
$$\{x:f(x)>a\} \subseteq \bigcup_{k=1}^\infty \{x:f(x)>r_k\}$$
Answer: This might be helpfull:.....
if $ y \in \lbrace { x:f(x)>a \rbrace}$ then it is clear that $y>a$, and by archimedian property of real numbers there exists $n \in N$ such that $y > \dfrac{1}{n}>a$. the result follows. i.e. $y \in \cup \lbrace { x:f(x)>r_k \rbrace}$


LASSO relationship between $\lambda$ and $t$

Question: My understanding of LASSO regression is that the regression coefficients are selected to solve the minimisation problem:
$$\min_\beta \|y - X \beta\|_2^2 \ \\s.t. \|\beta\|_1 \leq t$$
In practice this is done using a Lagrange multiplier, making the problem to solve
$$\min_\beta \|y - X \beta\|_2^2 + \lambda \|\beta\|_1 $$
What is the relationship between $\lambda$ and $t$?  Wikipedia unhelpfully simply states that is "data dependent".
Why do I care?  Firstly for intellectual curiosity.  But I am also concerned about the consequences for selecting $\lambda$ by cross-validation.
Specifically, if I'm doing n-fold cross validation, I fit n different models to n different partitions of my training data.  I then compare the accuracy of each of the models on the unused data for a given $\lambda$.  But the same $\lambda$ implies a different constraint ($t$) for different subsets of the data (i.e., $t=f(\lambda)$ is "data dependent").
Isn't the cross validation problem I really want to solve to find the $t$ that gives the best bias-accuracy trade-off?
I can get a rough idea of the size of this effect in practice by calculating $\|\beta\|_1$ for each cross-validation split and $\lambda$ and looking at the resulting distribution.  In some cases the implied constraint ($t$) can vary quiet substantially across my cross-validation subsets.  Where by substantially I mean the coefficient of variation in $t>>0$.
Comment: Upvoting to cancel out the unexplained downvote. The question is well outside my expertise but it seems reasonably formulated.
Answer: This is the standard solution for ridge regression:
$$
\beta = \left( X'X + \lambda I \right) ^{-1} X'y
$$
We also know that $\| \beta \| = t$, so it must be true that
$$
\| \left( X'X + \lambda I \right) ^{-1} X'y  \| = t
$$.
which is possible, but not easy to solve for $\lambda$.
Your best bet is to just keep doing what you're doing: compute $t$ on the same sub-sample of the data across multiple $\lambda$ values.
Comment: Can you explain the intuition for why $||\beta|| = t$? I would think that this would only be true if the minima for the $RSS^{OLS}$ solution falls outside of the L1-ball given a specific $\lambda$. Otherwise, wouldn't $||\beta|| \le t$ ?
Answer: This question relates to Is the magnitude coefficient vector in Ridge regression monotonic in lambda? which sketches a situation for ridge regression, but it is similar for Lasso.

Consider the relationship of the optimal RSS as a function of the value of $t = \vert \beta \vert$. Say that this function is $RSS = f(t)$.
The goal of lasso is to find the $\beta$ which minimizes $$\text{Cost}(\beta) = RSS(\beta) + \lambda \vert\beta\vert$$
We could describe the cost as well as a function of the magnitude of the coefficients $t$
$$\text{Cost}(t) = f(t) + \lambda t$$
this is minimized when
$$\frac\partial{\partial t} \text{Cost}(t) = \frac\partial{\partial t} f(t) + \lambda = 0 $$
And the relationship between $\lambda$ and $t$ is
$$\lambda = - \frac\partial{\partial t} f(t)$$
This function $f(t)$, the size of the RSS for a given size of the estimates of the coefficients, is dependent on the data.


how to secure or hide my javascript code?

Question: Is there anyway to hide or secure my javascript code. Because anyone can easily
see my javascript logic on my website using view page source and it's harmful for me. Please tell me any method you know for securing the javascript code or for making it difficult to understand using any encryption method with cannot easily decrypt.
Comment: Nope, it can't be done. If you want to hide it, you need to do something server-side.
Comment: If you need to do things with private code, do it on the server. If the browser can run the JavaScript, a person can see it.
Comment: You can't.  One the JavaScript hits my browser, I can see it and do what I want with it.
Comment: thanks dud it's really helpful.
Answer: You can't. Don't put sensitive code, keys, information, or logic on the client. The only thing you can do is make it harder to read by running your code through an obfuscator.


Copy vs move in std::pair braced initialization

Question: I have the following code and its output printed below. I can't seem to understand why one set of braced initialization results in the move constructor being called, while the other results in the copy constructor. I have somewhat narrowed it down to direct-list-initialization vs copy-list-initialization per https://en.cppreference.com/w/cpp/language/list_initialization
I just can't quite figure out which case my code belongs to. Thanks in advance.
#include <cstdint>
#include <iostream>
using namespace std;

struct Foo {
  Foo() {
    cout << "create foo\n";
  }

  ~Foo() {
    cout << "delete foo\n";
  }

  Foo(const Foo& f) {
    cout << "copy foo\n";
  }

  Foo(Foo&& f) noexcept {
    cout << "move foo\n";
  }

  Foo& operator=(const Foo& f) = delete;

  Foo& operator=(Foo&& f) = delete;
};

int32_t main() {
  pair<uint32_t, Foo> f1{0, Foo{}};  // Calls move ctor
  cout << "------------------------\n";

  pair<uint32_t, Foo> f2{0, {}};     // Calls copy ctor
  cout << "------------------------\n";

  return 0;
}

This results in
create foo

move foo

delete foo

------------------------

create foo

copy foo

delete foo

------------------------

delete foo

delete foo

Answer: Let's take a look at two of the two-argument constructors of pair: [pairs.pair]
EXPLICIT constexpr pair(const T1& x, const T2& y);
template<class U1, class U2> EXPLICIT constexpr pair(U1&& x, U2&& y);

The second constructor uses perfect forwarding, and U2 cannot be deduced from {}.  Therefore, the first version is selected when {} is used.  When Foo{} is used instead, the argument has type Foo, so U2 is deduced to be Foo, causing the forwarding version to be selected.
Comment: While your explanation makes sense about the compiler choosing which version to call, I can't seem to convince myself that it is indeed the case.

I specified the Foo constructor as 'explicit' and I get an error that reads:
error: converting to 'const Foo' from initializer list would use explicit constructor 'Foo::Foo()'
Comment: @tree Are you using C++17?  In C++17, both of these constructors are conditionally `explicit`, i.e., `explicit` if any of the constructors they need call is `explicit`.  They were unconditionally `explicit` in previous versions, and the change to conditional `explicit` was applied as a Defect Report.
Comment: Yes, I am using c++17.
So what you're saying is because I declared my Foo constructor explicit, I MUST use `Foo{}` instead of `{}`.
Comment: @tree Oh, you mean the compiler rejected `{}`?  Yeah, in that case `explicit` constructors are not considered, since argument passing is copy-initialization (i.e., non-`explicit` initialization).
Comment: Yes, the moment I added the `explicit` to the Foo constructor,  the compiler rejected the `{}` initialization for `Foo`
Comment: @tree Yeah, I meant to say that argument passing uses copy-initialization, so passing `{}` as an argument is like using `const T2& y = {}` to initialize the parameter `y`
Comment: Let me see if I understand...
Because I specified the `Foo` constructor as `explicit`, the way to think about the correct way to initialize it would be `const T2& y = Foo{}`?
Comment: @tree Yes.  So passing `Foo{}` to a parameter will work fine too.
Comment: Let me try to summarize what I've learned...
The compiler can't determine the type for the perfect fowarding `std::pair` constructor when using `{}` to initialize `Foo` because the type is missing, therefore the next best match is the `std::pair` copy constructor where the `Foo` argument is `const T2& y` which results in `Foo`'s copy constructor being called. By adding `explicit` to `Foo`s constructor, the compiler rejects the implicit construction of `Foo` when it matches `const T2& y`


Recurrence relation - 2 consecutive 0s

Question: I have a question about this question:
Recurrence relation find the number of binary strings that contain two consecutive zeros
In your answer,

No, it takes each bit separately, except for the last two. It says the
  string can end in 00,01,10,11. If it ends in 00 it is acceptable
  regardless of what came before-that is the 2n−2. If it ends in
  anything else, it must have been acceptable before, or have the 00
  come from the addition. Adding a 1 can never make a string acceptable,
  so you can add it to the end of an−1 strings. We still haven't
  accounted for the ones that end in 10, and that is the an−2.

I'm a little confused about why the case '11' is counted in the a(n-1) case but not the a(n-2) case. Can you not also add '11' to the end of any a(n-2) string and maintain that the string before still has substring '00'?
Thanks in advance,
Eric
Answer: We can account for $11$ in the $a_{n-2}$, case but it makes the $a_{n-1}$ case harder to deal with. Here's what would happen:
We have $4$ endings we can add to an $n-2$ length string to get to an $n$ length string: $00,01,10$, and $11$. Of these, the $10$ case and the $11$ case can't add any consecutive $0$s, so together they give us $2a_{n-2}$ valid strings. As in the other construction the $00$ case gives us a $2^{n-2}$ term (since it doesn't matter what the previous digits were). Finally, we are left with the $01$ case. This case is a little tricky to deal with because it will not just give us $a_{n-1}$ strings because we have the additional restriction that the last digit of the $n-1$ length string is a $0$. Okay, so how many valid strings of length $n-1$ are there whose last digit is $0$?. Well, as we had before the number of valid length $n-1$ stings whose last digit is $1$ is just $a_{n-2}$. Hence the number of valid $n-1$ length string who end in $0$ is $a_{n-1}-a_{n-2}$. This gives us the recurrence relation
$$a_n=2a_{n-2}+a_{n-1}-a_{n-2}+2^{n-2}=a_{n-2}+a_{n-1}+2^{n-2}$$
which is exactly what we had before except it took a bit more work.
The idea in the original solution is to avoid this difficulty by working backwards. First, if we add a $1$ to a valid $n-1$ length string, we get a valid $n$ length string, so we get an $a_{n-1}$ term (note here we are dealing with both the $01$ and $11$ cases because we are just requiring that the last digit be $1$). This leaves us with the $10$ and $00$ cases. The $00$ case we immediately deal with as before (getting a $2^{n-2}$ term). The $10$ case now just gives us a term of $a_{n-2}$ since we can't add any consecutive $0$s by adding $10$. Putting this into a recurrence relation gives us exactly the same thing as above, but we avoid having to cancel any terms.

Recurrence relation - 2 consecutive 0s


Convert hex value to decimal in C but keep getting incorrect value, plus too few argument error when calling func

Question: Hello I am trying to convert a hex value into the decimal form but for some reason the result I'm getting each time is negative and completely incorrect. Additionally I would like to take that decimal number and then convert it into it binary value. I have created func's for both but have run into the problem of "too few arguments" when calling my bin() func. If somebody could point me in the right direction and explain what I am doing wrong I would sincerely appreciate it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define arraysize 20

int decimal() {

    int i = 0, val, len;
    char hex1[arraysize];
    long long dec = 0, base = 1;

    len = strlen(hex1);

    for (i = len--;i >= 0; i--) {
        if (hex1[1] >= '0' && hex1[i] <= '9') {
            dec += (hex1[i] - 48) * base;
            base *= 16;
        }
        else if (hex1[i] >= 'A' && hex1[i] <= 'F') {
            dec += (hex1[i] - 55) * base;
            base *= 16;
        }
        else if (hex1[i] >= 'a' && hex1[i] <= 'f') {
            dec += (hex1[i] - 87) * base;
            base *= 16;
        }
    }
    printf("Your decimal value is: %lld\n",dec);
    return 0;
}

int bin(long long dec) {

    int a[10], i;

    for (i = 0; dec > 0; i++) {
        a[i] = dec % 2;
        dec = dec / 2;
    }
    printf("\nThe binary value is: ");
    for (i = i - 1; i >= 0; i--) {
        printf("%d", a[i]);
    }
    return 0;
}

int main() {

    char hex1[arraysize];

    printf("Enter your HEX value: ");
    fflush(stdin);
    fgets(hex1, arraysize, stdin);

    decimal(hex1);
    bin();
}

Comment: The best advice would be to learn how to debug your own code. Run your program in a debugger and step thru it to trace it's execution flow and variable values. As for the second problem you are obviously missing a required arg in the `bin()` call which takes one arg.
Comment: The `decimal` function does not take a parameter yet there is one passed. The `bin` functions expects a parameter but none is passed. The `decimal` function doesn't work because the function does not accept the string that is input and instead it tries to convert an uninitialized array.
Comment: @fishbrains This call len = strlen(hex1); invokes undefined behavior.
Comment: @fishbrains: you can accept one of the answers by clicking on the grey checkmark below its score.
Answer: There are multiple problems in your code:

hex1 should be passed as an argument to decimal(). As posted, your code has undefined behavior because hex1 is an uninitialized local array.

i = len-- initializes i to the value of len, hence one position too far. Use i = len - 1 instead.

if (hex1[1] >= '0' && hex1[i] <= '9') uses hex[1] instead of hex[i]

you should use expressions with character constants '0', ('A' - 10) and ('a' - 10) instead of hard coded magical values 48, 55 and 87.

the array a is too short in function bin(). You should give it a length of at least 64.

the argument in bin() should have unsigned long long type.

fflush(stdin); has undefined behavior.

Here is a modified version:
#include <stdio.h>

unsigned long long decimal(const char *hex) {
    unsigned long long dec = 0;
    int i, c;

    for (i = 0; (c = hex[i]) != '\0'; i++) {
        if (c >= '0' && c <= '9') {
            dec = dec * 16 + (c - '0');
        } else
        if (c >= 'A' && c <= 'F') {
            dec = dec * 16 + (c - 'A' + 10);
        } else
        if (c >= 'a' && c <= 'f') {
            dec = dec * 16 + (c - 'a' + 10);
        }
    }
    return dec;
}

void bin(unsigned long long dec) {
    char a[65];
    int i;

    a[64] = '\0';
    for (i = 63;; i--) {
        a[i] = '0' + dec % 2;
        dec = dec / 2;
        if (dec == 0)
            break;
    }
    printf("The binary value is: %s\n", a);
}

int main() {
    char hex1[20];

    printf("Enter your HEX value: ");
    if (fgets(hex1, sizeof hex1, stdin)) {
        unsigned long long dec = decimal(hex1);
        printf("Your decimal value is: %llu\n", dec);
        bin(dec);
    }
    return 0;
}

Comment: @RetiredNinja: yes indeed, answer updated, thank you.
Answer: The "too few arguments" error means exactly what it says: you are calling the bin() function with no arguments. In your function definition, you defined bin() as taking a long long dec argument. When you call bin(), you must give it an argument, like
bin(7);

You have made the opposite mistake in the line above:
decimal(hex1);

You defined decimal() as taking no arguments, yet you called it with a char[] argument. In your decimal function you can remove the line where you declare an array of chars, and instead make that an argument of the function:
int decimal(char* hex1) {

    int i = 0, val, len;
    long long dec = 0, base = 1;

    . . .

You may want to further research the semantics of passing an array as an argument to a function.
Answer: Try this and replace char hex1[arraysize]="FFFFFFFFFFFFFFFF"; as needed:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define arraysize 20
#define bin_arraysize 64

unsigned long long decimal(char* hex1) {

        long long dec = 0, base = 1;
        int len = strlen(hex1);
        for(int i = len-1;i >=0; i--) {
               if(hex1[i] >= '0' && hex1[i] <= '9') {
                        dec += (hex1[i] - 48) * base;
                        base *= 16;
               }
                else if(hex1[i] >= 'A' && hex1[i] <= 'F') {
                        dec += (hex1[i] - 55) * base;
                        base *= 16;
                }
               else if(hex1[i] >= 'a' && hex1[i] <= 'f') {
                       dec += (hex1[i] - 87) * base;
                       base *= 16;
               }
        }
        printf("Your decimal value is: %llu\n",dec);
        return dec;
}

void bin(unsigned long long dec) {

        int a[bin_arraysize], i;

        for(i = 0; dec > 0; i++) {
                a[i] = dec%2;
                dec = dec/2;
        }
        printf("\nThe binary value is: ");
        for(i = i - 1; i >= 0; i--) {
                printf("%d", a[i]);
                }
        return;
}

int main() {

        char hex1[arraysize]="FFFFFFFFFFFFFFFF";
        unsigned long long dec=decimal(hex1);
        bin(dec);
}