Android Java Firebase Auth and Save User

Question: I get some information from users during the registration process. I want to register each username to be unique. I call my methods as follows.
if(!nameRegister.isEmpty() && !surnameRegister.isEmpty()
                        && !usernameRegister.isEmpty() && !emailRegister.isEmpty()
                        && !passwordRegister.isEmpty() && !passwordConfirmRegister.isEmpty()){
                if (passwordRegister.equals(passwordConfirmRegister)) {

                    isUsernameTaken = checkUsernameIsExist(nameRegister, surnameRegister, usernameRegister, emailRegister, passwordRegister);

                    if(!isUsernameTaken)
                        isMailAuthenticationSuccess = createUserWithEmailAndPassword(nameRegister, surnameRegister, usernameRegister, emailRegister, passwordRegister);

                }else{
                    passwordConfirm.setError("Passwords does not match.");
                    passwordConfirm.requestFocus();
                }

                if(isMailAuthenticationSuccess)
                    saveUserToFirebase(newUser);

            }

Its contents are as follows.
private boolean checkUsernameIsExist(final String nameRegister, final String surnameRegister, final String usernameRegister, final String emailRegister, final String passwordRegister) {

    FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
    DocumentReference docIdRef = rootRef.collection("users").document(usernameRegister);
    docIdRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document.exists()) {
                    isUsernameTaken = true;
                    Log.d(TAG, "Document exists!");
                    Toast.makeText(Register.this, "User name already taken", Toast.LENGTH_LONG).show();
                } else {
                    Log.d(TAG, "Document does not exist!");
                    Toast.makeText(Register.this, "User can be taken", Toast.LENGTH_LONG).show();
                }
            } else {
                Log.d(TAG, "Failed with: ", task.getException());
            }
        }
    });
    return isUsernameTaken;
}

private boolean createUserWithEmailAndPassword(final String nameRegister, final String surnameRegister, final String usernameRegister, final String emailRegister, String passwordRegister) {

    auth.createUserWithEmailAndPassword(emailRegister, passwordRegister)
            .addOnCompleteListener(Register.this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if(!task.isSuccessful()){
                        email.setError("Mail is already taken");
                        email.requestFocus();
                    }else{
                        newUser = new User(nameRegister, surnameRegister, usernameRegister, emailRegister);
                        isMailAuthenticationSuccess  = true;
                        auth.signOut();
                        startActivity(new Intent(Register.this, Login.class));
                        finish();
                    }
                }
            });
    return  isMailAuthenticationSuccess;

}

private static void saveUserToFirebase(User newUser) {

        FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
        firebaseFirestore.collection("users").document(newUser.getUsername())
                .set(newUser)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Log.d(TAG, "User add success.");
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.w(TAG, "user can not be added.", e);
                    }
                });
    }

Method can not add true boolean value to my variables. I think, addOnCompleteListener did not end before when assign to value my booleans.
However, if the user name can be obtained after user name control, user authentication is successful, but writing to Firebase does not take place. What could be the reason for this? I am waiting for your help.
Comment: Hi @Frank van Puffelen, my question is i call my saveUserToFirebase method succesfully. I can add my listeners also add logs inside of them. But  my listener can not work and can not save my object to cloud firestore. Why is not working? If you have any idea please give me an advice.
Comment: If you execute the code in a debugger and place breakpoints on both lines you'll see that your `return isUsernameTaken;` runs before the `isUsernameTaken = true;`.  I linked a number of questions that explain why that is, why you can't return a value that is asynchronously loaded, and how you can work around this.
Comment: Hi again Frank, many thanks for your help. I will check your linked questions. Have a nice day.
Comment: Frank first link is useful for me. Thank you so much for helping :)
Answer: call this method "createUserWithEmailAndPassword" in onSuccess of this method "checkUsernameIsExist" and make sure that your return type is void.
Comment: Hi, this is work but i tried before when i ask. I can not triggered add my user to firebase. I can call saveUserToFirebase method everything seems fine but can not trigger addOnCompleteListener or addOnSuccessListener. When i call my saveUserToFirebase method inside of createUserWithEmailAndPassword's onComplete nothing gonna happen.
Answer: A simple suggestion is that you call the saveUserToFirebase(newUser) inside the createUserWithEmailAndPassword() function just before you set isMailAuthenticationSuccess  = true;
Or call that function inside
if(!isUsernameTaken){
isMailAuthenticationSuccess = createUserWithEmailAndPassword(nameRegister, surnameRegister, usernameRegister, emailRegister, passwordRegister);
if(isMailAuthenticationSuccess)
 saveUserToFirebase(newUser); }
That might solve your problem.

Or you can try the below code

if(!nameRegister.isEmpty() && !surnameRegister.isEmpty() && !usernameRegister.isEmpty() && !emailRegister.isEmpty() && !passwordRegister.isEmpty() && !passwordConfirmRegister.isEmpty()){
    if (passwordRegister.equals(passwordConfirmRegister)) {
        checkUsernameIsExist(nameRegister, surnameRegister, usernameRegister, emailRegister, passwordRegister);
    }else{
        passwordConfirm.setError("Passwords does not match.");
        passwordConfirm.requestFocus();
    }
}

//checkUsernameIsExist
private void checkUsernameIsExist(final String nameRegister, final String surnameRegister, final String usernameRegister, final String emailRegister, final String passwordRegister) {
    FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
    DocumentReference docIdRef = rootRef.collection("users").document(usernameRegister);
    docIdRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                isUsernameTaken = true;
                Log.d(TAG, "Document exists!");
                Toast.makeText(Register.this, "User name already taken", Toast.LENGTH_LONG).show();
            } else {
                Log.d(TAG, "Document does not exist!");
                Toast.makeText(Register.this, "User can be taken", Toast.LENGTH_LONG).show();
                createUserWithEmailAndPassword(nameRegister, surnameRegister, usernameRegister, emailRegister, passwordRegister);
            }
        } else {
        Log.d(TAG, "Failed with: ", task.getException());
        }
        }
    });
}
// createUserWithEmailAndPassword
private void createUserWithEmailAndPassword(final String nameRegister, final String surnameRegister, final String usernameRegister, final String emailRegister, String passwordRegister) {
    auth.createUserWithEmailAndPassword(emailRegister, passwordRegister)
    .addOnCompleteListener(Register.this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if(!task.isSuccessful()){
                email.setError("Mail is already taken");
                email.requestFocus();
            }else{
                newUser = new User(nameRegister, surnameRegister, usernameRegister, emailRegister);
                saveUserToFirebase(newUser);
                isMailAuthenticationSuccess  = true;
                auth.signOut();
                startActivity(new Intent(Register.this, Login.class));
                finish();
            }
        }
    });
}

private static void saveUserToFirebase(User newUser) {
    FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
    firebaseFirestore.collection("users").document(newUser.getUsername())
    .set(newUser)
    .addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.d(TAG, "User add success.");
            Toast.makeText(Register.this, "User added successfully", Toast.LENGTH_LONG).show();
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.w(TAG, "user can not be added.", e);
            Toast.makeText(Register.this, "Couldn't add User. Try again later.", Toast.LENGTH_LONG).show();
        }
    });
}

Comment: Hi @BEAGLE, i tried these almost 5 minutes ago thank you :)  When i call my saveUserToFirebase method inside of createUserWithEmailAndPassword's onComplete nothing gonna happen. I have no idea i can call method and this is the right way i think. But it does not work. If you have any other idea im waiting thank you again.
Comment: Try adding few toasts inside the saveuser() to see the how far the code is executing. See if newUser.getUsername() returns value. can be referencing issue.
Comment: Try adding few toasts inside the saveuser() to see the how far the code is executing. See if newUser.getUsername() returns value. can be referencing issue.
Comment: Hi, i add Logs but i can not see any logs. It looks like my saveUserToFirebase method can be called but cant do anything :/ I can not understand why this is happening.


When remote machine dies, MPI manager failed to detect it with MPI_Irecv call

Question: I am writing a program to detect the sudden crash of remote machine. The manager process runs on machine 1 and the worker process runs on machine 2. The manager server sends a message to the worker process by calling MPI_Isend.  The remote worker get message by calling MPI_Irecv. After each call, I always check their return code to see if there is issue with MPI_COMM_WORLD. I also check return code of MPI_Test which runs after the send and recv calls.
Somehow, the return code is always 0 even after I rebooted machine 2 suddenly. I can see MPI_Isend always return value 0.  Please give me some advice on how to detect remote machine failure.
BTW, I did use following statement:
MPI_Errhandler_set(MPI_COMM_WORLD,MPI_ERRORS_RETURN);

Comment: Which MPI library are you using? Fault tolerance is a non-standard feature at the moment so it will depend heavily in whether you're using MPICH or Open MPI.
Comment: Ah. There's no guarantee that short sends will return an error. It's possible that the messages are sent eagerly which does not require a round trip message. This means that if you need to know whether there was a failure, you'll need to do something that will force communication via something like an `MPI_BARRIER`.
Comment: We are using MPICH either 2 or 3.  We are trying to implement some basic fault tolerance features until Argonne roll out fault tolerance  in the future.  Thanks!
Comment: There is some fault tolerance in those versions, you add the flag `--disable-auto-cleanup` and it will return errors to you. On the other hand, if you're not seeing failures at all, that's weird and I'm not sure what's going on.
Comment: FYI, Argonne is working on better FT for a future release. Hopefully that will be out within a few months.
Comment: I used --disable-auto-cleanup.  Same result.

On Manager, here are the calls.
rc = MPI_Isend(...)
rc = MPI_Test(...)

On workers, here are the calls.
rc = MPI_Irecv(...)
rc = MPI_Test(...)

Did check return code.  Always success.

While the program is running, I rebooted one of the nodes.  Here is the message,
Connection to wb201.qa2.ch3.qa.i.com closed by remote host.

As you can see, one of the workers is gone.  The system printed some warning message.  However, the manager process still sends message to that process and getting success return code back.

Thank you!
Answer: Probably should have turned this into an answer long ago to make it easier for other to track this down.

As has been discussed in other posts, MPI_Send and friend's completion does not necessarily indicate that a message has been received on the other end. Only MPI_Ssend implies any sort of completion and even that only indicates that the receiver has started receiving the message into its buffer.
For this particular problem, MPI_Ssend would probably be enough as it would indicate that a failure has occurred, though it would slow things down.
In the end, you can't rely on the sender side semantics to tell you that a failure has occurred without doing extra work in MPI. There's no guarantees built into the standard to do so because they would be expensive. If you must know quickly on the sender side, use MPI_Ssend. Otherwise, do a bunch of operations, then do something synchronizing later (like an MPI_Ssend or an MPI_Barrier if you want to validate all processes at once).


$node object not populating with data

Question: I'm using the Rules module to execute custom PHP script whenever a new node is saved after importing via Feeds module.
<?php

$lid = db_insert('location')->fields(array(
    'additional' => $node->field-address, //saves as '0'
    'city' => $node->field-locality, // saves '0'
    'province' => $prov, // //saves correctly
    'country' => 'xx', //saves 'xx' correctly
    'latitude' => $node->field-latitude-temp, //saves as 0.00000
    'longitude' => $node->field-longitude-temp, //same
    'source' => 1,
    'is_primary' => 0
))->execute();

This is the location table (from the Location module) and I'm importing data from a csv file.
All the other constant values are saved properly except for when it is coming from the $node object. Lat and Lon goes 0.00000 while all the other string values such as city and address also goes 0.
Been dealing with this for hours.
EDIT: I'm using Feeds module. But I need to import also location data. While a row is getting committed to db, the values are all 0!
node:field-latitude-temp shows the actual imported value correctly when viewing the node. But it is not getting absorbed in within the PHP Execute custom code page in Rules.
Comment: Any reason you're not using the Feeds module? Also which hook are you suing? Are you sure its called after node save?
Comment: @Queenvictoria I have edited my post above.
Comment: From where you are getting the $node object? are you doing any node_load or the node object is supplied via any hook?
Comment: It is supplied by the 'Execute Custom PHP Code' page via the Rules module. I have edited to include an image.
Comment: @Queenvictoria Also, the Feeds module can't import data to Location, not sure why though, so what I did was to temporarily save it to another field and then let drupal copy that value directly to the database using the execute code.
Comment: Okay, I figured this out. I can use [node:field-latitude-temp] to pass the value to the database and it works. But still my question is outstanding to $node variable.
Answer: I am not sure this can help you, but I don't think $node->field-address or $node->field-longitude-temp are valid syntax by $node object, you should use $node->field_address['und'][0]['value'] or with entity_metadata_wrapper function, eg:
$nodeWrapper = entity_metadata_wrapper('node', $node);
$nodeWrapper->field_address->value()

Comment: Yes, this appears to be the issue, though I'd suggest trying `$nodeWrapper->field_address->raw()` to get a value more suitable for `db_insert`
Comment: @DavidThomas yes, you're right, `raw()` will be the right method for insert operations..
Comment: Thanks @xurshid29 for taking the time. Right now I just figured out I can use 'Location Feeds' to import location data using Feeds module. I have been looking for this. Though will keep your solution in mind.

$node object not populating with data


Strange Javascript behaviour

Question: I am using JQuery to append images, like this:
$('#event_list_main').append('');

I am assign a highlight function to each image I create and append! The problem is that the highlight function does not execute.
//Highlight function
function highlight()
{
    var indicator = $(this).data("count");
    alert(indicator);

}

the "this" part doesnt seem to work.I want this to refer to each event created.
for example if I created 3 events
event_1
event_2
event_3
and I click on "image event_2" then "this" must refer to "image-event_2"
Comment: Can you confirm that `highlight` is a global function?
Comment: Also, consider delegating the "click" event to the `'#event_list_main'` element...
Answer: Try onclick="highlight.call(this);"
However, it would be much cleaner to properly attach an event handler:
var img = $('');
img.on('click', highlight);
$('#event_list_main').append(img);

Or even more readable:
var img = $('', {
    'class': 'listed_event',
    id: 'event_' + event_counter,
    src: 'final_tutorial_buttons/event.png'
}).height(50).width(50).data('count', event_counter).on('click', highlight);
$('#event_list_main').append(img);

Comment: It would be even cleaner this way: `var img = $('').attr({class: 'listed_event', id: 'event_' + event_counter, 'data-count': event_counter, src: 'final_tutorial_buttons/event.png'}).click(highlight).appendTo('#event_list_main')`. On several lines, of course.
Comment: It would be even more cleaner with a template.
Answer: That's not unexpected behavior, you're not passing the this value. But you expect it because jQuery does that automatically for you.
This is an easy fix:
$('#event_list_main').append('');

Even though it'd be better to replace it all together with:
$('')
     .click(highlight).appendTo("#event_list_main");

Please see this post for more information about how call(), apply() and this.

Strange Javascript behaviour


add new row to server-side asp script table

Question: I have a table which contains row and column. Is there any way that the user can click on the button and the initial table table can add on a new row to the created script? Below is my code for initial table.
    <form name=form1 method=POST action=add.asp>

     product

     quantity

     brand

<INPUT NAME="name" TYPE="reset" VALUE="Clear">
    <INPUT NAME="name1" TYPE="submit" VALUE="Submit">

    </form>

This is the view of my initial table.
    | product  |       |
    | quantity |       |
    | brand    |       |

Is there any way could let the user can click on the button on the web page and the asp script can auto add on  for new row and column in the asp script so that the asp script will become
    <form name=form1 method=POST action=add.asp>

     product

     quantity

     brand

<INPUT NAME="name" TYPE="reset" VALUE="Clear">
    <INPUT NAME="name1" TYPE="submit" VALUE="Submit">

    </form>

    | product  |       |
    | quantity |       |
    | brand    |       |
    |          |       |

Can anyone help me on this?
Answer: If you just want the fourth row to appear when the button is pressed then all you need to do is put a conditional statement around your fourth row - ie
<% If request.form("name1") <> "" then %>

<% End If %>

Obviously though the new row would disappear when you reload the page.  Is this all you want or do you want your changes to be preserved for future users.
NB, I think your second code sample is missing an opening  tag for the fourth row
Comment: Hi John, ya, the function that I needed is to do preserved for future usage. I needed the code can auto add on new row and column on the server-side script whenever the user want to add on new data requirement as they click on the button.
Comment: In that case you need code which writes to a file or a database - probably a database if we're talking about multiple table rows.  There are plenty of tutorials on the internet for both, here are some links to point you in the right direction. http://www.codefixer.com/tutorials/form_to_database.asp http://www.w3schools.com/asp/asp_ref_filesystem.asp http://www.w3schools.com/asp/asp_ref_textstream.asp


How do I switch from a recommended release to a development snapshot?

Question: Is there a non-Drush, Ludwig way to switch from the recommended release of a module to a development snapshot in Drupal 9, for example copying the development snapshot files and run update.php?
The Drush answer for Drupal 7 given in How can I update from the recommended release of a module to it development snapshot? suggests to do that.
In my case, I want to switch to the development snapshot of the Address module to resolve the doctrine/collections missing when using Ludwig on Drupal 9 issue.
Answer: You can install the dev version of Drupal modules by setting the version constraint as 1.x-dev. For example: composer require drupal/token:1.x-dev.
Read more: https://www.drupal.org/docs/develop/using-composer/using-composer-to-install-drupal-and-manage-dependencies#specify-version
Comment: Composer is the standard.
Comment: Composer can be daunting if you've never worked with the command line, but it's actually not so hard to learn, and once you do, you'll never go back. It can be frustrating when Composer reports a conflict, but Composer support in Drupal is extensive, and there are Composer support communities as well. And fixing a conflict reported by Composer is better than having an unrealized conflict causing bugs in a non-Composer system. Here's a series I wrote on Composer for Drupal users that may help: https://www.morpht.com/blog/drupal-and-composer-part-1-understanding-composer
Comment: I'm using Ludwig insted of composer. Is there a non-composer way for setting the version constraint? Thx!
Comment: No clue. Ludwig is a non-standard method of managing Drupal code, so you'll find that there won't be much support for Ludwig issues - you'll likely need to work through them yourself for the most part.
Comment: You may want to lock it to a specific commit when using a branch by appending #COMMIT-HASH to the version. See https://www.drupal.org/docs/develop/using-composer/using-composer-to-install-drupal-and-manage-dependencies#s-requiring-a-specific-commit-of-a-module
Comment: Composer is the standard/the best way to go, but there certainly  is  a reason/demand for what Ludwig offert since there is more than 10k sites that use it.
Comment: It's simply not worth using it because you won't find universal support like you will for Composer in the PHP ecosystem.
Comment: How many of those 10k are Drupal 8+ though? Vanishingly few I would imagine. Ludwig isn't relevant for Drupal 8+, it really would be a good idea to move your site to the supported package workflow


Interesting Property of Numbers in English

Question: I was playing with the letters in numbers written in English and I found something quite funny. I found that if you count the number of letters in the number and write this as a number and then count the number of letters in this new number and keep repeating the process, you will arrive at the number 4.
I've confirmed this (using a computer program) for all numbers up to 999999 and was wondering if there's a way to prove this or to find a counter example for which it does not hold.
Just to give an example of the above statement, let's start with thirty seven (I chose this randomly)
Thirty seven has 11 letters in it, Eleven has 6 letters in it, Six has three letters in it, Three has 5 letters in it, Five has 4 letters in it.
It may look like I just picked this number, so let me show this for another random number, say 999.
Nine hundred and ninety nine has 24 letters in it, Twenty four has 10 letters in it, Ten has 3 letters in it, Three has 5 letters in it, Five has 4 letters in it.
What are your thoughts on how to prove this?
(Just a note: I only confirmed this for numbers written in the standard British way of writing numbers - for example 101 is one hundred and one)
Answer: Define $f: \mathbb{N} \to \mathbb{N}$ as the number of letters in a given natural number spelled out.
Four is the only fixed point under $f$, and it's not too difficult to see that $f$ is almost always strictly decreasing with the only exceptions being one, two, three and four. So the $n^{th}$ iterate of $f$ must eventually become smaller than 5, which doesn't leave very many cases to verify.
Comment: Is there actually a systematic way to name arbitrarily large numbers in English?  It seems that one would have to specify this before claiming that your $f$ is eventually decreasing.
Comment: There is such a systematic method of naming numbers in English, although the details escape me. Given that a 1000-factor increase in the size of the number results in roughly a 28-35 letter increase in name size ("three hundred and thirty three -illion" and so on) it's clear that the naming convention will never catch up. Consider also what it would take for the size of the name to grow as the number: you'd have to write in unary.
Comment: @ccc This is a bad question: Why have you NEVER voted on any question, up or down? (That needn't be answered.)
Comment: @ccc I suppose one would have to make the assumption that the numbering system is relatively uniform - and if no such nomenclature exists for a certain number, that the number of letters in that number would not spike by an enormous amount of digits.  Perhaps one could adopt the convention of saying one million million for one million squared, for instance, so that all numbers may be accounted for.
Comment: @ccc Do those Hebrew letters used for Cantor algebra accomplish that (naming arbitrarily large numbers)? I don't recall exactly though...
Comment: @ccc you're right, I was assuming the existence of such a systematic way of naming numbers, and that no new name for a large number will be excessively long.
Comment: @FeralOink: No, aleph and beth are for denoting transfinite cardinals, compared to which any natural number is insignificant.
Comment: @jwodder I *do* appreciate your explanation. I dug around a bit on Google and the math blogoverse, yet remained puzzled. Most didn't even use aleph and bet (some other symbols, maybe due to rendering?), or they failed to differentiate between the magnitude of the size difference between natural numbers and transfinite cardinals. (Well, failed to make the distinction in a way that was comprehensible to me). Thank you so much for your help!
Answer: Note that the number of letters in the number is almost always going to be less than the number itself; in fact, this should be true for all numbers greater than four.  Four is the only number which has this property (that the number of letters is equal to the number itself).  Therefore, we can say that if a number repeats eventually, it must repeat at 4.  Furthermore, since the value of the number of letters in the number is always less than the number itself for values greater than 4, the number is always decreasing until four.
So, all that remains is to show that the numbers 3,2, and 1 always go to 4 eventually, and then we can know that it will repeat.  3 goes to 5 which goes to 4.  Both 1 and 2 go to 3 which go to 5 which go to 4.  Though this is fairly informal, this is the gist of how it could be shown.
Comment: As an interesting side note, no such number should occur in French.  There exists no number when spelled out such that the number of letters is equal to the number, but you can get patterns such as 3,5,4,6,3,5,4,6,... because 3 is trois which goes to 5 which is cinq which goes to 4 which is quatre which goes to 6 which is six, which goes back to three...
Answer: HINT
$2 \to 3 \to 5 \to 4$
$3 \to 5 \to 4$
$4 \to 4$
$5 \to 4$
$6 \to 3 \to 5 \to 4$
$7 \to 5 \to 4$
$8 \to 5 \to 4$
$9 \to 4$
$10 \to 3 \to 5 \to 4$
etc.
Comment: I don't mean this as an exhaustive list (!), as this is what you have shown for n < 999999. Rather, if you can show that the function (as Dustan writes) decreases to eventually give you a value less than 10 (or 5), then you're done.
Comment: You should edit your comment into your answer


Reference request: probability distributions + rigorous derivation of results (including densities!)

Question: I am looking for a detailed book on probability distributions themselves.
It should have a long list of common probability distributions, it should speak of why they are useful for what particular application, and it should explain/prove why the definition of the distribution (i.e., the density function or mass function) actually does what it is supposed to do, and it should then derive key results such as moments, etc.
It is in particular the explanation of where the density comes from that I am interested in.
Is there such a book, or is one forced to read the original papers where the distributions were first introduced (which I would rather not do, since those papers are usually written in more advanced language, and it is more neat to have a single source than dozens of different ones).
Comment: I feel like any good application-oriented intro book on probability will do this, eg Ross.
Answer:
Univariate Discrete Distributions, 3rd Edition by Norman L. Johnson, Adrienne W. Kemp, Samuel Kotz
Continuous Univariate Distributions, Volume 1, 2nd Edition by Norman L. Johnson, Samuel Kotz, N. Balakrishnan
Continuous Univariate Distributions, Volume 2, 2nd Edition
by Norman L. Johnson, Samuel Kotz, N. Balakrishnan
Discrete Multivariate Distributions by Norman L. Johnson, Samuel Kotz, N. Balakrishnan
Continuous Multivariate Distributions, Volume 1: Models and Applications, 2nd Edition by Samuel Kotz, N. Balakrishnan, Norman L. Johnson
Comment: Well, they are rather EXPENSIVE... :-(


Limit of $ \int_1^a \frac{\mathrm dt}{\sqrt{t(t-1)(a-t)}},a\rightarrow1^+$

Question: I would like to find the limit of $$ \int_1^a \frac{\mathrm dt}{\sqrt{t(t-1)(a-t)}}$$
when $$ a\rightarrow1^+$$
It seems that $$ \int_1^a \frac{\mathrm dt}{\sqrt{t(t-1)(a-t)}}\sim_{a\rightarrow 1^+} \pi$$
What bothers me is that $a$ is in the integrand and I cannot find an equivalent of $$\frac{1}{\sqrt{t(t-1)(a-t)}}$$ when $a\rightarrow1^+$
Moreover the integral $$ \int \frac{\mathrm dt}{\sqrt{t(t-1)(a-t)}}$$ "cannot be computed", is not simple.
Do you have any idea?
Answer: Don't say "cannot be computed".  It is an elliptic integral:
$$
U(a):=\int_{1}^{a} \frac{dt}{\sqrt{t (t - 1) (a - t)}} = \frac{2 K \Bigl(\sqrt{\frac{a - 1}{a}}\Bigr)}{\sqrt{a}}
$$
and of course $2K(0) = \pi$.
Now, of course, the question is to show $K(0)=\pi/2$ directly, without using knowledge of elliptic integrals.  For that I chose a change of variables:
$u=(t-1)/(a-1)$ to make this an integral from $0$ to $1$
$$
U(a) = \int_0^1\frac{du}{\sqrt{u(1-u)(1+(a-1)u)}}
$$
Now the limit at $a=1$ is clear:
$$
U(1) = \int_0^1 \frac{du}{\sqrt{u(1-u)}} = \pi
$$
Comment: +1. I was writing with the solution with the same change of variable.
Comment: @GEdgar: it's simply awesome!
Comment: Thank you very much for this nice answer! I would never have thought of such a substitution!
Comment: Your edit brought this to the top of the list, and I thought, "I know how to do that." When I opened the page, I saw my deleted answer (deleted because it was too similar). Bummer.


Logic Pro X 192kHz sample rate problem

Question: I have a strange issue – when I set my project's sample rate to 192kHz my sound gets odd and I can't use most of Waves plug-ins no more. So watch the video:
Comment: Have you checked the obvious things like what the maximum sample rate is that is supported by your plugins and your interface? What if you change the sample rate, save, then close and reopen Logic? What if you create a new session at 192 kHz before you put anything into the session?
Comment: I see, it's not recorded audio, it's a virtual bass instrument. Why would you try to play back at 192 kHz on a system that doesn't support it?
Comment: @KolobCanyon Pretty sure it's user error. If you're just using the internal sound on a computer, Logic is just going to automatically downsample it for you and you won't be able to record at a rate higher than the hardware supports.
Comment: @ToddWilcox Everything works on master bus.  I'll try to change project's sample rate while it's empty.
Comment: @ToddWilcox And I don't use extenal audio interfaces.
Comment: What internal interface do you use and have you confirmed its supported sample rates? If you're just using what came with the computer, it almost certainly doesn't support 192kHz. That's definitely step one. Also try saving, closing and reopening.
Comment: @ToddWilcox  The weird thing is that Bass Amp Designer (its a standard plugin that is included in Logic) doesn't really support 192kHz.
Comment: If you recorded audio at one sample rate and then change the sample rate of the project to a different rate, it's gonna sound messed up. Is that how you're using the bass amp designer plugin? With recorded audio? The video isn't really clear to me.
Comment: You might want to submit this to Apple's support logic page. It's hard to tell whether it is the plug-in or Logic causing this... or your audio interface
Comment: @ToddWilcox Oh I see. so he's not using an audio interface. Just the built in software instrument and piano roll.
Answer: Ok I got it. I set up a similar Logic session and tested different things.
Short answer: Your system doesn't have the processing power to support 192 kHz sample rate for the amp designer plugins. There might be other plugins that won't work either.
The way I figured this out is by changing the buffer size. Click on Logic Pro X -> Preferences -> Audio. Look for I/O Buffer Size. Increase this in steps and then playback with the Amp Designer on at 192 kHz. You should see the audio quality get slightly and slightly better. On my system, it never sounds good and if I set the maximum buffer size it says my system can't handle a buffer that big. If I set a smaller than default buffer size, the audio gets worse and eventually my system can't sync MIDI and audio any more.
Two points:

There's really not much point at running at 192 kHz unless you're a professional working on a movie or video game - in which case you'd have a system that can support it.
If you want to go above 48 kHz, you should really invest in a quality USB 3.0 or Thunderbolt audio interface that supports higher sample rates. That will help with buffer sizes also.
Comment: @EugenEray Ah I was confused because in an earlier comment you wrote that you weren't using an external interface. You're probably going to find that no one wants to take delivery of 192 kHz audio anyway, so at some point you'll have to downsample it. I wouldn't worry too much about anything higher than 96 kHz.
Comment: I'm just trying to release my song into public. About audio interface: Focusrite Clarett 2Pre (that I have) does support a 192kHz sample rate (for recording). Using it everything sounds much better.
Comment: "There's really not much point at running at 192 kHz" – indeed, and I'd extend this to _**even if** you're a professional working on a movie or video game_. The main benefit of sample rates >40kHz is that the AD-converters can operate with more liberal filtering, but high-grade ADs do that _anyway_ and merely downsample the digital result before it enters the software in case 44.1 or 48 kHz is chosen, which is the same what will be done in mastering anyway. The only reason to keep the sample rate high during processing is to avoid aliasing in nonlinear effects (distortion, limiters)...
Comment: ...but unless you're _completely wrecking_ the signal with distortion (in which case quality will hardly matter anyway), the headroom offered by 96 kHz should be plenty for everybody. And anyways most decent nonlinear effect plugins have an oversampled mode (or use higher-order ODE algorithms, which is generally more effective than any oversampling), so they don't need high DAW sample rates. — Here's [a relevant rant](https://people.xiph.org/~xiphmont/demo/neil-young.html) by Monty from Xiph.org.
Answer: Ok, the problem was, that IK Multimedia MODO BASS doesn't support 192kHz sample rate (although it works) and all crackle comes from it. So I've gotta use some other synthesizer for bass guitar. Maybe Native Instruments KOMPLETTE 11 is worth trying.
Comment: Maybe lower sample rates are worth trying also.
Comment: Yes. I'd be ready to bet you wouldn't be able to tell apart the final rendered results of 48 kHz and 192 kHz with these plugins.
Comment: @leftaroundabout  But source matters a lot.
Comment: No it doesn't, except if you do some very highly nonlinear processing (and even then it's probably no issue, because everything will sound plain broken distorted anyway) or use badly-designed effects which are calculated with the assumption of an "infinite sample rate" (that often simplifies calculations, but this is just a matter of laziness on the designer's behalf). Anybody who claims that processing at >96 kHz has any intrinsic benefit had better back it up with some double-blind experiments.
Comment: In case you're not so into DSP, here's an analogy: processing at 192 kHz is like quadroupling your car's fuel tank volume because there's a leak somewhere. That may, in a sense, solve a problem and increase the range, but it's totally inefficient and in principle tackles the issue at the wrong spot.

Logic Pro X 192kHz sample rate problem


Call custom form in a block

Question: I am trying to call a custom form in a block. The form is written in my custom module.
I tried different ways to call the form, but not getting the form.
Here is the syntax, I last tried.
$form = drupal_get_form('my_custom_form');
print drupal_render($form);
//my_custom_form is my form_id

(or)
drupal_render(drupal_get_form('my_custom_form'));

Here is the link I found a similar question, but didn't get the correct solution for my question.
Form within a block
Comment: I tried that way. The below answer is the same for that question. I want a new way of doing it. I want to know an newer methods of doing it.
Answer: You should return your form using drupal_get_form in the content definition of your block. Drupal will do the rest.
For example like this:
function YOURMODULE_block_info()
{
    $blocks = array();

    $blocks['custom_block'] = array(
        'info' => t('Custom block example'),
        'title' => t('Custom block example'),
        'region' => 'content',
        'status' => 1,
    );

    return $blocks;
}

function YOURMODULE_block_view($delta = '')
{
    $block = array();

    switch ($delta) {
        case 'custom_block' :
            $block['content'] = YOURMODULE_block_content();
            break;
    }

    return $block;
}

function YOURMODULE_block_content()
{
    return drupal_get_form('my_custom_form');
}

function my_custom_form($form, &$form_state)
{
    // Build your form

    return $form
}

Comment: Yes, I tried this. Is there any other method to do this?
Comment: You also can directly call the `drupal_render` on the form and return it as `#markup` content for the block ... but you already tried ... which isn't working for you. Do you have some content of the block rendered on the page? (i.e.: the block wrapper html, title, ...)
Comment: Anyway as the requirement is urgent, I am using the old method. Thanks for your help.

Call custom form in a block


Use redirect after content creating and use $node

Question: I modified my submit handler to be redirected to a "thank you" page after creating some content. So far so good.
But I want to use some data of the node just created, so how can I transfer the $node-data of the just created node to my thank you page?
I created a new block to be shown only on the thank you page and I want to show some $node-data in my block...
function mymodule_block_view($delta = '') {
  switch ($delta) {
    case 'your_block':
      $block['subject'] = 'Share by mail';
      $block['content'] = mymodule_sharebutton();
      break;
  }

  return $block;
}

function mymodule_sharebutton() {
  $output = 'share';

  return $output;
}

I already tried with passing $node, $form, $form_state,... but with no luck.
Comment: To make it simpler when you are redirecting perhaps you could slip in node id as a parameter in the url, say `/thank-you/3` You could use that to do `node_load(nid)` or if you think that url will look ugly you could set nid to a session variable before calling `drupal_redirect` in submit handler and use session variable in thank-you page.
Comment: Oh, I like the sound of that. Let me take a look at this.
Comment: For some reason, there is no `$node` variable in my submithandler function...
Comment: `$form_state` contains `nid`, you need to use that and get `$node` from `node_load()`
Comment: no `$form_state` is loaded in my submithandler :(
Answer: Use arg(1); - (nid of the current node) in the hook_block_view and pass it in the link
function mymodule_block_view($delta = '') {
  switch ($delta) {
    case 'your_block':
      $nid = arg(1);
      $block['subject'] = 'Share by mail';
      $block['content'] = 'share?nid='.$nid.'';
      break;
  }
  return $block;
}

Once you do that, you can make your thank_you page react on the nid argument by loading the node:
$node = node_load($nid);

and extracting from it whatever you need


Pycharm cann't find the packages or modules installed with pip on windows

Question: Pycharm doesn't sync with the pip packages though i have added the path in environment variable.
The following elements will clear the topic:
already installed sklearn package:

pycharm can't find that package:

environment variable:
Comment: Have you tried using CMD or Jupyter Notebook?
Answer: The thing is that pycharm creates all of your projects inside a virtual environment. So the packages that you installed outside the virtual environment(global site packages) does not get inherited in to your project. There is a simple solution for that. When you create a pycharm project, make sure to check the "inherit global-site packages" checkbox as shown here.Then you'll be able to import all the packages to your virtual environment, provided they have been installed in your computer.

Alternatively you can install all the packages separately using "pip install" in the pycharm terminal. If the package has been installed outside the virtual environment, pip will use cached files instead of downloading the package again.
Or you can install the packages using Settings -> Project -> Project Interpreter as the other answers suggests.
Answer: If you did not "inherit global-site packages" upon creating the project, check in the project tree under External Libaries, if the folder is marked in red. I.e. if you do not use the systems default interpreter , Lib/site-packages could be marked in red.
To add those libraries afterwards, go to: File-Project(your project)\Project Structure,
select +Add Content Root, browse to site-packages (or the respective folder you want to add), and add it. After clicking OK the folder will not be marked red any longer. (tested in PyCharm 2020.3)
Comment: Man, thank you, you saved me a lot of pulled hair. I had issue that everything works, then missing packages are reported, then I reinstall, it works again for a while and then stops working and whole story repeats. Actually my .venv folder was added to a excluded list for some reason. I had to delete it from that list.
Comment: Just to add to this, for me the issue was coming and going away as I would reinstall package in question. I realised that Mac is adding -icloud extension to some files and for that reason library gets corrupt. So solution to this is to either exclude folder from being uploaded to iclous or to turn off checkmark for optimization (Optimize Mac Storage) in Icloud setting.
Answer: In PyCharm, go to File / Default Settings / Project Interpreter
On that page there is a plus in the bottom left, whatever modules you have installed through pip you may need to manually install there. Or you can change your project interpreter to make sure you are using the correct interpreter with all your installed modules.
Answer: Seems like the interpreter selected isn't where you think it is. If you're using a different interpreter than the system's default, it won't load the modules. To add the modules in PyCharm, go to your Settings, Project Interpreter, the Add Button, and install it with PyCharm's integrated package management.


How to calculate using derivative definition

Question: I am trying to find the derivative of $f$ at $x=1$ when $y=\sqrt{3x+1}$ using only the following derivative definition:
$$f^\prime(1)=\lim_{x\to1}\frac{f(x)−f(1)}{x−1}$$
I think I need to get rid of the radical first, but I simply cannot find the right way. I am relearning math after many years, so please bear with me.
Comment: Use the conjugate expression :  $f(x)-f(1)=\dfrac{f(x)^2-f(1)^2}{f(x)+f(1)}$.
Comment: I think you may have mixed up [how to write equations](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) with how to write code, but I've fixed that now.
Comment: @ J.G. Yes, you're right. I need to learn the difference. Thank you.
Answer: Since $(\sqrt{3x+1}-2)(\sqrt{3x+1}+2)=3(x-1)$,$$f^\prime(1)=\lim_{x\to1}\frac{\sqrt{3x+1}-2}{x-1}=\lim_{x\to1}\frac{3}{\sqrt{3x+1}+2}=\frac34.$$
Answer: Hint: $\displaystyle\sqrt b-\sqrt a=\frac{b-a}{\sqrt b+\sqrt a}$.


MVC — Show user's information from database into TextBoxFor()

Question: I found countless links online for getting a value from a textbox in View but none for getting a value from the database into the textbox. I need to show the user's profile information so that he can edit them. I'm sure it's easy... as long as you know how! Any idea? Thanks in advance!
View
@model Project.Models.membre

@using (@Html.BeginForm("Profil", "Membres", FormMethod.Post))
{

        @Html.LabelFor(model => model.name)
        @Html.TextBoxFor(model => model.name, new { @Value = ???????? })

}

Controller
public ActionResult Profil()
{
    return View();
}

Comment: Yes that's what I needed, thanks. I'll make an answer below.
Comment: Will you include your controller code? Since you have a model attached in your view, we need to assign a value to Model.Name.
Comment: I see, ok last step, will you include the full view code? I need the @ Model that is declared at the top of the view.
Answer: Here are 2 ways to assign value to that; We could either

Assign the value in the controller
Assign the value in the view

You could use either of the two.
To assign a value to model.Name in the view, razor framework allows you to interact with objects or write programming code using @{ //Your code here }
@model Project.Models.membre

@{
  // Write your code here
  model.Name = "Pensum"
}

@using (@Html.BeginForm("Profil", "Membres", FormMethod.Post))
{

        @Html.LabelFor(model => model.name)
        @Html.TextBoxFor(model => model.name)

}

OR
To assign a value to model.Name in the controller, we should first instantiate an object (membre object) then assign a value to it then pass it to the view.
using Project.Models;

public ActionResult Profil()
{
    // instantiate object
    membre m = new membre();

    // assign value to property
    m.Name = "Pensum";

    // pass to the view
    return View(m);
}

EDIT from OP (with database solution)
public ActionResult Profil(membre user)
{
    var session = Session["login"];

    using(database db = new database())
    {
        var userdb = db.membre.Where(x => x.login == session).FirstOrDefault;
        user.Name = userdb.Name;
    }
    return View(user);
}

Comment: *Me to myself* — See? So easy... Thanks!
Answer: Yes, its easy with your Razor view HTML controls.
The thing you missed is to pass the model from the controller:
public ActionResult Profil()
{
    var user = dbContext.Members.Where(m=>m.loginid == Session["loginid"]).FirstOrDefault();
    return View(user);
}

Please use proper type casting of the session variable as of your database field type.
And in view, I think waht you did will work!
Comment: How is `int id` passed? I tried passing the `user` class as paramater but the properties are set to null. I'm not sure where I can set their values.
Comment: Can you show me from where you are calling the "Profil" Action?
Comment: It is from the navbar in a layout.. So basically, from 3 or 4 possible views that wear this layout. `@Html.ActionLink("Profil", "Profil", "Membres", null, new { @class = "nav-link" })`
Comment: I assume, the page is showing the profile of the current user. If so, you have stored the current/logged in user's data in somewhere (may be in cookie/session). You can get the user id or at least any unique data of the user. What is your case?
Comment: I just used a session variable `Session["login"] = login username`. I use it to do a query and get the property values. I don't know how to set the user's values before as he logs in. Do I create a new instance of user in the home controller which will be passed implicitely when clicking on the ActionLink? Because I don't send the paramater like we do in the console for example. Like I said, I'm logging in by checking in a query, go to profil, do another query to get the user's values.... It's not really optimal.
Comment: I think, I'm failing to understand your case. My Bad. I'm trying to clear you about something: 1) A logged in user clicked to see his/her profile. In that case we must have the login id of that user in the session variable (as you stated). We can fire a  query to get that user from the database and pass that to the view. 2) Admin/Any user trying to see a member profile. In this case, s/he needs to provide the user id/name to determine which user's profile to show.
Comment: `public ActionResult Profil(member user) { }` — I don't understand where the parameter user is passed. It's not like I wrote some code `Profil(myaccount);` I just clicked on an ActionLink that is calling a controller. So where do I have to set the values of the parameter to pass? As of right now, it's null. I am doing a second query to get the values of `user` by searching with his session id. The first one was to check if the login was valid... Shouldn't I just be able to save the user's values upon logging in and then just use the values in the profile instead of having to do a second query?
Comment: It works too, but it still doesn't explain why I can pass a parameter in the controller if I'm never using it. I have to do a query to find out which user is logged in to get his profile information. It's not practical imo since I already know which user is connected.
Comment: The controller action here is not getting a parameter. If you know which user is logged in, just get the user details as a model and pass it to the view (as my answer shows).


Posso subir pastas junto com o código no GitHub?

Question: Eu já coloquei códigos nos meus repositórios no Github uma vez, porém agora estou mexendo com site pelo Netbeans utilizando HTML5, e tenho outras pastas como do CSS, Javascript e afins. Tem possibilidade de, ao subir o código, subir essas pastas também?
Answer: O Git não permite ter diretórios vazios. Mas quando preciso subir uma pasta crio um arquivo oculto dentro do diretório para fazer upload desse diretório. Por exemplo:
touch pasta/.teste

Aplique o git add pasta/ para adicionar uma pasta específica ou git add . para subir todas as pastas e as alterações.
Comment: Bem lembrado, jow +1
Comment: o CakePHP usa um arquivo `.empty`
Comment: Eu nunca tinha pensado nisso, +1.
Comment: E uma grande parcela da comunidade utiliza o arquivo `.gitkeep`.
Answer: Pode, desde que estas pastas não estejam listadas no arquivo .gitignore e não estejam vazias elas serão enviadas para o repositório.
Não esqueça de adicionar as pastas antes de commitar
git add pasta/.gitkeep

Se quiser enviar uma pasta que não tenha arquivos no commit, vai ser necessário usar algum método alternativo pra isso.
Uma abordagem que eu uso bastante é criar um arquivo vazio com o nome .gitkeep. Dessa forma, consigo saber qual a utilidade do arquivo só olhando para o seu nome.
Você pode criar este arquivo usando o comando touch
touch pasta/.gitkeep

Comment: E se não estiverem vazias. Pastas vazias são desconsideradas pelo `git` (por padrão, creio eu).
Comment: Para pastas vazias é só add uma index.html com nada dentro, assim que faço pelo menos
Answer: Eu gosto de fazer de um jeito que aprendi a fazer nos projetos no Laravel. Quando preciso ter a pasta em produção, mas não preciso que os arquivos dentro dessas pastas sejam monitorados, eu crio um  .gitignore dentro da pasta em questão e coloco o seguinte trecho:
E coloco PastaQueEuQuero/.gitignore:
*
!.gitignore

Nesse caso apenas o arquivo .gitgnore junto com a pasta é mandado para o repositório ao fazer git add PastaQueEuQuero.
Answer: Eu aprendi a criar as pastas assim:inserir a descrição da imagem aqui
Dentro do Repositório seleciono:
Add File/ Create new file
após aparecer o endereço
Repositorio/ digite aqui o nome da pasta a ser criada + "/"
complete com um arquivo .txt e no botão a direita verde - Commit Changes preencha todos os campos até salvar


Determine whether the following series converges or diverges ( root test or ratio test)

Question:
Series $\displaystyle\sum_{k=1}^{\infty}\left[\frac{(k!)^3}{(3k)!}\right]^k$

Attempted the root test but got a test that wasn't conclusive. Can you integrate two tests in one? Could I take the root test and then use the Ratio test?
Any help is appreciated.
Answer: Using the root test gives
$$\lim_{n\to\infty}\frac{(n!)^3}{(3n)!}=0\lt1$$
so the series converges.
Comment: How do we know that this is equal to 0?
Comment: @lj_growl $0\lt\frac{(n!)^3}{(3n)!}\lt \frac1n$ for all $n\in\mathbb{N}$. You should be able to prove this by induction.


Permanecer estilo do hover ao abrir um submenu Dropdown

Question: Preciso que a cor do hover permaneça ao abrir o submenu.
Meu submenu funciona, só quero que fique marcado o menu o qual ele está vinculado.
Segue o código de exemplo:
HTML:

Link 1  »

Link 2

Link 3

Link 4

Link 2

Link 3

Link 4

CSS:
ul {
    width: 200px;
    background: #ccc;
    list-style: none;
    padding: 0;
    border: 1px solid #999;
}

ul li {
    border-bottom: 1px solid #999;
    position: relative;
}

ul li:last-child {
    border-bottom: none;
}

ul li a {
    color: #000;
    display: block;
    padding: 5px;
}

ul li a:hover {
    background:#999;
}

ul li ul {
    display:none;
    position: absolute;
    top:0;
    left: 200px;
}

ul li:hover > ul {
    display: block;
}

Pode vê-lo em funcionamento aqui: http://jsfiddle.net/ze8xtpxt/
Answer: Isto é possível alcançar com uma pequena mudança no teu código CSS.
Primeiro vamos aplicar uma class à lista principal para que seja mais facil trabalhar com ela e para apontarmos com mais precisão aquilo que queremos modificar ou aplicar estilos, para evitar possíveis conflitos no futuro com outras listas.
Esta class vai se chamar .menu por exemplo, que aplicada no código HTML ficará:

Link 1  »

Link 2

Link 3

Link 4

Link 2

Link 3

Link 4

De seguida iremos então fazer a tal simples modificação no código CSS.
Se reparares no teu código CSS, tens algo como:
ul li a:hover {
    background:#999;
}

Nós iremos substituir este bocado de código com o código abaixo, que irá fazer o mesmo trabalho que ele já estava a fazer, só que ele agora irá também aplicar o estilo pretendido, que é ficar como ativo (ou seja com aquela cor de background cinzento mais escuro) quando estamos a fazer hover sobre o sub-menu.
.menu li:hover > a {
    background:#999;
}

Aqui tens o resultado e exemplo online no jsFiddle.
Comment: Era isso mesmo! Muito obrigado!


Is an NVS complete iff it is non meagre?

Question: Let $V$ be an NVS. We know by Baires theorem that complete $\implies$ nonmeagre. What about the converse? Can we have a non complete space that is nonmeagre or not?
For metric spaces the answer is yes we can, just disjoint union a complete space and a meagre space e.g. $\mathbb{Q}\underline{\cup} \mathbb{R}$, then the $\mathbb{Q}$ part makes it not complete and the $\mathbb{R}$ part makes it nonmeagre. But no similar tactic works for an NVS so I think the answer will be no.
Comment: @Physor Put the lines parallel in $R^2$, say the $Q$ line has y coordinate $1$ and $R$ line has $y$ coordinate $0$. It is meagre in $R^2$ but not in itself with the subspace topology (because it contains a copy of $R$)
Comment: Direct sum approach doesnt work, you can basically disprove it in the general case, essentially because of the reasons you mention in your third comment
Answer: Each infinite dimensional Banach space $X$ contains a dense hyperplane which is of second category in itself:
Let $\{b_j: j\in J\}$ be a Hamel base of $X$, thus each $x \in X$ has a
representation
$$
x= \sum_{j \in J} \varphi_j(x)b_j
$$
with $\varphi_j(x) \not= 0$ for at most finitely many $j \in J$. For each $j \in J$ let $Y_j$ be the kernel of the linear functional $\varphi_j$. Assume by contradiction that $Y_j$ is of first category in $X$ for infinitely many $j \in J$. Let $I \subseteq J$ be a countable infinite subset such that $Y_j$ is of first category $(j \in I)$. Then for each $x \in X$ there is some $j \in I$ with $\varphi_j(x)=0$. So
$$
X=\bigcup_{j \in I} Y_j
$$
is of first category, a contradiction. Thus there are (many) $Y_j$ such that $Y_j$ is of second category in $X$. Such an $Y_j$ is then also of second category in itself. Moreover it can't be closed (otherwise it would be a closed strict subspace of $X$, hence of first category). By the same reasoning it is dense in $X$ and therefore it is not complete.
Comment: Excellent............


non-existent service, yet cache is cleared and module is enabled

Question: I'm trying to access a Drupal service for normalizing content, yet the service is non-existent, even though the module "hal" is enabled and the service is defined. How can I get the service "serializer.normalizer.entity.hal"?
root@0968b6d03cdb:/var/www/html# drush cr
 [success] Cache rebuild complete.

root@0968b6d03cdb:/var/www/html# drush pml|grep hal
  Web services                      HAL (hal)                                               Enabled    9.3.0

root@0968b6d03cdb:/var/www/html# drush ev "\Drupal::service('serializer.normalizer.entity.hal');"

In Container.php line 156:

  You have requested a non-existent service "serializer.normalizer.entity.hal".

root@0968b6d03cdb:/var/www/html# cat core/modules/hal/hal.services.yml
services:
  serializer.normalizer.entity_reference_item.hal:
    class: Drupal\hal\Normalizer\EntityReferenceItemNormalizer
    arguments: ['@hal.link_manager', '@serializer.entity_resolver', '@entity_type.manager']
    tags:
      - { name: normalizer, priority: 10 }
  serializer.normalizer.field_item.hal:
    class: Drupal\hal\Normalizer\FieldItemNormalizer
    tags:
      - { name: normalizer, priority: 10 }
  serializer.normalizer.field.hal:
    class: Drupal\hal\Normalizer\FieldNormalizer
    tags:
      - { name: normalizer, priority: 10 }
  serializer.normalizer.file_entity.hal:
    class: Drupal\hal\Normalizer\FileEntityNormalizer
    arguments: ['@entity_type.manager', '@hal.link_manager', '@module_handler', '@config.factory', '@entity_type.repository', '@entity_field.manager']
    tags:
      - { name: normalizer, priority: 20 }
  serializer.normalizer.timestamp_item.hal:
   class: Drupal\hal\Normalizer\TimestampItemNormalizer
   tags:
     # Priority must be higher than serializer.normalizer.field_item.hal.
     - { name: normalizer, priority: 20 }
  serializer.normalizer.entity.hal:
    class: Drupal\hal\Normalizer\ContentEntityNormalizer
    arguments: ['@hal.link_manager', '@entity_type.manager', '@module_handler', '@entity_type.repository', '@entity_field.manager']
    tags:
      - { name: normalizer, priority: 10 }
  serializer.encoder.hal:
    class: Drupal\hal\Encoder\JsonEncoder
    tags:
      - { name: encoder, priority: 10, format: hal_json }

  # Link managers.
  hal.link_manager:
    class: Drupal\hal\LinkManager\LinkManager
    arguments: ['@hal.link_manager.type', '@hal.link_manager.relation']
  hal.link_manager.type:
    class: Drupal\hal\LinkManager\TypeLinkManager
    arguments: ['@cache.default', '@module_handler', '@config.factory', '@request_stack', '@entity_type.bundle.info', '@entity_type.manager']
  hal.link_manager.relation:
    class: Drupal\hal\LinkManager\RelationLinkManager
    arguments: ['@cache.default', '@entity_type.manager', '@module_handler', '@config.factory', '@request_stack', '@entity_type.bundle.info', '@entity_field.manager']

I can get other services, just not the "hal" one I want. For example,  drush ev '\Drupal::service("node.node_route_context");' works fine.
Answer: You can't get it directly because normalizer services are private since Drupal 8.6, see https://www.drupal.org/node/2936397:

Using encoder/normalizer services directly is not supported, one must use the @serializer service, which will then call the appropriate encoder/normalizer services. Services that have the normalizer or encoder tag really are internal/private implementation details to culminate in an operational @serializer service. These never were APIs. They implement Symfony's "Serializer component" API.

This is also why the service is not listed when looking at all available services:
/var/www/html# drupal debug:container | grep 'hal'
hal.link_manager             Drupal\hal\LinkManager\LinkManager
hal.link_manager.relation    Drupal\hal\LinkManager\RelationLinkManager
hal.link_manager.type        Drupal\hal\LinkManager\TypeLinkManager

As you can see, none of the services from core/modules/hal/hal.services.yml, that are tagged as normalizer are listed.


What is an omega sequence?

Question: Sorry if this is a very basic question. I've just been reading some papers where they define a series of relations $\langle R_1, R_2 . . . \rangle$ as an $\omega$ sequence, and I wasn't sure what it meant.
Is it something to do with the natural numbers? Is there anything special about calling it an $\omega$ sequence, or would people understand $\langle R_1, R_2 . . \rangle$ in the same way without it?
Thanks
Answer: They just mean that the sequence has indices $1, 2, 3, \ldots$, which they think of  as the ordinal $\omega$.  More generally, if the indices came from some ordered set $A$ instead of from $\omega$, they might call the sequence an $A$-sequence. For example, if we had an uncountable "sequence" $\langle R_i  : i \in \omega_1\rangle$ this would be called an $\omega_1$-sequence.
By default, a "sequence" is finite or an $\omega$-sequence - the term "$\omega$-sequence" is relatively specialized, usually only used in areas close to set theory.
Comment: Thank you for the help, that was really useful
Comment: The term *$\omega$-word* (i.e. $\omega$-sequence of letters) is commonly used in theoretical computer science.

What is an omega sequence?


Session ID is changing in CodeIgniter

Question: I am using the session feature of CodeIgniter, and I'm running this code:
$session_id = $this->session->userdata('session_id');
echo "My Session ID is $session_id";

And it keeps changing every time I load the page. Does this mean that sessions are not being saved properly? Is there any way to debug this and find out why? Or am I not using this library correctly?
I don't get any errors when I enable error reporting, and I'm using the autoload ability of CI to load the session library:
$autoload['libraries'] = array('session');

Any advice would help thanks!
Example Output of the Code above:
My Session ID is 7c92bac53d2654df6e87eb4e4cb25467
.. reload ..
My Session ID is c6dd14aed2499760f788a1364dcab030
UPDATE: My session configurations inside config.php look like this:
$config['sess_cookie_name']     = 'ci_session';
$config['sess_expiration']      = 7200;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie']  = FALSE;
$config['sess_use_database']    = FALSE;
$config['sess_table_name']      = 'ci_sessions';
$config['sess_match_ip']        = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update']  = 300;

So I have found that
session_start();
$_SESSION['myvar']='var';

doesn't store anything either, something seems to be wrong with the session storage on my linux server.
My session save path has apache:apache 775 permissions. Perhaps this should be moved to serverfault?
Comment: Could be an in-built session fixation prevention mechanism though it sounds a bit extreme changing it on each request
Comment: Are you saving your session to the DB?
Comment: @AlienWebguy Thanks for the response, I updated my question with the session configuration, I'm not using a DB
Comment: @Phil, sorry I'm not familiar with in-built session fixation prevention mechanisms
Comment: @Pete Are you using [Native Session](http://codeigniter.com/wiki/Native_session/) or another alternative session library? For more information on session fixation, see http://en.wikipedia.org/wiki/Session_fixation
Comment: @Phil, Thanks for the read, I think I understand, so the changing of the Session ID maybe be intentional for security reasons. however I can't store anything in the session. I am using Native Session
Comment: Hi, did you fix that problem? Answer doesn't help to solve the problem with session values saving.
Answer: According to CI's Session.php, the ID is changed on every update, but they keep a reference to the old ID so that they can update it right row.
Also, according to the doc: "session_id" is regenerated (by default) every five minutes".
Is there any reason why you need to access "session_id"? If you need some sort of fixed ID, you should create your own "my_session_id", that way it won't change between request.
$uniqueId = uniqid($this->CI->input->ip_address(), TRUE);
$this->session->set_userdata("my_session_id", md5($uniqueId));

Comment: Thanks for the answer Laurent, I have found that even the normal session array isn't working properly on the server, I just thought that the session id would indicate which session the current user was in. But obviously my problems are deeper than that
Answer: By replacing the directory system/libraries/ session per the most recent version (from the CI website), the problem will be solved.
There were several bugs in the session libraries of CI and they are already resolved.
Answer: @this.lau
You could mention the link of the file will be useful for the beginners.
i.e. CodeIgniter/system/libraries/Session.php
Answer: Changing session_id is normal in CI.
But I had a problem. Session values were not saving, not persistent only in CI.
I fixed it by updating Codeigniter to the latest version, which is currently
3.1.6.
Answer: One possible issue that you can have i described here: https://github.com/EllisLab/CodeIgniter/issues/3108
The thing is stupid as it can be. If you set cookie name with dots it will regenerate session id every time you reload the page. And of course, you would not be able to keep any user specific data!
Answer: If you don't want to update session on every five minutes do the following changes.
go to the session.php file in the System/libraries/Session.php
and set all parameters like
public $sess_encrypt_cookie;public $sess_use_database;... to blanks
 It's working for me
Comment: I think changing the session update from the default five minutes is more easily accomplished by changing the config.php value to something other than 300 (60 seconds x 5 minutes):

$config['sess_time_to_update']

Session ID is changing in CodeIgniter


How to set default form values based on query string, if the form uses AJAX file upload

Question: I have a Book content type with a file upload field.
I'm using Filefield Sources module with Plupload integration for getting the file upload widget.
I need to set a default value based on the query string passed on node/add/book page.
However, the files are uploaded via AJAX, calling the file/ajax page, and losing all default values I set. Obviously, custom query string is not present in that call, and when the form is re-generated, I get an error.
Any ideas on how can I make sure that default values stay in the form?
Thanks!
Answer: I forgot to post the answer.
To keep the data persistent between AJAX calls, you should store it in the $form_state variable. This is how it worked in my case:

Check if I already have the data in $form_state.
If not and if there is query string, get the data, sanitize/validate it and store in $form_state.

This way it works even for AJAX calls where query string parameters are not available.


if-else condition for update a table in a stored procedure in SQL Server 2005

Question: I want to update some data in a specified case, else these columns are not to be updated.
What can I write code in a stored procedure for this?
Comment: Help us help you by providing more detail, like an example.
Answer: You can use a case to control whether you assign a new value or keep the old value.
update <sometable>
set field = case when <condition> then <newvalue> else field end
where <condition>

Example:
update questions
set reply = case when @input is not null then @input else reply end
where answer = 42

Comment: @devio: Yes, for the specific case where the condition is a check for null, the isnull function can be used instead of a case, but I wanted to show the case as it can be used for any kind of condition. :)
Comment: @Guffa: +1 for this being my preferred solution as well. Maybe you should edit your answer and change "@input is not null" to "" to make clear that field update will occur if some condition applies, independent of @input.
Comment: @Thorsten: Good point, I edited the anwer to have a pseudo code that shows the principle and an example.
Comment: take care bro!!!
Answer: Use Case statement in Update clause
like
SQL Statement #6
UPDATE titles
       SET price =
                 CASE
                   WHEN (price < 5.0 AND ytd_sales > 999.99)
                                   THEN price * 1.25
                   WHEN (price < 5.0 AND ytd_sales < 1000.00)
                                   THEN price * 1.15
                   WHEN (price > 4.99 AND ytd_sales > 999.99)
                                   THEN price * 1.2
                   ELSE price
                 END

Taken from SQL SERVER UPDATE
Also you can go with if..else statement
If you would have been in SQL SERVER 2008, you could have avail the flavor of MERGE statement
Answer: Just an example:
IF @a <= 0
BEGIN
    UPDATE table SET counter = @a, name = 'Minati'
END
ELSE
BEGIN
    UPDATE table SET name = 'Minati'
END

Answer: May be you can build the condition in the update command and easily run more than one update with the diferent conditions. It may not be the most elegant way but it is prety eficient. It depends of your needs.
UPDATE table SET field=value WHERE <<condition>>
UPDATE table SET field=value2 WHERE <<condition2>>


How to find the linear transformation associated with a given matrix?

Question: Good day, I have a little doubt: It is well known that given two bases (or even one if we consider the canonical basis) of a vector space, every linear transformation $T:V \rightarrow W$ can be represented as a matrix, but since this is an isomorphism between $L(V,W)$ and $\mathbb{M}_{m\times n}$ where the latter represents the space $m\times n$ matrices on the same field in which are defined respectively vector spaces. That's where my question comes up, I know find the matrix associated with the linear transformation, but not know how to move from the matrix transformation, ie given any matrix, find the linear transformation that defines it. I wish you could please explain the theoretical process and to see a practical example. Thank you very much, I know it's definitely something silly, but I'm still a student.
Answer: The columns of the matrix tell us where the basis vectors of the domain are mapped, in terms of the basis vectors of the codomain. Since every vector in the domainis a linear combination of the basis vectors (in a unique way), we can extrapolate, in a sense, the image of any given vector. Let $A$ be an $m\times n$ matrix (with coefficients in a field $F$) with columns $A_1, ..., A_n$. Let $V$ be an $n-$dimensional $F-$vector space, and $W$ an $m-$dimensional $F-$vector space, with ordered bases $(v_1, ..., v_n)$ and $(w_1, ..., w_m)$, respectively. Finally, let $T$ be the linear transformation associated with $A$, and let $v\in V$ with $v = c_1v_1 + ... + c_n v_n$ (remember, this expression for $v$ as a linear combination of basis vectors is unique). Then
$$T(v) = T(c_1v_1+...+c_nv_n) = c_1T(v_1)+...+c_nT(v_n) = c_1A_1 + ... + c_nA_n$$
So, this is how the matrix lets us calculate the image of any vector. Notice that the expression on the right is just the matrix $A$ multiplied by the vector $[c_1, c_2, ..., c_n]^T$.
For example, if we let $V = W = \Bbb{R}^2$ (considered as $\Bbb{R}-$vector spaces) with the standard basis, let $$A =
 \left[ \begin{array}{ccc}
1 & 2 \\\
2 & 3  \end{array} \right]$$
And let $T$ be the linear transformation associated with $A$, and let $v = [1,5]^T$. Then
$$T(v) = 1\cdot T(e_1) + 5\cdot T(e_2) = [1,2]^T+5[2,3]^T = [11,17]^T = A\cdot v$$
Comment: Thank you for your contribution! But I do not understand something, the vector $(1,5)$ where it came from? assuming we are working with the canonical basis. And in the last expression $Av$, this seems to be a vector not the algebraic expression of $T$ ?. Please, you can better explain your example?
Comment: I just chose an arbitrary vector to show how you can take any vector, and use the matrix to find its image under the associated linear transformation.
Comment: Sure, I understand, but that's not my question, my question is given the matrix $A$ I want to find is the linear transformation $T$ associated with $A$, I did not mean vector image. Can you explain this please?
Comment: I don't quite get what you mean by "find the linear transformation"; a linear transformation is just a special function which assigns an image to each element of the domain. If you know how to find the image of a given vector, then you know everything about the linear transformation.
Answer: I am not sure what you expect, say $T$ is your linear transform, and $A$ represents it in the basis for $V = \{a_1,\dots,a_n\}$ and $W = \{b_1,\dots,b_m\}$.
Then we say $Ta_j = \sum_i A_{ij}b_i.$
This should completely define what $T$ "does".  Typically, one defines the action of $T$ on the basis vectors $a_i$ in order to determine what $T$ "looks like".  Otherwise, one can not write down much about $T$.  Please clarify what type of answer you are expecting if this is not sufficient.
Comment: If we are dealing with a linear operator $T:V \to V,$ then we can determine some more properties that hold for $T$ independent of basis, such as tr($T$), det($T$), rank($T$), etc.  but these things do not fully characterize $T$.  As stated, the action of $T$ between two bases is enough to fully define the transformation.
Answer: Suppose that you have an $m,n$ matrix $A$. Choose a basis $B$ of $V$ and another one $B'$ of $W$. The linear transformation associated with $A$ relative to the bases $B$ and $B'$ is $T(v) = Av$, where $v$ is to be written as a column whose entries are the coefficients of $v$ in the basis $B$ and the resulting column $T(v)$ has entries which are the coefficients of $T(v)$ in the basis $B'$. If you choose other bases, you get different linear transformations
Comment: Thank you so much for your contribution!, but can you explain me with this matrix A=\begin{bmatrix}{3}&{2}\\{-8}&{1}\end{bmatrix}.? Please.
Comment: Assuming the canonical basis of $\mathbb R^2$, the associated linear transformation is for $v=(v_1,v_2)$, $T(v) = Av^T = (3v_1 +2v_2, -8v_1+v_2)^T$ (where $^T$ is the transpose)
Comment: By the way, it was not nice of you to switch the accepted answer. Make up your mind then choose (please don't re-accept my answer)
Comment: Oh, thank you very much for the explanation, I ask you a million apologize for the inconvenience, I'm really new to the forum, I figured I could choose several answers, all seems good contribution and I am grateful for it. It has never been my intention to hurt anyone's feelings
Comment: You are very welcome, there's no need to apologize. Welcome to MSE! Almost all answers over here are good contributions and people carefully typeset equations with Mathjax and organize their answers. So yes, it is difficult to choose among answers
Comment: Thank you so much for the support!. But I do not still have some clear what happens now with $T$ if the base I choose is not canonical, for example want to see $T$ in the following bases of $\mathbb{R}^2$: $B=\{(1,-2),(0,5)\}$ and $B'=\{(3,-1),(-4,0)\}$? Now what is the expression of $T$?
Comment: You can find the transition matrix from $B$ to the canonical basis and the transition matrix from $B'$ to the canonical basis and things become easier. I am short of time now, you can read about this on the Internet (Google: transition matrix - linear algebra)
Comment: Very well, thank you very much for the advice, you have been so kind. How I could contact you in future questions in this way? Greetings from Venezuela, here are 9:33 am. =)


Verificar Consistência de um backup SQL Server em C#

Question: Como posso fazer a verficação de integridade do arquivo de backup de um banco SQL Server em C#??
Usei o seguinte namespace e classes para gerar o backup:
  Microsoft.SqlServer.Management.Smo {
  ServerConnection
  Server
  Backup
  BackupDeviceItem }

Gostaria de saber como verifico o arquivo BACKUP010101.BKP por exemplo.
Pensei em algo do tipo RESTORE VERIFYONLY, mas não sei como fazer dentro C#.
Answer: Fiz um teste aqui com esse código e funciona, é só um exemplo.
Altere ele para ficar de acordo com o que você exatamente quer.
Ele está usando RESTORE VERIFYONLY que você quer, o comando vai verificar o backup, se estiver bom ele retorna 'OK', se não, vai retornar a mensagem de erro do Sql Server.
 public partial class Form1 : Form
 {
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string connectionString1 = (@"Data Source =localhost; Initial Catalog = XXXXXXXXXXXXXXXXXX; Integrated Security = True");
        SqlConnection cn = new SqlConnection(connectionString1);
        cn.Open();
        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = @"begin try RESTORE VERIFYONLY FROM DISK = 'c:\home\bkp.bak' SELECT 'OK'; end try begin catch select ERROR_MESSAGE(); end catch";

        cmd.CommandType = CommandType.Text;
        cmd.Connection = cn;
        var resultado = cmd.ExecuteScalar();
        MessageBox.Show(resultado.ToString());
        cn.Close();
    }
 }

Comment: Funcionou, obrigado.
Answer: using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System;

class A {
   public static void Main() {
      // Connect to the local, default instance of SQL Server.
      Server srv = new Server();

      // Reference the AdventureWorks2012 database.
      Database db = srv.Databases["AdventureWorks2012"];

      // Note, to use the StringCollection type the System.Collections.Specialized system namespace must be included in the imports statements.
      System.Collections.Specialized.StringCollection sc;

      // Run the CheckTables method and display the results from the returned StringCollection variable.
      sc = db.CheckTables(RepairType.None);

      foreach (string c in sc) {
         Console.WriteLine(c);
      }
   }
}

https://msdn.microsoft.com/en-us/library/ms162133.aspx


How do I create a node using web services and Anonymous user?

Question: I have successfully installed the Services module and created a service with which I can retrieve a node or even several nodes (using Views Services)
I've now configured an endpoint, whose purpose is to allow an application to create nodes through a JSON call.
After much messing about I finally configured the following JSON call:
<code>{
"type":"demande-de-rdv",
"uid":"0",
"language":"und",
"status":"1",
"promote":"0",
"sticky":"0",
"title":"JSON Post using http_request",
"body":"Morbi sit amet leo molestie, luctus metus aliquet, pellentesque lacus! Suspendisse at laoreet nulla. Nunc sed tincidunt dolor. Donec condimentum     odio non nisl condimentum, id euismod arcu rhoncus? Nullam sit amet ante convallis, viverra nulla in, laoreet leo. Fusce vitae iaculis libero. Phasellus scelerisque varius augue, quis vulputate sapien vehicula vel. Sed at est at felis dignissim rutrum. Sed porta tristique sapien et viverra. Nunc ac elit tristique, laoreet lacus at, pharetra elit. Morbi sit amet commodo dolor? Donec consectetur justo vel fringilla rutrum"
}
</code>
However, when I post the call I get the reply "403 : Access denied for user anonymous", this despite the fact that I have configured the content type to be creatable by Anonymous (and have created a node for the content type in question to test it). I also gave Anonymous all the permissions on the Services module just in case, but it made no difference.
Where i am going wrong?
Comment: Try remove sessions authentication from that endpoint
Comment: Don't see how I can do that. Under the "Authentication" tab, I get this message: "No authentication modules are enabled, all requests will be anonymous"
Comment: I have posted to /node and it works for anonymous after granted that permission and cleared cache by the way you don't have to set the field uid and it's not necessary
Comment: Your body field is formatted incorrectly no matter what. It should be `body: { und: [ { value: 'hello world' } ] }`, also try removing the status, promote and sticky properties, those are usually reserved for admins.
Comment: @tyler.frankenstein - I did as you suggested and got a step forward (I think) inasmuch as now my service returns "401 Unauthorized : Missing required argument node". I tried modifying the request by putting {node[...]} around the whole, but no luck. Is there anywhere where the proper format is documented?
Comment: @MartinK http://tylerfrankenstein.com/code/drupal-services-examples - see the POST call for node CRUDI, you shouldn't have to wrap it at all, unless you are trying to update a node.
Answer: I have posted to /node and it works for anonymous after granted that permission and cleared cache by the way you don't have to set the field uid and it's not necessary if you set

$request_url = 'domain/endpoint/node';

<code>// Node data
$node_data = array(
  'title' => 'product testing',
  'type' => 'product',
    "uid" => 0,
    "language" => "en",
    "sticky" => 0
);
//$node_data = http_build_query($node_data);
$data = json_encode($node_data);

// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json')
);
curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Set POST data
curl_setopt($curl, CURLOPT_HEADER, FALSE);  // Ask to not return Header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

$response = curl_exec($curl);
</code>


Jinja Invalid Filter, filter is built in

Question: I have read through the Jinja documentation and am using the truncate filter. I have used it exactly as defined in the documentation.
From the docs:

truncate(s, length=255, killwords=False, end='…', leeway=None)
  Return a truncated copy of the string. The length is specified with the first
  parameter which defaults to 255. If the second parameter is true the
  filter will cut the text at length. Otherwise it will discard the last
  word. If the text was in fact truncated it will append an ellipsis
  sign ("..."). If you want a different ellipsis sign than "..." you can
  specify it using the third parameter. Strings that only exceed the
  length by the tolerance margin given in the fourth parameter will not
  be truncated.

Here is my code:
{% if post.replies.all %}

{% for reply in post.replies.all %}

            {{reply.by}}: {{reply.content|truncate(14)}}

{{ reply.content }}

{% endfor %}

{% endif %}

I get the following traceback after testing:

What am I doing wrong?
Comment: Are you sure Django is treating the template as Jinja? You might get that error if it was treated as Django template language. In Jinja, I would expect you to call `post.replies.all()`.
Comment: I'm not certain. I checked my version to make sure I had Jinja2 and I in fact only had 1.2. I upgraded to Jinja2 to no avail.
Answer: You are quite simply not using Jinja. You are using the Django template language.
Django's built-in filters are documented here; the filter that truncate strings is called truncatechars. You also need to use Django syntax to pass the parameters to the filter.
{{reply.content|truncatechars:14}}

Comment: You need to change the template backend - see [the docs](https://docs.djangoproject.com/en/1.11/topics/templates/#support-for-template-engines). I really recommend not doing this though unless you have a very good reason; apart from anything else, as Alasdair pointed out, some other parts of your template are already based on Django syntax not Jinja.
Comment: Assuming you mean "why would it still be using Django template language":  why wouldn't it? If you haven't changed the template backend, you haven't done anything to tell it to use Jinja.
Comment: Thanks for your answer! How can I switch and use jinja instead? I have 'jinja2' listed in my `INSTALLED_APPS` in `settings.py`, but I guess that's simply not working.
Comment: Thank you for your concise answers. I have one question though, why would it still be using jinja if I have jinja listed in my `INSTALLED_APPS` setting?


Nullable warning in Blazor in object List and API (controller) calling

Question: I'm new in Blazor and I'm a little bit confused about warnings and nullable. If I declare a varible like this: List<Course> result = new List<Course>();
I get a warning in here: result = await ClientHttp.GetFromJsonAsync<List<Course>>("api/GetCourses");
But if I set the variable as nullable: List<Course>? result = new List<Course>();
The first warning dissapears but I get a new one: result.Remove(aux);
So, I can build with the warnings and I could hide them but I would like to know what is really happening and how control it.
Comment: One things to learn is this: warnings are good, and unhandled exception crashes in development are GREAT.  I would only add a null check or null ignore to get rid of that green squiggly line when I'm VERY SURE I can't ever have a null value-- like if my api is on the same server as my main Blazor page, and always will be for eternity.  If you wave away a warning with an operator too early in development, then you are inviting a debugging session later.  Consider the green squiggle a "TODO: add exception handler here" unless you are 100% confident.
Answer: Because you initialize result it is safe to remove the ? from the declaration:
//List<Course>? result = new List<Course>();
  List<Course> result = new List<Course>();

and to use the 'null forgiving operator' !,  like this:
//result = await ClientHttp.GetFromJsonAsync<List<Course>>("api/GetCourses");
  result = await ClientHttp.GetFromJsonAsync<List<Course>>("api/GetCourses")!;

In the rest of your code you can now use result. , without the ?. Which is the main goal of enabling 'nullable reference types'.
When the Get fails it is up to your error handling, but the code as-is is Ok. I don't even know when (if) GetFromJsonAsync returns null, it will throw in all relevant cases.
Comment: I agree 100%.  My answer to the OP is to leave the warning until you 100% know that you can never have an error-- or take the 10 seconds to write a block to handle the error.
Comment: I edited a little, getting rid of the `?` is essential here.
Comment: I think the "!" operator is really dangerous.  Too many people will just realize "the warning goes away if I add '!', and then they're back to square 1: having unhandled null exceptions."
Comment: After reading all of your comments, it seems the best practice is control the null and/or try-catch. Which is how I work in asp.net, there is no nullable there.
Answer: When a variable is set to be nullable, it may occasionally become null.
You need to check if the result is null before removing an item.
If the result is null, a null exception will be thrown.
result?.Remove(aux);


Limit with variable: non-defined expression

Question: Decide whether or not the following functions have a limit at the indicated point
$$\lim_{x \rightarrow0}\frac{1}{x^2}$$
$x=0 $
It is not defined....try from left to right
Comment: One could say $\lim\limits_{x\rightarrow0}(1/x^2)=\infty$. Contrast this with  $\lim\limits_{x\rightarrow0}(1/x)$; which isn't defined, even in the infinite sense.
Comment: thanks, but that doesn't explain the left to right meaning
Answer: I hope this answers your question.
If limit $\lim_{x \rightarrow 0} f(x)$ exists then $\lim_{x \rightarrow 0_-} f(x)$ and $\lim_{x \rightarrow 0_+} f(x)$ exists and also
$$\lim_{x \rightarrow 0_+} f(x)=\lim_{x \rightarrow 0_-} f(x)$$
In your case that's:
$$\lim_{x \rightarrow 0_+} \frac{1}{x^2}= \infty=\lim_{x \rightarrow 0_-} \frac{1}{x^2}$$
So your limit exists: $$\lim_{x \rightarrow 0} \frac{1}{x^2}=\infty$$
As David Mitra suggested you can compare it to $\lim_{x \rightarrow 0} \frac{1}{x}$ where one sided limits are not equal.


Jenkins script to update job config: restricted agent and using docker container

Question: I'm using a Jenkins script to update several jobs. I'm able to update the description, SCM credentials, and so on.
But I can't find how to :

a) unset the option to restrict the agent (restrict where this project can be run)
b) set the option "Docker container" (DockerJobProperty)

Jenkins version: 1.609.3
Thanks in advance for any help.
Regards,
Sébastien
Comment: I found the solution for (a) by setting the assignedLabel property of my Item to null.
Answer: If it can help someone else here is the answers.
a) item.assignedLabel = null
b) item.addProperty(new com.nirima.jenkins.plugins.docker.DockerJobProperty(false, "", false, true))
Regards


How to control path alias in custom node form #validate function?

Question: To change form values in code, I understand that the right way is to add a validate function with hook_form_alter, to append the function's name to the #validate array then use form_set_value.
When I inspect the form array at this point though, I cannot see a way to reliably determine the parents of the path value.
e.g. I have
$form_state['groups']['additional_settings'][4]['alias']

And I can only assume that the 4 index is not always going to be 4; that it might be a different number if more modules are installed etc.
So how can I set the alias? (I also need to un-set pathauto's checkbox so it does not auto-generate a new path.) Am I doing it in the right place?
Thanks.
Answer: You will find the values submitted by the user in $form_state['values]. So you can just fetch the ones submitted alter them and them send them back to the form. And the path settings are located at $form['path']. $form_state['groups'] is just a way of grouping form elements together.
/**
 * Implements hook_node_form_FORM_ID_alter().
 */
function MYMODULE_form_node_form_alter(&$form, &$form_state) {
  // Add our validate function to all node forms.
  $form['#validate'][] = 'MYMODULE_alter_node_path';
}

/**
 * Custom form validate function.
 */
function MYMODULE_alter_node_path($form, &$form_state) {
  // Fetch the path values submitted.
  $value = $form_state['values']['path'];
  // Do your changes to the path and unset pathauto checkbox.
  $value['alias'] = 'new-alias';
  $value['pathauto'] = FALSE;
  // Set the values in the form.
  form_set_value($form['path'], $value, $form_state);
}

Comment: Thanks. Part of my problem was my [debugger config](http://stackoverflow.com/questions/24302203/vdebug-xdebug-only-showing-first-32-elements-of-arrays) which meant I did not know of the existence of the `path` key in `$form`! But also I did not know you could do composite value setting in the way you have illustrated, which is interesting. I find it a little confusing, so I've gone with two calls to `form_set_value`, one to `$form['path']['alias']` and one to `$form['path']['pathauto']`. Many thanks