Setting five alarms daily and update them on a button click

Question: Please excuse me if this is a noob question. I have tried every possibility I could to set five alarms daily from the five edit texts. But nothing worked! I also have a button (not shown in this code) which updates these edit texts (therefore should update the alarm times as well). Here's my code:
for (int i = 0; i < 5; i++) {
            switch (i) {
            case 0:
                fajr.setText(result[i]);
                tFajr = new GregorianCalendar();
                tFajr.set(year, month, day,
                        Integer.parseInt(result[i].substring(0, 2)),
                        Integer.parseInt(result[i].substring(3, 5)));
                break;
            case 1:
                zuhr.setText(result[i]);
                tZuhr = new GregorianCalendar();
                tZuhr.set(year, month, day,
                        Integer.parseInt(result[i].substring(0, 2)),
                        Integer.parseInt(result[i].substring(3, 5)));
                break;
            case 2:
                asr.setText(result[i]);
                tAsr = new GregorianCalendar();
                tAsr.set(year, month, day,
                        Integer.parseInt(result[i].substring(0, 2)),
                        Integer.parseInt(result[i].substring(3, 5)));
                break;
            case 3:
                maghrib.setText(result[i]);
                tMaghrib = new GregorianCalendar();
                tMaghrib.set(year, month, day,
                        Integer.parseInt(result[i].substring(0, 2)),
                        Integer.parseInt(result[i].substring(3, 5)));
                break;
            case 4:
                isha.setText(result[i]);
                tIsha = new GregorianCalendar();
                tIsha.set(year, month, day,
                        Integer.parseInt(result[i].substring(0, 2)),
                        Integer.parseInt(result[i].substring(3, 5)));
                break;
            }
        }

P.S: fajr,zuhr,asr,maghrib,isha are the five EditTexts. I tried to use a pending intent and an alarm manager to fire the alarms but it didnt work. Does any one have a good suggestion?
Comment: what did not work? shure your code gets triggered? Whats an "alarm", because it looks like an AsyncTask?
Comment: Rewrite the question. Clear communication is the first step.  You need to say what is wrong, where/how your code is triggered, and if you are using an AlarmManager.  If not you probably sould.
Comment: People, kindly see the edit above.
Comment: @AdnanZahid How to set it in background without any user interaction?
i.e. Calculate prayer time and set notifications for it?
Answer: First of all you need to declare a pending intent for each of the alarms. So if you want 5 alarms you will need to run it 5 times
PendingIntent sender = PendingIntent.getBroadcast(context,intent_code, intent, 0);

and the intent_code should change as well. Every time you register a new one you have to use a different code. In my application I have a random number generated every time that is executed. You can also pass data to your notification trough here using the Intent. Mind the difference between Intent and PendingIntent.
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("title", "some title");
intent.putExtra("notes","some notes");
Random r = new Random();
intent_code = r.nextInt();
PendingIntent sender = PendingIntent.getBroadcast(context,intent_code, intent, 0);

After that you need to register your alarm. Again 5 times, one for each alarm  you want to trigger.
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, Time_in_milis_from_now_till_your_alarm, sender);

You need a BroadcastReceiver to receive your alarm and display the notification. I am pasting my whole class. This will be triggered after the time set in the Time_in_milis_from_now_till_your_alarm. And you can run pretty much whatever you like in here. I don't know what kind of alarm you want, in my case I'm using a notification. You can find the details about the notification here and here.
public class AlarmReceiver extends BroadcastReceiver {

    @Override
     public void onReceive(Context context, Intent intent) {
        Log.d("receiver", "received");
        NotificationManager mManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Bundle b = intent.getExtras();

        int icon = R.drawable.icon; // icon from resources
        CharSequence tickerText = b.getString("title"); ; // ticker-text
        long when = System.currentTimeMillis(); // notification time
        CharSequence contentText = b.getString("notes");; // message text
        Toast.makeText(context, tickerText, Toast.LENGTH_SHORT).show();

        Intent notificationIntent = new Intent(context, AppDelegate.class);

        // notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent contentIntent = PendingIntent.getActivity(context,
                                                                0,
                                                                notificationIntent,
                                                                Intent.FLAG_ACTIVITY_NEW_TASK);

        // the next two lines initialize the Notification, using the
        // configurations above
        Notification notification = new Notification(icon, tickerText, when);
        notification.setLatestEventInfo(context,tickerText, contentText, contentIntent);

        mManager.notify(12, notification);
     }

}

Last, don't forget to declare your broadcast in the manifest or it wont work. This goes inside application tag.

If you have any problems with the alarm manager methods you can find the documentation here.
All the best!
Edit
To play a sound use the MediaPlayer as recomended by the developer's guide. Keep the file mysound.mp3 in your folder /res/raw. And you just call the following method in your BroadcastReceiver!
public void playSound() {
     MediaPlayer sound = MediaPlayer.create(this, R.raw.mysound);
     sound.setOnCompletionListener(new OnCompletionListener() {
     @Override
     public void onCompletion(MediaPlayer mp) {
            mp.release();
     }

     });

    quadrantChangeSound.start();
   }

Comment: Thank you for the help, I'll award you the bounty.
P.S: I'd be really grateful if you could show how to play an mp3 file instead of displaying a notification.
Comment: Just updated my answer. Don't forget to accept it if it works for you.  I'm glad I could help!
Answer: It looks to me like you're trying to do this in an AsyncTask as @Rafael_T suggested. What you need to do is use AlarmManager and have it send a broadcast when the alarms go off for you to handle. Here is a good tutorial on how to do it.
Answer: I developed some similar application.
I used an AlarmManger to solve this and it worked fine.
To set the wakeup date I created an calendar object. In case you want to setup the alarm for the next day, you have to add 24 hours.
This is how you get the time:
Calendar calNew = Calendar.getInstance();
        calNew.set(Calendar.HOUR_OF_DAY, hour);
        calNew.set(Calendar.MINUTE, minute);
        calNew.set(Calendar.SECOND, 0);

        Calendar calNow = Calendar.getInstance();
        // Get the AlarmManager service
        if (calNew.getTimeInMillis() < calNow.getTimeInMillis()) {
            calNew.add(Calendar.HOUR_OF_DAY, 24);
        }

And this is how you setup the AlarmManager:
// INTENT AND ALARMMANAGER PLANING
    Intent intent = new Intent(context, AlarmReceiver.class);

    sender = PendingIntent.getBroadcast(context, INTENT_CODE, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    am = (AlarmManager) getSystemService(ALARM_SERVICE);
    am.set(AlarmManager.RTC_WAKEUP, calNew.getTimeInMillis(), sender);

Comment: I'm sorry my friend, it doesn't work. Do I need to setup a corresponding INTENT_CODE (for eg: 12345) in the AlarmReceiver.class as well? Also as I said I need to fire this alarm five times a day, should I do the same thing for all of them or can there be a better/more efficient way?
Comment: If it is just the alarm, I think you can just repeat this process 5 times and just change the value of calNew. You won't have to setup a new INTENT_CODE.
Comment: What about sender = PendingIntent.getBroadcast(context, INTENT_CODE, intent,PendingIntent.FLAG_UPDATE_CURRENT); should i simply remove the INTENT_CODE from it? And what about the AlarmReceiver.class?


django upload image gives InMemoryUploadedFile error on validating

Question: I am trying to make an upload image form. but it crashes on a succesfull clean in ym form (get 'InMemoryUploadedFile' object has no attribute 'get')
My form clean:
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _
from django.conf import settings

def clean(self):
    content = self.cleaned_data['avatar']
    content_type = content.content_type.split('/')[0]
    if content_type in settings.CONTENT_TYPES:
        if content._size > settings.MAX_UPLOAD_SIZE:
            raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(content._size)))
    else:
        raise forms.ValidationError(_('File type is not supported'))
    return content

my setting attributes:
MAX_UPLOAD_SIZE = 1310720
CONTENT_TYPES = ['image']

The errors work fine. but when no ValidationError is found i get that InMemory error.
What do i do wrong?
Answer: You've returned self.cleaned_data['avatar'] from def clean() which should be def clean_avatar(). clean() should return the whole cleaned_data anyhow.


Calculating moments of a function of independent Gaussians

Question: Suppose we have
$$f(g) = \log\left(\sum_{i = 1}^N
\begin{cases}
|a_i| e^{g_i}, & a_i \geq 0 \\
|a_i| (2 - e^{g_i}), & a_i < 0
\end{cases}
\right)
$$
where $g = (g_1, \ldots, g_N)$, each $g_i$ is independently $\mathcal{N}(\mu_i, \sigma_i^2)$, and $\sum_{i = 1}^N |a_i| = 1$.
I want to calculate the mean and variance of $f(g)$.
For my practical purposes, each $\mu_i$ and $\sigma_i$ are relatively close to zero, so I have attempted a solution by taking a second order Taylor-expansion of $f$ around 0.
\begin{align}
f(g) &= \log\left(\sum_{i = 1}^N
\begin{cases}
|a_i| (1 + g_i + \frac{g_i^2}{2} + O(g_i^3)), & a_i \geq 0 \\
|a_i| (1 - g_i - \frac{g_i^2}{2} + O(g_i^3)), & a_i < 0
\end{cases}
\right) \\
&= \log\left(\sum_{i = 1}^N
|a_i| + a_i g_i + \frac{a_i g_i^2}{2} + O(g_i^3))
\right) \\
&= \log\left(1 + \sum_{i = 1}^N
a_i g_i + \frac{a_i g_i^2}{2} + O(g_i^3))
\right) \quad \text{since } \sum_{i = 1}^N |a_i| = 1 \\
&= \left(\sum_{i=1}^N a_i g_i + \frac{a_ig_i^2}{2}\right) - \frac{\left(\sum_{i=1}^N a_i g_i + \frac{a_ig_i^2}{2} + O(g_i^3) \right)^2}{2} + \sum_{i=1}^N O(g_i^3) \\
&= \left(\sum_{i=1}^N a_i g_i + \frac{a_ig_i^2}{2}\right) - \frac{\left(\sum_{i=1}^N a_i g_i\right)^2}{2} + \sum_{i=1}^N O(g_i^3)
\end{align}
so my approximation is
$$\tilde{f}(g) = \left(\sum_{i=1}^N a_i g_i + \frac{a_ig_i^2}{2}\right) - \frac{\left(\sum_{i=1}^N a_i g_i\right)^2}{2}$$
and
\begin{align}
\mathbb{E}[\tilde{f}(g)] &= \sum_{i=1}^N \left(a_i \mu_i + \frac{a_i (\mu_i^2 + \sigma_i^2)}{2}\right) - \frac{\left(\sum_{i=1}^N a_i \mu_i\right)^2 + \left(\sum_{i=1}^N a_i^2 \sigma_i^2\right)}{2}\\
Var(\tilde{f}(g)) &= \ ?
\end{align}
My calculations start getting very messy very quickly once I try to compute $Var(\tilde{f}(g))$, and furthermore, I am not so sure whether these approximations are kosher to begin with. Am I making assumptions about higher order moments of each $g_i$ that I am not justifying? I am implicitly guessing that I need to keep the quadratic terms of my Taylor expansions to have a reasonable estimate of the second moment of $f(g)$, is this correct?
Thank you for the help!
Answer: In general, we can use a multivariate Taylor expansion of the whole function to compute the expectation and the variance (rather than expanding the exponential terms and then the logarithm).
The second order expansion around some (column) vector $g'$ is
$$f(g) \approx f(g') + \nabla f(g')^T(g-g') + \frac{1}{2} (g-g')^T \mathbf{H}_f(g') (g-g')$$
where $\mathbf{H}_f(g')$ is the Hessian of $f$ at $g'$.
The expectation can be approximated by our second order expansion about the mean ($g' = \mu$):
\begin{align}
\mathbb{E}[f(g)] &\approx \mathbb{E} \left[ f(\mu) + \nabla f(\mu)^T(g-\mu) + \frac{1}{2} (g-\mu)^T \mathbf{H}_f(\mu) (g-\mu) \right]\\
                &= f(\mu) + \nabla f(\mu)^T\mathbb{E} \left[ (g-\mu) \right] + \frac{1}{2} \mathbb{E} \left[ (g-\mu)^T \mathbf{H}_f(\mu) (g-\mu) \right]\\
                &= f(\mu) + \frac{1}{2} Tr\left(\mathbf{H}_f(\mu) \Lambda \right)\\
\end{align}
where $\Lambda$ is the covariance matrix of $g$.
Now, if we want to compute $\mathbb{E}[f(g)^2]$, we can use the expansion of $s(g) = f(g^2)$ around $g'$, where:
$$\nabla s(g') = 2f(g') \nabla f(g')$$
and
$$\mathbf{H}_s(g') = 2f(g')\mathbf{H}_f(g') + 2\nabla f(g') \nabla f(g')^T$$
Then the expectation of $f(g)^2$ can be approximated by another second-order Taylor series centered at $\mu$:
\begin{align}
\mathbb{E}[f(g)^2] &\approx \mathbb{E} \left[ s(\mu) + \nabla s(\mu)^T(g-\mu) + \frac{1}{2} (g-\mu)^T \mathbf{H}_s(\mu) (g-\mu) \right]\\
                &= f(\mu)^2 + 2f(\mu)\nabla f(\mu)^T\mathbb{E} \left[ (g-\mu) \right] + f(\mu) \mathbb{E} \left[ (g-\mu)^T \mathbf{H}_f(\mu) (g-\mu) \right] + \mathbb{E} \left[ (g-\mu)^T \nabla f(\mu) \nabla f(\mu)^T (g-\mu) \right]\\
                &= f(\mu)^2 + f(\mu) \mathbb{E} \left[ (g-\mu)^T \mathbf{H}_f(\mu) (g-\mu) \right] + \mathbb{E} \left[ (g-\mu)^T \nabla f(\mu) \nabla f(\mu)^T (g-\mu) \right]\\
                &= f(\mu)^2 + f(\mu)Tr\left(\mathbf{H}_f(\mu) \Lambda \right) + Tr\left(\nabla f(\mu) \nabla f(\mu)^T \Lambda \right)
\end{align}
Finally,
\begin{align}
Var(f(g)) &= \mathbb{E}[f(g)^2] - \mathbb{E}[f(g)]^2\\
          &\approx f(\mu)^2 + f(\mu)Tr\left(\mathbf{H}_f(\mu) \Lambda \right) + Tr\left(\nabla f(\mu) \nabla f(\mu)^T \Lambda \right) - \left(f(\mu) + \frac{1}{2} Tr\left(\mathbf{H}_f(\mu) \Lambda \right)\right)^2\\
          &= Tr\left(\nabla f(\mu) \nabla f(\mu)^T \Lambda \right) - \frac{1}{4} \left( Tr\left(\mathbf{H}_f(\mu) \Lambda \right)\right)^2
\end{align}
We can also compute these approximations around $g' = 0$ as I originally asked, instead of at $g' = \mu$.
$$\mathbb{E}[f(g)] \approx \mathbb{E}[f(0) + \nabla f(0)^T(g-0) + \frac{1}{2} (g-0)^T \mathbf{H}_f(0) (g-0)]$$
We have:
$$f(0) = \log\left(\sum_{i=1}^N a_i\right) = 0$$
$$\nabla f(0)_i = a_i$$
$$\mathbf{H}_f(0)_{ij} = a_i(\delta_{ij} - a_j)$$
So:
\begin{align}
\mathbb{E}[f(g)] &\approx \mathbb{E}[a^Tg + \frac{1}{2} g^T \mathbf{H}_f(0)g)] \\
                 &= a^T\mu + \frac{1}{2} Tr(\mathbf{H}_f(0)\Lambda) + \frac{1}{2} \mu^T\mathbf{H}_f(0)\mu
\end{align}
And:
\begin{align}
\mathbb{E}[f(g)^2] &\approx \mathbb{E} \left[ s(0) + \nabla s(0)^T(g-0) + \frac{1}{2} (g-0)^T \mathbf{H}_s(0) (g-0) \right]\\
                &= f(0)^2 + 2f(0)\nabla f(0)^T\mathbb{E} \left[ g \right] + f(0) \mathbb{E} \left[ g^T \mathbf{H}_f(0) g \right] + \mathbb{E} \left[ g^T \nabla f(0) \nabla f(0)^T g \right]\\
                &= \mathbb{E} \left[ g^T \nabla f(0) \nabla f(0)^T g \right]\\
                &= Tr\left( \nabla f(0) \nabla f(0)^T \Lambda\right) + \mu^T \nabla f(0) \nabla f(0)^T \mu\\
                &= Tr\left( \nabla f(0) \nabla f(0)^T \Lambda\right) + (a^T\mu)^2\\
\end{align}


How to access to google project from ui rather than link get from eclipse console

Question: I have developed a tool for handling google sheet using spring boot with google sheet api. When I run the application from UI ,then eclipse console will show a link for OAuth authentication so that to get data in UI Eclipse console.I need to get back to console and take the link to browser for authentication. So my question is how to authenticate it through UI rather than going to console manually.
I selected react js as UI, and I added GoogleLogin to it
`
This tool is requir a google account to access<GoogleLogin
<code>        clientId="my client id"
        redirectUri="http://localhost:8888/Callback"
        scope="https://www.googleapis.com/auth/spreadsheets"
        responseType="code"
        accessType="offline"
        buttonText="Choose account"

        onSuccess=""

        onFailure="" ></GoogleLogin>
        </div>`
</code>
even though react js code worked,i will get the sheet data only after authenticating using link given in console.Please help me to solve this
Answer: You may redirect it directly but it would only work in case you are having that url working.
Let suppose, I'm hosting my application on http://localhost:8080/myProject then it would be redirect you to some url, you would be get that using this way.

Generate Credentials.json file while keeping redirect url blank.
Put this file to resources
Run project again
It will give you the response url, Do something for mapping that URL to your needed re-directional url.

Let me know if you need anything more in this.


App crashes when adding code into fragment activity

Question: I'm new to android studio so I want to create an app that is using a navigation drawer to switch between 3 different fragments. I used the pre-built navigation drawer from android studio and I wanted to put some code into one of the fragments. But as soon as I initialize the TextView (or other things) the app immediately crashes when I try to open the fragment.
Here the code in the GalleryActivity:
    public class GalleryFragment extends Fragment {

    private FragmentGalleryBinding binding;
    private TextView testTV;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        GalleryViewModel galleryViewModel =
                new ViewModelProvider(this).get(GalleryViewModel.class);

        binding = FragmentGalleryBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        final TextView textView = binding.textGallery;
        galleryViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initWidgets();

        testTV.setText("Hello");
    }

    public void initWidgets(){
       testTV = testTV.findViewById(R.id.text_gallery);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}

fragment_gallery.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.gallery.GalleryFragment">

    <TextView
        android:id="@+id/text_gallery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:textAlignment="center"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Logcat:
2022-06-07 03:32:20.006 12339-12339/com.example.testapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.testapp, PID: 12339
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.TextView.findViewById(int)' on a null object reference
        at com.example.testapp.ui.gallery.GalleryFragment.initWidgets(GalleryFragment.java:46)
        at com.example.testapp.ui.gallery.GalleryFragment.onViewCreated(GalleryFragment.java:40)
        at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3019)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:551)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1840)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1764)
        at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1701)
        at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:488)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2022-06-07 03:32:20.040 12339-12339/com.example.testapp I/Process: Sending signal. PID: 12339 SIG: 9

Can someone tell me what I am doing wrong?
Thanks in advance!
Comment: Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it)
Answer: You never initialize testTV, so it is null. Then you try and use it to initialize itself in this command, which is never going to work.
testTV = testTV.findViewById(R.id.text_gallery); // testTV is null

If you must use findViewById you need to call it on the root view, which you could pass in from onViewCreated (e.g. view.findViewById()). However, since you are using a binding all of that is unnecessary, you can access the view directly from the binding like this
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    // no need to save testTV as a class member, it is already
    // saved in the binding
    binding.textGallery.setText("Hello");
}

The binding class is an auto-generated helper class that has already called findViewById on all the views in the layout and saved them as class members (it does that when you create it with the MyBinding.inflate() call). When using a binding you should almost never need to use findViewById nor should you need to store off individual views.


Using custom CSS3/HTML on generated pages?

Question: I created new pages on my (soon to be) photography website using Panels and Views. I want to have my own hover effects for pictures on my albums page. How am I supposed to use custom HTML and CSS3 animations like those found here on these images which are loaded by modules such as Panels and Drupal which are basically creating their own markup on the page load i.e. not in hard coded files which I can add markup to.
Comment: Hello, and welcome to Drupal Answers. This question is off-topic as per [FAQ].
Answer: You can override the views template and create your own template/markup to achieve what you want.  You can read more on how to achieve that here: http://drupal.org/node/1089656


How to find the tangent hyperplane in $n$-dimensions?

Question: I asked a similar question a week ago. I know the equation now but I do not know how to prove that that is indeed the desired equation. I found an article which proves the same for $z = f(x,y)$ using vectors.
Can we prove this without using vectors and (possibly) for $n$-dim?
Using the Frechet derivative, we arrive at $J_f(\mathbf{x}) \cdot h = 0$ for $h \to 0$. Can we continue from here? I am fine with a different method too as long as it does not use vector cross product, etc explicitly.
Comment: I would be tempted to approach this using [differential forms](https://en.wikipedia.org/wiki/Exterior_derivative), but before this, what do you mean by hyper-plane? A linear equation than constrains Cartesian coordinates and is only fulfilled for points lying on the plane?
Comment: @Cryo In 2D, the tangent is a line, in 3D, it's a 2D plane, I am trying to generalize this. Don't know what exactly should I call it.
Comment: I am not asking for a word, but for a mathematical definition (no rudeness implied :-)). Without this it is hard to answer the question. Let's say you have Cartesian coordinates $x^{(1)},\dots x^{(n)}$ to describe every point in your $n$-dimensional space. Is hyperplane an equation $a_1\,x^{(1)}+\dots+a_n\,x^{(n)}=c$ where $a_{\dots}$ and $c$ are constants?
Comment: @Cryo I think so, yes. Does this look like a line vector or a space? (I am looking for an $(n-1)$ dimensional space.) Can you as well tell me how would a line vector tangent look like in this case?
Answer: The answer you got when $n=3$ can be exactly performed for a larger dimension.
The tangent plane at $z_0$ is given by the hyper plane equation.
$$g(z)= f(z_0)+J_f(z_0)\cdot (z-z_0)$$
Comment: Well I meant, I am looking for a *proof*, not the equation.
Comment: We'll, a proof depends on definitions. What is your definition of the tangent plane?
Comment: In an $n$-dim space, I am considering the $(n-1)$-dim hyperplane to a function at a (given) point.
Comment: That is not an answer to the question. How do you define the tangent hyperplane to a map at a point?
Comment: Can you tell me if there's a difference between the [Tangent Vector](https://en.wikipedia.org/wiki/Tangent_vector#Definition), [Directional Derivative](https://en.wikipedia.org/wiki/Directional_derivative) and the equation you wrote? Also, what is the dimension of $g(z)$ in your equation?
Comment: I'll answer to your questions… when you'll have answer to mine first. Which is just asking you to define a word of the title of your question.
Comment: Sorry, I don't know how to define it, which is why I asked this to you. I might have been able to frame it with one of those I mentioned in my previous comment. I am only trying to extend the "line tangent in 2D, plane tangent in 3D" notion to more than 3 dimensions. The notion is $(n-1)$-dim hyperplane that touches a (given) point $p \in \text{Im}(f)$ at only one point.
Comment: One common definition of the tangent hyperplane is exactly with the equation I provided in my answer. It is indeed an hyperplane providing that the Jacobian doesn't vanish.
Comment: I see. So can you now tell me (1) the difference between the three terms, if at all they are different? I don't quite see any difference b/w Directional derivative and Tangent Vector. (2) What would the line vector equation at the point $p$ look like?
Answer: Line, plane etc. are just words unless you have a good definition in your head, and the problem is that these things can be defined in different ways. As far as I see, there is no single best definition, there is only the one that suits you best. Nevertheless, I will try cover what I can
$n$-dimensional space
Let us agree to work in $\mathbb{R}^n$ space with Cartesian coordinates $x^{(1)}\dots x^{(n)}$. At each point in that space one can trivially obtain $n$-dimensional basis of orthonormal vectors $\mathbf{\hat{x}}_1\dots\mathbf{\hat{x}}_n$ attached to the coordinates.
$\left(n-1\right)$-dimensional hyperplane in $n$-dimensional space
Let us define hyper-plane as all the points from $\mathbb{R}^n$ that satisfy a linear equation:
$$
hyperplane\left[\left(a_1, \dots a_n\right), c\right]=\Big\{\left(x^{(1)},\dots x^{(n)}\right) \in\mathbb{R}^n \:\Big|\: \sum_i a_i x^{(i)}=c \Big\}
$$
Where $c\in \mathbb{R}$ is a constant, and $a_i \in \mathbb{R}$ are constants with at least one of the $a_i\neq 0$.
Without loss of generality, let $a_n \neq 0$. One can then establish a map from some other $(n-1)$ dimensional $\mathbb{R}^{n-1}$ space, with coordinates $y^{(1)},\dots y^{(n-1)}$:
$$
\begin{align}
\phi &:\mathbb{R}^{n-1} \to \mathbb{R}^n \\
\phi\left(y^{(1)},\dots y^{(n-1)}\right)&=\left(y^{(1)},\dots y^{(n-1)}, \frac{c-\sum_{i=1}^{n-1} a_i y^{(i)}}{a_n}\right)
\end{align}
$$
It should be easy to show that $\phi$ is a bijective map from $\mathbb{R}^{n-1}$ to $
hyperplane\left[\left(a_1, \dots a_n\right), c\right]$ so hyper-plane defined as above can be regarded as $\mathbb{R}^{n-1}$.
A special case of this is $n=2$. In which case a hyper-plane would be all the points that satisfy $a_1 x^{(1)} + a_2 x^{(2)}=c$ which clearly is an equation for a straight line.
Tangent hyper-plane
Let there now be a sufficiently smooth function $f: \mathbb{R}^n\to \mathbb{R}$. Equation
$$
f\left(x^{(1)},\dots,x^{(n)}\right)=A
$$
will define a surface in $\mathbb{R}^n$. Now consider a curve that lies on this surface. That is, consider a map $\lambda:\mathbb{R}\to\mathbb{R}^n$ such that:
$$
f\left(x^{(1)}\left(\lambda\right),\dots,x^{(n)}\left(\lambda\right)\right)=A,\quad \mbox{for all relevant } \lambda
$$
The tangent to $\lambda$-curve at point $P=\left(x^{(1)}_P,\dots x^{(n)}_P\right)$ is:
$$
\frac{d}{d\lambda}\Big|_P=\sum_{i=1}^n \frac{dx^{(i)}}{d\lambda}\Big|_P \mathbf{\hat{x}}_i
$$
Let us define a tangent hyper-plane to $f=A$ surface at $P$ as all the points one can get to by moving from $P$ along the tangent vector defined by any curve that lies in $f=A$ surface and goes through $P$
$$
T_P f=\Big\{\left(x^{(1)}_P+s\cdot v^{(1)},\dots x^{(n)}_P+s\cdot v^{(n)}\right)\: \Big|\: s\in \mathbb{R},\,v^{(i)}=\frac{d x^{(i)}}{d\lambda}\Big|_P,\,\lambda=\mbox{curve on the surface and going through P}\Big\}
$$
In the above definition, consider what restrictions are placed on $v^{(i)}$. Clearly since $\lambda$-cruve is on the surface:
$$
\begin{align}
f\left(x^{(1)}\left(\lambda\right),\dots,x^{(n)}\left(\lambda\right)\right)&=A \\
\sum_{i=1}^n \frac{\partial f}{\partial x^{(i)}}\Big|_P\cdot\frac{dx^{(i)}}{d\lambda}\Big|_P&=\sum_{i=1}^n \frac{\partial f}{\partial x^{(i)}}\Big|_P\cdot v^{(i)}=0
\end{align}
$$
So if I take a generic point $Q=\left(x^{(1)}_Q,\dots x^{(n)}_Q\right)\in T_p f$ then:
$$
\sum_{i=1}^n \frac{\partial f}{\partial x^{(i)}} \Big|_P\cdot x^{(i)}_Q=\sum_{i=1}^n \frac{\partial f}{\partial x^{(i)}} \Big|_P\cdot x^{(i)}_P + s\cdot \sum_{i=1}^n \frac{\partial f}{\partial x^{(i)}}\Big|_P\cdot v^{(i)}=\sum_{i=1}^n \frac{\partial f}{\partial x^{(i)}} \Big|_P\cdot x^{(i)}_P + 0 = c
$$
Where I have defined constant $c=\sum_{i=1}^n \frac{\partial f}{\partial x^{(i)}} \Big|_P\cdot x^{(i)}_P$ in the last stage. Now also define constants $a_i=\frac{\partial f}{\partial x^{(i)}} \Big|_P$ and you will find that:
$$
T_pf = \Big\{\left(x^{(1)},\dots x^{(n)}\right) \in\mathbb{R}^n \:\Big|\: \sum_i a_i x^{(i)}=c \Big\}
$$
which matches my previous definition of the hyper-plane. I have missed few steps but they should be easy to fill.
Summary
So in answer to your question. "How do I find the hyper-plane". All you need is constants $c$ and $\{a_i\}$, which can be obtained from the derivatives of $f$ at $P$

Replying to comments
For the purposes of this discussion, $f=A$ defines a manifold embedded into $\mathbb{R}^n$. I talked about tangents to curves on the surface. Each tangent was tangent vector the only difference is that I did not make any effort to restrict my discussion to the manifold, i kept it all embedded in $\mathbb{R}^n$. This is indeed the choice you can make. You can restrict your discussion to things intrinsic to the manifold. But then, to talk about vectors on the manifold you need to introduce a concept of tangent space at each point of the manifold. Consider for example a vector pointing to the north in US and in Europe. You can keep these vectors as 3d and then compare them with ease, or you could say that these vectors live in 2d tangent spaces of US and Europe, respectively. You would then need some sort of connection to compare these two vectors.
One thing I did use here was to talk about tangents as derivatives, e.g.
$$
\frac{d}{d\lambda}
$$
for the tangent along the curve parametrized by $\lambda$. This also is the directional derivative, i.e. the operator that, given some function $f$ will return how much this function changes as one moves along the curve, divided by change in $\lambda$.
The answer given by @mathcounterexamples.net is a bit too short to comment, but the answer given in the link you provided more or less boils down to the same thing. Hyperplane corresponds to linear equation parametrized by constants: $\sum_i a_i x^{(i)}=c$ in my notation or $ax+by+cz=C$ in the notation of @Sebastiano.
PS
It feels to me that you are not too confident about representing vectors as derivatives (along curves), i.e. if I have curve parameterized by $\lambda$ and another one parametrized by $\mu$ and both curves go through some point $P$, at that point I can talk about vectors $\alpha \frac{d}{d\lambda}+\beta\frac{d}{d\mu}$ for constants $\alpha$ and $\beta$. This, for example, could be the tangent vector to curve $x^{(i)}\left(\kappa\right)=x^{(i)}_P+\kappa\cdot\left(\alpha\frac{d x^{(i)}}{d\lambda}\Big|_P+\beta\frac{d x^{(i)}}{d\mu}\Big|_P\right)$ since:
$$
\frac{d}{d\kappa}\Big|_P=\frac{d x^{(i)}}{d\kappa}\Big|_P\frac{\partial}{\partial x^{(i)}}=\left(\alpha\frac{d x^{(i)}}{d\lambda}\Big|_P+\beta\frac{d x^{(i)}}{d\mu}\Big|_P\right)\frac{\partial}{\partial x^{(i)}}=\alpha\frac{d x^{(i)}}{d\lambda}\Big|_P\frac{\partial}{\partial x^{(i)}}+\beta\frac{d x^{(i)}}{d\mu}\Big|_P\frac{\partial}{\partial x^{(i)}}=\alpha\frac{d}{d\lambda}\Big|_P+\beta\frac{d}{d\mu}\Big|_P
$$
Does this make sense? If not, IMHO, it might be a good idea to raise some questions on this matter - I could try answering them.
Comment: That makes a lot of sense. While you have explained it properly, you chose not to use the matrix notation. Could you tell me if there's a difference between the [Tangent Vector](https://en.wikipedia.org/wiki/Tangent_vector#Definition), [Directional Derivative](https://en.wikipedia.org/wiki/Directional_derivative), the equation you wrote and the equation user:mathcounterexamples.net wrote (in the other answer)?
Comment: @dictatemetokcus I have added some comments. I think the answer is growing too long. I would suggest raising new questions rather than appending to this one


Lilypond: define MIDI output file name

Question: I am trying to make Lilypond create a MIDI output file whose name corresponds song title, but I didn't succeed so far. Maybe someone can help?
From the Lilypond notation reference (https://lilypond.org/doc/v2.20/Documentation/notation/creating-output-file-metadata):

For each type of output file, only the \header definitions of blocks that define separate files of that type, and blocks higher in the block hierarchy, will be consulted. Therefore, [...] for MIDI files, all headers above or at the \score level are used.

Here is my code:
\music = { \relative c'4 d e f}

\bookpart {
  \header {
    title = "my Title"
  }
  \score {
    \music
    \midi { }
  }
}

I expected to get a midi file named my Title.midi, but instead, I get a file whose name is the name of the lilypond file (so if myLilypondFile.ly, then myLilypondFile.midi).
From the same source:

The title variable sets also the sequence name for MIDI. The midititle variable can be used to set the sequence name independently of the value used for typeset output.

So I tried adding midititle to my existing header:
\header {
    title = "my Title"
    midititle = "my midi Title"
}

but it did not change anything. It seems the midititle variable isn't even known (I use Frescobaldi and it does not syntax highlight that variable).
My lilypond file is version 2.20.0 and I have also installed GNU lilypond 2.20.0.
Comment: Don't put too much stock into whether Frescobaldi recognizes things like "midititle".  The syntax highlighting sometimes lags behind the latest version, and somethings are just missing.
Comment: May I ask how that would help you? For me, getting `myLilypondFile.midi` out of `myLilypondFile.ly` sounds very reasonable (apart from `myLilypondFile` being a very unhelpful file name). I don't even think Lilypond can put things into arbitrarily named files. Btw. "sequence name" is a name stored within the MIDI. Some MIDI players, like timidity, will show it while playing, some (most?) will not.
Comment: @Ramillies My file contains several songs and I want to create midi files for each of them in order to check if I wrote the scores correctly. Standard behaviour is the creation of `myLilypondFile.midi`, `myLilypondFile-1.midi`, `myLilypondFile-2.midi` and so on. But with this, it is hard to find the right file for a certain song.
Comment: @Kjara: Then I would tell you to use `\bookOutputSuffix` (which would change the `-1`, `-2` etc. to something else -- one use could be `mySong-soprano.midi`, `mySong-alto.midi` etc.), but the answer below is more universal.
Answer: You're on the right track for sheet music title and midi file title, but you should use \bookOutputName to control the resulting filename:
\header {
  title = "File title"
  midititle = "midi title"
}
music = \relative c' {
  c1
}
\book {
  \bookOutputName "pdf_file_only"
  \score {
    \new Staff \music
  \layout {}
  }
}
\book {
  \bookOutputName "midi_file_only"
  \score {
    \new Staff \music
  \midi {}
  }
}

Comment: Wow, I knew about `\bookOutputSuffix` but I didn't know (or think) this would exist...

Lilypond: define MIDI output file name


Create link to views page that preselects the filters of an entire vocabulary?

Question: I have a view that filters by different taxonomy terms, using multiple vocabularies. Im using the better exposed filter module.
I need different links to this view page which make different options pre-selected. By copying the url from when 1 term is selected I can easily make a link which works in this way:
my-site/resources?tid%5B%5D=22&keys=
I also need to make a link where all the terms from a vocabulary are selected. The client for this website will be able to add new terms to this vocabulary. If I simply copy the url with all the terms selected then this wont select a new term when its created.
How can I create a link to the view page which preselects all the terms from a vocbulary, that will still select all the terms when new ones are created?
Answer: Based on the URL provided:
<code>function MODULE_NAME_build_taxonomy_views_link($taxonomy_tid) {
  $vocabulary = taxonomy_vocabulary_load($taxonomy_tid);
  if (!$vocabulary) {
    return;
  }
  $term_ids = array();
  foreach (taxonomy_get_tree($taxonomy_tid) as $term) {
    $term_ids['tid'][] = $term->tid;
  }

  return l($vocabulary->name, 'resources', array('query' => $term_ids));
}
</code>


Proof that $\sum_{n=0}^{\infty}(-1)^{n} = \frac{1}{2}$. Is there any error?

Question: So, I proved that:
$$\int f(\ln x)\ dx = x \sum_{n=0}^{\infty}(-1)^{n} f^{(n)}(\ln x) \ \ \ +\ \ C$$
where $f^{(n)}$ is the nth derivative of $f$.
if we let $f(x) = e^{x}$ then $f^{(n)}(x) = e^x$ as well, so:
$$\int e^{\ln x}\ dx = x \sum_{n=0}^{\infty}(-1)^{n} e^{\ln x} \ \ \ +\ \ C$$
giving us:
$$\int x\ dx = x^{2} \sum_{n=0}^{\infty}(-1)^{n} \ \ \ +\ \ C$$
if we differentiate both sides with respect to $x$ we end up with:
$$x=2x \sum_{n=0}^{\infty}(-1)^{n}$$
giving us:
$$\sum_{n=0}^{\infty}(-1)^{n} = \frac{1}{2}$$
Am I doing something wrong or is this valid? Because I've learned that that series is divergent, yet through this method I've proven it to be $\frac{1}{2}$ wich is also its Cesàro sum.
Comment: @Dunkelheit : My dear friend, asking a question is never wrong, if anything does not seem right then you MUST question it, so thank you for making me think, before replying I needed to recheck that was the case, last time I looked up "Cesàro sum" was 1993 :)
Comment: it would be a good idea to write up a formal derivation of the first line and see where it fails in your case
Comment: What you claim to have proved in the first line can't possibly be true if the series on the right-hand side doesn't converge. And that is the case here.
Comment: @Conrad I'll show you the proof
Comment: When you divide by $x$ in the second step, it shouldn't be $\frac{C}{x}$ not only $C$?
Comment: @rlartiga We can let $C = 0$ I think and look at a special case of the first equation I think.
Comment: @rlartiga that can bue fixed quite easily
Comment: why not just plugin -1 in geometric series instead? why is all this sing and dance needed ? not sure why you are bothering with all the above, although I admit it is nice, read more on euler's manipulation instead of running "proof" verfications by internet crowd.
Comment: @Arjang: the geometric series does not converge in $x=-1$.
Comment: @Dunkelheit : there is tag "Cesàro summable" , so yes you are right that it does not converge classically but it converges under the Cesàro summability.
Comment: @Arjang: You're right, didn't noticed it, sorry for that.
Answer: Always keep in mind that a proof that holds for any finite case need not hold in the infinite case. In the context of your proof, the following equality holds for any $n\in\mathbb{N}$:
$$\int_a^xf\circ\log t\,dt=x\sum_{i=0}^n(-1)^if^{(i)}\circ\log x-a\sum_{i=0}^n(-1)^if^{(i)}\circ\log a+(-1)^n\int_a^xf^{(n+1)}\circ\log t\,dt,$$
which you can easily adapt your above proof to show via induction. However, this does not imply that the equality holds as $n\to\infty$, because $\infty$ is not a natural number - induction simply does not work in the infinite case. For your choice of $f=\exp$, we have on the right-hand side:
$$\lim_{n\to\infty}\left[x\sum_{i=0}^n(-1)^i\exp x-a\sum_{i=0}^n(-1)^i\exp a+(-1)^n\int_a^xt\,dt\right]$$
but this limit does not exist for any value of $x$, since the sum $\sum_{i=0}^\infty(-1)^i$ diverges. Therefore, you can't extend this identity to the infinite case without checking that the sum on the right-hand side actually converges - otherwise the equality is meaningless.
However, when that series above does converge and the "remainder term" consisting of the integral on the right goes to zero, you can still use it to get some interesting results - for example, try taking $f:x\mapsto x^n$, and you can find a series expression for the following integral:
$$\int_a^x\log^nt\,dt$$
Answer: Let
$$
g_n(x)=\sum_{k=0}^n(-1)^kxf^{(k)}(\log(x))\tag1
$$
then
$$
\begin{align}
\frac{\mathrm{d}}{\mathrm{d}x}g_n(x)
&=\frac{\mathrm{d}}{\mathrm{d}x}\sum_{k=0}^n(-1)^kxf^{(k)}(\log(x))\tag2\\
&=\sum_{k=0}^n(-1)^kf^{(k)}(\log(x))+\sum_{k=1}^{n+1}(-1)^{k-1}f^{(k)}(\log(x))\tag3\\[6pt]
&=f(\log(x))+(-1)^nf^{(n+1)}(\log(x))\tag4
\end{align}
$$
which gives
$$
g_n(x)=\int f(\log(x))\,\mathrm{d}x+(-1)^n\int f^{(n+1)}(\log(x))\,\mathrm{d}x\tag5
$$
$g_n$ tends to a limit if $f^{(n+1)}$ vanishes uniformly on compact sets. In the example in the question, $f(x)=e^x$, it does not. Instead we get
$$
g_n(x)=\frac{1+(-1)^n}2\,x^2+C_n\tag6
$$
Plugging $(6)$ into $(2)$ and dividing by $x$ gives
$$
1+(-1)^n=2\sum_{k=0}^n(-1)^k\tag7
$$
which is a true statement, but does not lead to the sum tending to $\frac12$.
Answer: By mathematical induction $$\int_a^x f(\ln t)\ dt = \sum_{n=0}^{N}(-1)^{n} [tf^{(n)}(\ln t)]_a^x+(-1)^{N+1}\int_a^x f^{(N+1)}(\ln t) dt$$ is true for any $N\in\mathbb{N}$ and $a\gt0.$
But passing from this finite sum to an infinite series is rather technical. One obvious condition that can make this happen is restrict $f$ to be a polynomial and, then carefully extend the result for power series via Taylor polynomials. This in return will capture functions like $\exp(x)$ in your construction.
Since $\lim_{t\to 0^+} t(\ln (t))^n=0$ for any $n,$ we let $a\to 0^+$ to make things bit simpler. But, we still need to prove the uniform convergence for the infinite series by carefully choosing the domain of $f^{(n)}\circ\ln.$
If it is the case, I guess, after some effort we would be able to use Abel summations to conclude the desire result.


Signifying "all" when pulling data from an array

Question: So I have an array that contains several numbered entries that are all identical, like this:
var levels = new Object;
levels = {
    0:{
        name: "xxx1",
        ratesBR: {
            stone: 1,
            wood: 5,
            copper: 0,
        }
        ratesFS: {
            food: 10,
            water: 10,
            sacrifice: 0,
        }
    }
    1:{
        name:"xxx2",
        ratesBR: {
            stone: 1,
            wood: 5,
            copper: 0,
        }
        ratesFS: {
            food: 10,
            water: 10,
            sacrifice: 0,
        }
    }
}

So my question is this, say I want to check that 'stone' is greater than or equal to 1 in all the "levels" (0,1, etc.) using
if levels.XX.ratesBR.wood >= 1

but in place of XX, I am wondering what I can use to signify "all" I have looked around and the closest I came was the every() function but I don't think that is what I am looking for. I have no idea what the "all" signifier would even be called, so I am turning to Y'all for a direction to go in. Thanks.
Comment: That's not an array.
Answer:
So I have an array...

That's not an array, it's a non-array object. It just has property names "0", "1", etc. (yes, they're strings even though they've been written as numbers).

and the closest I came was the every() function but I don't think that is what I am looking for.

It is, but it's slightly awkward to apply it to a non-array object. We can do so by using Object.keys to get the object's keys, and then using every on that.
In ES5, you'd do it like this:
if (Object.keys(levels).every(function(key) { return levels[key].ratesBR.wood >= 1; })) {
    console.log("All are >= 1");
} else {
    // No, at least one isn't
    console.log("At least one isn't >= 1");
}

Live Example:

var levels = {
  0: {
    name: "xxx1",
    //lifeStage:
    ratesBR: {
      stone: 1,
      wood: 5,
      copper: 0
    },
    ratesFS: {
      food: 10,
      water: 10,
      sacrifice: 0
    }
  },
  1: {
    name: "xxx2",
    //lifeStage:
    ratesBR: {
      stone: 2,
      wood: 0,
      copper: 0
    },
    ratesFS: {
      food: 10,
      water: 10,
      sacrifice: 0
    }
  }
};

if (Object.keys(levels).every(function(key) { return levels[key].ratesBR.wood >= 1; })) {
    console.log("All are >= 1");
} else {
    // No, at least one isn't
    console.log("At least one isn't >= 1");
}

In ES2015+, an arrow function can make it more concise:
if (Object.keys(levels).every(key => levels[key].ratesBR.wood >= 1)) {
    console.log("All are >= 1");
} else {
    // No, at least one isn't
    console.log("At least one isn't >= 1");
}

Live Example:

var levels = {
  0: {
    name: "xxx1",
    //lifeStage:
    ratesBR: {
      stone: 1,
      wood: 5,
      copper: 0
    },
    ratesFS: {
      food: 10,
      water: 10,
      sacrifice: 0
    }
  },
  1: {
    name: "xxx2",
    //lifeStage:
    ratesBR: {
      stone: 2,
      wood: 0,
      copper: 0
    },
    ratesFS: {
      food: 10,
      water: 10,
      sacrifice: 0
    }
  }
};

if (Object.keys(levels).every(key => levels[key].ratesBR.wood >= 1)) {
    console.log("All are >= 1");
} else {
    // No, at least one isn't
    console.log("At least one isn't >= 1");
}

If levels really were an array (which I'd recommend), you'd just use every directly on it:
// IF `levels` WERE AN ARRAY
if (levels.every(entry => entry.ratesBR.wood >= 1)) {
    console.log("All are >= 1");
} else {
    // No, at least one isn't
    console.log("At least one isn't >= 1");
}

Live Example:

var levels = [
  {
    name: "xxx1",
    //lifeStage:
    ratesBR: {
      stone: 1,
      wood: 5,
      copper: 0
    },
    ratesFS: {
      food: 10,
      water: 10,
      sacrifice: 0
    }
  },
  {
    name: "xxx2",
    //lifeStage:
    ratesBR: {
      stone: 2,
      wood: 0,
      copper: 0
    },
    ratesFS: {
      food: 10,
      water: 10,
      sacrifice: 0
    }
  }
];

if (levels.every(entry => entry.ratesBR.wood >= 1)) {
    console.log("All are >= 1");
} else {
    // No, at least one isn't
    console.log("At least one isn't >= 1");
}

And the ES5 version:
// IF `levels` WERE AN ARRAY
if (levels.every(function(entry) { return entry.ratesBR.wood >= 1; })) {
    console.log("All are >= 1");
} else {
    // No, at least one isn't
    console.log("At least one isn't >= 1");
}

Comment: @Akmedrah: That doesn't change the answer. I assumed the variable was declared, and the `= new Object` part of that statement is thrown away, as you overwrite the value in `levels` in the very next statement (with an object created via an object initializer).
Comment: I saw it, and sorry I forgot to add the var levels = new Object.
Answer: You could do something like this:
var levels = {
  0:{
    name: "xxx1",
    //lifeStage:
    ratesBR: {
      stone: 1,
      wood: 5,
      copper: 0
    },
    ratesFS: {
    food: 10,
    water: 10,
    sacrifice: 0
  }
},
1:{
    name: "xxx1",
    //lifeStage:
    ratesBR: {
      stone: 1,
      wood: 5,
      copper: 0
    },
    ratesFS: {
    food: 10,
    water: 10,
    sacrifice: 0
  }
}
}

var array = $.map(levels, function(value, index) {
    return [value];
});
for(var i =0; i < array.length; i++){
  console.log(array[i].ratesBR.stone);
}

Comment: There is no jQuery tag on the question, nor is jQuery used anywhere within it. jQuery answers to non-jQuery questions are not useful.
Comment: Separately: You're creating an array of arrays, but then not using the resulting array correctly; the code would fail with trying to read `ratesBR` of `undefined`.


Difference between the map() module and imap() in the multiprocessing calculation

Question: I have a piece of code with a multiprocessing implementation:
q = range(len(aaa))
w = range(len(aab))
e = range(len(aba))

paramlist = list(itertools.product(q,w,e))

def f(combinations):
     q = combinations[0]
     w = combinations[1]
     e = combinations[2]
# the rest of the function

if __name__ == '__main__':

     pool = mul.Pool(4)
     res_p = pool.map(f, paramlist)

     for _ in tqdm.tqdm(res_p, total=len(paramlist)):
           pass

     pool.close()
     pool.join()

Where 'aaa, aab, aba' are lists with triple values of type:
aaa = [[1,2,3], [3,5,1], ...], etc.

And I wanted to use imap() to be able to follow the calculation progress using module tqdm().
But why does the map() show me the length of the list(res_p) list correctly, but when I change to imap(), the list is empty? Can you track progress using the map() module?
Answer: tqdm doesn't work with map because map is blocking; it waits for all results and then returns them as a list. By the time your loop is executed, the only progress to be made is what happens in that loop—the parallel phase has already been completed.
imap does not block, since it returns just an iterator, i.e. a thing you can ask for the next result, and the next result, and the next result. Only when you do that, by looping over it, the next result is waited for, one after another. The consequence of it being an iterator means that once all results have been consumed (the end of your loop), it is empty. As such, there's nothing left to put in a list. If you wish to keep the results, you could append each in the loop, for example, or change the code to this:
res_p = list(tqdm.tqdm(pool.imap(f, paramlist), total=len(paramlist)))

for res in res_p:
    ... # Do stuff

Comment: Thanks for your help and explanation! :)


Data aparecendo em 1 post só

Question: Olá galera estou com um problema que quando eu faço varias postagens no mesmo dia que seria a mesma data ela só aparece no ultimo post
.
    <article  id="post-<?php the_ID(); ?>" <?php post_class( 'cf' ); ?> role="article">

                             <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>

                          <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>">      <div class="box-index" style=" background-image:url(<?php echo $image[0];?>); ">

                               <a class="index-tro"href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?>

 <?php the_date(); ?>

<?php the_excerpt(); ?>

Comment: Isso aí é wordpress?
Comment: sim isso é wordpress @rray
Answer: Olá, tente usar...
echo get_the_date();

no lugar de
the_date();

Data aparecendo em 1 post só


Ball and urn problem

Question: Let's say there are three types of balls, labeled $A$, $B$, and $C$, in an urn filled with infinite balls. The probability of drawing $A$ is $0.1586$, the probability of drawing $B$ is $0.81859$, and the probability of drawing $C$ is $0.02275$.
If you draw $6$ balls, what's the probability that you drew $3 A$s, $2 B$s, and $1 C$?
I know what the answer is but I don't know how to set up the problem appropriately. It's not just a simple counting problem because the balls have weighted probabilities... Any push in the right direction is appreciated!
Answer: The appropriate probability distribution for this question is the multinomial distribution, which is a generalization of the binomial distribution.  That is to say, let $\boldsymbol X = (A,B,C)$ be a vector-valued random variable that counts the number of balls drawn of each type. Then the parameters are $n = 6$, $p_1 = 0.1586$, $p_2 = 0.81859$, and $p_3 = 1 - p_1 - p_2 = 0.02275$.  Then $$\Pr[\boldsymbol X = (3,2,1)] = \frac{6!}{3!2!1!} p_1^3 p_2^2 p_3^1.$$
Comment: I've never covered the multinomial distribution so by my intuitive answer I was missing the $3!2!1!$ in the denominator. This gives the correct solution, thank you!
Answer: The result of a draw can be represented as a $6$-letter word over the alphabet $\{A,B,C\}$.
Let us first count the number of words over this alphabet that have $3$ $A$'s, $2$ $B$'s, and $1$ $C$.
The location of the $A$'s can be chosen in $\binom{6}{3}$ ways, and for each way the location of the $B$'s can be chosen in $\binom{3}{2}$ ways, for a total of $\binom{6}{3}\binom{3}{2}$.
Any particular such word has probability $p_A^3p_B^2p_C^1$, where $p_A$, $p_B$, and $p_C$ are the probabilities of drawing a ball of type $A$, of type $B$, of type $C$. For given the very large size of the urn, we can assume that the results of successive draws are independent.
Thus the required probability is
$$\binom{6}{3}\binom{3}{2}p_A^3p_B^2p_C^1.$$
Answer: Any sequence of the sort $ABACAB$ has the same probability to occur. So it comes to finding how many distinct words there are having $3$ times an $A$, $2$ times a $B$ and $1$ time a $C$.
You could start with $6$ open spots and then placing the $A$'s. That gives $\binom{6}{3}$ possibilities.
Then place the $B$'s. That gives $\binom{3}{2}$ and finally place $C$ on the single spot that is left.
There are $\binom{6}{3}\times\binom{3}{2}=60$ possibilities so the corresponding probability is $60\times p_A^3p_B^2p_C$

Ball and urn problem


asp conditional include error Microsoft VBScript compilation error '800a0400'

Question: I followed Martha's suggestion here:
if page is default then include if not default then
And I am missing something, as I can't get it to display the slider.
Here is the slider code, and how I am using Martha'e suggestion.
This is the slider (bootstrap carousel) code (to be integrated with Martha's suggestion)

                DFD Fioriere

This is what happens:
If I put the above code inside
<%
Sub DisplaySlider()
slider code
    %>
<%
End Sub
%>

I get this error when loading default.asp

Microsoft VBScript compilation error '800a0400'
Expected statement
/afz_includes/jumbotron.asp, line 3

If I wrap slider code in ' I get same error but line 4
If I wrap slider code in " I get same error (line 3)
I also tried to wrap each line of slider code with ", and chnaged the " of classes and ids to ', but keep getting th error.
Here is what I put on the default.asp, and the other pages

<%
scriptname = Request.ServerVariables("Script_Name")
If InStr(scriptname, "default.asp") > 0 Then
    DisplaySlider
Else
    Response.Write "

"
End If
%>

I am not sure if it was a typo, anyhow I tried to save the slider both as html, and asp, but same error.
Comment: Can you elaborate on `DisplaySlider` code? Is it properly finished with a `End` keyword?
Comment: Looks like your sub procedure is missing `End Sub`.
Comment: Thank you both. Yes the end snip is there (    <%
End Sub
%>)  I just concentrated where slider code is supposed to be according to my understanding of Martha's suggestion. Updated the OP
Answer: It looks like you've put the slider's code inside the ASP code delimiters (the <% and %>), so the compiler is trying to treat it as VBScript, which it obviously isn't.
In ASP classic, you put your server-side VBScript code inside <% %> blocks. HTML code does not go inside those blocks, unless you're Response.Write-ing it.
<%
Sub DisplaySlider()
%>

        ...

<%
End Sub
%>

Comment: Thank you. Yes I thought that is not the way to go, but I tried it after using it the way you are suggesting, in this case the slider does not display, but the spacer div works fine.


$x^2\frac{dy}{dx}+xy+1=0$

Question: Solve the following differential equation by the form of homogeneous equation. Letting $y=vx$
The equation:
$x^2\frac{dy}{dx}+xy+1=0$
I can't separate variables
My solution steps are:
$x^2(v+x \frac{dv}{dx})+x^2v+1=0$
$(v+x \frac{dv}{dx})+v=\frac{-1}{x^2}$
$2v+x \frac{dv}{dx}=\frac{-1}{x^2}$
How to separate variables x and v?
Comment: Your equation is not homogeneous to start with. This method does not lead to a separable equation if the original one is not homogeneous. Your equation is actually linear for $y(x)$, so you can just multiply by the integrating factor.
Comment: You solve a problem by thinking about the problem. Where the problem comes from may or may not be useful information.
Comment: I know that but the book added it under homogeneous questions
Comment: @AnwarIsied Then your book is wrong.
Answer: Instead, let $v = xy$ such that $\frac{dv}{dx} = y + x\frac{dy}{dx}$
$x^2 \frac{dy}{dx} + xy = x\frac{dv}{dx}$ and so $x^2\frac{dy}{dx} + xy + 1 = x\frac{dv}{dx} + 1 = 0$
You can solve $x\frac{dv}{dx} = -1$ by seperating.
Answer: Divide the proposed DE by $x$ in order to obtain
\begin{align*}
x^{2}y' + xy + 1 = 0 & \Longleftrightarrow xy' + y = -\frac{1}{x}\\\\
& \Longleftrightarrow (xy)' = -\frac{1}{x}\\\\
& \Longleftrightarrow xy = -\ln|x| + k\\\\
& \Longleftrightarrow y(x) = -\frac{\ln|x|}{x} + \frac{k}{x}
\end{align*}
and we are done.
Hopefully this helps !

$x^2\frac{dy}{dx}+xy+1=0$


$F\cup G \le V$ if and only if $F \subseteq G$ or $G\subseteq F$

Question: In an exercise I'm asked to prove the following result:

Let $V$ be a vector space and $F,G \le V$. Prove that $F\cup G \le V$ if and only if $F \subseteq G$ or $G\subseteq F$.

I was able to prove that $F \subseteq G \vee G\subseteq F \to F\cup G \le V$ But I'm not being able to prove the opposite.
How can I do so?
Answer: If there are elements $x\in F\setminus G$ and $y\in G\setminus F$ then $x+y$ is a sum of elements in $F\cup G$, and since by assumption this is a subspace we have $x+y\in F\cup G$. So $x+y\in F$ or $x+y\in G$. Let's assume $x+y\in F$. Then, since $F$ is a subspace:
$y=(x+y)-x\in F$
But this in a contradiction, because $y\in G\setminus F$. Similarly, if $x+y\in G$ then:
$x=(x+y)-y\in G$
Which is again a contradiction, because $x\in F\setminus G$.


Mailbox file of mutt suddenly disappeared

Question: I have recently seen that my entire mailbox with mutt has suddenly disappeared. I don't know how to backup, if it is possible ?
I am on Linux Debian 10.
The sent file of all mails sent has not disappeared, that's weird.
Maybe there are traces of this removing into files /var/log/mail* ?
If someone could know what's happened.
Answer: If your lucky, it's an update of default configuration.
To confirm it, list directories in your /var/mail
You should find a directory for a domain, then a directory for your user like:
firstname.lastname@example.com > /var/mail/domain.tld/user/
A mail directory should have at least directories : cur, new, tmp
Each file in thoses directories are a single mail.
Check into your ~/.muttrc (if it exist) to define where your mail are stored.
https://wiki.debian.org/Mutt
like:
set mbox_type=maildir
set mbox="~/mail/inbox/"
set spoolfile="~/mail/inbox/"
set folder="~/mail/"
set record="~/mail/sent/"
set postponed="~/mail/postponed/"

If your mails are into /var/mail/domain.tld/user/ use something like this on your .muttrc file
set mbox_type=maildir
set mbox="/var/mail/domain.tld/user/inbox/"
set spoolfile="/var/mail/domain.tld/user/inbox/"
set folder="/var/mail/domain.tld/user/"
set record="/var/mail/domain.tld/user/sent/"
set postponed="/var/mail/domain.tld/user/postponed/"

You can backup the directory with your mailbox, using borg or other software:
https://github.com/kahun/awesome-sysadmin#backups


Change entity reference field widget based on condition?

Question: I am using Drupal 8. In user registration form, I use an entity reference field to a profile. I wanted to display inline entity reference form widget or entity select widget based on role.
For this, I tried to use hook__field_widget_form_alter(), but it didn't work.
Is there any way to solve this problem?
Answer: For D7, you use hook_field_widget_properties_ENTITY_TYPE_alter but the problem is that in D8 this hook no longer exists.
Took a while to figure out an answer for D8, but here it is.
Since D8 allows you to create Form Display Modes:
1) Add a form mode

2) Select the entity type, User in this case

3) Add name to it

4) In Manage Form Display, click on Custom Display Settings and checkmark it

5) Click on the alternate view mode and change widget

Then in custom module you change the view mode if it has a certain role
/**
 * Implements hook_entity_form_display_alter()
 */
function mymodule_entity_form_display_alter(\Drupal\Core\Entity\Display\EntityFormDisplayInterface &$form_display, array $context) {
  if ($context['entity_type'] == 'user' && $context['bundle'] == 'user') {
    $current_user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    if ($current_user->hasRole('administrator')) {
      // change the display mode
      $id = $context['entity_type'] . '.' . $context['bundle'] . '.alternate';
      $storage = \Drupal::entityTypeManager()
        ->getStorage('entity_form_display');
      $alt_display = $storage->load($id);
      $form_display = $alt_display;
    }
  }
}


Birth-death process invariant distribution

Question: Let $X_n$ be a birth-death process, with birth rates $\lambda_n$ and death rates $\mu_n$ (with $\mu_o=0$ and $\lambda_{-1}=0$). How do you show that the invariant distribution $\pi_i$ is:
$\pi_0=\Big[ 1+ \sum_{k=0}^\infty \frac{\lambda_k\lambda_{k-1}\dots\lambda_0}{\mu_{k+1}\mu_k\dots \mu_1}\Big]^{-1}$
and
$\pi_{n+1}=\frac{\lambda_n}{\mu_{n+1}}\pi_n$?
I used the definition of invariant distribution, and arrived at the formula
$\pi_i=\frac{\pi_{i-1}\lambda_{i-1}+\pi_{i+1}\mu_{i+1}}{\lambda_i+\mu_i}$,
but I have no idea how to use this to prove what I'm being asked to prove.
Answer: With $\dfrac{\pi_{i-1}\lambda_{i-1}+\pi_{i+1}\mu_{i+1}}{\lambda_i+\mu_i}$, replace $\pi_{i-1}$ by  $ \dfrac{\mu_i}{\lambda_{i-1}} \pi_i$ (just a restatement of $\pi_{n+1}=\frac{\lambda_n}{\mu_{n+1}}\pi_n$) and replace $\pi_{i+1}$ by  $ \dfrac{\lambda_i}{\mu_{i+1}}\pi_i$.  So long as you are not dividing by $0$, this clearly gives $\pi_i$.
Then note that if $\pi_{n+1}=\frac{\lambda_n}{\mu_{n+1}}\pi_n$ then you need to set $\pi_0=\Big[ 1+ \sum_{k=0}^\infty \frac{\lambda_k\lambda_{k-1}\dots\lambda_0}{\mu_{k+1}\mu_k\dots \mu_1}\Big]^{-1}$ to get $\sum_{n=0}^\infty \pi_n = 1$.
So the distribution you are asked to show is the invariant distribution is indeed an invariant distribution: it is invariant as it satisfies the formula you found, and it is a probability distribution as it is non-negative and sums to $1$.  Since there is only one invariant distribution in this case,, this must be it.


$e, \varphi$ and $\pi$ in a right angle

Question: \begin{align}
e &= 2.7182\ldots \\
\varphi &= 1.618 \ldots \\
\pi &= 3.1415\ldots \\
\end{align}

\begin{align}
e^2 &= 7.38905\dots \\
\varphi^2 &= 2.61803\ldots \\
\implies e^2 + \varphi^2 &= 10.00708 \ldots \\
&> \pi^2 \\
&= 9.8696 \ldots
\end{align}
$10.00708 - 9.8696 = 0.137485 \Rightarrow 0.1375 \Rightarrow 137.5$deg is the Golden Angle
How come $\pi$ is short by the value of the Golden Angle?
Comment: What you seem to be saying is that $e^2+\varphi^2-\pi^2 \approx \dfrac{0.36}{\varphi^2}$.  Since there is not equality, this does not look that special to me
Comment: Not sure what is your question, but the angle on your figure is not a right angle.
Comment: *10.00708 - 9.8696 = 0.137485>>>> 0.1375 >>>> 137.5deg* : This comparison doesn't make sense since the left hand's unit is the square of your length unit (say, $m^2$) and the right hand's unit is in degrees (or thousands of degrees if I read you well).
Comment: Please use [MathJax](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to format your question nicely
Comment: I figured it was coincidence more than meaning. Just found it to be a strange coincidence and wondered if there is more to it!
Answer: Hunt for near misses for long enough and you will find them.  In this case, the sum is out by more than 1% which seems too much to be interesting.  The coincidental similarity to an angle in degrees is also uninteresting since it depends on the arbitrary choice of 360 degrees in a circle.
Answer: It is not a right triangle in your diagram above precisely because $\pi^2 \neq \varphi^2 + e^2$.
There is the Kepler triangle, which has sides $(1, \varphi, \sqrt{\varphi})$ for which $$1+\varphi = \varphi^2$$

$e, \varphi$ and $\pi$ in a right angle


I can't get the correct current language in node URLs

Question: In D8, I have a website set up with 5 languages, using file path, like so:
 website.com/en/link
 website.com/en-us/link
 website.com/fr-ca/link
 etcetera.

I've made a view of blogs and resources. It includes a filter to current language selected for page and Not Specified-- this is to include articles that are intentionally set to Not Specified, so they show up for ALL languages. ( I don't want to have to turn 1000 blog posts into 4000 duplicates)
Problem is, the view is showing the link to items ONLY in the default language (EN)
Regardless of what language I view the website in.
I'm using a hidden "Link to Content" field within a custom field for each item. I've UNchecked 'use absolute url'.  I'm not sure what else to do. It doesn't make sense to me that it would be ignoring the site's current language.
If it's relevant, the link within the custom field is written like this:
 {{ title }}

I also added in a "Content: Translation language" field, to verify I was looking at the correctly filtered language. the URL uses default language regardless of whether the item's language is specified or not.
Update: I've also ensured the bottom middle column in Views is set like this:
 Rendering Language:Content language selected for page

This did not solve the problem. As a further test, I've also unchecked 'not defined' in my filter. While filtering to only nodes of the current language selected for page, I Still get URLs to the default language.
Also, the view has been translated into all relevant languages. Not sure how to change how the {{ view_node }} renders though. I assume it should be programmically pulling the current language when generating a URL. This {{ view_node }} is where the language is appearing. It seems like it should not be, though. The node alias shouldn't contain the language, I thought.
Comment: In the middle column of views UI go to section `LANGUAGE` and set `Rendering Language:Interface text language selected for page` - this will link to the current language IF that entity exists in that language. Non-translated entities don't own a translated link, they will always point to the original language.
Comment: @Hudri I've changed this setting - but still no luck. Even translated items are still generating the default language link.   Side note - if unspecified nodes will always send a user to the default language, I may need to determine a way to manually generate the urls using positions?
Comment: Have you translated the views page? If you filter for `current language selected for page`, you need a translation of the views page itself too.
Comment: @Hudri - yes. The view is translated, but there's no place to modify. If I expand the custom field in the views translation, it's still just "{{ title }}" which generates the default language. I don't know how to customize that {{view_node}} piece. It's just a token, even within the views translate page. So, I have nothing to translate - assuming I've understood?
Comment: @Hudri oh, wait.. I just caught something in what you said there: 'views page' . this is a views block set into another page. I wonder if I need to translate the block as well. Going to try that now.
Comment: @Hudri translating the view and it's containing block did not solve the problem. I'm finding I may have to copy these into completely new view blocks that show on each language. Doing this, I get the correct language - but it's very inefficient and will be hell to edit in 5 locations every time a change needs to be done
Answer: After narrowing down the issue, I think I've stumbled into an actual existing, known issue: Entity Links fields does not have translation support.
https://www.drupal.org/project/drupal/issues/2877994
I still need to figure out how to apply a patch, but I suspect this is actually a duplicate of the above issue.
Comment: No patch needed, the latest Drupal version is fixed.


Condição "If" não entra na estrutura

Question: Estou tendo um problema com meu código,eu recebo um arquivo xlsx, e faço o procedimento todo correto. mas o arquivo vem com algumas virgulas que precisam ser retiradas, e quando eu faço o if pra verificar se possui a virgula ele não reconhece e não executa minha estrutura condicional, e caso não exista virgula eu não quero que faça nada, alguém pode me ajudar onde estou errando.
def main(bi):
    // Essa tabela possui virgula, mas ele não entra nessa condição abaixo
    if bi['Localizador [Outros, Aéreo, Cruise]'] == ',':
        bi['A'] = bi['Localizador [Outros, Aéreo,Cruise]'].str.split(',').str[0]
        bi['A'].fillna("null", inplace=True)

        def f(bi):
            if bi['A'] == "null":
                val =  bi['Localizador [Outros, Aéreo, Cruise]']
            else:
                    val = bi['A']
            return val
        bi['B'] = bi.apply(f, axis=1)
        bi['Localizador [Outros, Aéreo, Cruise]'] = bi['B']

        del bi['A']
        del bi['B']
    else:
        bi['Localizador [Outros, Aéreo, Cruise]']

Comment: Você consegue disponibilizar uma amostra dos seus dados, e adaptar a pergunta para que ela tenha um exemplo [minimo, completo e verificável](https://pt.stackoverflow.com/help/minimal-reproducible-example) do problema?
Comment: Poderia exemplificar uma parte desse arquivo xlsx ?
Comment: é um arquivo xml comum, que eu transformo em uma string e depois em um DF.
Essa coluna vem alguns numero(Ex: 123456,123456,123456) quando eu seleciono o split sem o if ele roda normalmente e a coluna passa a ficar assim (Ex : '123456'), mas quando eu faço o if verificando se possui virgula na coluna, ele não entra no split mesmo contendo virgula
Comment: Você teria que verificar então se a string possui uma vírgula, e do jeito que está, vc está conferindo se a string(conteúdo da coluna) é somente uma string
Comment: Acho que você quis dizer algo desse tipo ( if "," in bi['Localizador [Outros, Aéreo, Cruise]']: ) mas também não funcionou
Answer: Se o valor recebido do bi['Localizador [Outros, Aéreo, Cruise]'] for uma string, então ele não entrará no if porque você definiu para ele a condição de se a string for igual a ",". O correto a se fazer é colocar a condição desta forma:
if "," in bi['Localizador [Outros, Aéreo, Cruise]']:
    ...

Da forma que você estava fazendo, você conseguiria entrar na condicional somente se a string fosse somente um ",".
Comment: Entendi oque quis dizer, mas não funcionou ele continua sem entrar no if, como se não existisse a virgula. o meu arquivo quando estou fazendo essa condição não e String ele é um DataFrame
Comment: Putz. Dessa forma não vou poder ajudar então porque eu não trabalho com pandas, desculpa.
Answer: Você está fazendo a verificação errada. Na 3° linha você esta dizendo:
if bi['Localizador [Outros, Aéreo, Cruise]'] == ',':

É outras palavras você está verificando de essa variável é igual a uma virgula.
A verificação correta é você verificar se a variavel contém uma virgula:
if "," in bi['Localizador [Outros, Aéreo, Cruise]']:

Comment: Isso foi o mesmo exemplo que o Jean comentou logo acima, obrigado mas não funcionou assim.
Answer: Consegui achar uma forma dele verificar antes se existe essa virgula no meu DF é um pouco de Gambiarra mas funcionou assim, vou publicar o código usado.
\\\ Crirei uma nova variavel para checar se existe "," na minha coluna com o (str.contains) ele retonar a quantidade de linhas que existem com virgulas
bi_check = bi[bi['Localizador [Outros, Aéreo, Cruise]'].str.contains(",") == True]

\\\ Aqui ele verifica quantas linhas com virgula possui no arquivo.
tam = len(bi_check)

\\\ se houver virgula o arquivo sera Maior que 0 então ele vai entrar no meu If e fazer o split
if tam > 0:
     bi['A'] = bi['Localizador [Outros, Aéreo, Cruise]'].str.split(',').str[0]
     bi['A'].fillna("null", inplace=True)
     def f(bi):
        if bi['A'] == "null":
            val =  bi['Localizador [Outros, Aéreo, Cruise]']
        else:
            val = bi['A']
        return val
     bi['B'] = bi.apply(f, axis=1)
     bi['Localizador [Outros, Aéreo, Cruise]'] = bi['B']
     del bi['A']
     del bi['B']
\\\ caso contrario ele vai me retornar a tabela normal.
else:
 bi = bi

Condição "If" não entra na estrutura


How to control how many times a function is run in a period of time?

Question: I want to do this because if I don't itemstack.damageItem(1, player) gets called too often when clicking rapidly and the durability of this tool runs out too quickly.
@Override
public boolean itemInteractionForEntity(ItemStack itemstack, EntityPlayer player, EntityLivingBase target) {
         if (!target.worldObj.isRemote) {
        target.motionY = 0.25;

        float xDis = (float) (target.posX - player.posX);
        float zDis = (float) (target.posZ - player.posZ);
        float tangent = zDis / xDis;
        float angle = (float) Math.atan(tangent);

        float length = (float) 1;

        float xProj = (float) (length*Math.cos(angle)*Math.signum(xDis));
        float zProj = (float) (length*Math.sin(angle)*Math.signum(xDis));

        target.motionX = xProj;
        target.motionZ = zProj;

        itemstack.damageItem(1, player);
    }

    return false;
}

If I use Thread.sleep(200); it wants me to add a throw which in the end would mean I would have to change the base code or I would have to surround it with a try/catch (What does this do).
Comment: Then pausing the game is not what you want to do, you want to set a timestamp and check it against the `System.currentMills` and throw away any events that come in too fast/soon.
Comment: Is there a limitation to using Thread.sleep() in this section?
Comment: **Why** do you think you want to pause the game in this method?
Comment: You cannot sleep / wait since that would just freeze the game while this code blocks.
Comment: @zapl what could I do insted?
Comment: You don't have to add a throws.  You can wrap the Thread.sleep() with a try catch block and do nothing if an exception occurs.
Comment: @Jarrod Roberson I want to do this because if I don't the game tends to double click instead of just once so the durability on the tool runs out too quick.
Answer: What you want to do is use is Rate Limiting
Here is an thread safe example implementation that has a function that part of its logic is rate limited using only JDK 1.7 Standard classes ( JSR305 annotations don't count against this as they should be in every project no matter what size!).
I show this approach to show that a simple solution can be had without additional dependencies. But using a prebuilt/pretested library is a much better approach.
Guava and Guice are standard dependencies in pretty much all my projects so see below
Relevant code excerpt from complete example Q21866253.java
@Override
public void functionToBeRateLimited(@Nonnull final String caller)
{
    // do some stuff every time here
    super.timesCalled.get(caller).incrementAndGet();

    // do some stuff only after a certain time has elapsed since the last time it was done
    if (shouldRun(caller))
    {
        // Your itemstack.damageItem(1, player); code would go here!
        System.out.println(String.format("%s Called Rate Limited Logic every %d ms", caller, DELTA));
    }
}

private Boolean shouldRun(@Nonnull final String caller)
{
    return currentTimeMillis() - LASTED_CALLED_BY_AT.get(caller).get() >= DELTA;
}

Google Guava RateLimiter
If you need more sophistication and features or you need to Rate Limit a fair number of functions, I would just go ahead and use this.
This is more heavy weight because it uses Threads to keep from blocking the calling thread, but it is much more feature rich and flexible.
Both approaches have their place and time.
Google Guava RateLimiter.java JavaDoc
Self Contained Complete Test Harness coded with multiple threads
The following Gist has a fully self contained ready to run test harness Q21866253.java of course you need the dependencies.
You could remove the JSR305 annotations, but you shouldn't really do that.
This includes a bonus Guava RateLimiter based implementation as well!
Answer: This will stop the logic from being run more than once in a second:
private static Boolean shouldRun = true;

@Override
public boolean itemInteractionForEntity(ItemStack itemstack, EntityPlayer player, EntityLivingBase target) {
  if (shouldRun) {
    if (!target.worldObj.isRemote) {
        target.motionY = 0.25;

        float xDis = (float) (target.posX - player.posX);
        float zDis = (float) (target.posZ - player.posZ);
        float tangent = zDis / xDis;
        float angle = (float) Math.atan(tangent);

        float length = (float) 1;

        float xProj = (float) (length*Math.cos(angle)*Math.signum(xDis));
        float zProj = (float) (length*Math.sin(angle)*Math.signum(xDis));

        target.motionX = xProj;
        target.motionZ = zProj;

        itemstack.damageItem(1, player);
    }

    shouldRun = false;

    new java.util.Timer().schedule(
        new java.util.TimerTask() {
            @Override
            public void run() {
              shouldRun = true;
            }
        },
       1000
    );
  }
}

If a second is too long, just change that 1000 there to 500 or something less.
Comment: or just store current time + 1000 as next allowed time, creating a thread is overkill.


Spring Security custom authentication filter using Java Config

Question: I'm trying to configure Spring Security using Java config in a basic web application to authenticate against an external web service using an encrypted token provided in a URL request parameter.
I would like (I think) to have a security filter that intercepts requests from the Login Portal (they all go to /authenticate), the filter will use an AuthenticationProvider to process the bussiness logic of the authentication process.
Login Portal --> Redirect '\authenticate' (+ Token) --> Authenticate Token back to Login Portal (WS) --> If success get roles and setup user.
I have created a filter..
<code>@Component
public final class OEWebTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
        if (request instanceof HttpServletRequest) {
             OEToken token = extractToken(request);
             // dump token into security context (for authentication-provider to pick up)
             SecurityContextHolder.getContext().setAuthentication(token);
        }
    }
    chain.doFilter(request, response);
}
</code>
An AuthenticationProvider...
<code>@Component
public final class OEWebTokenAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private WebTokenService webTokenService;

    @Override
    public boolean supports(final Class<?> authentication) {
        return OEWebToken.class.isAssignableFrom(authentication);
    }

    @Override
    public Authentication authenticate(final Authentication authentication) {
         if (!(authentication instanceof OEWebToken)) {
             throw new AuthenticationServiceException("expecting a OEWebToken, got " + authentication);
        }

        try {
            // validate token locally
            OEWebToken token = (OEWebToken) authentication;
            checkAccessToken(token);

            // validate token remotely
            webTokenService.validateToken(token);

            // obtain user info from the token
            User userFromToken = webTokenService.obtainUserInfo(token);

            // obtain the user from the db
            User userFromDB = userDao.findByUserName(userFromToken.getUsername());

            // validate the user status
            checkUserStatus(userFromDB);

            // update ncss db with values from OE
            updateUserInDb(userFromToken, userFromDB);

            // determine access rights
            List<GrantedAuthority> roles = determineRoles(userFromDB);

            // put account into security context (for controllers to use)
            return new AuthenticatedAccount(userFromDB, roles);
        } catch (AuthenticationException e) {
            throw e;
        } catch (Exception e) {
             // stop non-AuthenticationExceptions. otherwise full stacktraces returned to the requester
             throw new AuthenticationServiceException("Internal error occurred");
        }
    }
</code>
And my Spring Security Config
<code>@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    OESettings oeSettings;

    @Bean(name="oeAuthenticationService")
    public AuthenticationService oeAuthenticationService() throws AuthenticationServiceException {
        return new AuthenticationServiceImpl(new OEAuthenticationServiceImpl(), oeSettings.getAuthenticateUrl(), oeSettings.getApplicationKey());
    }

    @Autowired
    private OEWebTokenFilter tokenFilter;

    @Autowired
    private OEWebTokenAuthenticationProvider tokenAuthenticationProvider;

    @Autowired
    private OEWebTokenEntryPoint tokenEntryPoint;

    @Bean(name="authenticationManager")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth)  throws Exception {
        auth.authenticationProvider(tokenAuthenticationProvider);
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean () {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(tokenFilter);
        registrationBean.setEnabled(false);
        return registrationBean;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/authenticate**").permitAll()
            .antMatchers("/resources/**").hasAuthority("ROLE_USER")
            .antMatchers("/home**").hasAuthority("ROLE_USER")
            .antMatchers("/personSearch**").hasAuthority("ROLE_ADMIN")
            // Spring Boot actuator endpoints
            .antMatchers("/autoconfig**").hasAuthority("ROLE_ADMIN")
            .antMatchers("/beans**").hasAuthority("ROLE_ADMIN")
            .antMatchers("/configprops**").hasAuthority("ROLE_ADMIN")
            .antMatchers("/dump**").hasAuthority("ROLE_ADMIN")
            .antMatchers("/env**").hasAuthority("ROLE_ADMIN")
            .antMatchers("/health**").hasAuthority("ROLE_ADMIN")
            .antMatchers("/info**").hasAuthority("ROLE_ADMIN")
            .antMatchers("/mappings**").hasAuthority("ROLE_ADMIN")
            .antMatchers("/metrics**").hasAuthority("ROLE_ADMIN")
            .antMatchers("/trace**").hasAuthority("ROLE_ADMIN")
            .and()
                .addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class)
                .authenticationProvider(tokenAuthenticationProvider)
                .antMatcher("/authenticate/**")
                .exceptionHandling().authenticationEntryPoint(tokenEntryPoint)
            .and()
                .logout().logoutSuccessUrl(oeSettings.getUrl());
    }
}
</code>
My problem is the configuration of the filter in my SpringConfig class. I want the filter to only come into effect when the request is for the /authenticate URL, I've added .antMatcher("/authenticate/**") to the filter configuration.
<code>.and()
                .addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class)
                .authenticationProvider(tokenAuthenticationProvider)
                .antMatcher("/authenticate/**")
                .exceptionHandling().authenticationEntryPoint(tokenEntryPoint)
</code>
When I have this line in all other URLs are no longer secured, I can manually navigate to /home without authenticating, remove the line and /home is authenticated.
Should I be declaring a filter that is only applicable to a specific URL?
How can I implement this whilst maintaining the security of other URLs?
Answer: I've resolved my issue by performing a check on the authentication status in the filter before involking the authentication provider....
Config
<code>.and()
    .addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class)
    .authenticationProvider(tokenAuthenticationProvider)
    .exceptionHandling().authenticationEntryPoint(tokenEntryPoint)
</code>
Filter
<code>@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    logger.debug(this + "received authentication request from " + request.getRemoteHost() + " to " + request.getLocalName());

    if (request instanceof HttpServletRequest) {
        if (isAuthenticationRequired()) {
            // extract token from header
            OEWebToken token = extractToken(request);

            // dump token into security context (for authentication-provider to pick up)
            SecurityContextHolder.getContext().setAuthentication(token);
        } else {
            logger.debug("session already contained valid Authentication - not checking again");
        }
    }

    chain.doFilter(request, response);
}

    private boolean isAuthenticationRequired() {
    // apparently filters have to check this themselves.  So make sure they have a proper AuthenticatedAccount in their session.
    Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
    if ((existingAuth == null) || !existingAuth.isAuthenticated()) {
        return true;
    }

    if (!(existingAuth instanceof AuthenticatedAccount)) {
        return true;
    }

    // current session already authenticated
    return false;
}
</code>
Comment: Can You post the code of those classess: `OEWebToken`, `AuthenticatedAccount` and `extractToken(request)` method implementation? I would help me a lot with my rest service. Thanks in advance.
Comment: I wans't able to make this work. [this baeldung blog post](https://www.baeldung.com/spring-security-multiple-entry-points) helped me to solve my similar situation


Free/Cheap Exchange backup option?

Question: I'm working with a nonprofit on implementing some IT solutions for them. They are running an SBS 2011 with Exchange. I'm trying to figure out a way to do mailbox level backups for them.
I am aware of the ability to use Export-PST from a 32 bit computer with the Exchange tools, but we don't have any 32 bit computers! They're all running 64 bit Windows 7.
By the way, the reason I'd like to do mailbox level backups is so that I can rsync them off site for redundancy.
Any suggestions?
Thanks kindly. :-)
Answer: The built in 'Windows Server Backup' utility can backup Exchange - take a look at this guide.
Comment: Thanks for the suggestion Chopper3, we are currently using the Windows Server Backup for on site backup. However, I am hoping to do a mailbox level backup (hopefully to PST or similar files) that I can rsync off site.
Answer: Keep it simple stupid.
Microsoft's DPM tool does the trick.  Allows for Exchange backups and per-mailbox recovery.  You can buy either a fully loaded box to take the backups or get a DPM license as part of the Action Pack.
Lastly, there are several methods to backup to a virtual tape library that you can then store in another location or even upload to Amazon or Azure.
Comment: Dunno, it was pretty much plug it in and configure when we bought one from Dell.  The off-site stuff is a bit more work, but when you get an all-in-one box its pretty simple yes.
Comment: Good answer, but I don't think that a fully blown DPM backup recovery environment classifies as "simple stupid", does it?
Comment: Is it cheap though?
Comment: An Action Pack License is $300 or so, minimum hardware is under $2k.  We purchased our box from Dell with discounts for $1500. Of course it goes above and beyond the Exchange backup question as it can do all Windows, File Server and SQL backups as well. So in my opinion yes it is cheap for what you get.
Comment: I see where you're coming from in terms of the value for money, but considering the original question is talking about a nonprofit organisation I wonder if they would be prepared to spend even that sort of money. +1 from me though, I think it's a good solution.
Comment: I like your idea, but unfortunately all data must be kept in Canada per privacy regulations with this nonprofit. So no joy on backing up to Amazon or Azure. :-(
Comment: OK, so just backup to tape and store it somewhere. Or like a said, a virtual tape drive (hard drive instead) and store the drive somewhere for off-site backups.
Answer: Not a terribly elegant solution, but if you set your clients to use Cached Exchange Mode, you could back up the .OST file (i.e. the offline copy of each user's mailbox) from each machine. This assumes that all of the Windows 7 clients are connected to the network all the time and you may run into problems if the OST file is locked, but it's food for thought anyway.
Comment: I thought that OST's weren't portable. i.e. they were tied to that account on that computer?
Comment: To restore an OST a bodge that often works is to login on a client machine as the user to be restored then open outlook and let it start syncing email, then turn it off and move the hd to another machine, replace the freshly generated OST with your backup, then return the HD to the original machine and boot without network cable and I've found I can normally access the OST in outlook in order to move data to PST's. Backup the backup OST before trying this though.
Comment: @MarkHenderson It's not pretty but you can get into them, but only if you store a complete offline cache.  You have the option not to.
Comment: I thought they were basically PST files in disguise - or can at least be converted to something that can be opened like a PST file.
Answer: You could cerainly write some scripts to do full mailbox exports to pst files. This wouldn't be a very elegant way to do it, but it would be possible.
Export-Mailbox -Identity email@example.com –PSTFolderPath C:\Temp\joe.pst
Comment: Unfortunately, this command must be ran from a 32Bit PC. As stated in the initial question, there are no 32 Bit PCs to do this from. :-(
Comment: You could from XP mode.

Free/Cheap Exchange backup option?


Trouble with looping in VBA (access) to put items on a form and position them correctly

Question: I've been trying to make a form with 68 items while positioning all the items on a form via a loop, but this loop isn't working :(  Can someone please help me get this to work? I've tried looking everywhere but can't see what to do :/
<code>  Dim Items(67) As String
  For x = 0 To 67
    Items(x) = "Ctl" & x
  Next

  #It goes from 1 here as I manually set up 1 otherwise (x - 1) wont work.
  For x = 1 To 67
    Form_Home.Items(x).Top = 0
    Form_Home.Items(x).Left = (Form_MainScreen.Items(x - 1).Left) + (Form_MainScreen.Items(x - 1).Width)
    Form_Home.Items(x).Height = 225
    Form_Home.Items(x).Width = 500
  Next
</code>
Thank you everyone :)
Comment: Why do you think you need to do this?
Answer: What do you mean with Form_Home.Items? if you already have controls added to your forms, probably there is a Controls collection, so you can iterate trough it and set its properties, assuming each control has a name of the form Ctl0, Ctl1, Ctl2... then you can proceed as follow:
<code>Dim ct_name as String
Dim ct_name_before as String
For x = 1 To 67
   ct_name_before = "Ctl" & CStr(Cint(x-1))
   ct_name = "Ctl" & CStr(x)
   Form_Home.Controls(ct_name).Top = 0
   Form_Home.Controls(ct_name).Left = (Form_MainScreen.Items(ct_name_before).Left) + _
                                      (Form_MainScreen.Items(ct_name_before).Width)
   Form_Home.Controls(ct_name).Height = 225
Next
</code>
Some version of VBA allow you to create array of controls sharing all the same name and having different index, then you can iterate through the array to get each control.


How to add css files based on breakpoint in library?

Question: We have the following mytheme.breakpoints.yml file and a simple library mylibrary that is added through our mytheme. Within the mylibrary there are two libraries, one that is optimized for desktop small and another for mobile breakpoints.
How would I add the mobile css file only for when the browser's breakpoint is less than 756px, but load desktop small breakpoint when browser's breakpoint is greater than 756px?
mytheme.breakpoints.yml
mytheme.mobile
  label: mobile
  mediaQuery: 'all and (max-width: 756px)'
  weight: 1
  multipliers:
    - 1x
mytheme.desktopSmall
  label: desktop small
  mediaQuery: 'all and (min-width: 756px)'
  weight: 1
  multipliers:
    - 1x

mytheme.libraries.yml
mylibrary:
  version: 1.0
  css:
    theme:
      css/some/path/desktop-small.min.css: { /* load only for min width > 756px*/ }
      css/some/path/mobile.min.css: { /* load only for max width < 756px*/ }

Adding Use Theme Breakpoints as Media Queries for Theme CSS Libraries for reference.
Comment: Screen size detection occurs at the browser level after loading the assets. The best approach is to add the different rules in CSS media queries
Comment: @IsmailCherri Yes, we do follow that approach where we use media queries. However,  using that approach we found that the aggregated CSS files included all the media queries even when they were not needed.
Comment: Please refer to this https://www.drupal.org/docs/8/theming/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme#libraries-options-details
Answer: This is the solution I found.
mytheme.libraries.yml
mylibrary:
  version: 1.0
  css:
    theme:
      css/some/path/desktop-small.min.css: { media: "all and (min-width: 756px)" }
      css/some/path/mobile.min.css: { media: "all and (max-width: 755px)" }

Comment: Did I miss anything? I have create a global-styling: css and there I have added

      css/style-tab.css: { media: all and (min-width: 768px) and (max-width: 1024px)}
      css/style-mob.css: { media: all and (max-width: 767px)}
But still able to see both the files getting loaded at both the resolution


What is the value of the integral $\int_0^{\frac{\pi}{2}} (1+\csc(x))^{k+\frac{1}{2}} \, \,dx$?

Question: When I was messing around with some integrals I got the result that
$$\sum_{k=0}^\infty \frac{(-1)^k}{2k+1} \int_0^{\frac{\pi}{2}} (1+\csc(x))^{k+\frac{1}{2}} \, \,dx = \frac{\pi^2}{6}$$
Now I would like to solve the integral, but I don't really have any idea (I wonder whether it's possible at all?). I tried to change $1+\csc(x)$ in terms of sines and cosines (using this) so that one gets
$$\int_0^{\frac{\pi}{2}} (1+\csc(x))^{k+\frac{1}{2}} \, \,dx = \int_0^{\frac{\pi}{2}} \left(\frac{\cos^2(x)}{\sin(x)(1-\sin(x))}\right)^{k+\frac{1}{2}} \, \,dx$$
...but I can't see how this would lead anywhere.
Comment: Just out of curiosity : how did you get the nice $\frac {\pi^2}6$ ?
Comment: @ClaudeLeibovici I like messing around with integrals that have a known value (["Integral milking"](https://math.stackexchange.com/questions/2821112/integral-milking)), and so I used [this](https://math.stackexchange.com/questions/2251046/how-to-show-the-following-integral-int-0-frac-pi2-cot-1-sqrt1-csc) result and used the taylor series for $\cot^{-1}(x)$. I might have done some error tho...
Comment: $\large\int$ diverges for $\large k = 1,2,3,\ldots$.
Answer: I think that there is a problem around $x=0$ except for $k=0$. Using Taylor series and bionmial expansion
$$(1+\csc(x))^{k+\frac{1}{2}}=\frac 1 {x^k}\left(\frac{1}{\sqrt{x}}+\left(k+\frac{1}{2}\right)
   \sqrt{x}+O\left(x^{3/2}\right)\right) $$
Answer: Since $\sum_{k\ge0}\frac{(-1)^kz^{2k+1}}{2k+1}=\arctan z$, your series is $\int_0^{\pi/2}\arctan\sqrt{1+\csc x}dx$. This is $\infty$ as @ClaudeLeibovici noted, because for small $x$ the integrand is $\sim x^{-1/2}$. It's more interesting if we delete the $k=0$ case, giving $\int_0^{\pi/2}(\arctan\sqrt{1+\csc x}-\sqrt{1+\csc x})dx$, which WA can only numerically evaluate.
Comment: Your WA link provides a numerical computation but no closed form.  However, your WA link is (apparently) to a definite rather than indefinite integral.  How do you know, based on the results given by your WA link, that there is no closed form answer to the corresponding indefinite integral?
Comment: @user2661923 [Good question](https://www.wolframalpha.com/input/?i=integrate+arctan%28sqrt%281%2Bcsc+x%29%29-sqrt%281%2Bcsc+x%29).