Interval of confidence (for several tests)

Question: Assume I am measuring the glycemic index with a blood glucose meter and its results fall within a $20\%$ range of real lab results.
Example if the real blood glucose (BC) is $100$, the meter can return a value $80 \leq x \leq 120$.
Given several tests (n), I would like to know how can I statistically define my interval of confidence for the actual blood glucose (BC), knowing that each result falls in an interval of $[-20\%, +20\%]$ of the real BC.
A naive approach would create a system on inequalities, but I want to approach this problem from a more rigorous statistic standpoint.
Comment: Are these $n$ tests from the same person (i.e. the same assumed underlying true BC)?
Comment: @COOLSerdash yes, these n tests are from the same person and taken in a short amount of time - hence we can assume the true BC stays constant.
Comment: Great, then the answer of @BruceET is correct, in my view.
Answer: Rather than trying to describe variability of individual meter measurements
as being the meter reading $\pm 20$ or $\pm 20\%,$ it might be better to make a confidence interval based on your $n$ measurements.
If $n$ is small, you might say the the standard deviation of
measurements is $\sigma = 10.$ That amounts to saying that
each individual true glucose value is within $\pm 20$ of the given meter reading 95% of the time. Then using statistical principles, you can get
somewhat shorter intervals based on the average of $n$ measurements.
One important statistical principle here is that averages are less variable than individual values:

For example, suppose $n = 6$ meter readings on the same subject average $\bar X = 103.2.$ In that case, assuming a normal distribution, a 95%
confidence interval would be of the form $\bar X \pm 1.96\sigma/\sqrt{n}.$ For the numbers assumed above, the confidence interval
would be $(95.2,\, 111.2).$
If $n$ is larger, you might use the sample variance of the
actual meter measurements to estimate $\sigma$ (instead of your rule of $\pm 20$ for individual measurements). For example, here are $n = 15$
hypothetical measurements for which the sample mean is
$\bar X = 99.54$ and the sample standard deviation
$S = 7.07.$
<code> 113.8 105.0 104.6  98.1  97.3  96.2 107.1  94.5
  95.2 100.4  99.5 107.8  90.7  96.1  86.8
</code>
A 95% confidence interval is of the form $\bar X \pm t^*S/\sqrt{n}.$ This is known as a t confidence interval because it is based on Student's t distribution. In this case with $n = 15$ meter readings,
$t^* = 2.14$ cuts probability $0.025$ from the upper tail of Student's t distribution with $n-1 = 14$ degrees of freedom.
Computation leads to the interval $(95.6, 103.4).$

Notes: (1) Formulas for sample mean and variance:
$$\bar X = (X_1 + X_2 + \cdots + X_n)/n = \frac 1 n \sum_i X_i.$$
And
$$S = \sqrt{\frac{1}{n-1}\sum_i (X_i - \bar X)^2}.$$ You can
use a statistical calculator or statistical software to compute $\bar X$ and $S.$
(2) You can read about t confidence intervals in an elementary statistics textbook or in Wikipedia under Confidence Intervals.
Comment: (+1) The problem is that the range changes according to the real BC: For a real BC of 120, the $\pm$20% range is not $\pm$20 anymore, but $\pm$24 (from 96 to 144). As we don't know the real BC, assuming a standard deviation of 10 is assuming the real BC is 100, if I'm not mistaken. For a real BC of 120, the corresponding standard deviation would be 12.25.
Comment: Got that. But whatever the the $\pm 20\%$ turns out to be, taking the average of several will give a shorter confidence interval.
Comment: Are you talking about repeated measurements of the same underlying true BC, as in repeated measurements of the same person? If yes, your approach works fine.
Comment: The problem is indeed that I do not know what's the real BC, therefore I don't know the standard deviation to use for computing the interval of confidence from a normal distribution.  How do I get the standard deviation when I have, let's say, n=6?
Comment: Not sure exactly what you're asking. If you can guess the half width of the CI for normal data that's about $2\sigma/\sqrt{n}.$ If you know $n,$ you might get a good guess at $\sigma.$


Use angular-oauth2-oidc and "silent refresh" without white listing silent-refresh.html

Question: I'm trying to use the angular-oauth2-oidc Silent Refresh implementation in combination with the implicit flow configured in an IdentityServer4 server. I've got a proof of concept working inside an ng new ng-and-ids4 --minimal application with this component:
import { Component } from '@angular/core';
import { AuthConfig, OAuthService, JwksValidationHandler, OAuthErrorEvent } from 'angular-oauth2-oidc';

@Component({
  selector: 'app-root',
  template: `
Welcome!

      <button (click)='login()'>login</button>
      <button (click)='logout()'>logout</button>
      <button (click)='refresh()'>refresh</button>

Your Claims:

{{claims | json}}

Your access token:

{{accessToken}}
`,
  styles: []
})
export class AppComponent {
  constructor(public oauthService: OAuthService) {
    this.oauthService.configure({
      issuer: 'http://localhost:5000',
      redirectUri: window.location.origin + '/',
      silentRefreshRedirectUri: window.location.origin + '/silent-refresh.html',
      clientId: 'my-spa',
      scope: 'openid profile',
      silentRefreshTimeout: 5000, // For faster testing
      sessionChecksEnabled: true,
    });

    this.oauthService.tokenValidationHandler = new JwksValidationHandler();

    this.oauthService.loadDiscoveryDocumentAndLogin();
    this.oauthService.setupAutomaticSilentRefresh();
    this.oauthService.events.subscribe(e => {
      if (e instanceof OAuthErrorEvent) { console.error(e); }
      else { console.warn(e) }
    });
  }

  public get claims() { return this.oauthService.getIdentityClaims(); }
  public get accessToken() { return this.oauthService.getAccessToken(); }

  login() { this.oauthService.initImplicitFlow(); }
  logout() { this.oauthService.logOut(); }
  refresh() { this.oauthService.silentRefresh(); }
}

On the IDServer4 side I'm configuring my client like this:
new Client
{
    ClientId = "my-spa",
    AllowedGrantTypes = GrantTypes.Implicit,
    AllowAccessTokensViaBrowser = true,
    AccessTokenLifetime = 30, // Seconds (for testing purposes)
    RedirectUris = { "http://localhost:4200/", "http://localhost:4200/silent-refresh.html" },
    PostLogoutRedirectUris = { "http://localhost:4200/" },
    AllowedCorsOrigins = { "http://localhost:4200" },
    AllowedScopes =
    {
        IdentityServerConstants.StandardScopes.OpenId,
        IdentityServerConstants.StandardScopes.Profile,
    }
}

As you can see, on the server I've whitelisted "http://localhost:4200/silent-refresh.html" in the Client's RedirectUris property.
My question is whether you can configure angular-oauth2-oidc in a way that it doesn't require me to whitelist the silent-refresh.html page?
The reason I ask is because I want to use this Silent Refresh approach also in situations where it might not be so easy to change the IdentityServer side. Also, looking at Damien Bod's example of Silent Refresh in an Angular application I feel it should somehow be possible, because there such a whitelisting is not mentioned.
PS. If I don't include the extra option for the RedirectUris, then I get Invalid redirect_uri: http://localhost:4200/silent-refresh.html on the server (logs) and a silent_refresh_timeout OAuthErrorEvent in the client side library.
Comment: @RyanBuening Nope. I'm still curious about an answer (a) because the other library seems to be able to do it and (b) because I might end up in a similar scenario in the future (regardless of m3n7alsnak3 being right that this is in fact a -possibly political- problem) . But in my current project it turned out to be easier to get the white list changed than to carry on solving this on the front-end.
Comment: @RyanBuening After playing some more with the library I do think it should be possible, because the iframe html doesn't do much, and I suppose you could also hack that into your app's index.html. But I haven't tried it.
Comment: ...and now you're the most active member of this library's community :-)  @Jeroen
Comment: If you remove it from the Client RedirectUri's you get an "unaothorized client" error?
Comment: @m3n7alsnak3 No, I get `Invalid redirect_uri: http://localhost:4200/silent-refresh.html` then on the server (logs) and a `silent_refresh_timeout` `OAuthErrorEvent` in the client side library.
Comment: Got it. Honestly I think that Damienbod is using something on top of `angular-oauth2-oidc` and not the OOTB silent refresh (check his `export class OidcSecuritySilentRenew` class). I guess that you can use the default url (http://localhost:4200 in your case) as a silent renew redirect url, and implement some logic on the entry point of your app, but for me it is not the clearest approach. Why are you saying that you won't be able to make changes on IDS side? How are you going to whitelist the default URL at this point?
Comment: @m3n7alsnak3 On my current project I own the IDServer codebase and have now made the necessary changes. On another project though I would like this same aapeoach, but there a change request to the IDServer might take weeks, if it even gets through the politics. That's why I asked.
Comment: If adding a new client to the identity server requires a change request (which for me means change in the code base), then you have far bigger problem than the silent redirect url
Comment: @Jeroen did you ever solve this? I'm having the same issue.
Answer: After working some more with the library, I think the answer is that you can't easily do it.
If you have to do it, you'd need to tweak the index.html that serves the Angular app so that it bootstraps differently. Basically, the silent refresh would load that file instead of the silent-refresh.html file, so the index will have to have 2 moduses: one for the regular app loading, and another one that effectively does this:
parent.postMessage(location.hash, location.origin);

Because that's all the silent-refresh.html does. This can prove a bit difficult though, because it would require hooking into the generation of index.html when the CLI creates a production build.
So even though it's technically possible, it's not very pragmatic to do so.


GLMNET in R: Difference between DFMAX and PMAX

Question: In glmnet in R, what is the difference between dfmax and pmax when creating a model with both ridge and lasso penalties?
Is the following interpretation correct?
Let's say we have we run a glmnet elastic net with 500 predictors and we only want to include in 3 predictors in the final model; i.e. we want the lasso eliminate 497 predictors. In order to do so, do we set dfmax = 500 and pmax = 3?
Comment: You only need `pmax=3`. The `dfmax` argument is to limit the extent of the forward search, eg if you had thousands of predictors and you knew in advance that you were only interested in modelling a hundred of them at a time.
Answer: I believe it is actually pmax that limits the forward search. If pmax is set to a low number, a warning message about early termination of the lambda path is given.  I have noticed however, that if dfmax is used with cv.glmnet it behaves as expected, but not necessarily if used with vanilla glmnet. I think there may be a bug.


Drupal can't create image styles for files located in theme directory

Question: I have an image located in sites/all/themes/mytheme/images directory.
I'm displaying it programmatically with attached image style like:
<code>  $style =  array(
    'style_name' => 'my_style',
    'path' => drupal_get_path('theme', 'mytheme') . '/images/' . $filename,
    'width' => 30,
    'height' => 30,
    'alt' => $alt,
    'title' => $title,
  );

  return theme('image_style', $style);
</code>
First error: 404:

"NetworkError: 404 Not Found -
  http://j.dev/sites/default/files/styles/my_style/public/sites/all/themes/mytheme/images/img.png?itok=qsTbAc8I"

Log report:

Source image at public://sites/all/themes/mytheme/images/img.png not
  found while trying to generate derivative image at
  public://styles/my_style/public/sites/all/themes/mytheme/images/img.png.

I'm sure that img.png exists in sites/all/themes/mytheme/images
File permissions:

sites/all/themes/mytheme/images: 777
sites/default/files/styles/my_style: 777
Answer: core module Image Style allow only images from
public:// file system (sites/default/files).
For using image styles with any other images, you should install the Imagecache External module.

Imagecache External is a utility module that allows you to store external images on your server and apply your own imagecache (D6) / Image Styles (D7).
Answer: Your code will not work with the images located inside the theme directory.
From the specific Drupal documentation
path:  The path of the image file relative to the Drupal files
   directory.  This function does not work with images outside the files directory nor with remotely hosted images. This should be in a format such as  images/image.jpg', or using a stream wrapper such as    'public://images/image.jpg'.
Reference
Answer: It's actually possible to generate image style with the trick which image module uses to generate image style preview (see theme_image_style_preview()):
<code>$original_path = drupal_get_path('theme', 'mytheme') . '/images/' . $filename;
$thumb_file = image_style_path('my_style', $original_path);
if (!file_exists($thumb_file)) {
  $style = image_style_load('my_style');
  image_style_create_derivative($style, $original_path, $thumb_file);
}

$style =  array(
  'style_name' => 'my_style',
  'path' => $original_path,
  'width' => 30,
  'height' => 30,
  'alt' => $alt,
  'title' => $title,
);
return theme('image_style', $style);
</code>


Matlab GPU computing

Question: I want a code that check the computer that my designed software (GUI) is working on it using a CUDA-Core graphic card (Nvidia) or not. So after getting 'true; value from it, my software activate some features for accelerating process.
Thanks.
Answer: You could use the function gpuDevice. For me I get the following output:
ans =

CUDADevice with properties:

                  Name: 'GeForce GTX 660 Ti'
                 Index: 1
     ComputeCapability: '3.0'
        SupportsDouble: 1
         DriverVersion: 6
        ToolkitVersion: 5.5000
    MaxThreadsPerBlock: 1024
      MaxShmemPerBlock: 49152
    MaxThreadBlockSize: [1024 1024 64]
           MaxGridSize: [2.1475e+09 65535 65535]
             SIMDWidth: 32
           TotalMemory: 2.1475e+09
            FreeMemory: 1.7126e+09
   MultiprocessorCount: 7
          ClockRateKHz: 1019500
           ComputeMode: 'Default'
  GPUOverlapsTransfers: 1
KernelExecutionTimeout: 1
      CanMapHostMemory: 1
       DeviceSupported: 1
        DeviceSelected: 1

(Note: you can access the different properties by simple dot reference, e.g. ans.MultiprocessorCount will give 7.)
Also see the following pages:

MATLAB Central article

Help #1 - GPUDevice class

Help #2 - Identify and Select a GPU Device

Edit
I just tested this on a computer that doesn't have the CUDA driver installed. What I get is the following exception (that is actually thrown by the current() method of the GPUDevice class):
...'
Error using gpuDevice (line 26)
There is a problem with the CUDA driver associated with this GPU device. See www.mathworks.com/gpudriver to find and install the latest
supported driver.

Caused by:
    The CUDA driver could not be loaded. The library name used was 'nvcuda.dll'. The error was:
    The specified module could not be found.

For this reason I suggest first surrounding gpuDevice with a try-catch block and only if it was successful, proceeding with checks like parallel.gpu.GPUDevice.isAvailable(1).
There are still cases not covered by my answer, such as setups with more than one GPU (such as an non-CUDA on-board one + add-on CUDA card) or systems without a CUDA GPU, but that have CUDA drivers installed. For multi-GPU cases you should also use the methods:
parallel.gpu.GPUDevice.count and parallel.gpu.GPUDevice.select(idx).
Comment: from your edited information, when we use `try-catch` what should we insert in `catch` part? I don't want my program return an exception or something like that.
Comment: I suppose you should use an equivalent code that will run on the CPU or CPUs (using `matlabpool`,`parfor` and so on).
Comment: More information : I have a check box in my program. It is `Enable` when GPU-computing is available in a system and it is `Disable` when there isn't any`CODA-Core` graphic card in system, So I only want check availability of CODA-Core` graphic card in the system.
Comment: So what's the question\problem? How to correctly set the value of the checkbox? (I don't see why the user should be able to change this manually, unless he wants to force a CPU compution)
Comment: As you said you code return a error in a computer that there isn't any CODA-enabled graphic card in it. true true? So I think I should use `try-catch`. in try I should `Enable` check box and in catch mode I should `Disable` it?
Comment: Yes, that should work. Or change the `Value` to `true` or `false` (depending on what you want to achieve)
Comment: My program user select that he want use GPU-computing or not. If he has a system that is CODA-Enabled, he can check this check box, In other cases it is disable.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/58262/discussion-between-dev-il-and-user2991243).

Matlab GPU computing


Does the improper integral $\int_0^1 \frac{1}{x}\sin\frac{1}{x^2}$ exist?

Question:
Does the improper integral $\displaystyle\int_0^1 \frac{1}{x}\sin\frac{1}{x^2}$ exist?

I don't know how to use the comparison test, and I cannot find a proper comparison function.
Comment: HINT: Try $u = 1/x$
Answer: By a change of variables $u=\frac1{x^2},\frac{du}{dx}=-\frac2{x^3}$:
$$\int_0^1\frac{\sin(1/x^2)}x=\frac12\int_1^\infty\frac{\sin u}u\,du$$
Thus the original integral converges, since $\int_0^\infty\frac{\sin u}u\,du=\frac\pi2$ (see here for example). Indeed, its value is
$$\frac12\left(\frac\pi2-\operatorname{Si}(1)\right)=0.31235\dots$$
where $\rm{Si}$ is the sine integral.
Answer: If you set $y = 1/x^2$ i.e. $x = y^{-1/2}$ then $dx = -\frac12y^{-3/2}dy$, so $dx/x = -\frac12 dy/y$, and the integral becomes
$$ -\frac12\int_1^\infty \frac{\sin (y)}ydy$$
the convergence of the original integral is the same question as the convergence of
$$ -\frac12\lim_{a\to\infty} \int_1^a \frac{\sin (y)}ydy$$
The answer is yes, the improper integral exists, one can follow the proofs in Evaluating the integral $\int_0^\infty \frac{\sin x} x \,\mathrm dx = \frac \pi 2$?, but you won't get as clean a result. This integral evaluates to  $-\frac12(\operatorname{Si}(1)-\frac{\pi}{2})$.


Coinbase api returning mostly empty arrey

Question: I am trying to test coinbase api. Api authorized fine but most functions are returning empty arrey, bellow is my code sample
<?php
require_once('vendor/autoload.php');
use Coinbase\Wallet\Resource\Account;
use Coinbase\Wallet\Client;
use Coinbase\Wallet\Configuration;
use Coinbase\Wallet\Enum\CurrencyCode;
use Coinbase\Wallet\Resource\Transaction;
use Coinbase\Wallet\Value\Money;
use Coinbase\Wallet\Resource\Address;

$apiKey='********';
$apiSecret='********;';

$configuration = Configuration::apiKey($apiKey, $apiSecret);
$client = Client::create($configuration);

$accounts = $client->getAccounts();
$account = $client->getPrimaryAccount();
$auth = $client->getCurrentAuthorization();
$user = $client->getCurrentUser();
$paymentMethods = $client->getPaymentMethods();

echo "accounts arrey". json_encode($accounts)."
";//empty arrey
echo "primary account arrey".json_encode($account)."
";//empty arrey
echo "current auth arrey".json_encode($auth)."
";//printing data perfectly
echo "current user arrey".json_encode($user)."
";//empty array
echo "payment methods arrey".json_encode($paymentMethods)."
";//empty array

?>

All of echo printing empty array except $authbellow is output screenshot
Comment: If some function of the library not working you should maybe ask the creator of this library. I think you use the official [PHP wrapper for coinbase API](https://github.com/coinbase/coinbase-php) or? I just had a short look on it and the function which returns an empty array use API endpoints which are not described in the official API documentation.
Comment: Yes I used official api, ok tnx for your suggestion. Let me  open issue on github.actually they reply after 2/3 days thats why I posted here if someone can help me to solve quickly. And tnx again
Answer: This problem was solved by using $response=$client->decodeLastResponse(); and echo $response


Is there a way to pull data by sum one column and based on another

Question: I am trying to sum amount by account by month and have the result shown in another Cell by account.
<code>=AND($E1>=MONTH(E1:E8),SUMPRODUCT(($F$1:$F$8>=MONTH(E1:E8)=6*($D$1:$F$8=D1))>=0))*6
</code>
<code>Account                 Amount          Month
06962-5001121            3.00           July
06962-5001122            3.00           July
06962-5001123            6.00           July
</code>
What actually happened was 0 in cell

D
E
F

1
Account
Date
Amount

2
06962-5001121
2023-06-10
1

3
06962-5001123
2023-06-11
2

4
06962-5001121
2023-06-11
1

5
06962-5001122
2023-06-12
2

6
06962-5001122
2023-06-13
1

7
06962-5001121
2023-06-14
1

8
06962-5001123
2023-06-15
2

9
06962-5001123
2023-06-16
2
Comment: How `July` is related with column E? What's your expected result?
Comment: Make a pivot table of your data!
Comment: What is your expectations of this part? `$F$1:$F$8>=MONTH(E1:E8)=6`
Answer: <code>=LET(r, D2:F9,
     m, 6,
     a, TAKE(r,,1),
     b, INDEX(r,,2),
     c, INDEX(r,,3),
     u, SORT(UNIQUE(a)),
HSTACK(u,
       MMULT(--(TOROW(a)=u),(MONTH(b)=m)*c)))
</code>
Comment: Sorry P. My mistake left out the =6 after the month function. Thanks again for your help.
Comment: I appreciate your quick response However, that:, 06962-06962-50011121 18 Should be 3
06962-50011122 18 Should be 3
06962-50011123 36 Should be 6, It would appear the sum is multiplied by 6
Comment: sorry P can I add another column to the equation  col G,  Payment
Payment
Payment
OD INTEREST
OD PROTECTION FEE
Transfer
LOAN INTEREST
MORTGAGE PAYMENT
I tried to enter d, INDEX(r,,4), and increased the a to include G unfortunately, I got a #REF once again thanks for the help.
Comment: I am new to Stack overflow and apologize if I am confusing. I found that in my download from the Business (Bank) I have two additional columns G and H. I can put the information into another sheet and do calculations there manually. What you provided me P with works great however I have been trying to add in the other two columns and keep getting #Value or #SPILL. I can index the columns with no problem but cannot get them to display on the output. Thanks again for any assistance you can give me. Norm
Comment: Spill error is typically occuring when the spill range (the size of the spill result) covers a cell which is not clear of data. If you click the cell of the formula it shows blue surroundings around where it tries to spill. Add columns if required, or clear the cells within that range if you can.
Comment: As for the extra columns, I don't know what your exact intention is with these extra columns, but likely you need to add a filter condition to the uniques and add these same conditions to the mmult, but how depends on what you require.
Comment: Thanks for your assistance. However I was using a sample and it does not work on the real data.,
Comment: Thanks for your assistance. However I was using a sample and it does not work on the real data. Chequing , 06962-5001375 , 2023-08-01 ,  Cheque # ,  INSURANCE , THE PERSONAL ,  -269.88

I added the values for indexing to 7 however I get an error #Value so I changed the * C, Value to g and got another error. When I evaluated the Formula in the first a,TAKE(r,,1),I  N/A  for r,,1. I also increased the range to include column g. Would appreciate if you could help me out. As I am going crazy with the hours spent on this formula. thanks.
Comment: In that case open a new question with new (dummy) data including the extra columns and your expectations with that. PS you can post your data as markdown table https://www.tablesgenerator.com/markdown_tables
Comment: maybe you can share the formula you tried. I may be able to spot if something may be off.
Comment: This is the actual data:
Comment: I don't see a difference. Am I missing something?
Comment: I edited the bottom part to show as markdown table. You can generate a table like that by pasting your data directly from Excel into the table generator using the link I shared.


Assigning multiple values in a combo box to multiple cells

Question: I'm trying to create a search box using a combo box in Excel where it retrieves data from a two column table in excel. I have a simple excel spreadsheet table with two columns as follows,
ID   | Name
001  | Peter
002  |  James

So far, the combo box I have created retrieves the row data (ID & Name) successfully when I type a keyword. But when I select one it only outputs the data values to one cell A5. (Assume linked cell is A5)
For ex:
If I select "001  Peter" from combo box it outputs only "001" to the linked cell value in combo box. How can I assign two column values (ID & Name) to two different cells when selected?
Thanks.
Answer: If the text in the ComboBox has every thing you want to send to cell A5 then the code would be
Private Sub ComboBox1_Change()
    Range("A5").Value = ComboBox1.Text
End Sub

This is providing your ComboBox is ComboBox1 - look out for this if you have other ComboBoxes on the sheet
Comment: It outputs only the value "001" to the cell A5. I want the values "001" to be inserted to A5 and "Peter" to be inserted to B5 when selected.
Comment: What method are you using to get info from two separate columns in to a single combobox?


NodeJS 18 breaks DNS resolution of localhost from 127.0.0.1 to ::1

Question: I am working on a NodeJS monorepo which had applications on nodeV16 and I upgraded those to nodeV18. Many of those use localhost for communication. With Node 16, the localhost used to resolve in 127.0.0.1 but after the upgrade, it started resolving into ::1 and thus breaking the apps at multiple places.
I found over the internet that Node.js 17 switched from resolving host names to IPv4 by default to resolving to the order given by the OS. This was an intended change done in nodejs/node#39987, which nevertheless caused issues in downstream projects, as reported in nodejs/node#40537.
Has anyone faced this in the past and if yes, how did you fix this? I am new to Node and could use some guidance.
We are using linux machines and I am not sure why the order of DNS resolution in the OS is IPv6 first. Not sure if we can change it somehow?
Thanks in advance!
Answer: No, the update doesn't "break" DNS resolution.

I am not sure why the order of DNS resolution in the OS is IPv6 first. Not sure if we can change it somehow?

The order of DNS resolution is IPv6 first because IPv6 is the current-gen internet and IPv4 is an old legacy protocol. Yes, it is possible to change this in the OS (see /etc/gai.conf), but it's usually not a good idea.
If you're contacting localhost, this can happen over both IPv4 and IPv6. In order to do that, you need to switch your apps to use "::" instead of "0.0.0.0" which will make it listen on both IPv4 and IPv6. (Or, if they're currently listening on 127.0.0.1, change that to ::1).
If you really need the old behaviour back (= you're planning to continue operating applications that do not support current-gen internet) you can try the command line option --dns-result-order=ipv4first which will make sure localhost (and other DNS names) resolve to IPv4 again.


Choose text file and Read Android

Question: I chose a text file from storage and got its path (FilePath), am trying to read the content of that text file and put it in edittext..i am using the code below to get text file data and put it in edittext (eTPronounce)
 File sdcard = Environment.getExternalStorageDirectory();

//Get the text filea
                File file = new File(sdcard,FilePath);

//Read text from file
                StringBuilder text = new StringBuilder();

                try {
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    String line;

                    while ((line = br.readLine()) != null) {
                        text.append(line);
                        text.append('\n');
                    }
                    br.close();
                }
                catch (IOException e) {
                    //You'll need to add proper error handling here
                }

//Find the view by its i

//Set the text
           eTPronounce.setText(text);

            }
        });

If i replace  FilePath (in the second line) with any directory where there is text file it works.For example if I replace FilePath with "Download/text.txt" it works .
I used this link to get FilePath
THANKS
Comment: full code http://jpst.it/D5an
Comment: do you add use-permission
Comment: if it reads the file than what is the issue, i think you should check the existence of the file first than try to read it
Comment: i used permissions yes
Comment: Try my code  getData() return a uri
Answer: I think you should be using below constructor
File(File dir, String name)

or you can use
File(String path)

If you are specifying directory name then you only need to give the file name as shown in the first example.Otherwise you can use the second one with the complete file path
Comment: so i should replace this    File file = new File(sdcard,FilePath); with this    File file = new File(String,FilePath);
Comment: No use new File(FilePath).

I assume that FilePath is the complete path of the file
Comment: Brooooooooooooooooooo I love you thankssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss
Answer: if(resultCode==RESULT_OK){
    if(data == null || data.getData == null){
       //Log.e()
      return;
    }
FilePath = getPath(data.getData(),mActivity);
setfilename.setText(FilePath);
}

    public static String getPath(Uri uri,Context ctx) {
        String res = null;
        if(null==uri){
            return res;
        }
        if (uri != null && uri.toString().startsWith("file://")) {
            return uri.toString().substring("file://".length());
        }
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = ctx.getContentResolver().query(uri, proj, null, null, null);
        if(cursor!=null){
            if(cursor.moveToFirst()){
                try {
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    res = cursor.getString(column_index);
                }catch (Exception ignored){
                }finally {
                    closeCursor(cursor);
                }
            }
        }
        closeCursor(cursor);
        return res;
    }

Comment: Thanks for the help !

Choose text file and Read Android


Paramaters of Functions Imported Using the DllImport Attribute

Question: I am trying to import some winapi functions into my wpf project(written in c#) but I do not know how to "convert" some of their paramaters, for example the function
<code>BOOL WINAPI GetClientRect(
  _In_  HWND   hWnd,
  _Out_ LPRECT lpRect
);
</code>
takes a pointer to a RECT struct and modifies its contents. If I were to import this function using the DllImport attribute it would look like:
<code>[DllImport("user32.dll"]
public static extern bool GetClientRect(IntPtr hwnd, ???);
</code>
How do I handle the pointer to RECT object?
Comment: There is a site full of pinvoke: http://www.pinvoke.net/default.aspx/user32.getclientrect . Have you tried them? There is a definition for a RECT.
Comment: (note that sometimes that site is wrong :-) They have some problems with 32-to-64 bits)
Comment: Also http://stackoverflow.com/questions/13086927/call-getclientrect-winapi
Comment: well looks like pinvoke.net should do it.. i should have asked here first before searching myself for hours lol ...
Comment: Then you should better your google-fu... If you search for *GetClientRect pinvoke* then the first link is for pinvoke.net, the third is for the stackoverflow answer linked by mpiatek
Comment: There is a Pinvoke.Net plugiun for Visual Studio
Answer: <code>[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
    public int Left, Top, Right, Bottom;
}

[DllImport("user32.dll")]
static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
</code>


Calcular quantidade de incrementos para que 2 números se tornem iguais

Question: O problema:

Com um nome muito criativo, o Protagonista está em seu primeiro
episódio de sua incrível saga!
Em uma tarde qualquer Z, o melhor amigo do Protagonista, desafiou o
mesmo para um desafio super divertido.
Z escreve dois números inteiros A e B em um quadro branco e pergunta
se o Protagonista pode fazer com que os dois inteiros se tornem iguais
usando o número mínimo de movimentos.
Em um movimento, o Protagonista pode fazer uma das seguintes ações:

Escolher um dos números e adicionar 3 a ele (x = x + 3).

Escolher um dos números e adicionar 2 a ele (x = x + 2).

Sabendo disso, como o Protagonista sabe que você é muito bom ele pediu
para que você ajudasse ele nessa missão e o dissesse qual a quantidade
minima de movimentos que ele precisa para fazer com que os dois
números se tornem iguais. Você recebe dois inteiros (1 <= A, B <=
10^5).  Deve ser impresso um único inteiro N, equivalente a quantidade
minima de movimentos que o Protagonista precisa para fazer.

Minha tentativa:
A entrada ali é padrão da questão pois ele informa os dois números na mesma linha, eu criei uma lista já adicionando eles convertidos pra inteiros pq eles anteriormente eram strings.
Usei a função max() e min() pra pegar os respectivos valores (maior e menor).
As variáveis estão nomeadas assim pois ainda estava testando, c1 e c2 são os contadores dos movimentos de soma que eu faço no menor número, a e b são duas variáveis temporárias que eu criei pra pegar o valor do menor número.
Depois eu tento criar uma lista de números pulando de 2/3 até chegar no maior número, incrementando o contador a cada repetição.
No final eu comparo qual contador é menor, pois seria a resposta final, o primeiro if, ficou assim pois em alguns casos o contador de ambos ficava igual ex: quando a entrada era 6 e 8.

entrada = str(input()).split()

numeros = []

for i in entrada:
    numeros.append(int(i))

B = max(numeros)
A = min(numeros)

div, mod = divmod(B-A, 3)
if mod != 0:
    div += 3 - mod

print(f'{div}')

Comment: Poderia descrever em texto qual foi a lógica que tentou implementar?
Comment: Com calma, que não esta dando para entender. Você recebe dois números, no menor você vai o somando de três em três, no maior você vai somando de dois em dois. Você quer saber quantas somas serão necessárias para que os valores sejam iguais?
Comment: Você pode colocar tudo isso direto na pergunta ao [edit]. Melhor que deixar isso nos comentários.
Comment: @AugustoVasques depois eu tenho que dizer qual é o menor movimento que eu faço pra igualar os número (usando 3 ou 2)
Comment: Agora ficou claro, vou só mexer um pouco para facilitar a leitura.
Comment: @AugustoVasques, vou receber dois números, pelo que eu entendi um maior e um menor. o personagem da questão tem duas opções: somar 3 ao número ou somar 2 ao número até eles ficarem iguais (maior e menor número da entrada)
Comment: @Woss tudo bem.
Comment: Aproveitando, `input` já retorna uma string, então fazer `str(input())` é desnecessário. E se você já tem certeza absoluta que sempre serão 2 números na mesma linha, pode fazer direto: `a, b = map(int, input().split())`
Comment: João, reverti sua última edição porque é importante que a pergunta tenha o código que vc tentou. Saiba mais em: https://pt.meta.stackoverflow.com/a/5484/112052
Answer: Complementando a outra resposta (que como o próprio autor reconheceu, em alguns casos pode falhar), segue um pequeno ajuste.
A ideia continua a mesma: pegamos a diferença entre os números e dividimos por 3 (vamos chamar o resultado desta divisão de n).
Se a divisão for exata (ou seja, se o resto for zero), isso quer dizer que a está a exatamente n incrementos de 3 de b. Até aqui, está igual ao raciocínio da outra resposta.
Se o resto da divisão for 2, então basta fazer mais um incremento de 2 (ou seja, continua igual à outra resposta):
a  | a + 3 | a + 6 ... | a + 3n |   2   b
   <---------------------------->   ^
        n incrementos de 3          |
                                    \_ 1 incremento de 2

Total: n + 1 incrementos

Mas e se o resto da divisão for 1? Isso quer dizer que temos o seguinte:
a  | a + 3 | a + 6 ... | a + 3n |   1   b
   <---------------------------->
        n incrementos de 3        + 1

A princípio, bastaria mais um incremento de 3 em a e um incremento de 2 em b (que foi o sugerido na outra resposta), totalizando n + 2 incrementos. Mas na verdade dá para fazer assim:

em vez de n incrementos de 3, fazemos n - 1 incrementos de 3. Com isso, ainda faltará 4 para chegar a b
em seguida, fazemos 2 incrementos de 2

a  | a + 3 | a + 6 ... | a + 3(n - 1) |   4     b
   <---------------------------------->   ^
        n - 1 incrementos de 3            |
                                          \_  2 incrementos de 2, totalizando os 4 que faltam

Total: n + 1 incrementos

No total, teremos n - 1 incrementos de 3, e 2 incrementos de 2, totalizando n + 1 incrementos.

Ou seja, no fundo tudo se resumiria a:

divide b - a por 3
se a divisão for exata, o resultado da divisão é a resposta
se não for exata, soma 1 ao resultado da divisão

Mas ainda não é suficiente
Se a diferença entre a e b for menor que 3, o valor de n é igual a zero, então não dá para aplicar a regra acima, pois não temos como fazer n - 1 incrementos de 3 (pois isso daria "-1 incrementos").
Então neste caso específico temos:

se o resto for 1, teria que ser 2 incrementos (1 de 3 em a e 1 de 2 em b)
se o resto for 2, teria que ser 1 incremento de 2 em a
se o resto for zero, é porque a e b são iguais, então precisa de zero incrementos

Juntando tudo, ficaria assim:
# ler os valores de "a" e "b"...

qtd, resto = divmod(b - a, 3)
if resto != 0:
    if qtd == 0: # quando a diferença entre a e b é menor que 3
        qtd = 3 - resto
    else:
        qtd += 1
print(f'Foram necessários {qtd} movimentos')

E aproveitando, se você sabe que a entrada sempre terá 2 números na mesma linha e nada mais, pode lê-los assim:
a, b = map(int, input().split())

E se eles não necessariamente estiverem em ordem (por exemplo, se o a puder ser maior que o b na entrada), pode calcular a diferença usando abs, para que retorne o valor sem sinal:
qtd, resto = divmod(abs(b - a), 3)

Desta forma você não precisa se preocupar em criar uma lista com os números, para depois pegar o max e o min.
Ou ainda, como são apenas 2 números, bastaria invertê-los se o a for maior:
a, b = map(int, input().split())
if a > b:
    a, b = b, a
qtd, resto = divmod(b - a, 3)
etc...

Answer:
A solução apresentada nesta resposta não funciona para todas as situações.

Não analisarei seu código, pois você compreendeu errado o problema e o código não reflete o que se pede no exercício.

Considerando que você possui os números A e B (B > A).
A cada "movimento" você pode decidir se deseja incrementar em 2 ou incrementar em 3 qualquer um dos números, até que fiquem numericamente iguais. Por exemplo, considerando que A=2 e B=13, precisamos sair de 2 até igualar a 13.

Podemos adicionar 3 em A, obtendo A=5;
Podemos adicionar 3 em A, obtendo A=8;
Podemos adicionar 3 em A, obtendo A=11;
Podemos adicionar 2 em A, obtendo A=13;

Portanto, foram necessários 4 "movimentos". Mas e se fosse A=2 e B=12?

Podemos adicionar 3 em A, obtendo A=5;
Podemos adicionar 3 em A, obtendo A=8;
Podemos adicionar 3 em A, obtendo A=11;
Podemos adicionar 2 em B, obtendo B=14;
Podemos adicionar 3 em A, obtendo A=14;

Sendo necessários, agora, 5 "movimentos".
A lógica se simplifica em:

Enquanto a diferença B-A for maior ou igual a 3, incremente A em 3;
Se a diferença B-A for igual a 2, incremente A em 2;
Se a diferença B-A for igual a 1, incremente B em 2;

Em código, ficaria algo como:
quantidade = 0

while (B-A > 0):
  quantidade += 1
  if B-A >= 3:
    A += 3
  elif B-A == 2:
    A += 2
  else:
    B += 2

print(f'Foram necessários {quantidade} movimentos')

Ou ainda:
quantidade = 0

while (B-A >= 3):
  quantidade += 1
  A += 3

if B-A == 2:
  A += 2
  quantidade += 1
elif B-A == 1:
  B += 2
  A += 3
  quantidade += 2

print(f'Foram necessários {quantidade} movimentos')

Essa solução não é ideal, embora seja mais simples de entender, pois sua complexidade computacional é O(n), em que o número de operações realizadas será diretamente dependente da entrada. Para B >> A, haverá impacto em performance.
Matemática ❤
Você não precisa de um laço de repetição para saber quantas vezes você irá incrementar em 3 o valor de A até ele se aproximar de B. A matemática já te diz isso em uma operação.

Se o valor B-A for múltiplo de 3, você precisará (B-A)//3 movimentos - apenas incrementos de 3 em A;
Se o resto da divisão de B-A por 3 for 2, você precisará (B-A)//3 + 1 movimentos - vários incrementos de 3 e um de 2 em A;
Se o resto da divisão de B-A por 3 for 1, você precisará (B-A)//3 + 2 movimentos - vários incrementos de 3 em A, um incremento de 2 em A e um incremento de 2 em B;

Entenda // como divisão inteira entre os operandos.

Portanto:
quantidade = 0

if (B-A) % 3 == 0:
  quantidade = (B-A) // 3
elif (B-A) % 3 == 1:
  quantidade = (B-A) // 3 + 2
else:
  quantidade = (B-A) // 3 + 1

print(f'Foram necessários {quantidade} movimentos')

Essa solução é ideal, mesmo que inicialmente pareça mais complexa, pois sua complexidade computacional é O(1), realizando exatamente o mesmo número de operações, independente da entrada. O impacto em B >> A será o mesmo que quando B é muito próximo de A.
Matemática ❤ v2.0.0
Graças a colaboração do @hkotsubo nos comentários lembrando da função divmod, é possível ainda fazer:
A = 2
B = 13

div, mod = divmod(B-A, 3)

if mod == 2:
    mod = 1
elif mod == 1:
    mod = 2

print(f'Foram necessários {div+mod} movimentos')

Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](https://chat.stackexchange.com/rooms/119107/discussion-on-answer-by-woss-calcular-quantidade-de-incrementos-para-que-2-numer)
Comment: muito obrigado @hkotsubo
Answer: Só uma pequena reescrita (de gosto ofuscado e duvidoso) da versão @hkotsubo, no intuito de descomprimir dum trabalho chato que tenho que fazer...
a,b = sorted(map(int,input().split()))
q,r = divmod(b-a,3)
print( q + (r!=0) + (b-a==1))


How to exclude the Overlapping records/time in Excel

Question: Is there any build in function or a ways to exclude the overlapping records in Excel directly. Specifically, based on timestamp. Please refer the following example. Row 2 and 4 (in Example) are overlapping, I am trying to exclude the overlapping records. I tried by using the rank function to exclude the duplicates but I was un-able to exclude it.
Example:
  S.NO  SQ  Date    [Start Time]    [End Time]
    1   1   1/9/2015    18:00        23:55
    1   1   1/9/2015    19:00        22:55
    1   2   1/9/2015    19:00        23:59
    1   2   1/9/2015    19:00        21:59

Expected Output:
  S.NO  SQ  Date    [Start Time][End Time]  Expected Out put    Comments
    1   1   1/9/2015    18:00   23:55       5.92
    1   1   1/9/2015    19:00   22:55       0                   Exclude this record
    1   2   1/9/2015    19:00   23:59       4.98
    1   2   1/9/2015    19:00   21:59       0                   Exclude this record

Answer: The data sample provided seems may not cover all the relevant possibilities, interpreting 'overlap' as being wholly within (discounting the boundaries), assuming that S.NO is in A1 that only adjacent entries need be considered, then:
 =24*IF(ROW()=2,E2-D2,IF(AND(C2+D2>=C1+D1,C2+E2<=C1+E1),0,(E2-D2)))

in F2 and copied down to suit and with ColumnF formatted:
0.00;;0

and left justified, and with:
=IF(F2>0,"","Exclude this record")

in G2 and copied down to suit produces:

once the labels have been filled in F1 and G1.
Answer: Make the datarange an excel table: In the example Table1.
In a new column in the table, enter the following formula, using the new FILTER command in Excel365:
=CHOOSECOLS(FILTER(Table1[[S.No]:[EndTime]],([Date]=[@Date])*([StartTime]<[ @EndTime ])*([EndTime]>[@StartTime]),""),2)
If the formula results in more than 1 record, this formula will result in a #Spill! error (error code 9). This can then be used for subsequent processing, like conditional formatting.
Please note: No spaces allowed in ColumnNames in the Table; in the Filter Array exclude the new column in the table, otherwise a circular reference occurs. More conditions can be added if needed to the result in a unique record. The multiplication symbol * indicates an AND condition. The CHOOSECOLS is used to prevent spill errors if any data are in columns to the right.
If the new column is outside of the table, the last row may result in multiple rows answer, not a spill error.
If not all used column cells in a row are filled, a #value error results.


Python : Using dot to make each sentence a new line in the presence of decimal points

Question: I want to have each sentence in a new line. A sentence ends by a . . I tried the following code:
import re
text='This text has (15.16 +/- 1.01). And it also has 20.1 km(3) during 4/2002-
and 1/2018'
text=re.sub('\.', '\n',text)

When I try to make each sentence a new line by replacing . with \n I get four lines instead of two because of the decimal points. I do not need to keep the numbers. I just want to get the alphabetic characters and clean everything else
This text has
And it also has during and

And solution?
Answer: >>> import re

>>> text='This text has 15.16. And it also has 64.6190. twent one guns. hi. 16. 40.5'

>>> print(re.sub('[\d]*\.(?:[\d]*[\.]*[\ ]*)*', '\n',text))

#OUTPUT
This text has
And it also has
twent one guns
hi

Edit: Do you want to eliminate +/-?
>>> text = 'This text has 15.16 +/- 1.01. And it also has 64.6190. hi. the tommy is bad. + one-two is negative one.'

>>> print(re.sub('[\d]*\.(?:[\d]*[\.]*[\ ]*)*|[\ ]*[+\-\/]+[\ ]*', '\n',text))

#OUTPUT
This text has

And it also has
hi
the tommy is bad

one
two is negative one

Comment: Thanks for the answer. However, this code work for the example above by if I have  20.27 +/- 1.95 then it will give an additional line for +/-. I changed the original post accordingly.
Comment: Hmmm. I'm not quite sure what you mean so I'll make an edit with input and about based on your post. Do you also want the regex to delete the `+/-`?
Comment: Yes it would be better to delete everything from the text and just keep the alphabetic characters. I change the post accordingly.
Comment: Got it. I made a new edit. Not e, it will leave extra newlines (\n)'s because it is replacing each query it matches with `\n`. To make it act different I would have to embed the re.subs but your question only asks to replace everything with `\n` for now
Answer: Edit:
this one is even simpler
text=re.sub(r'(\d*\.)+', r'\n',text)

you can adjust regex pattern as you wish, simply:
import re
text='This text has 15.16. And it also has 64.6190.'
text=re.sub(r'\d*\.\d*\.', r'\n',text)

print(text)

output:
This text has
 And it also has

Explanation: look for any number of digits followed by dot, then again any number of digits followed by dot and replace it with new line


Need help movig DNS providers (ZoneEdit to DynDNS)

Question: I have a domain name and I use GoDaddy as my registar. My DNS provider is ZoneEdit. I'm staying with GoDaddy as my registrar, for now, but I want to switch DNS providers to DnynDNS. I already purchased an account with DynDNS.
In the process of switching, I want to avoid any downtime, especially when it comes to email (MX records). I'm a bit nervous and I want to double check with someone who has done something like this before that I'm doing things right. I'm especially interested in someone familiar with DynDNS and Google Apps which is where I host my e-mail. I'm somewhat confused by the priority settings for MX records. Also, do you suggest simply going to GoDaddy and changing my settings to point to DynDNS or should I do something else to avoid downtime?
Could you make sure that what I have with ZoneEdit:

Here is what I have entered into DynDNS:

Thanks!
Answer: DNS MX record priorities are really just what they sound like.  You give each record a priority (the lower the number the higher the priority) and in theory mail servers try the highest priority record first, and if it doesn't respond they try the next one, etc.
I'm a little unsure why you've got records listed from 10 to 70, have a look at this for the relative priorities between the servers - http://www.google.com/support/a/bin/answer.py?answer=174125
If Zoneedit and Dyn will both be hosting your DNS records (at least for the immediate future) you should be fine, just change the name server delegation at Godaddy and after a while (depending how often the root reloads) you'll see queries will start using the Dyn DNS servers.
It's one of those things that seems a lot scarier than it actually is so long as you do it right.
Comment: thanks for the link to google,the priorities I had were values that I had gotten from some other google FAQ, weird that they suggest such diversity of values.
Answer:
Why is the TTL for your A records only 60 seconds? Make them 3600 seconds like the rest of your DNS records. There's no valid reason to have the TTL so short.
Is your domain name a secret? Why black it out? Do you think it's some kind of security risk to let us see what your domain name is?
The records you have setup at DynDNS look fine to me (except for the aforementioned TTL of the A records), although I would suggest setting the MX priority to be the same as it's currently set up.
Comment: Not sure why only 60 seconds. Is it just adding extra pressure to the DNS server?


How to dynamically make properties of a dynamic type optional?

Question: I know there is a way to generate a type dynamically: Typescript dynamically create types based on object
But I can't find a way to make some properties of the dynamically generated type optional.
For example, say I have a object
const obj = {
  keyName1: {
     type: 'string',
     required: true
  },
  keyName1: {
     type: 'string',
     required: false
  },
}

How do I make a type based on this object? Given that some properties are optional (if required is false).
If I simply have this object:
const obj = {
  keyName1: 'string'
}

I could make a type with:
  type Generate<T> = T;
  type Generated = Generate<typeof myObj>

But with optional parameters, I don't know how...
Answer: You'll first need a utility type mapping each type string (eg 'string') to its type (string).
Then, map the object properties and do Obj[K]['required'] extends true ? to conditionally check whether to alternate with undefined or not. See this answer for how to separate out the optional properties from the non-optional properties in the new object.
const obj = {
  keyName1: {
    type: 'string',
    required: true
  },
  keyName2: {
    type: 'number',
    required: false
  },
} as const;
type Obj = typeof obj;
type TypesByTypeof = {
    'string': string;
    'number': number;
}

type ObjType = {
  [key in keyof Obj as Obj[key]['required'] extends true ? key : never]: TypesByTypeof[Obj[key]['type']]
} & {
  [key in keyof Obj as Obj[key]['required'] extends false ? key : never]?: TypesByTypeof[Obj[key]['type']]
}

Result:
type ObjType = {
    readonly keyName1: string;
} & {
    readonly keyName2?: number | undefined;
}


Python - Pull values from list

Question: I have a list of lists:
list_1 = [['1','a'],['1','b'],['1','c'],['2','a'],['2','d'], ['1','c']]

How can I iterate through the list to append the second value to another list while grouping by the first value. So it would look something like this:
list_2 = [['a','b','c','c'],['a','d']]

Comment: Suggestion use `defaultdict(list)` for output instead of list of lists.
Answer: One way to do it would be in two steps - first, find the unique 'keys' in list_1, then filter list_1 into multiple lists based on those keys.
unique_keys = set(elem[0] for elem in list_1)
list_2 = [[elem[1] for elem in list_1 if elem[0] == key]
         for key in unique_keys]
# [['a', 'd'], ['a', 'b', 'c', 'c']]

The set is ordered in order of last occurrence of any given key, which is why the output is backwards from what you'd expect. To fix this, do set(elem[0] for elem in reversed(list_1)) instead.
Comment: The time complexity is `O(n^2)` right. Using `defaultdict(list)` reduces it to `O(n)`.
Comment: @Ch3steR You're absolutely right, and I've upvoted your answer. At the time I was too lazy to reread the `defaultdict` docs, and so presented a suboptimal solution.
Comment: Your answer is expressive and pure python approach very good for python beginners. So upvoting.
Answer: Use defaultdict.
from collections import defaultdict

res=defaultdict(list)

for key,val in list_1:
    res[key]+=val
#res looks like this {'1': ['a', 'b', 'c', 'c'], '2': ['a', 'd']}
print(list(res.values())) # [['a', 'b', 'c', 'c'], ['a', 'd']]

Python - Pull values from list


Deletar múltiplas linhas dinamicamente com PDO?

Question: Digamos que eu tenha uma tabela de usuários (id | nome) e que onde eles são listados (client-side) eu possa selecionar vários deles e deletá-los ao mesmo tempo.
Como eu poderia fazer isso num banco MySQL utilizando PDO?
Eu sei que o MySQL permite o uso da cláusula IN que serviria para esse tipo de query. Ex:
DELETE FROM usuarios WHERE id IN (37,45,58) # deletaria os ids 37, 45 e 58

O problema é que como os ids seriam dinâmicos e o PDO utiliza prepared-statements, não sei como procederia com o código nele. Imagino que seria algo como:
$query = $pdo->prepare("DELETE FROM usuarios WHERE id IN :ids");
$query->bindParam(':ids', [37,45,58]); #array de ids vindo de um $_POST, por exemplo.
$query->execute();

Teria alguma forma de fazer algo como o código acima, com valores dinâmicos?
Answer: Podes fazer uso da função str_repeat() do PHP para gerar uma string repetindo o ? por cada ID presente na tua matriz:
$ids = //... seja lá como você recupera os ids

$mParams = str_repeat('?,', count($ids) - 1) . '?';
$sth = $db->prepare("DELETE FROM usuarios WHERE id IN ($mParams)");
$sth->execute($ids);

Por exemplo se tivesse um
$ids = [11, 23, 34, 47];

O str_repeat vai gerar uma saída:

?,?,?,?

Ficando
$sth = $db->prepare("DELETE FROM usuarios WHERE id IN (?,?,?,?)");

Comment: Funcionou perfeitamente! Obrigado.
Comment: @Zuul Obrigado pela edição
Answer: nas minhas consultas PDO utilizo sempre parâmetros nomeados então não é possível usar o "coringa" ?, uso o seguinte trecho de código
$ids = array(); // sua variável
$sql = 'SELECT ...';
$parameters = array(); // variável de parâmetros passada para execute()
$in = array();
foreach ($ids as $key => $value) {
  $keyname = ':id' . $key;
  $parameters[$keyname] = $value;
  array_push($in, $keyname);
}
$sql .= 'WHERE id IN (' . join(', ', $in) . ')';


Why isn't the playing time for women players in sports like soccer shortened in a similar way in which the playing time for women's tennis is?

Question: If women playing for shorter periods of time makes for better marketability in tennis, why isn't the same logic applied to other (even more) physically grueling sports like soccer where players play for even longer periods of time? Wouldn't the women's game also benefit from some form of modification in the rules or format just as women's tennis benefitted from it?
Answer: Because your premise is wrong.
Women playing shorter matches in tennis isn't for "marketability", it's an excuse that's been used for many years to pay less money to women. Women are just as capable of playing a high-quality 5 set match as men are, suggesting that other sports should be crippled because of an outdated notion that women aren't "strong enough" to play for as long as men is frankly a backwards, sexist suggestion.


How do you prove that for $|x−x_0|<\delta \Rightarrow |f'(x)−f'(x_0)|<\epsilon$.

Question: How do you prove that for $|x−x_0|<\delta \Rightarrow |f'(x)−f'(x_0)|<\epsilon$, when $g'(x)$ is continuous.
I know that $|x−x_0|<\delta \Rightarrow |f(x)−f(x_0)|<\epsilon$, but I'm seeing proofs that require it works for the derivative of f as well. How does that work?
Comment: This is false in general. There are differentiable functions with discontinuous derivative.
Comment: See this: https://math.stackexchange.com/questions/112067/how-discontinuous-can-a-derivative-be
Comment: Also: https://math.stackexchange.com/questions/292275/discontinuous-derivative
Comment: And, when searching for such a function, whose derivative is discontinuous, you might find it among the first derivatives of functions whose second derivative is discontinuous.
Comment: I gave you the links that follow @IvoTerek 's comment.
Comment: I think the question is incomplete. Please have a relook at it.
Comment: I have edited it to include that g'(x) is contin.
Comment: See [this](https://math.stackexchange.com/a/1029374/721644)
Answer: Hint:
Think of a discontinuous function, and integrate it. Then you'll find a counter-example.
Comment: Well just choosing any discontinuous function won't work. You have to choose a function with essential discontinuity. Note that the integrated function may be not be differentiable at points where original function is discontinuous. Also see this answer: https://math.stackexchange.com/a/3516923/72031
Comment: And this answer https://math.stackexchange.com/a/3518190/72031
Comment: @ParamananSingh, thank you for the remark and links! I'll examine them carefully.


Contact equivalent but not right equivalent holomorphic functions

Question: This question is from Greuel et al., Introduction to Singularities and Deformations Exercise 2.1.3.

Consider the unfolding $$f_t(x,y,z)=x^p+y^q+z^r+txyz,\quad \frac{1}{p}+\frac{1}{q}+\frac{1}{r}<1.$$
Show that for all $t,t'\neq 0$ and $t\neq t'$, $f_t$ and $f_{t'}$ are contact-equivalent but not right-equivalent.

My attempt: I already proved that the two are contact-equivalent by explicitly finding an automorphism $\varphi$ of $\mathbb{C}\langle x,y,z\rangle$ such that there is a unit $u\in \mathbb{C}\langle x,y,z\rangle$ satisfying $\varphi(f_t)=uf_{t'}$. What I'm stuck is to prove that they are not right-equivalent. I once tried to prove that the Milnor number of $f_t$ and $f_{t'}$ are different, but they turned out to be equal, so I have to find another way. Does anyone have ideas?
Thanks in advance!
Answer: I don't have an account, so I can't post this as a comment. But it seems that there is a counter-example to the second part of this question. In particular, consider $$f_t(x, y, z) = x^6 + y^6 + z^6 + txyz$$ with $t = 1$ and $t' = -1$. If we define an automorphism $\varphi$ of $\mathbb{C}\langle x, y, z \rangle$ by
\begin{align}
x &\mapsto e^{i\pi/3}x, \\
y &\mapsto e^{i\pi/3}y, \\
z &\mapsto e^{i\pi/3}z,
\end{align}
then we have that
\begin{align}
\varphi(f_t) &= \varphi(x^6 + y^6 + z^6 + xyz) \\
&= (e^{i\pi/3}x)^6 + (e^{i\pi/3}y)^6 + (e^{i\pi/3}z)^6 + (e^{i\pi/3}x)(e^{i\pi/3}y)(e^{i\pi/3}z) \\
&= x^6 + y^6 + z^6 - xyz \\
&= f_{t'}
\end{align}
Thus, in this case $f_t \overset{r}{\sim} f_{t'}$.
As a further comment, it would not have been possible to use the Milnor number to distinguish the $f_t$ either. The book mentions that over a characteristic $0$ field such as $\mathbb{C}$, contact equivalence implies that the Milnor number is also equal. Since we already know that $f_t \overset{c}{\sim} f_{t'}$ for all $t$, $t' \neq 0$, we cannot use the Milnor number to show that $f_t \not\overset{r}{\sim} f_{t'}$.


In terms of matrices: $\forall v\in V,\phi(\phi(v))=0$

Question: $\phi: V\to V$( a linear operator here)
How to interpret $\forall v\in V,\phi(\phi(v))=0$ in terms of matrices? Can I have some hint?

I suppose $\phi(V)= \begin{bmatrix} \phi(v_1)\\\phi(v_2)\\\dots\\\phi(v_n)\end{bmatrix}$ for $V=\dim n$
Comment: Let $V=\mathbb{R}^2$ and consider $\phi(x,y)=(y,0)$.What is the matrix representing $\phi$?
Comment: @Moya $\begin{bmatrix} 0&1\\0&0 \end{bmatrix}$?
Comment: Yes! Now, do you see that $\phi(\phi(x,y))=0$?
Comment: @Moya Oh that does work indeed, thanks. I am trying to find all such linear operators, but I wasn't sure how to think of it and this helps. So I am looking at some matrix representationm, $M$, for $\phi$ and taking $MMV=0$?
Comment: Yes, you take the matrix representation of $\phi$ in some fixed basis and you want that $M^2=0$, since this is the only operator with this property. These are called nilpotent matrices if you're curious (actually, nilpotent refers to a matrix $M$ such that $M^n=0$ for some $n$. This is the special case $n=2$).
Comment: @Moya Would it be called $2-\operatorname{Nilpotent}$ then, or in some way mention that the $n=2$? Thanks for that, grad to know
Comment: It's called the degree.
Comment: @Moya This helped an immense amount, the wiki article on Nilpotent matrices is insanely relevant to my confusion. Thank you so much
Comment: Here is a hint: try to think in terms of the diagonals...
Answer: $\phi(\phi(v))=0$ is equivalent to saying that this $A^2=0$. What does this mean? This means that $A$ has a nilpotency index of $2$. So what we want is to find all nilpotent index $2$ matrices of size $n\times n$. What matrices satisfy this?
All matrices are similar to a Jordan form and hence there is some $J$ Jordan form satisfying  $A=P^{-1} J A$. This $J^2=0$ also, and since all nilpotent matrices have eigenvalues of $0$, we form some combination of Jordan blocks of the form:
$$\begin{bmatrix}0&1&\\0&0&1\\&&\ddots&\ddots\\0&\dots&&0&1\\0&\dots&&&0\end{bmatrix}_{n\times n}$$
Now another fact we know is the following:
$$J^2=\begin{bmatrix}{J_1}^2\\&{J_2}^2\\&&\ddots\\&&&&{J_n}^2\end{bmatrix}$$
Where $J_i$ are the jordan blocks making up this Jordan form. What this means is, each of $J_i$ must have a nilpotency index of $2$.
What size Jordan blocks have a nilpotency index of $2$?
$\begin{bmatrix}0\end{bmatrix}$ and $\begin{bmatrix}0&1\\0&0\end{bmatrix}$ are the only two such sizes. Why? The three by three case and above will always have a nilpotency index greater than $2$.
This means that all such matrices are equivalent to some permutation of Jordan blocks of size $1$ and $2$ across the diagonal.


How do I accept info from a file and input it into an array?

Question: I have a file with these values:
9 10 11 9.5 10.2 9.8 10 8.7 9.3 9.1 9 8.9
4 5 5 4 6 5 4 3 4 5 5 4
8 11 10 8.5 10.7 9 11 8.5 9.4 9 10 9.9
5 5 5 5 5 5 5 5 5 5 5 5
9 9 9 9 9 9 9 9 9 9 9 9
4 5 5 4 6 5 4 3 4 5 5 4
8 9 10 8.5 9.2 8.8 9 7.7 8.3 8.1 8 7.9
7 4 6 6 6 5 6 6 6 6 5 6
10 11 12 10 11.2 9 11 9.7 9 9.1 10 9.9
6 5 6 6 6 5 6 6 6 6 5 6
10 9 11.2 9.5 10.8 9 10.3 8 9.3 9.1 9 8.9
5 4 5 4 6 5 4 3 4 5 5 4
9 10 10.4 8.5 10.2 9.2 11.1 8 9.4 9 10 9.9
6 4 5 5 5 5 5 5 5 5 5 5
10 8 9.6 9 9.6 9.7 9 9 9.7 8 10 9
5 4 5 4 6 5 4 3 4 5 5 4
9 8 10.8 8.5 9.5 8 9.5 7 8.3 8.1 8.8 9
5 4 5 4 6 5 4 3 4 5 5 4
11 10 11 10 11.3 9.4 11 9 9.5 8 10 7
4 5 5 4 6 5 4 3 4 5 5 4

I need to accept these values into an array, so I can then get the largest number out of every other line, and the lowest out of the other lines.
Say I make an array
float array[20][12];

This doesn't seem to work:
fscanf(ifp, "%f", &main_array[20][12]);
So how can I accept these values into my array?
Comment: if your file is a text file, you have to go over it line by line and over every element in line and scan them into a proper array entry.
Answer: you need to read value by value, using a loop, you could make something like this:
float array[20][12];
int n = 20 * 12;
int i;
for(i = 0; i < n; i++)
    fscanf(ifp, "%f", (&array[0][0] + i));

That's because you cannot read all file at once.
Another way, and maybe more easy to understand(because not uses pointer arithmetic) is:
int i, j;
for(i = 0; i < 20; i++)
    for(j = 0; j < 12; j++)
     fscanf(ifp, "%f", &array[i][j]);


What happens at the server when a request is made and client quits immediately?

Question: I would like to know what would happen if I have a code like that in a php page doit.php:
$url="http://someServer.com/somepage.php";

$i=10;
while($i--){
getDataFromAnotherServer($url);
}

now, knowing that function getDataFromAnotherServer() can take up to a second or two...
What would happen if a user is asking for that doit.php and immediately close the browser ?
Would the function still be called 9 times (the loop would reach i==0) or stop somewhere in the middle?
Thanks
Comment: Is it that difficult to just try?
Comment: Do you need it to continue? There's [ignore_user_abort()](http://us3.php.net/manual/en/function.ignore-user-abort.php) if so.
Answer: The script will be aborted (unless there is no attempt to send data to the client during that time). To prevent the script from ending early due to client disconnect, use ignore_user_abort.
More detailed info on PHP connection handling can be found here:
http://www.php.net/manual/en/features.connection-handling.php
Answer: the script would abort. the getDataFromAnotherServer function may take a few seconds im guessing as you don't control the server. this could cause the maximum execution to be reached as well. just something to bare in mind. ignore_user_abort may give the desired result


Prove that $f(x)>0$ near $x=0$

Question: Given that $f(x) \in C^{5}$ and $$ f(0)=f'(0)=f''(0)=f^{(3)}(0)=f^{(4)}(0)=0 $$ $$f^{(5)}(0)>0 $$
Prove that $$f(x)>0$$ near $x>0$
I know that this can be proved with Taylor's expansion, but can it be proved using the definition of the derivative and the Mean value theorem by proving that $f^{(4)}(x)>0$ near $x>0$ and so on with the rest of the derivatives?
Comment: First you need to copy the problem correctly. Your "Prove that in $f(x)>0$ near $x>0$" makes no sense - what the problem asked was "Prove that $f(x)>0$ for $x>0$ near $0$". Yes, this can be done very easily by MVT, exactly as the hint for the problem says. What do you get when you attempt to apply MVT to deduce something about $f^{(4)}(x)$ for $x>0$ near $0$? (Two hints: $f^{(5)}$ is the derivative of $f^{(4)}$, and you're given that $f^{(5)}$ is continuous, which shows that $f^{(5)}>0$ for $x>0$ near $0$.)
Comment: Hmm. I figured English was not your native language, but I assumed you'd been given the problem in English (in which case simply copying it correctly would be good to help with the English). The idea that it was your own English translation hadn't occurred to me - if it had I wouldn't have been so snarky. Sorry. (I leave it as an exercise to figure out what "snarky" means...)
Comment: @DavidC.Ullrich Yup edited. I translated it from my language.. I'm a bit weak with this English mathematics!
Comment: @DavidC.Ullrich I really wonder how you come that using MVT was given as a hint for this problem. I don't like the tone of your comment, even though you apologized.
Comment: @wythagoras Seems pretty clear. Because the solution using MVT is so utterly trivial. I can imagine the OP being given a hint to use MVT and not seeing how it applied. But that would indicate that he hadn't really internalized MVT sufficiently; I can't imagine him understanding MVT well enough to conjecture on his own that it might apply without also seeing _how_ it applies.
Answer: Since $f$ is $C^5$, $f^5$ is continuous and, therefore, $> 0$ on a neighbourhood of $0$.
From there, you can use the mean value theorem, or simply integrate $f^5$ around 0, and repeat.
Comment: Thank you for giving me relief! I have the full solution for this question.. If needed by someone I will post it.
Cheers.
Comment: @SijaanHallak It is a good idea to post your solution, so that others who visit the question can also see the full solution.

Prove that $f(x)>0$ near $x=0$


ImportError: 'useNavigate' is not exported from 'react-router-dom'

Question: When trying to import useNavigate from react-router-dom, I get the following error:
Attempted import error: 'useNavigate' is not exported from 'react-router-dom'.

My Import statement:
import { useNavigate } from 'react-router-dom';

Comment: which doc are you referring ? [react router dom](https://reactrouter.com/web/api/Hooks) or [react router dom github](https://github.com/ReactTraining/react-router/tree/master/packages/react-router-dom). Neither of them are having `useNavigate`. What are you trying to achieve ?
Comment: @SagarMore i am trying to navigate to the next screen
Comment: @SagarMore documentation:``` In v6, this app should be rewritten to use the navigate API. Most of the time this means changing useHistory to useNavigate and changing the history.push or history.replace callsite.

// This is a React Router v6 app
import { useNavigate } from 'react-router-dom';

function App() {
  let navigate = useNavigate();
  function handleClick() {
    navigate('/home')
  }
  return (

go home

  );
}```
Comment: i guess then, you might have to check if you have installed/using correct version of react-router-dom. Have you installed using this ?

`npm install react-router-dom@next`
Answer: You are trying to use the latest features of react-router.
Please make sure that you installed the email@example.com .

It is React Router v6 which gives you a useNavigate hook

Please refer here for further reading from the React Router team
Two quick ways to check the version:

Verify from the package.json file
Run npm list --depth=0 to view the various packages in your project
Answer: If you're using react router v5 you can use useHistory.
import { useHistory } from "react-router-dom";

use:
history.push('/your-component')

Answer: I faced issue as like this: "useNavigate is not exported from 'react-router-dom"
My solution  - I uninstalled the react-router-dom and I have reinstalled it... now this issue is resolved for me..


In iOS 15, 'throwing -10878' occurs many times when connecting AVAudioPlayerNode to mainMixerNode

Question: I encountered a problem when executing the following code on iOS 15. This occurs on both a simulator and a real device. In addition, this doesn't occur on iOS 14.
import AVFoundation

class MyAudio {
    let audioEngine: AVAudioEngine
    let audioFile: AVAudioFile
    let playerNode: AVAudioPlayerNode

    init() {
        audioFile = try! AVAudioFile(forReading: Bundle.main.url(forResource: "sound", withExtension: "mp3")!)
        audioEngine = AVAudioEngine()
        playerNode = AVAudioPlayerNode()
        audioEngine.attach(playerNode)
        audioEngine.connect(playerNode, to: audioEngine.mainMixerNode, format: audioFile.processingFormat)

        do {
            try audioEngine.start()
            playerNode.play()
        } catch {
            print(error.localizedDescription)
        }
    }
}

It will print these outputs.
2021-10-02 17:29:14.534934+0900 audio-sample-2021-10-02[11337:353838] throwing -10878
2021-10-02 17:29:14.537588+0900 audio-sample-2021-10-02[11337:353838] throwing -10878
2021-10-02 17:29:14.537895+0900 audio-sample-2021-10-02[11337:353838] throwing -10878
2021-10-02 17:29:14.538194+0900 audio-sample-2021-10-02[11337:353838] throwing -10878
2021-10-02 17:29:14.538512+0900 audio-sample-2021-10-02[11337:353838] throwing -10878
2021-10-02 17:29:14.538822+0900 audio-sample-2021-10-02[11337:353838] throwing -10878
2021-10-02 17:29:14.539127+0900 audio-sample-2021-10-02[11337:353838] throwing -10878
2021-10-02 17:29:14.539434+0900 audio-sample-2021-10-02[11337:353838] throwing -10878
2021-10-02 17:29:14.539789+0900 audio-sample-2021-10-02[11337:353838] throwing -10878

Although these errors occur, the sounds can be played without any crashes. However, it consumes a lot of time for initializing than usual. Is there any way for resolving this problem?
Comment: My app has this problem as well since iOS 15. It seems this error is thrown by AUComponent and means "kAudioUnitErr_InvalidParameter": https://johnnn.tech/q/getting-errors-when-running-ar-app-template-in-xcode/ I also have no initial crashes BUT my app also uses RealityKit which then complains that there is basically not enough performance for it to run properly, and I assume these two issues are connected. Very frustrating as I had no problems with iOS 14… :/
Comment: Does this answer your question? [Getting "throwing -10878" when adding a source to a mixer](https://stackoverflow.com/questions/69206206/getting-throwing-10878-when-adding-a-source-to-a-mixer)
Comment: on macOS at least this is actually thrown at the attach(node)
Answer: To fix this issue change to:
audioEngine.connect(playerNode, to: audioEngine.outputNode, format: audioFile.processingFormat)

Comment: Any idea why this works, and more importantly what do you do if you you actually want to connect multiple nodes to the mixer?


using a gre tunnel as default route

Question: I have two private networks (A, B) that connects via another company's private network (C). Network A has internet access. I want to make a tunnel between B and A that goes through C. Then network B will use A as default route for internet access.
Network A: 10.20.0.0/24, on C: 10.10.15.3
Network B: 10.20.1.0/24, on C: 192.168.25.3
10.10.15.3 can access 192.168.25.3 and vice versa
Network A tunnel script:

ip tunnel add tunnel0 mode gre local 10.10.15.3 remote 192.168.25.3 ttl 64
  ip link set tunnel0 up
  ip addr add 10.20.200.1/30 peer 10.20.200.2/30 dev tunnel0
  ip route add 10.20.1.0/24 via 10.20.200.2

Network B tunnel:

ip tunnel add tunnel0 mode gre local 192.168.25.3 remote 10.10.15.3 ttl 64
  ip link set tunnel0 up
  ip addr add 10.20.200.2/30 peer 10.20.200.1/30 dev tunnel0
  ip route add 10.20.0.0/24 via 10.20.200.1
  ip r d default && ip r a default via 10.20.200.1

From GW on network B:

traceroute to 10.20.0.1 (10.20.0.1), 30 hops max, 38 byte packets
   1  10.20.0.1 (10.20.0.1)  4.685 ms  4.505 ms  4.478 ms
traceroute to 10.20.0.14 (10.20.0.14), 30 hops max, 38 byte packets
   1  10.20.200.1 (10.20.200.1)  4.643 ms  4.387 ms  4.555 ms
   2  10.20.200.1 (10.20.200.1)  4.423 ms  4.473 ms  4.437 ms
traceroute to 220.127.116.11 (22.214.171.124), 30 hops max, 38 byte packets
   1  10.20.200.1 (10.20.200.1)  4.595 ms  4.461 ms  4.628 ms
   2  10.20.200.1 (10.20.200.1)  4.476 ms  4.521 ms  4.536 ms

something's not right.... but why?
Comment: No, but I can set the default route via the tunnel since 10.10.15.3 and 192.168.25.3 talks directly to each other via the bridge.
Comment: You cannot allow a tunnel to become the route to its own destination or the tunnel implodes.
Answer: lol
I forgot to accept FORWARD by default on 10.10.15.3 :(

using a gre tunnel as default route


Initialization order of static readonly field

Question: I'm curious of the C# spec says anything about the order of initializing static field's in C# 5 (.net4).  For instance:
public class Test
{
   public static readonly string A = "hi";
   public static readonly string B = "bye";
   public static readonly string DEFAULT = A;
}

In testing (Mono 2.x) they seem to be initialized in the order they appear in code.  eg. As is, DEFAULT will have the value "hi", but if I move the definition for DEFAULT above A and B, it will be assigned NULL because A hasn't been assigned yet.
Is there a guarantee that the variables are initialized in order? Or is it up to the compiler?
Thanks.
Answer: It is in the order that they appear in. See here.

The static field variable initializers of a class correspond to a
  sequence of assignments that are executed in the textual order in
  which they appear in the class declaration.

Also, when you have a static constructor:

If a static constructor (Section 10.11) exists in the class,
  execution of the static field initializers occurs immediately prior to
  executing that static constructor. Otherwise, the static field
  initializers are executed at an implementation-dependent time prior to
  the first use of a static field of that class.


shortest distance between points avoiding eclipse

Question: What is the shortest path between two points (-3,0) and (3,0) that avoids the interior of the ellipse $\frac{x^2}{2}+\frac{y^2}{1}=1$
I should use the maximum principle for state constraints, but I have a problem with the part where the path touches ellipse on some time interval? I know it should be a straight line away from the obstacle.
Comment: It's [ellipse](https://en.wikipedia.org/wiki/Ellipse), not [eclipse](https://en.wikipedia.org/wiki/Eclipse).
Comment: There is *no* shortest path that avoids the ellipse $\ \frac{x^2}{2}+y^2=1\ $.  Do you mean the shortest path that avoids *its interior* $\ \frac{x^2}{2}+y^2<1\ $?
Comment: Yes, its interior
Answer: The shortest path from the point $\ (-3,0)\ $ to the point $\ (3,0)\ $  within the set $\ \left\{(x,y)\,\left|\,x^2+2y^2\ge2\right.\right\}\ $ comprises a straight line from the point $\ (-3,0)\ $ to the ellipse, and tangent to it at the point where they meet, a segment of the ellipse from that point to its reflection in the $\ y$-axis, and the straight line from the latter point to the point $\ (3,0)\ $.  There are two such paths, illustrated in red and green in the diagram below. While this is intuitively obvious, and I'm sure it's true, I'm not aware of any succinct way of proving it.  If you're willing to accept it as established, however, here's a way of finding the coordinates of the points where the lines from $\ (-3,0)\ $ are tangent to the ellipse.
Let $\ (a,b)\ $ be the coordinates of the point where the red line from $\ (-3,0)\ $ meets the ellipse.  Then $\ b>0\ $, and the coordinates where the green line from $\ (-3,0)\ $ meets the ellipse will be $\ (a,-b)\ $, by symmetry.  For the red line to be tangent to the ellipse at $\ (a,b)\ $, its slope must be the same as that of the ellipse at that point. The slope of the line is
$$
\frac{b}{a+3}\ ,
$$
and the slope of the ellipse is its derivative $\ \frac{dy}{dx}\ $ at the point in question.  Differentiating the equation of the ellipse gives
$$
0=x+2y\frac{dy}{dx}=a+2b\frac{dy}{dx}\ ,\ \text{  or}\\
\frac{dy}{dx}=-\frac{a}{2b}
$$
at the point $\ (a,b)\ $.  Equating this to the slope of the line gives
\begin{align}
\frac{b}{a+3}&=-\frac{a}{2b}\ ,\ \text{  or}\\
2b^2&=-a^2-3a\\
&=2-a^2\ ,
\end{align}
because the point $\ (a,b)\ $ lies on the ellipse.  It follows from this last equation that $\ a=-\frac{2}{3}\ $, and then $\ b=\frac{\sqrt{7}}{3}\ $.
The equation of the line segment from the point $\ (-3,0)\ $ to the point $\ \left(-\frac{2}{3}, \frac{\sqrt{7}}{3}\right)\ $ is
$$
y=\frac{x+3}{\sqrt{7}}\ .
$$
The reflection of the point $\ \left(-\frac{2}{3}, \frac{\sqrt{7}}{3}\right)\ $ in the $\ y$-axis is $\ \left(\frac{2}{3}, \frac{\sqrt{7}}{3}\right)\ $, and the equation of the line segment from that point to the point $\ (3,0)\ $ is
$$
y=\frac{3-x}{\sqrt{7}}\ .
$$

As TonyK has pointed out in a comment, the length of the elliptical part of these paths cannot be expressed in terms of elementary functions of the coordinates of its end points and the parameters of the ellipse. Its length is given by
\begin{align}
\int_{-\frac{2}{3}}^\frac{2}{3}\sqrt{1+\left(\frac{dy}{dx}\right)^2}\,dx&=2\int_0^\frac{2}{3}\sqrt{1+\frac{x^2}{4y^2}}\,dx\\
&=2\int_0^\frac{2}{3}\sqrt{\frac{1-\frac{x^2}{4}}{1-\frac{x^2}{2}}}\,dx\\
&=2\int_0^\frac{2}{3}\sqrt{\frac{1-\frac{1}{2}\left(\frac{x}{\sqrt{2}}\right)^2}{1-\left(\frac{x}{\sqrt{2}}\right)^2}}\,dx\\
&=2\sqrt{2}\int_0^\frac{\sqrt{2}}{3}\sqrt{\frac{1-\frac{t^2}{2}}{1-t^2}}\,dt\\
&=2\sqrt{2}E\left(\arcsin\left(\frac{\sqrt{2}}{3}\right)\,\left|\,\frac{1}{\sqrt{2}}\right.\right)\ ,
\end{align}
where $\ E(\,\cdot\,|\,\cdot\,)\ $ is the incomplete elliptic integral of the second kind.  The length of the straight line from $\ (-3,0)\ $ to $\ \left(-\frac{2}{3}, \frac{\sqrt{7}}{3}\right)\ $ is
$$
\sqrt{\left(3-\frac{2}{3}\right)^2+\frac{7}{9}}=\frac{2\sqrt{14}}{3}\ ,
$$
so the shortest distance is
$$
\frac{4\sqrt{14}}{3}+2\sqrt{2}E\left(\arcsin\left(\frac{\sqrt{2}}{3}\right)\,\left|\,\frac{1}{\sqrt{2}}\right.\right)\ ,
$$
for which WolframAlfa gives the approximation
$$
6.33877741851728513700827575564\ .
$$
Comment: This answers the question ("What is the shortest path?"). But the OP may be interested to know that the _length_ of this shortest path can't be expressed explicitly, containing as it does an arc of an ellipse.
Comment: No, not, at least, as an elementary function of the coordinates of the end points of the arc of the ellipse and the ellipse's parameters.  The length of the arc of the ellipse can,  however, be expressed in terms of an [incomplete elliptic integral of the second kind](https://en.wikipedia.org/wiki/Elliptic_integral#Incomplete_elliptic_integral_of_the_second_kind). The expression is a little tedious to derive, and I don't think it would be particularly informative, but if the OP wants it, I'm willing to add it to my answer.
Comment: When you say the arc length can be expressed in terms of an elliptic integral, you are putting the cart before the horse. The elliptic integral is _defined_ as the arc length.
Comment: In any case, I've now added the derivation to my answer.


Duration of follow-up in staggered entry survival designs

Question: Suppose a clinical trial recruits $n$ patients and follows them for a maximum of $t$ years for a time-to-event outcome, like death. The objective is to find the expected number of person-years follow-up for these patients accounting for the event process. Obviously, if no events, then the person years follow is $nt$.
If the distribution of the event process $F$ is exponential with rate parameter $\theta$, I find I can agree with simulated results using $$\sum_{i=1}^nF^{-1}(i/(n+1)$$
where $F^{-1}(i/(n+1)$ is the expected event time for the $i$-th order statistic.
However, I'm a little puzzled how to adapt this for a "ramp-up" design. This is where the the patients are recruited over a fixed interval $r < t$. If we assume a triangular entry, and no events occur, then it's straightforward to calculate the expected person-years follow-up as $n(t-r)+nr/2$.

Is there a convenient closed form expression for the expected person-years follow-up when the study entry is triangular over a ramp up period?
Answer: Happily, as a probability problem, the calculation is relatively straightforward.
For a triangular ramp up, the maximum observation time $u_i$ is given by
$$u_i = r ((n-i)/n) + t; \quad i = 1, 2, \ldots, n$$
where $i$ denotes order of entry into the cohort.
Therefore the chances of being included in the sample as an event is given by $F(u_i)$ and the expected number of deaths in the sample at follow-up is $d = \sum_{i=1}^n F(u_i)$. The sample median $\hat{M}$ for a survival sample with censored observations is given by:
$$ \hat{M} = \log(2) \sum_i^n{\text{Event Times}_i}/d.$$
So one can easily input the median for sample median and multiply by number of deaths, dividing by $\log(2)$ to obtain the cumulative follow-up.


how can you count number of digits used in numbers from -2^127 to (2^(127) - 1)

Question: There are numbers from -2^127 to (2^127)-1.
I want to count the number of digits used in all the numbers.
For example
If I have numbers from -100 to 100
then number of digits used is $2*(1*9 + 2*90 + 3*1) + 1$ (including 0 only once)
9 numbers having 1 digit.
90 numbers having 2 digits.
1 number having 3 digits.
but same for all -100 to 0 numbers therefore double the answer
and we forgot the 0 so $+ 1$.
Comment: It goes just the same way, just a lot longer. And the last *group* of powers of ten is incomplete. You can convert this into a weird iincomplete Arithmetic-Geometric Progression, i think. But that wouldn't go much nicer.
Comment: @chubakueno Any shorter method ?
Comment: Wouldn't there be 90 two digit numbers? You would have a truncated $\sum_{n=0}^{}9(n+1)10^n$ Actually that we
Answer: [There are 90 two-digit positive integers, not 89.]
Note that $38<\log_{10}(2^{127}-1)<39$, so $2^{127}$ has 39 digits. Then the number of digits in numbers from $1$ to $2^{127}-1$ is $$d=1\cdot9+2\cdot90+3\cdot900+\cdots+38\cdot9\cdot{10}^{37}+39\cdot(2^{127}-10^{38}),$$
and the number of digits used in the numbers from $-2^{127}$ to $2^{127}-1$ is therefore $2d+2=13048790087694377852849387467616738024564$.
If each digit weighs one microgram, this is several times the mass of the sun.
Comment: Count them: 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99. There are 90. It's easy to see there must be an even number, because they go even, odd, even, odd, ... even, odd.
Comment: Yup. We could factor the $9$ and do this as an artithmetic-geometric series sum and correct the last truncated term, but I don't know if that would be worthy.
Comment: @MukulKumar you are counting [10-99] **inclusive** . This is a common confusion , is called the [fencepost problem](http://en.m.wikipedia.org/wiki/Off-by-one_error) :)
Comment: Oh, yes Now I got it So there are actually 101 numbers! not 100. @chubakueno The confusion was never there in my mind (fencepost problem), but I thought that there are 100 numbers from 0 - 100 but there are 101 numbers!
Comment: @MukulKumar *That* is the fencepost problem! It happens often, even more when programming languages with  0-indexed arrays, trust me :)
Comment: @chubakueno Curse my brain for using shortcuts! (saw on TV that brain uses shortcuts to provide answers which are wrong some-tines)


Meaning of two arrows below the limit sign

Question: I have the following expression whose precise meaning I am trying to decipher:

where the first term is a function of both $n$ and $t$, where as the second is only of $t$. I would like to know precisely what the limit with the two arrows bellow means.
Could someone give me a precise analysis definition of this?
EDIT: Here is the statement and proof
Comment: If "the first term is a function of both n and t, it should be written $y_n(t)$, not just $y_n.$ Alternatively, you should put parenthesis around $y_n-y.$
Comment: If so, could you please give some more context, so that we can "repair" (and explain) this formula?
Comment: By "more context" we mean please [edit] the question to show us enough of the surrounding text.
Comment: I have added the whole statement and the proof. Some of the notation I bealive is standard but if that is also required, I can be found at https://dec41.user.srcf.net/notes/IB_L/numerical_analysis.pdf from page 27 onwards.
Comment: Another problem is that $h$ appears (twice) below the $\lim$ sign, but nowhere in your function.
Comment: Apologies but this is not my work. I took the screenshot from a collection of notes. I am trying to understand what the author meant.
Comment: Of course. The context is Numerical Analysis and this is part of a theorem for the convergence of the Euler Method.
Answer: Since
$$y_{n+1}=y_n+hf(t_n,y_n)\quad\text{and}\quad t_n=nh,$$
$y_n$ depends on $n$ but also (implicitely) on $h$ (but not on any $t$).
The two conditions $h\to0,nh\to t$ are redundant.
$nh\to t$ (as $n\to\infty$) is sufficient.
The $\epsilon-\delta$ translation of this limit is:
$$\forall\epsilon>0\quad\exists N\in\Bbb N,\exists\delta>0\quad\forall n\ge N,\forall h\in\left[\frac{t-\delta}n,\frac{t+\delta}n\right]\quad|y_n-y(t)|<\epsilon.$$
Comment: Hi. So one lets $nh$ be a constant at takes the limit as $n$ tends to infinity?
Comment: No, $nh$ is not constant. $n$ tends to $\infty$ and $hn\to t$ (so $h\sim\frac tn\to0$). If you prefer: let $y_n=Y(n,h)$ one takes $\lim_{n\to\infty,k\to t}(Y(n,k/n)-y(t)).$
Comment: At least, that is what is claimed in the (i) statement of the theorem. But it seems the author is cheating in the proof and only does what you write, i.e. he takes $t=t_n=nh.$
Comment: I apologise but I do not follow. Could you give the epsilon-delta version of the statement instead?


Running apache2 and tomcat6 on port 80

Question: I have apache2 and tomcat6 installed on ubuntu 9.10. By default tomcat6 port no is 8080.
I want to run tomcat and apache on port 80. For tomcat virtual hosting it should navigate to tomcat webapps and for apache it should direct to var/www.
Plz any one give me step by step guide to achive this.
Thank you!
I made tomcat to run on port 80 with mod_jk module installation.
Is it possible to run tomcat on port 80 and as well as on 8080?. Because I'm using "Application Manager" monitoring tool and I have to monitor tomcat. It requires tomcat to be running on any port. As I did port forwarding(mod_kj), when I try to specify the tomcat port to get it monitored, I'm getting the error "Service is not running" on that port. I tried the ports 80,8080,8009... checking in the server.xml file.
Answer: Read more about mod_proxy_ajp or mod_jk. One of these modules will help you to have tomcat apps served by apache.
You cannot have two services on the same port, unless, you bind the services to different IPs.
Assuming you have two IPs you bind apache on first IP port 80 and tomcat on the second.
The easiest is using apache modules. Search for tomcat and apache configs that meet your needs.
HTH
Comment: Thank you I have both apache and tomcat running on port 80. I need help on how to use tomcat6-admin- "manager webapps" and "host-manager webapps" on the browser. With manager webapps on the browser I could deploy my .war file to /var/lib/tomcat6/webapps. Is it possible to deploy to remote server from my local 'manager webapps' page.
Comment: All you need to know is here: http://tomcat.apache.org/tomcat-6.0-doc/manager-howto.html.
Answer: This article, even though it is dated, might be of some help:
http://tomcat.apache.org/tomcat-3.2-doc/tomcat-apache-howto.html
I think the key there is to install a web-server adapter.
Comment: You could simply link to the current how to: http://tomcat.apache.org/connectors-doc/webserver_howto/apache.html
Answer: I solve this problem with nginx.
See: http://nginx.org/en/docs/howto_setup_development_environment_on_ec2.html
and: http://www.yanaga.com.br/2012/02/utilizando-o-iptables-ou-ngninx-para.html (pt BR)
Comment: Welcome to serverfault. It's usually a encouraged to make your answer so they include details in addition to just links. If the link goes away then your answer becomes useless. Please add some of the details.

Running apache2 and tomcat6 on port 80


Fermat's Last Theorem Resources

Question: Are there any resources which describe FLT in a very tangible way which will motivate students to be interested in this subject?
Comment: You mean,  a very large margin?
Comment: @matqkks: You might want to review https://matheducators.stackexchange.com/questions/12226/what-is-most-motivating-way-to-introduce-fermats-little-theorem.
Comment: I like Paulo Ribenboim's books.  One is "Fermat's Last Theorem for Amateurs."  Another is "13 Lectures."  He writes concisely but somehow kindly.
Answer: Leo Corry had written a reasonably concise note on the Fermat's last theorem (including some historical anecdotes). I found it as a very interesting read. Since, the question included 'motivation' as an aspect, one thing that will help is to introduce the history and drama associated with it. This draft surely will be a helpful one, in that regards.
https://www.tau.ac.il/~corry/publications/articles/pdf/Fermat-History.pdf
Answer:
Fermat's Enigma: The Epic Quest to Solve the World's Greatest Mathematical Problem
I recommend this book based on my personal experience. When you start reading it, it's almost impossible to put it down.
Answer: About ten years ago I wrote a monograph directed at students with a high school competency. It goes through many proofs of intermediate results that preceded the Wiles proof, but no higher analysis. It focuses on the mathematics, and not the history. I don't know whether it is still in print. See:
https://www.amazon.com/Conversations-Fermat-Keith-Backman/dp/158909445X

Fermat's Last Theorem Resources


What are best practices for choosing the beta for an F-measure score?

Question: There's some discussion on what F-measure means. I understand that the beta parameter determines the weight of recall in the combined score. In specific one answer states that "for good models using the $F_{\beta}$ implies you consider false negatives $\beta^2$ times more costly than false positives." beta < 1 lends more weight to precision, while beta > 1 favors recall (beta -> 0 considers only precision, beta -> +inf only recall).
If you want to weight precision or recall higher than the other, how do you decide on the beta? I'm a bit unclear on the math behind the F-measure, so does a beta = .5 mean that precision is weighted 2x as much as recall?
Comment: From $\beta^2$, $\beta=0.5$ would suggest that precision would be weighted 4 times as much as recall,  at least according to the one answer cited.
Answer: Don't use F scores at all. Every criticism of accuracy collected at Why is accuracy not the best measure for assessing classification models? applies completely equally to precision, recall and all F scores. Instead, use proper scoring rules.
Comment: I have a sneaking suspicion that there's additional concern with F-scores because they combine conditional probabilities with very different condition: Would you care to have a look at the last part of https://stats.stackexchange.com/a/99921/4598 and let me know what you think of that?
Comment: I completely share your concerns about proper scoring rules, but it is possible to derive quadratic errors analogously to Brier's score that capture certain aspects of predictive behaviour like sensitivity, specificity or the predictive values (and in consequence, also an analogoue to the F-measures). They have the continuous behaviour and favorable variance properties of Brier's score/MSE, but are not themselves proper scoring rules since they focus on subgroups of cases. They can be combined, though (e.g. into Brier's score). Paper: http://arxiv.org/abs/1301.0264
Comment: ... I thus feel like the improper scoring aspect could be repaired. One may argue that they belong more to the decision aspect than the probability density prediction. Still I think it may be sensible to (even outside the application scenario we discuss in the paper) to have metrics at hand for the decision stage that use a closely related metric to what was used before.