text:
Q: Asp.Net Identity Claims Table Not Created Did I mess up the normal table creation by implementing my own mapping to the our existing user table? When running the application the normal AspNet tables are not generated in the database.
I was able to figure out how to map the AspNetUsers table to our existing table in our database using the following code:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<ApplicationUser>().ToTable("DBUser");

        var entity = modelBuilder.Entity<ApplicationUser>();

        entity.HasKey(x => x.UserID);
        entity.Ignore(x => x.Id);
        entity.Ignore(x => x.PhoneNumber);
        entity.Ignore(x => x.PhoneNumberConfirmed);
        entity.Ignore(x => x.EmailConfirmed);
        entity.Ignore(x => x.LockoutEnabled);
        entity.Ignore(x => x.LockoutEndDateUtc);
        entity.Ignore(x => x.PhoneNumber);
        entity.Ignore(x => x.PhoneNumberConfirmed);
        entity.Ignore(x => x.SecurityStamp);
        entity.Ignore(x => x.TwoFactorEnabled);
        entity.Ignore(x => x.AccessFailedCount);

        entity.Property(x => x.UserID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
        entity.Property(x => x.PasswordHash).HasColumnName("Password");
}

However, when I run the application and register a user for the first time, the normally created AspNet prefixed tables like UserClaims, UserLogins, UserRoles, and Roles are not created for some reason, and it does insert a record into my DBUser table with the correct information.
Since I'm using an existing database, should I assume that I need to manually create these tables?
Any help with this would be greatly appreciated.


text:
Q: Wishlist - Add all to cart goes to 404 page instead When I click "Add All to Cart" on the wishlist page, I get a 404 error and the address in the bar is http://www.blahblahblah.com/wishlist/index/allcart/. The items are not added to cart.
A slightly different error occurs if I "Add all to Cart" from the share wishlist email, it then just goes straight to homepage.
I am using Magento CE v1.9.1.0 with unchanged version of /template/wishlist/view.phtml and have not changed any core files.
It looks like it's getting the wrong url?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Proper way of getting rows since a date accounting for DST? I have a datetime column, changedate, that I need to use to get rows that have changed in the last week since 1PM. This column is unfortunately in local time (EST). The server is Microsoft SQL Server 2016.
Here is the query I have now:
DECLARE @since datetime = DATEADD(week,-1,SMALLDATETIMEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), DAY(GETDATE()), 13, 0)) AT TIME ZONE 'Eastern Standard Time'
SELECT * FROM table WHERE changedate AT TIME ZONE 'Eastern Standard Time' >= @since

Since I'm using AT TIME ZONE for both the column and @since, will this properly account for DST changes? That's my understanding per the documentation I've found, but I'm not 100% sure if that's how it works or if I'm missing something.

A: First, figure out the time you're wanting to compare against:
-- Get the current date in the given time zone
DECLARE @today date = convert(date, sysdatetimeoffset() AT TIME ZONE 'Eastern Standard Time')

-- Get the date one week ago
DECLARE @dateOneWeekAgo date = DATEADD(week, -1, @today)

-- Join the date with the desired time (local to the same time zone)
DECLARE @since datetime = convert(datetime, @dateOneWeekAgo) + convert(datetime, timefromparts(1, 0, 0, 0, 0))

Then just compare it:
SELECT * FROM table WHERE changedate >= @since

That assumes your changedate field is a datetime or datetime2.  If it's a datetimeoffset, you should first convert the target value to a datetimeoffset in the same time zone and use that instead:
DECLARE @sinceDTO datetimeoffset = @since AT TIME ZONE 'Eastern Standard Time'

Regarding the approach you gave in the question, there two issues:

*

*getdate() gives the time based on the server's local time zone.  It's possible that it's not the same day in Eastern Time.

*You should never apply a function (whether an intrinsic like AT TIME ZONE or something else) against a table field in a where clause, because it makes the query non-sargable.  In other words, SQL would have to scan the entire table, rather than using an index.  The bigger the table, the slower the query would take.


text:
Q: Get the indices of the first and last rows and columns containing non-masked values in a numpy 2D array With a 2D masked array in Python, what would be the best way to get the index of the first and last rows and columns containing a non-masked value?
import numpy as np
a = np.reshape(range(30), (6,5))
amask = np.array([[True, True, False, True, True],
                  [True, False, False, True, True],
                  [True, True, True, False, True],
                  [True, False, False, False, True],
                  [True, True, True, False, True],
                  [True, True, True, True, True]])
a = np.ma.masked_array(a, amask)
print a
# [[-- -- 2 -- --]
#  [-- 6 7 -- --]
#  [-- -- -- 13 --]
#  [-- 16 17 18 --]
#  [-- -- -- 23 --]
#  [-- -- -- -- --]]

In this example, I would like to obtain:

*

*(0, 4) for axis 0 (since the first row with unmasked value(s) is 0 and the last one is 4; the 6th row (row 5) only contains masked values)

*(1, 3) for axis 1 (since the first column with unmasked value(s) is 1 and the last one is 3 (the 1st and 5th columns only contain masked values)).

[I thought about maybe combining numpy.ma.flatnotmasked_edges and numpy.apply_along_axis, without any success...]

A: IIUC you can do:
d = amask==False #First know which array values are masked
rows,columns = np.where(d) #Get the positions of row and column of masked values

rows.sort() #sort the row values
columns.sort() #sort the column values

print('Row values :',(rows[0],rows[-1])) #print the first and last rows
print('Column values :',(columns[0],columns[-1])) #print the first and last columns

Row values : (0, 4)
Column values : (1, 3)

Or
rows, columns = np.nonzero(~a.mask)
print('Row values :',(rows.min(), rows.max())) #print the min and max rows
print('Column values :',(columns.min(), columns.max())) #print the min and max columns

Row values : (0, 4)
Column values : (1, 3)

A: Here's one based on argmax -
# Get mask for any data along axis=0,1 separately
m0 = a.all(axis=0)
m1 = a.all(axis=1)

# Use argmax to get first and last non-zero indices along axis=0,1 separately
axis0_out = m1.argmax(), a.shape[0] - m1[::-1].argmax() - 1
axis1_out = m0.argmax(), a.shape[1] - m0[::-1].argmax() - 1


text:
Q: How to join get results per day without looping in stored procedure I am so sorry. I did not ask the question correctly. So here it is again:
I have a table containing number of posts, their destinations and their retrieval dates. What I want to do is for a date range and for each date in the range, find the latest number of posts for each destination that is earlier than the date. This needs to be done in a stored procedure and not looping through the date range. Is it possible? Thanks.
For example:
Destination  RetrievalDate       NumberOfPosts
-----------  ------------------  -------------
A            11/1/2011 12:00 AM  1
A            11/1/2011 1:00 AM   5
A            11/1/2011 5:00 AM   6
B            11/1/2011 12:00 AM  0
B            11/1/2011  4:00 AM  2
C            10/20/2011 5:00PM   1
A            11/2/2011 12:00 AM  8
A            11/2/2011 2:00 AM   9
B            11/2/2011 12AM      3

For example, in the above table, if the date range is 11/1/2011 - 11/3/2011, I would get
Destination  ReportDate  NumberOfPosts
-----------  ----------  -------------
A            11/1/2011   6
B            11/1/2011   2
C            11/1/2011   1
A            11/2/2011   9
B            11/2/2011   3
C            11/2/2011   1
A            11/3/2011   9
B            11/3/2011   3
C            11/3/2011   1

A: Following your edit you can use
declare @start date = '20111101'
declare @end date = '20111103';

WITH Dates(D)
     AS (SELECT @start
         UNION ALL
         SELECT DATEADD(DAY, 1, D)
         FROM   Dates
         WHERE  DATEADD(DAY, 1, D) <= @end),
     Destinations
     As (SELECT DISTINCT Destination
         FROM   YourTable)
SELECT CA.Destination,
       CA.[Number of posts],
       dt.D AS ReportDate
FROM   Destinations dst
       CROSS JOIN Dates dt
       CROSS APPLY (SELECT TOP 1 *
                    FROM   YourTable y
                    WHERE  dst.Destination = y.Destination
                           AND y.[Retrieval Date] <= DATEADD(DAY, 1, dt.D)
                    ORDER  BY y.[Retrieval Date] DESC) CA

Ideally you would substitute another table listing the distinct destinations rather than using the CTE one built from the main table.


text:
Q: In an ASP.NET View, how do I access my Model's values in Razor and assign it to a variable? In my view I have
@model Models.ViewModel.MyViewModel

I can get the values displayed with the Html.DisplayNameFor(model => model.my_id) method.  This works fine.
But I cannot get the value of a field in the model by doing anything like
int id = model.my_id;

Every time I use "model," Visual Studio cannot find a reference to it.  It does for the Html Helpers, but not when model is not in an Extension method like in the HtmlHelper (I thought it was an Extension Method).
I have tried many variations and various solutions I found on SO.  I am missing something fundamental, but I cannot find the answer of how to get the reference to model and its values.
It is also causing this to fail,
 @Html.ActionLink("Edit", "Edit", new { id = model.my_id })

What am I doing wrong?

A: Use Model with a capital M.
@{
    int id = Model.my_id;
}

@Html.ActionLink("Edit", "Edit", new { id = Model.my_id })


text:
Q: Convert an existing Replica Set In Mongodb to a Sharded Cluster I have a replica set with 3 nodes. Is there a way to convert this existing Replica Set to a Sharded Cluster. Please find below the config file of the replica set:

All of my 3 nodes in replica set have sharding enabled:-
sharding:
  clusterRole: shardsvr

A: sharding is enabled at the database level ....and then implemented at the collection level.   any operating replica set can work in a sharding environment but there wouldn't be a compelling reason to do sharding until you have multiple replica clusters working in parallel...  it's a big decision - no going back...and you need to be very clear on your sharding key....  so definitely invest time in learning the technology at the MongoDB University.


text:
Q: Why doesn't the Welch statistic follow the t-distribution Basing to my previous (still unanswered) question, I'm trying to find what happens when we constructing confidence interval for means difference using Student's t-test (for one or two samples), assuming that variances $\sigma_x^2$ and $\sigma_y^2$ for two populations $X \sim \mathcal{N}(\mu_x, \sigma_x^2)$ and $Y\sim \mathcal{N}(\mu_y, \sigma_y^2)$ are equal, when it really is not.
I know that in this case we simply use Welch t-test and in the bag, but I want to understand reasons of that.
Say we know our differences are equal and want to find confidence interval for means difference. Than with assuming null hypothesis $H_0: \mu_x = \mu_y$ we can just merge two samples into one and find $[\bar{X}_n - t_{\alpha, n-1}\frac{S_n}{\sqrt{n}}, \bar{X}_n + t_{\alpha, n-1}\frac{S_n}{\sqrt{n}}]$, where $S_n$ -- sample variance estimation. However, remember the fact that variances are not equal, so it means we can not perform such a test and need to perform Welch t-test with this statistic:
$$t = \frac{\bar{X}_n - \bar{Y}_m}{\sqrt{\frac{\sigma_x^2}{n} +  \frac{\sigma_y^2}{m} }}.$$
Also I believe we could use Student's t-test for two samples instead of one.
Question is: what problems causes using Student's tests instead of Welch's with $t$-statistic described above? Why exaclty do we need use it?

A:
What problems causes using Student's tests instead of Welch's with
t-statistic described above?

Let's back up a bit and rephrase. By "using Student's tests" what you are really saying is that in the case in which the variances $\sigma_x^2$ and $\sigma_y^2$  are unknown but can be assumed to be equal, a certain statistic $\frac{\bar{X}-\bar{Y}-(\mu_X-\mu_Y)}{S_p \sqrt{\frac{1}{n}+\frac{1}{m}}}$ follows the t-distribution with n+m-2 degrees of freedom ($S_p^2$=$\frac{(n-1)S_X^2+(m-1)S^2_Y}{n+m-2}$ is the pooled variance). That means we know the sampling distribution of this statistic and that is why we can contextualize probabilistically the single realized value of this statistic in our sample ($\bar{X}-\bar{Y}$) and draw an inference from it to the population parameter of interest ($\mu_x-\mu_Y$). Why does $\frac{\bar{X}-\bar{Y}-(\mu_X-\mu_Y)}{S_p \sqrt{\frac{1}{n}+\frac{1}{m}}}$ follow a t-distribution?
$\frac{\bar{X}-\bar{Y}-(\mu_X-\mu_Y)}{S_p \sqrt{\frac{1}{n}+\frac{1}{m}}}$=$\frac{\frac{\bar{X}-\bar{Y}-(\mu_X-\mu_Y)}{\sigma\sqrt{\frac{1}{n}+\frac{1}{m}}}}{{\sqrt{\frac{S_p^2}{\sigma^2}}}}$
The numerator has a standard normal distribution, while the denominator can be shown to have a $\chi^2$ distribution with $n+m-2$ degrees of freedom. Because the numerator and denominator are independent, we conclude (from the definition of the t-distribution) that their ratio is t distributed with $n+m-2$ degrees of freedom. Why does the numerator have the standard normal distribution? Because $\bar{X}-\bar{Y}$ is Normally distributed with mean $\mu_X-\mu_Y$ and variance $\frac{\sigma^2}{n}+\frac{\sigma^2}{m}=\sigma^2(\frac{1}{n}+\frac{1}{m})$. This last equality would not hold if $\sigma_x^2$ and $\sigma_y^2$ are not equal, which means that the $\sigma's$ in the above rightmost fraction do not cancel out; we cannot get from the right expression to the left one (which does not have any $\sigma's$).

So what does that mean?
If the variances $\sigma_x^2$ and $\sigma_y^2$  are unknown and cannot be assumed to be equal, the statistic $\frac{\bar{X}-\bar{Y}-(\mu_X-\mu_Y)}{S_p \sqrt{\frac{1}{n}+\frac{1}{m}}}$ does not follows the t-distribution. Can we find another statistic that has a well-behaved sampling distribution, maybe even one we've already catalogued? We've been unsuccessful at it thus far and not for the lack of trying. It is known as the Behrens-Fisher problem. B.L. Welch came up with an approximate solution: the Welch statistic. The Welch statistic is approximately distributed as a $t$ random variable. Why approximately distributed and not exactly distributed? Because the Welch statistic is the ratio of a standard normal random variable and a variable that is not exactly but only approximately $\chi^2$ distributed.

A: At the very end of your long question, you get around to the point, asking why not go ahead and use the two-sample pooled test, even when variances are not known to be equal, instead of using the Welch test. Here's why not:
Suppose you have a sample of size 10 from a normal distribution with SD $\sigma_1 = 4$
and a sample of size 40 from a normal distribution with $\sigma_2 = 1.$ Also suppose the two
sample means are equal: $\mu_1=\mu_2 = 50$
(so, $H_0$ is true) and that we want a test at the 5% level.
The following simulation in R shows the very bad behavior of
the pooled 2-sample t test. (Note parameter var.eq=T to get the pooled test.)
set.seed(2022)
pv = replicate(10^5, t.test(rnorm(10,50,4),
             rnorm(40,50,1), var.eq=T)$p.val)
mean(pv <= 0.05)
[1] 0.2948

Instead of the expected 5% significance level (Type I Error), we have significance level about 30%.
That is a massive false discovery rate.
By contrast, the significance level using the default Welch test in the t.test procedure,
we get very nearly the nominal 5% significance level. Although it uses an approximation, the Welch
test takes the unequal variances into account to give very nearly the correct results.
set.seed(2022)
pv = replicate(10^5, t.test(rnorm(10,50,4),
             rnorm(40,50,1))$p.val)
mean(pv <= 0.05)
[1] 0.05084

It is as simple as that. The pooled test gives
incorrect and misleading answers and the Welch
test gives correct answers.


text: Q: Evo PDF page index in table I am using EVO Pdf to generate PDF,ie URL to PDF conversion is used.I have many dynamic sections in HTML to show student details .I have a table which contains entry for each student.I need to add page number in this table to identify student.ie in which page of PDF Student details will come?


text:
Q: Chrome Extension CSP - unsafe-eval and unsafe-inline in 3rd party js library and stylesheet Browser - Chrome Version 85.0.4183.102
There are lot of threads around this topic but I could not find what is the safest and correct way to deal with 3rd party libraries.
I am using kendo grid (jQuery) in my chrome extension.. it has "unsafe-eval" and "unsafe-inline"... unless I set the below entry in manifest.json its not working.
"content_security_policy": "font-src data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-eval'; object-src 'self';"

Since its not safest practice.. how can I bypass this with hash or nonce.
Note: The Kendo library is downloaded and referred from local machine. (No CDN references)
'unsafe-line'
When I remove 'unsafe-inline' as expected its giving out 5 errors in my case and providing 5 different sha-256 hashes. I replaced 'unsafe-inline' with 5 hashes but still getting the same error.
Below is the error when I tried only with 1 hash.
Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' 'sha256-lzhPGNqxpwmBda/ftMrdga7dSTDWPq2rpjz66R6TVFw='". Either the 'unsafe-inline' keyword, a hash ('sha256-lzhPGNqxpwmBda/ftMrdga7dSTDWPq2rpjz66R6TVFw='), or a nonce ('nonce-...') is required to enable inline execution.
'unsafe-eval'
When I remove 'unsafe-eval' as expected giving out errors with no generated hash to replace.
'font-src data:'
yet to attempt to bypass.
I even tried nonce but did not work.
am I missing something? or do I need to live with 'unsafe-inline' and 'unsafe-eval'. If yes, what is the potential risk? I am planning to release this extension to public.
EDIT: I tried sandbox as suggested below.
Here is what I did.
index.html

        <link href="css/iframe.css" rel="stylesheet">

sandbox.html has kendo reference
Here is the manifest.json change
"sandbox": {
"pages:": [
  "sandbox.html"
]},"content_security_policy": "sandbox allow-scripts allow-same-origin allow-popups;"

I am still getting errors with kendo. Any suggestions?

A: 'unsafe-inline' in scripts and styles
Chrome unintentionally misleads you with hashes for inline styles. The same is with hashes for inline scripts:

*

* consiedres as inline and can be allowed with 'nonce-value' or/and 'hash-value' tokens.

*<tag onEvent='event_handler_script'> and  both considers as inlnie script but cannot be allowed by 'nonce-value' or/and 'hash-value' tokens. But Chrome calculates sha256 for them, because it prepares to implement 'unsafe-hashes' token (spec section is not normative so implementation is delayed support is implemented already).

Therefore is case (1) you could easily ged rid of 'unsafe-inline', in case (2) - you need to modify code first.
'unsafe-eval' in scripts
Content Security Policy spec does not provide way to allow unsafe scripts constructions via 'nonce/hash' tokens. Changes of the script code will be required, in some cases - purely "cosmetic".
CSP considers as eval-constructs:

*

*eval()

*setTimeout('string')

*setInterval('string')

*Function()

*setImmediate()

*execScript()

Note that setTimeout()/setInterval() are "eval" only when callback function passed as a string. If callback is an anonymous funct or "function by name" - those not fall under eval.
In this case, you can easily get rid of eval without changing the logic of the script.

A: For Chrome Manifest 3 you can add
{
  "content_security_policy":{
  "extension_page": "script-src 'self' 'wasm-unsafe-eval'; object-src 'self'" ,
  "sandbox": "extension_page": "script-src 'self' 'wasm-unsafe-eval'; object-src 'self'" ,
  }
}


text:
Q: Display dynamic list of Oxyplot charts in a listbox When displaying a chart using oxyplot in a wpf application:
<oxy:PlotView Title="My Chart" Model="{Binding SomePlotModel}"></oxy:PlotView>

Will display the chart.
But if you want to display multiple charts in a ListBox
<ListBox >
    <ListBoxItem>
        <oxy:PlotView Title="My Chart1" Model="{Binding SomePlotModel1}"></oxy:PlotView>
    </ListBoxItem>
    <ListBoxItem>
        <oxy:PlotView Title="My Chart2" Model="{Binding SomePlotModel2}"></oxy:PlotView>
    </ListBoxItem>
</ListBox>

The charts will not display. Why? How do you display a dynamic list of charts using Oxyplot?

A: Width and Height! Oxyplot line 583 of PlotBase
((IPlotModel)this.ActualModel).Render(this.renderContext, this.canvas.ActualWidth, this.canvas.ActualHeight);

If you dump a plot in a ListBox the width and height of the canvas for the plot are zero unless set.
This works in my example :
<ListBox >
<ListBoxItem>
    <oxy:PlotView Title="My Chart1" Model="{Binding SomePlotModel1}"  Width="200" Height="200"></oxy:PlotView>
</ListBoxItem>
<ListBoxItem>
    <oxy:PlotView Title="My Chart2" Model="{Binding SomePlotModel2}"  Width="200" Height="200"></oxy:PlotView>
</ListBoxItem>


text:
Q: Which time-frequency coefficients does the Wavelet transform compute? (I asked this on Stack Overflow a while ago and didn't get a satisfying answer, so I'm trying again here.)
The Fast Fourier Transform takes O(N log N) operations, while the Fast Wavelet Transform takes O(N).  But what, specifically, does the FWT compute?
Although they are often compared, it seems like the FFT and FWT are apples and oranges.  As I understand it, a more appropriate comparison would be the STFT (FFTs of small chunks over time) and the complex Morlet WT, since they're both time-frequency representations based on complex sinusoids (please correct me if I'm wrong).  This is often shown with a diagram like this:

(Another example)
The left shows how the STFT is a bunch of FFTs stacked on top of each other as time passes (this representation is the origin of the spectrogram), while the right shows the dyadic WT, which has better time resolution at high frequencies and better frequency resolution at low frequencies (this representation is called a scalogram).
In this example, N for the STFT is the number of vertical columns (ω axis), and a single O(N log N) FFT operation calculates a single row of N coefficients from N samples.
What I don't understand:  How many coefficients does a single O(N) FWT operation compute, and where are they located on the time-frequency chart above?  Which tiles get filled in by a single computation?
If we calculate an equal-area block of time-frequency coefficients using both, do we get the same amount of data out?  Is the FWT still more efficient than the FFT?
Concrete example using PyWavelets:
In [2]: dwt([1, 0, 0, 0, 0, 0, 0, 0], 'haar')
Out[2]:
(array([ 0.70710678,  0.        ,  0.        ,  0.        ]),
 array([ 0.70710678,  0.        ,  0.        ,  0.        ]))

It creates two sets of 4 coefficients, so it's the same as the number of samples in the original signal.  But what's the relationship between these 8 coefficients and the tiles in the diagram?

A: Well, since the wavelet transform is not precisely a time-frequency analysis but more a time-scale analysis one can not really display the wavelet coefficients in the time frequency plane. (However, even for the STFT the time-frequency plane is only a crutch for illustration purposes.)
Maybe it helps to think of $N=2^n$. Then you can analyze your signal into $n$ scales with the wavelet transform. See, e.g., this image with $n=3$:

Then the wavelet-transform stores the $c_{31}$ and all the $d_{ij}$'s. If you want to put the coefficients in the time-frequency plane you would have to stretch the tiles as you indicated in your figures. There would be $n$ vertical colums (in $\omega$), the rightmost having $2^{n/2}$ boxes and the number of boxes halving in each column (the last two containing just one box). This adds up to $2^n$.
However, I suggest to read Mallat's "A wavelet tour of signal processing - the sparse way" Chapters 1.3, 4.3 and 8.1. It's quite hard to produce illustrating figures for the wavelet transform here...
Considering the efficiency: To be a bit more precise, the discrete wavelet transform (DWT) of a signal of length $2^n$ and a filter with length $k$ takes $O(k2^n)$, while FFT is $O(n2^n)$ with comparable constants. Hence, DWT is faster it the filter is not too long.

A: A single O(N) FWT computes as many output samples as there are inputs.
I'm not sure about the exact ordering of the coefficients, but for a Haar-transform
of length 8 is calculated in the following 3 steps:

*

*Step 1: 8 -> 4:
4 samples should contain the (2x subsampled) result of a [+1,-1] filter.
These 4 will be stored in the final output
The other 4 samples contain the (2x subsampled) result of a [+1,+1] filter.
These 4 will be filtered again.

*Step 2: 4 -> 2:
2 samples of the [+1,-1] filter as stored in the final output.
The other two will  be filtered again.

*Step 3: 2 -> 1:
The [+1,-1] filter yields 1 output sample. Since this is the last step, the remaining
sample of the [+1,+1] filter is also stored.

A: I think the closest you would get to a FFT is to do a wavelet packet analysis with the Shannon wavelets both low and high pass bands iterated. The Shannon wavelet and scaling functions are closely related to the sinc functions which are often derived in first signal and systems courses to be the interpolating functions to be used in perfect reconstruction if no aliasing occured when sampling.
(Also perfect "band-pass boxes" in the Fourier domain are sincs in the time domain. Time shifting the sincs just changes how the boxes rotate in phase, but the frequencies remain in the same box.)

Edit: beware seems to be a bug in the wikipedia formula for mother wavelet function.
Wolfram mathworlds formula looks more reasonable.
Here is a verification of the orthogonality $\phi$ vs $\psi$ for one scale.


text:
Q: how to send the cookie from Apollo Studo my environment:

*

*Apollo server version 3.8.1

*Apollo express version 3.8.1

*

*I allowed the cors

 server.applyMiddleware({
        app,
        cors: {
          credentials: true,
          origin: [
              `http://localhost:${config.gql.port}/graphql`,
              'https://studio.apollographql.com'
          ]
        },
        onHealthCheck: () => healthCheck()
      });

*I set the trust proxy

export const app = express();
if (process.env.NODE_ENV !== 'production') {
  app.set("trust proxy", true);
  console.log("set trust proxy");
}

*I opened the Including cookie from the Apollo studio.

*I set the header
"x-forwarded-proto": "https"

But when I use ctx.req.cookies, I got undefined

I try from this blog.
https://blog.devgenius.io/graphql-apollo-studio-and-cookies-5d8519d0ca7e


text:
Q: Variable value lost within 2 classes I have tried the autocomplete code from here :
Need a VB.net Combobox derived class for pattern matched or contains autocomplete functionality
I added some code and I really don't understand why the NbrName is lost.
I added :
    Case Keys.Enter
                Text = _suggLb.Text
                [Select](0, Text.Length)
                _suggLb.Visible = False

                'Mika
                Dim myObject As Form1 = New Form1()
                myObject.SearchByName(Text)
                'Mika
    Return

and this :
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    'Mika Dim testbox As New AutoCompleteComboBox.SuggestComboBox
    Me.Controls.Add(testbox)
    testbox.DataSource = New List(Of String) From {"Janean Mcgaha", "Tama Gaitan", "Jacque Tinnin", "Elvira Woolfolk", "Fransisca Owens", "Minnie Ardoin",
    "Renay Bentler", "Joye Boyter", "Jaime Flannery", "Maryland Arai", "Walton Edelstein", "Nereida Storrs",
    "Theron Zinn", "Katharyn Estrella", "Alline Dubin", "Edra Bhatti", "Willa Jeppson", "Chelsea Revel",
    "Sonya Lowy", "Danelle Kapoor"}

    NbrName = 20
End Sub

Public Sub SearchByName(text As String)
    Dim StrTmp As String
    StrTmp = text + NbrName.ToString
End Sub

and unfortunately, the variable NbrName remains to 0.
Here under the whole code.
Can someone explain me where is the problem ?
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Linq
Imports System.Linq.Expressions
Imports System.Windows.Forms

Public Class Form1

    Dim testbox As New AutoCompleteComboBox.SuggestComboBox
    Public NbrName As Integer

    Public Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        'Mika Dim testbox As New AutoCompleteComboBox.SuggestComboBox
        Me.Controls.Add(testbox)
        testbox.DataSource = New List(Of String) From {"Janean Mcgaha", "Tama Gaitan", "Jacque Tinnin", "Elvira Woolfolk", "Fransisca Owens", "Minnie Ardoin",
        "Renay Bentler", "Joye Boyter", "Jaime Flannery", "Maryland Arai", "Walton Edelstein", "Nereida Storrs",
        "Theron Zinn", "Katharyn Estrella", "Alline Dubin", "Edra Bhatti", "Willa Jeppson", "Chelsea Revel",
        "Sonya Lowy", "Danelle Kapoor"}

        NbrName = 20
    End Sub

    Public Sub SearchByName(text As String)

        Dim StrTmp As String
        StrTmp = text + NbrName.ToString

    End Sub

End Class

Namespace AutoCompleteComboBox
    Public Class SuggestComboBox
        Inherits ComboBox
#Region "fields and properties"

        Private ReadOnly _suggLb As New ListBox() With {.Visible = False, .TabStop = False}
        Private ReadOnly _suggBindingList As New BindingList(Of String)()
        Private _propertySelector As Expression(Of Func(Of ObjectCollection, IEnumerable(Of String)))
        Private _propertySelectorCompiled As Func(Of ObjectCollection, IEnumerable(Of String))
        Private _filterRule As Expression(Of Func(Of String, String, Boolean))
        Private _filterRuleCompiled As Func(Of String, Boolean)
        Private _suggestListOrderRule As Expression(Of Func(Of String, String))
        Private _suggestListOrderRuleCompiled As Func(Of String, String)

        Public Property SuggestBoxHeight() As Integer
            Get
                Return _suggLb.Height
            End Get
            Set(value As Integer)
                If value > 0 Then
                    _suggLb.Height = value
                End If
            End Set
        End Property

        '''
        ''' If the item-type of the ComboBox is not string,
        ''' you can set here which property should be used
        '''
        Public Property PropertySelector() As Expression(Of Func(Of ObjectCollection, IEnumerable(Of String)))
            Get
                Return _propertySelector
            End Get
            Set(value As Expression(Of Func(Of ObjectCollection, IEnumerable(Of String))))
                If value Is Nothing Then
                    Return
                End If
                _propertySelector = value
                _propertySelectorCompiled = value.Compile()
            End Set
        End Property

        '''
        ''' Lambda-Expression to determine the suggested items
        ''' (as Expression here because simple lamda (func) is not serializable)
        ''' <para>default: case-insensitive contains search</para>
        ''' <para>1st string: list item</para>
        ''' <para>2nd string: typed text</para>
        '''
        Public Property FilterRule() As Expression(Of Func(Of String, String, Boolean))
            Get
                Return _filterRule
            End Get
            Set(value As Expression(Of Func(Of String, String, Boolean)))
                If value Is Nothing Then
                    Return
                End If
                _filterRule = value
                _filterRuleCompiled = Function(item) value.Compile()(item, Text)
            End Set
        End Property

        '''
        ''' Lambda-Expression to order the suggested items
        ''' (as Expression here because simple lamda (func) is not serializable)
        ''' <para>default: alphabetic ordering</para>
        '''
        Public Property SuggestListOrderRule() As Expression(Of Func(Of String, String))
            Get
                Return _suggestListOrderRule
            End Get
            Set(value As Expression(Of Func(Of String, String)))
                If value Is Nothing Then
                    Return
                End If
                _suggestListOrderRule = value
                _suggestListOrderRuleCompiled = value.Compile()
            End Set
        End Property

#End Region

        '''
        ''' ctor
        '''
        Public Sub New()
            ' set the standard rules:
            _filterRuleCompiled = Function(s) s.ToLower().Contains(Text.Trim().ToLower())
            _suggestListOrderRuleCompiled = Function(s) s
            _propertySelectorCompiled = Function(collection) collection.Cast(Of String)()

            _suggLb.DataSource = _suggBindingList
            AddHandler _suggLb.Click, AddressOf SuggLbOnClick

            AddHandler ParentChanged, AddressOf OnParentChanged
        End Sub

        '''
        ''' the magic happens here ;-)
        '''
        ''' <param name="e"></param>
        Protected Overrides Sub OnTextChanged(e As EventArgs)
            MyBase.OnTextChanged(e)

            If Not Focused Then
                Return
            End If

            _suggBindingList.Clear()
            _suggBindingList.RaiseListChangedEvents = False
            _propertySelectorCompiled(Items).Where(_filterRuleCompiled).OrderBy(_suggestListOrderRuleCompiled).ToList().ForEach(AddressOf _suggBindingList.Add)
            _suggBindingList.RaiseListChangedEvents = True
            _suggBindingList.ResetBindings()

            _suggLb.Visible = _suggBindingList.Any()

            If _suggBindingList.Count = 1 AndAlso _suggBindingList.[Single]().Length = Text.Trim().Length Then
                Text = _suggBindingList.[Single]()
                [Select](0, Text.Length)
                _suggLb.Visible = False
            End If
        End Sub

#Region "size and position of suggest box"

        '''
        ''' suggest-ListBox is added to parent control
        ''' (in ctor parent isn't already assigned)
        '''
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        Private Overloads Sub OnParentChanged(sender As Object, e As EventArgs)
            Parent.Controls.Add(_suggLb)
            Parent.Controls.SetChildIndex(_suggLb, 0)
            _suggLb.Top = Top + Height - 3
            _suggLb.Left = Left + 3
            _suggLb.Width = Width - 20
            _suggLb.Font = New Font("Segoe UI", 9)
        End Sub

        Protected Overrides Sub OnLocationChanged(e As EventArgs)
            MyBase.OnLocationChanged(e)
            _suggLb.Top = Top + Height - 3
            _suggLb.Left = Left + 3
        End Sub

        Protected Overrides Sub OnSizeChanged(e As EventArgs)
            MyBase.OnSizeChanged(e)
            _suggLb.Width = Width - 20
        End Sub

#End Region

#Region "visibility of suggest box"

        Protected Overrides Sub OnLostFocus(e As EventArgs)
            ' _suggLb can only getting focused by clicking (because TabStop is off)
            ' --> click-eventhandler 'SuggLbOnClick' is called
            If Not _suggLb.Focused Then
                HideSuggBox()
            End If
            MyBase.OnLostFocus(e)
        End Sub

        Private Sub SuggLbOnClick(sender As Object, eventArgs As EventArgs)
            Text = _suggLb.Text
            Focus()
        End Sub

        Private Sub HideSuggBox()
            _suggLb.Visible = False
        End Sub

        Protected Overrides Sub OnDropDown(e As EventArgs)
            HideSuggBox()
            MyBase.OnDropDown(e)
        End Sub

#End Region

#Region "keystroke events"

        '''
        ''' if the suggest-ListBox is visible some keystrokes
        ''' should behave in a custom way
        '''
        ''' <param name="e"></param>
        Protected Overrides Sub OnPreviewKeyDown(e As PreviewKeyDownEventArgs)
            If Not _suggLb.Visible Then
                MyBase.OnPreviewKeyDown(e)
                Return
            End If

            Select Case e.KeyCode
                Case Keys.Down
                    If _suggLb.SelectedIndex < _suggBindingList.Count - 1 Then
                        _suggLb.SelectedIndex += 1
                    End If
                    Return
                Case Keys.Up
                    If _suggLb.SelectedIndex > 0 Then
                        _suggLb.SelectedIndex -= 1
                    End If
                    Return
                Case Keys.Enter
                    Text = _suggLb.Text
                    [Select](0, Text.Length)
                    _suggLb.Visible = False

                    'Mika
                    Dim myObject As Form1 = New Form1()
                    myObject.SearchByName(Text)
                    'Mika

                    Return
                Case Keys.Escape
                    HideSuggBox()
                    Return
            End Select

            MyBase.OnPreviewKeyDown(e)
        End Sub

        Private Shared ReadOnly KeysToHandle As List(Of Keys) = New List(Of Keys) From {Keys.Down, Keys.Up, Keys.Enter, Keys.Escape}
        Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
            ' the keysstrokes of our interest should not be processed be base class:
            If _suggLb.Visible AndAlso KeysToHandle.Contains(keyData) Then
                Return True
            End If
            Return MyBase.ProcessCmdKey(msg, keyData)
        End Function

#End Region
    End Class
End Namespace


text:
Q: Chrome CSS Local Overrides instead of !important for Chrome Extension I originally made a Chrome Extension that overrides some of the margins, padding, and font size CSS on a website using !important. It was pretty cumbersome and a bit painful to update since the website is pretty complex.
I then discovered Local Overrides in the Chrome Developer Tools which allows me to make all my edits in Chrome, see the changes, and a CSS file is generated. Is there a good way to take the CSS file, build it into a Chrome Extension, and load it independently of the Chrome Developer Tools?

A: So I was able to figure this out by injecting the CSS file from Developer Tools via a Javascript content-script in my extension. I simply copy the CSS file to my extension directory and it is good to go with the following code in my JS file:
window.onload = function() {
var link = document.createElement('link');
link.href = chrome.extension.getURL('style.css');
link.type = 'text/css';
link.rel = 'stylesheet';
link.media = 'all';
document.getElementsByTagName('HEAD')[0].appendChild(link);
}

This did not require me to modify the CSS after the fact or use !important.


text:
Q: Splitting principle in equivariant cohomology The following is a weaker version of what is called splitting principle in
 Appendix C, page 12, see also for a lighter version Brions Eq cohom and eq intersection theory, page 6:
Let $G$ be a compact (complex) connected Lie group with torus $T\subset G$ and $N$ its normalizer, $W=N/T$ its Weyl group. Let $X$ be any $G$-variety.
Then, there is an isomorphism
$ H_G^* (X) \cong (H_T^*(X))^W $
of graded algebras. For $X=pt$ this is known to be Chevalley's restriction theorem.
My question is, can one drop the assumption on $G$ and $T$ to be compact? I came across an article  VarVas, page 12, where that has been claimed (with G=Gl_n, X quasi-projective) to be a standard result and no reference is provided.

A: The embedding of the unitary group $U_n$ into $GL_n(\mathbb C)$ is a homotopy equivalence; this is easily seen to imply that $H^*_{U_n}(X)$ is isomorphic to $H^*_{GL_n}(X)$. So the result for compact groups implies that for $GL_n$.
The same idea works for any reductive complex algebraic group $G$, since the embedding of a maximal compact subgroup into $G$ is a homotopy equivalence.


text:
Q: Convert symmetric matrix between packed and full storage? I'm new to numerical linear algebra, and I have just started using LAPACK and BLAS.
Is there a routine that can copy/convert a symmetric matrix between packed and full storage?
I have found dtrttp, which I can use to convert a double-precision full symmetric matrix to packed storage. However, these routines are meant for triangular matrices, so the corresponding dtpttr only fills a triangle of the full matrix. How can I fill the other half?

A: The obvious solution is to symmetrize the matrix by a "home-made/diy" code, the risk being to re-invent the wheel. It is pretty easy to write the for loops needed to symmetrize the matrix after dtpttr.
for(i=0;i<n;i++){
  for(j=i+1;j<n;j++){
    a[i*n+j]=a[j*n+i];
  }
}

Is it efficient enough for your application ? On a 10000x10000 matrix, these for loops last 0.88s on my PC, while dtpttr lasts 0.24s.
Here is the test code. Compile it with gcc main.c -o main -llapack -lblas -lm :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

void dtrttp_(char* UPLO,int* N,double* A,int* LDA,double* AP,int* INFO);
void dtpttr_(char* UPLO,int* N,double* AP,double* A,int* LDA,int* INFO);
void daxpy_(int* N,double* DA,double* DX,int* INCX,double* DY,int* INCY);

void dtpttf_(char* TRANSR,char* UPLO,int* N,double* AP,double* ARF,int* INFO);

int main(int argc, char **argv)
{

    int n=10;
    int info;

    double *a=malloc(n*n*sizeof(double));
    double *packed=malloc((n*(n+1))/2*sizeof(double));

    int i,j;
    for(i=0;i<n;i++){
        for(j=0;j<n;j++){
            a[i*n+j]=i+j;
        }
    }

    printf("matrix before pack\n");
    for(i=0;i<n;i++){
        for(j=0;j<n;j++){
            printf("%g ",a[i*n+j]);
        }
        printf("\n");
    }

    printf("\n");
    //pack
    dtrttp_("U",&n,a,&n,packed,&info);

    //unpack
    memset(a,0,n*n*sizeof(double));
    dtpttr_("U",&n,packed,a,&n,&info);

    for(i=0;i<n;i++){
        for(j=i+1;j<n;j++){
            a[i*n+j]=a[j*n+i];
        }
    }

    printf("matrix after unpack\n");
    for(i=0;i<n;i++){
        for(j=0;j<n;j++){
            printf("%g ",a[i*n+j]);
        }
        printf("\n");
    }

    free(a);
    free(packed);

    printf("timing...\n");

    n=10000;

    a=malloc(n*n*sizeof(double));
    packed=malloc((n*(n+1))/2*sizeof(double));

    for(i=0;i<n;i++){
        for(j=0;j<n;j++){
            a[i*n+j]=i+j;
        }
    }

    //pack
    dtrttp_("U",&n,a,&n,packed,&info);

    //unpack
    memset(a,0,n*n*sizeof(double));
    clock_t t;
    t = clock();
    dtpttr_("U",&n,packed,a,&n,&info);
    t = clock() - t;
    printf ("dtpttr took %f seconds.\n",((double)t)/CLOCKS_PER_SEC);
    t = clock();
    for(i=0;i<n;i++){
        for(j=i+1;j<n;j++){
            a[i*n+j]=a[j*n+i];
        }
    }
    t = clock() - t;
    printf ("symmetrize took %f seconds.\n",((double)t)/CLOCKS_PER_SEC);
    free(a);
    free(packed);

    return 0;
}


text:
Q: python tkinter phone should be displayed automatically I have a long list of Samsung phones, my list is very, very long. I want to provide some information about those phones. The picture of that phone should be displayed automatically. can you help
from tkinter import *
root=Tk()
root.geometry("600x600")
root.resizable(False, False)
def show_r():
    global key2
    key2=key.get()
    if key2 in Samsung2022:
        key3=key2.replace(" ","")
        key4=str(key3+".jpg")
        print(key4)
        #img=PhotoImage(file=key4)
        #img_label=Label(root, image=img)
        #img_label.place(x=50, y=10)
        la=Label(root, text=Samsung2022.get(key2), bg="#fff", font=('Arial',10))
        la.place(x=50, y=280)
key = StringVar()
Samsung2022={
    #2022
    "Galaxy A03": "SAMSUNG GALAXY A03 TOP SPECS",
    "Galaxy A13": "SAMSUNG GALAXY A13 TOP SPECS",
    "Galaxy A23": "SAMSUNG GALAXY A23 TOP SPECS",
    "Galaxy A33 5G": "SAMSUNG GALAXY A33 5G TOP SPECS",
    }
#Entry
key_entry = Entry(textvariable=key, bd=2,  font=('Arial',15) )
key_entry.place(x=120, y=35, width=300, height=40,)
#Button
key_button=Button(text="Click Me", command=show_r, bd=2, bg="#fff",)
key_button.place(x=429, y=25,)

root.mainloop()


text:
Q: Spring @Autowired repository not working in @Override Netty method I was developing a Netty Socket project with Spring Data but I'm definitely can't use Spring's repository class in @Override method. It works in any method other than the @Override method, I tried calling it with @PostConstruct.
@Repository
public interface AccountRepository extends CassandraRepository<Account, UUID> {}

@Service
public class WebSocketHandler extends ChannelInboundHandlerAdapter {

    public static List<String> requiredData = Arrays.asList(
            "request_type"
    );

    @Autowired
    private AccountRepository accountRepository;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if(!(msg instanceof TextWebSocketFrame)) return;

        System.out.println(accountRepository);//problems there, accountRepository always return null;

        JSONObject data;
        try {
            data = new JSONObject(((TextWebSocketFrame) msg).text());
        } catch (Exception ex) {
            return;
        }

        for(String required : requiredData) {
            try {
                data.get(required);
            } catch (Exception ex) {
                return;
            }
        }

        RequestModule requestModule = RequestAdapter.getModule(data.get("request_type").toString());
        if(requestModule == null) return;

        requestModule.onAction(ctx, data);
    }
}

public class Netty {
    private UnorderedThreadPoolEventExecutor executorGroup;

    public Netty() {
        UtilConsole.log("Netty sunucusu aktifleşiyor...");
        try {
            enable();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void enable() throws Exception {
        ResourceLeakDetector.setLevel( ResourceLeakDetector.Level.DISABLED ); // Eats performance

        EventLoopGroup producer = new NioEventLoopGroup(32);
        EventLoopGroup consumer = new NioEventLoopGroup(32);

        try{
            executorGroup = new UnorderedThreadPoolEventExecutor(32);

            ServerBootstrap bootstrap = new ServerBootstrap()
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .group(producer, consumer)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();

                            pipeline.addLast("httpServerCodec", new HttpServerCodec());
                            pipeline.addLast(new HttpObjectAggregator(Short.MAX_VALUE));

                            pipeline.addLast(executorGroup, "httpHandler", new NettyListener());
                        }
                    })
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 100000)
                    .option(ChannelOption.SO_RCVBUF, Integer.MAX_VALUE);

            UtilConsole.log("Netty sunucusu aktif edildi!");
            bootstrap.bind(Configuration.NETTY_PORT).sync().channel().closeFuture().sync();
        }catch(Exception ex){
            ex.printStackTrace();
            UtilConsole.log("Netty sunucusu aktif edilemedi.");
            throw ex;
        }finally{
            producer.shutdownGracefully();
            consumer.shutdownGracefully();
        }
    }

}

public class NettyListener extends ChannelInboundHandlerAdapter {

    private WebSocketServerHandshaker handshaker;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        if(msg instanceof HttpRequest){
            HttpRequest httpRequest = (HttpRequest) msg;

            HttpHeaders headers = httpRequest.headers();

            if("Upgrade".equalsIgnoreCase(headers.get(HttpHeaderNames.CONNECTION)) && "WebSocket".equalsIgnoreCase(headers.get(HttpHeaderNames.UPGRADE))){
                ctx.pipeline().replace(this, "websocketHandler", new WebSocketHandler());
                handleHandshake(ctx, httpRequest);
            }
        }
    }

This definitely doesn't work and accountRepository always returning null.
I want to be able to use a @Autowired variable in the @Override channelRead method, but it doesn't work.

A: Spring can do autowire, and all other "magic stuff", IF and only if it's spring itself that build the instance of the class.
The problem is in your NettyListener class where you build the instance with new WebSocketHandler(). In this way, Spring doesn't know anything about that, and can't initialize it properly.
My advice is to build your netty configuration passing the WebSocketHandler instance returned by spring in this way:
@Configuration
public MyAppConfiguration {

  @Autowire
  WebSocketHandler webSocketHandler

  @PostConstruct
  public void configureNetty() {
    //...netty-things I don't know...
    //netty.useHandler(webSocketHandler)
  }

}

OT: I saw UtilConsole.log() and as a general advice, never reinvent the wheel, and logging frameworks are more complex than they appears. A look to 'logback' (the most beloved by spring-framework) could help you.


text:
Q: Img.onload not firing when dynamically setting src to dataURI I am having trouble getting the onLoad handler to fire when the src of imgGraph is loaded with a generated dataURI. The dataURI is generated from a d3.js visualization (svg) using canvas.
var canvas = document.getElementById(visual + '-canvas');
if(visual == "graph"){
     console.log('graph logic n stuff')
     canvas.width = 558;
     canvas.height = 558;
     var graph = d3.select('#graph-svg').node();
     var svg_xml = (new XMLSerializer()).serializeToString(graph);
     var imgGraph = new Image();
     var context = canvas.getContext('2d');
     var imageData;
     imgGraph.onload = function(){
         console.log('img loaded')
         context.drawImage(imgGraph, 0, 0);
         imageData = getImgData(canvas);
         console.log(imageData)
         def.resolve(imageData)
     }
     console.log('setting src')
     imgGraph.src = "data:image/svg+xml;base64,"+btoa(svg_xml);
}

The img src is being set, but the img.onload is never fired.
When logging and surfing to the datauri, the image is being displayed however.
Other images seem to fire the onload event correctly.
DataURI - PasteBin

A: Don't base64 encode your svg.
Instead one should prefer an percent encoded version, or for huge svg, a blobURI :
img.src = 'data:image/svg+xml;charset=utf8,' + encodeURIComponent(yourSVGMarkup);

or
img.src = URL.createObjectURL(
  new Blob([yourSVGMarkup], {
    type: 'image/svg+xml;charset=utf8'
    })
  );

JSfiddle to demonstrate the difference.
But you should note that SVGs loaded inside an <img> element can't load any external resources. So you'll have to base64 encode all the images linked in your svg prior to extract the markup if you want to draw them on your canvas too.
When this will be done, your svg markup will indeed be long, and maybe too long for a dataURI version.
That's when the blobURI is useful.
PS: if you need help for appending your raster images inside your svg, check this Q/A

A: Try:
imgGraph.complete = function(){


text:
Q: Re-positioning hint text inside EditText after using custom background I am using a custom background for my EditText but the hint for my textfields don't get aligned properly afterwards.
This is what am getting

am using a custom background in my drawable folder like this:
<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:
          android="http://schemas.android.com/apk/res/android"
          android:shape="rectangle">

   <stroke
       android:width="8dp"
       android:color="#5647"/>

</shape>

and in my login.xml file i have :
<EditText
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:inputType="textPersonName"
        android:hint="@string/username_hint"
        android:ems="10"
        android:background="@drawable/orange_frame"
        android:id="@+id/signInUsernameTextField"
        android:layout_marginTop="209dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"/>
<EditText
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:inputType="textPassword"
        android:hint="@string/password_hint"
        android:background="@drawable/orange_frame"
        android:ems="10"
        android:id="@+id/signInPasswordTextField"
        android:layout_gravity="center_horizontal"
        android:layout_below="@+id/signInUsernameTextField"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"/>

How do I fix this please ?

A: You can try like this:
<EditText
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:inputType="textPersonName"
        android:hint="@string/username_hint"
        android:ems="10"
        android:paddingLeft="10dp"
        android:background="@drawable/orange_frame"
        android:id="@+id/signInUsernameTextField"
        android:layout_marginTop="209dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"/>
<EditText
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:inputType="textPassword"
        android:hint="@string/password_hint"
        android:background="@drawable/orange_frame"
        android:ems="10"
        android:paddingLeft="10dp"
        android:id="@+id/signInPasswordTextField"
        android:layout_gravity="center_horizontal"
        android:layout_below="@+id/signInUsernameTextField"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"/>

Attached screenshot as output:


text:
Q: Using a wildcard in the command line as sys.argv[2] The problem
I'm trying to write a script which converts a file type into another using SeqIO, ideally on the command-line I'd write:
python3 converter.py *.ab1 *.fas

But this doesn't work. However, when I use the following, it works fine:
python3 converter.py *.ab1 workingexample.fas

My current code
This my code at the moment.
import sys
from Bio import SeqIO

file = sys.argv[1]
outputfile = sys.argv[2]

with open(file, "rb") as input_handle:
    with open(outputfile, "w") as output_handle:
        sequences = SeqIO.parse(input_handle, "abi")
        count = SeqIO.write(sequences, output_handle, "fasta")

print("Converted %i records" % count)

Desired output:
A fix for
python3 converter.py *.ab1 *.fas

Which means I can run this on multiple files in the same directory with the same extension, and then output a file with the same name but the new converted extension.
(I'm not sure whether to tag this as a bash question or a python one, so I have tagged it as both, please correct me if I'm wrong)

A: Does something like this work?
import sys
import glob
import os
from Bio import SeqIO

file = sys.argv[1]
output_extension = sys.argv[2]

for f in glob.glob(file):
    filename, file_extension = os.path.splitext(f)
    outputfile = f.replace(file_extension, output_extension)

    with open(f, "rb") as input_handle:
        with open(outputfile, "w") as output_handle:
            sequences = SeqIO.parse(input_handle, "abi")
            count = SeqIO.write(sequences, output_handle, "fasta")

    print("Converted %i records" % count)

You can call it like this:
python converter.py '*.ab1' .fas

A: If I understand correctly, I think the issue is that *.ab1 matches a file (at least one), whereas *.fas doesn't match anything. This means that your program gets called like:
python3 converter.py first.ab1 second.ab1 third.ab1 *.fas

and *.fas is passed, unexpanded. Clearly from this example, you cannot rely on *.fas being the second argument - it is the last argument.
I would argue that the shell is helping you here by expanding the glob, and that there's no need to prevent it from doing its work by e.g. enclosing your arguments in quotes.
I would suggest that you call your script like:
python3 converter.py *.ab1 fas

Then change the code to:
import sys
import os.path
from Bio import SeqIO

files = sys.argv[1:-1]
output_ext = sys.argv[-1]

def get_output_filename(input_filename, output_ext):
    root, ext = os.path.splitext(input_filename)
    return "{}.{}".format(root, output_ext)

for in_file in files:
    out_file = get_output_filename(in_file, output_ext)
    with open(in_file, "rb") as input_handle, open(out_file, "w") as output_handle:
        sequences = SeqIO.parse(input_handle, "abi")
        count = SeqIO.write(sequences, output_handle, "fasta")
    print("Converted %i records" % count)

Since you're converting to "fasta" format no matter what the last argument is, then I guess you could just rename the script to convert_abi_to_fasta.py and drop the last argument.


text:
Q: Reference book on measure theory I post this question with some personal specifications. I hope it does not overlap with old posted questions.
Recently I strongly feel that I have to review the knowledge of measure theory for the sake of starting my thesis.
I am not totally new with measure theory, since I have taken and past one course at the graduate level. Unfortunately, because the lecturer was not so good at teaching, I followed the course by self-study. Now I feel that all the knowledge has gone after the exam and still don't have a clear overview on the structure of measure theory.
And here come my specified requirements for a reference book.

*

*I wish the book elaborates the proofs, since I will read it on my own again, sadly. And this is the most important criterion for the book.

*I wish the book covers most of the topics in measure theory. Although the topic of my thesis is on stochastic integration, I do want to review measure theory at a more general level, which means it could emphasize on both aspects of analysis and probability. If such a condition cannot be achieved, I'd like to more focus on probability.

*I wish the book could deal with convergences and uniform integrability carefully, as Chung's probability book.
My expectation is after thorough reading, I could have strong background to start a thesis on stochastic integration at an analytic level.
Sorry for such a tedious question.
P.S: the textbook I used is Schilling's book: measures, integrals and martingales. It is a pretty good textbook, but misprints really ruin the fun of reading.

A: When I learned the subject, I found three books to be immensely useful. Royden's Real Analysis is a good general book and has nice problems.  Bartle's elements of integration does the abstract theory of integration cleanly and concisely.  In addition, you need a good book on Lebesgue measure on Euclidean spaaces. For this I recommend Wheeden and Zygmund's Measure and Integral.

A: Donald L. Cohn-"Measure theory". Everything is detailed.

A: It seems unnecessary to add to this long list of great books, but
Real Analysis and Probability by R.M. Dudley is wonderful. His book fits your need to emphasize on both aspects of analysis and probability.

A: Perhaps my answers will be idiosyncratic, since I'm a philosopher of science who hasn't taken any math classes since Calculus (apart from some logic courses), and my main interest in measure theory was for the sake of probability theory.
David Williams, Probability with Martingales is great for concepts as well as proofs, but there's a lot that it doesn't cover, I feel.
I've gotten a lot out of J.L. Doob's Measure Theory, which presents some common ideas in ways that are more general and deeper than what one usually finds, I believe.  Has a bit of droll humor, now and then, too.  I don't understand all of it, but I've gotten a lot out of it.
However, these books do not focus on analysis, but seemed worth mentioning.
(*Avner Friedman, Foundations of Modern Analysis has an old-fashioned approach, as I understand, but I learned a lot from it as well.  This was where I started.  Munroe's Introduction to Measure and Integration fits well with Friedman's book.  I used them together.)
(OK, and now feel free to ignore this.  Most of the other answers are probably by people who are better informed.)

A: Textbook: Real and Complex Analysis by Walter Rudin
Explanation: Chapters 1, 2, 3, 6, 7 and 8 constitute an excellent general treatment of measure theory. Let me elaborate:
Chapter 1: The notions of an abtract measure space and an abstract topological space are introduced and studied in concurrence. This treatment allows the reader to see the close connections between the two subjects that appear both in practice and in theory. Elementary examples and properties of measurable functions and measures are discussed. Furthermore, Lebesgue's monotone convergence theorem, Fatou's lemma, and Lebesgue's dominated convergence theorem are proven in this chapter. Finally, the chapter discusses consequences of these results. The elegance of the treatment allows the reader to quickly become accustomed to the basic theory of measure.
Chapter 2: This chapter delves further into the intimate connection between topological and measure theoretic notions. More specifically, the chapter begins with a treatment of some important results in general topology such as Urysohn's lemma and the construction of partitions of unity. Afterwards, these results are applied to establish the Riesz representation theorem for positive linear functionals. The proof of this result is long but is nonetheless carefully broken into small steps and the reader should find little or no difficulty in understanding each of these steps. The Riesz representation theorem is applied in a particularly elegant manner to the theory of positive Borel measures. Finally, the existence and basic properties of the Lebesgue measure are shown to be a virtually trivial consequence of the Riesz representation theorem. The chapter ends with a nice set of exercises that discusses, in particular, some interesting counterexamples in measure theory.
Chapter 3: The basic theory of $L^p$ spaces ($1\leq p\leq \infty$) is introduced. The chapter begins with an elementary treatment of convex functions. Rudin explains that many elementary inequalities in analysis may be established as easy consequences of the theory of convex functions and evidence is provided for this claim. In particular, Holder's and Minkowski's inequalities are proven. These results culminate in the proof that the $L^p$ spaces are indeed complex vector spaces. The completeness of the $L^p$ spaces and various important density results are also discussed.
Chapter 6: This chapter discusses the theory of complex measures, and in particular, the Radon-Nikodym theorem. Von Neumann's proof of the Radon-Nikodym theorem is presented and various consequences are discussed ranging from the characterization of the dual of the $L^p$ spaces ($1\leq p\leq \infty$) to the Hahn decomposition theorem. These results culminate in the proof of the Riesz representation theorem for bounded linear functions. A knowledge of chapters $4$ and $5$ are necessary in this chapter although they do not strictly cover measure theory. Uniform integrability and the Vitali convergence theorem are treated in the exercises at the end of the chapter.
Chapter 7: The main topic of this chapter is Fubini's theorem. A wealth of nice counterexamples is discussed and an important application is presented: the result that the convolution of two functions in $L^1$ is again in $L^1$. A wonderful feature of this treatment is the generality; the result is established in one of the most general forms possible.
Chapter 8: This chapter treats differentiation of measures and the Hardy-Littlewood maximal function which is an important tool in analysis. A number of applications are presented ranging from a proof of the change of variables theorem in Euclidean $n$-space (in a very general form) to a treatment of functions of bounded variation and absolute continuity. Several results from this chapter are also used later in this book; most notable is the use of the differentiation theorem of measures in the study of of harmonic functions in chapter 11.
Let me summarize with some general comments regarding the book:
Prerequisites: A good knowledge of set-theoretic notions, continuity and compactness suffice for the chapters that I have described. An at least rudimentary knowledge of differentiation and uniform convergence is very helpful at times. One need not be acquianted with the theory of the Riemann integral beforehand although one should at least be acquianted with its computation. In short, a knowledge of chapters 1, 2, 3, 4 and 7 of Rudin's earlier book Principles of Mathematical Analysis is advisable before one reads this textbook.
Exercises: The exercises in this textbook are wonderful. Many of the exercises build an intuition of the theory and applications treated in the text and therefore it is advisable to do as many exercises as possible. However, you should expect to work to solve a few of the exercises. A number of important concepts such as convergence in measure, uniform integrability, points of density, Minkowski's inequality for convolution, inclusions between $L^p$ spaces, Hardy's inequality etc. are treated in the exercises. However, if you are truly stuck you will find that many of these results are either theorems or exercises with detailed hints in other textbooks. (E.g., Folland's Real Analysis.)
Content: I have already described the content in some detail but let me say that the content is about exactly what one needs to study branches of mathematics where measure theory is applied. Of course, this is with the assumption that one at least attempts as many exercises as possible since a number of important results (from probability theory, for example) are treated in the exercises.
Style: The proofs in Rudin are (with possibly minor exceptions) complete. Unlike a number of other mathematics textbooks, Rudin prefers not to leave any parts of proofs to the reader and instead focusses on giving the reader non-trivial exercises as practice at the end of each chapter. The book reads magnificently and the flow of results is excellent; almost all results are stated in context. It is fair to say that the main text of the book lacks examples, which is perhaps one of the only points of complaints by students, but the exercises do contain examples. Finally, the book is rigorous and is completely free of mathematical errors.
I hope this review of Rudin's Real and Complex Analysis is helpful! I have read virtually the entire book (over $4$ months) and I found it to be one of the most enjoyable experiences of my life. It really motivated me to delve deeper into analysis. Perhaps the same will be true for you. I certainly recommend this book with my deepest enthusiasm.

A: If you are looking for a book in measure theory, you should certainly get a copy of the book of that title by Halmos. You may need a second book for details on stochastic processes, but for the underlying analysis it will be hard to find a more comprehensive book, or a better-regarded author.

A: Foundations of modern probability, Second edition, by Olav Kallenberg.

A: Nobody seems to mention the book "Measure and Integration" by De Barra. It covers all the standard topics and is very detailed. The exercises have detailed solutions too.

A: Lang's Real and Functional Analysis
In my opinion, his treatment of integration is the best one I have ever seen.
Usually an author of a textbook on measure theory defines first $\int f d\mu$ for non-negative extended real valued functions $f$(see Rudin for example). Then he defines $\int f d\mu$ for extended real valued functions. And then he defines it for complex valued functions.
On the other hand, Lang defines it for real or complex valued functions all at once.
And his method also applies without any modification to functions taking values in a Banach space.
Most of all, his method is simple, clear and natural.
Halmos uses a similar method, but I think Lang is simpler, clearer and more natural.

A: If you want a book to be a comprehensive study of measure theory, you can hardly be more extensive than the five volumes by Fremlin.

A: [1] Paul Halmos. Measure Theory.
[2] Walter Rudin. Real and Complex Analysis.
[3] Gerald Follamd. Real Analysis.
[4] David Fremlin. Measure Theory. Volume 1-5.
[5] Vladimir Bogachev. Measure Theory. I and II.
[6] Richard Bass. Real Analysis for Graduate Students.
[7] Donald Cohn. Measure Theory.

A: Schilling was my introduction to the subject too. There are a few misprints, but a lot of them are corrected in the errata.
I've found Rudin's Real and Complex Analysis useful as a reference / second text. You could also take a look at Folland's Real Analysis. Terry Tao has notes about the subject on his blog, see here.
One of the most comprehensive books, besides Kallenberg's Foundations of Modern Probability, is probably Bogachev's Measure Theory (2-volumes). Its Table of Contents can be viewed at Springer.

A: Folland's text ("Real Analysis") is highly extensive and covers many topics in measure theory which you rarely see in other books, e.g. interpolation theorems for $L^p$ spaces. It also has a chapter on probability theory, in which he gives rigorous proofs to the basic theorems in the theory (the law of large numbers, the central limit theorem), talks about the construction of product spaces in the context of probability theory, and discusses Brownian motion and Wiener measure.

A: Richard F. Bass Real Analysis for Graduate Students_ Measure and Integration Theory  2011.this book is very good book for measure theory.this book has very good exercise.

A: I found the book Measure, Integration & Real Analysis by Sheldon Axler an excellent read.

*

*The book motivates definitions with examples and counterexamples.

*The book highlights the important parts so that you can peruse it.

*There are good end-of-chapter problems that drive in the concept learnt.

Axler brings a similar style to his more famous Linear Algebra book to the area of Measure Theory. The book is an easy read while being rigorous.
The book is aimed at active learning and may not be a comprehensive reference book (as requested in the question). Having said that, it provides excellent proofs, motivates definitions well and has a good topic coverage. It also helps that the author has made the book available on open access.

A: I suggest the following books:
The classical books
1- S. J. Taylor, Introduction to Measure and Integration, Cambridge University Press, 1973. (Very constructive book -may be hard-, personally, I use this book for abstract measure theory as a textbook)
2- E. Asplund and L. Bungart, A First Course in Integration, Holt, Rinehart and Winston, Inc., 1966. (It is very useful to understand Lebesgue's Integral and Measure theory on reals.)
Modern Books:
3- F. Burk, Lebesgue Measure and Integration: An Introduction, John Wiley & Sons, Inc. 1998. (my second recommended textbook)
4- F. Jones, Lebesgue Integration on Euclidean, Jones and Bartlett Publishers, 2001.
5- G. S. Nelson, A User-Friendly Introduction to Lebesgue Measure and Integration,  AMS, 2015. (Easy to understand, excellent for beginners, Recommended.)
6- W. Johnston, The Lebesgue Integral for Undergraduates, MAA Press 2nd ed 2015. (Easy to understand, excellent for beginners, Recommended.)
7- J. Yeh, PROBLEMS AND PROOFS IN REAL ANALYSIS: Theory of Measure and Integration, World Scientific 2014. (Good collection of exercises but you need to learn first)
General and interesting books are:
1- F. Burk, A Garden of Integrals, MAA, 2007. (I like this book and I recommend reading this book at first)
2- D. M. Bressoud, A Radical Approach to Lebesgue's Theory of Integration, Cambridge University Press, 2008.


text:
Q: Dúvida para estruturação de banco - SQL Server Boa noite!
Gostaria de pedir ajuda para ter algumas ideias, vou explicar mais ou menos o que gostaria:
Digamos que eu tenha dois banco de dados, um para servir como Central (recebe a informações de vários outros banco de dados), e outro que recebe a informação do sistema, e envia para o banco Central.
Certo, o que pode acontecer é de o banco local não enviar alguma informação para o banco central, e com isso ficar com alguma lacuna. O que gostaria de fazer é uma "verificação" da quantidade de informação entre os dois bancos.
O que pensei em fazer:

*

*Criar uma tabela no banco central, com a informação da quantidade de informações do banco local, central e a qual tabela está sendo verificada. Certo, a ideia era criar uma Procedure para verificar quando houvesse divergência, e então enviar uma solicitação para o banco local tentar a subir a informação faltando, minha dúvida seria, como eu poderia informar especificamente qual a informação que está faltando? Teriam dicas para estruturar melhor?

Na primeira imagem seria um exemplo de informações, e como elas podem estar divergente. Na segunda como seria a estrutura básica da tabela para verificar.
O problema é que muitas tabelas não seguem um padrão sequencial numérico (muitas possuem algumas colunas como PK). Pensei em criar uma outra coluna na tabela para deixar a soma total de algo, e com isso, validar qual o valor que está faltando (no exemplo, seria somado o (1,2,4), resultando em 7, e iria comparar com a soma do banco local que seria 10, com isso pegaria a diferença e enviaria a solicitação ao banco local para enviar a informação do valor divergente.


text:
Q: Avoid Gitlab-CI build for develop branch on finish release (git-flow) We are using Git-Flow with automatic builds and releases using Gitlab-CI.
Every commit on the develop branch triggers the build stage.
Every commit on the master branch triggers first the build stage and then the release stage (which uses the artifacts from the build stage).
This works fine, there is only one drawback for which I couldn't find a solution:
Whenever we finish a release in the git repository, this means commits on both develop and master branch. That also triggers the build stage on both branches, building from the exact same source versions (at this point there are two different commits that contain the exact same code).
I would like to avoid the build on the development branch, but only in this special case.
I don't think this is possible using the logic inside .gitlab-ci.yml, but that's ok. I would be glad if I could recognize this situation and end the build script early.
I think this means the following conditions have all to be met:

*

*We are on the develop branch. (simple)

*The current commit was merged from both master and develop.

*The merged master commit has a tag attached to it.

What git magic could I do to recognize if this is the case for a certain commit in the develop branch?
I am using Python for this, but I would appreciate helpful answers in any programming language :-)

A: maybe you can use only in gitlab-ci.yml
deploy-dev:
  stage: deploy-dev
  script:
    -  ./somescript.sh
  only:
    refs:
      - develop

deploy-prod:
  stage: deploy-prod
  script:
    -  ./somescript.sh
  only:
    refs:
      - master
      - tags


text:
Q: How to filter a collection based on a slice of string I have a document in MongoDB with a string type field called provider.
How can I construct a bson filter to return all the documents that have provider match a string in a provided slice?
I have tried the following, but doesn't seem to work
    {
        "provider", bson.D{
            {
                "$in", bson.A{providers},
            },
        },
    },
}

A: Try removing bson.A around providers
{
    "$in", providers,
},

The reason the bson.A around providers doesn't work is because it creates another array from iterating over all the elements inside providers:
providers := []string{"google", "yahoo"}
fmt.Println(bson.A{providers}) // [["google yahoo"]]


text:
Q: How to check in jQuery or javascript if image is available on remote server? I work with a large number of images that are stored on a remote server and I'd like to check (with jQuery or JS) which of them are available without loading them entirely. So far I tried 3 solutions, but none of them works like I want:
1.
var http = new XMLHttpRequest();
http.open('HEAD', imageUrl, false);
http.send();

if(http.status >= 400) {
    console.log("Error loading " + imageUrl);
}

With this one I get No 'Access-Control-Allow-Origin' header is present on the requested resource....
2.
$.ajax({
    type: "HEAD",
    async: true,
    url: imageUrl
}).done(function() {
}).fail(function() {
    console.log("Error loading " + imageUrl);
});

With this one I get the same error as above.
3.
var img = new Image();
img.onerror = function() { console.log("Error loading " + imageUrl) };
img.src = imageUrl;

This one works, but it loads entire images, which makes it very slow.

A: Yes, third option is the only legal way to do it with JavaScript in this situation. If you care about performance you can use your backend as proxy. You can send images urls array with regular AJAX and ping that urls with you backend.

A:

var imgURL_BASE = "http://www.hayabusa2.jaxa.jp/galleries/onc/nav20181002/";
var imgURL_NAME = "201810021659.jpg"

document.addEventListener('DOMContentLoaded', function() {
  var img = document.body.appendChild(document.createElement("img"));
  img.onload = function() {
    console.log("Image available");
    document.getElementById("testresult").innerHTML = "Image found.
";
  };
  img.onerror = function() {
    console.log("Image NOT available");
    document.getElementById("testresult").innerHTML = "Image not available.
";
  };
  img.src = imgURL_BASE + imgURL_NAME;
});
Check result:


text:
Q: Gimp 2.9 How add alpha channel In Gimp 2.9 I want to add an Alpha Channel (Layers>Transparency) I expect to see a layer of transparency beneath my main image. However t no new layer of transparency appears. Its in RGB mode.
What to do?

A: The alpha-channel is a property of a given layer. Adding one allows you to make transparent pixels later (for instance with the eraser), but doesn't make your layer transparent immediately.
The alpha-channel exists when the image is loaded from a format that allows transparency (such as PNG...). It is also added automatically to all new layersbecause it rarely makes sense to stack opaque layers (except for GIF animations).
There is no such thing as a "layer of transparency". The checkerboard pattern isn't a layer, it it below the lowest layer, you see it where all the stacked layer are transparent.

A: I am currently using Gimp 2.10 but if I remember properly I think you should select adding a new layer, whatever you choose will be right and then you will realize that adding an alpha channel option has been enabled.
If you're wondering why it seems like you magically get alpha channels sometimes, it looks like GIMP will add an alpha channel automatically when you add a layer (even if that layer doesn't have a background of type Transparency); I suspect that GIMP uses alpha channels for its internal use. E.g., this caught me off guard when editing a single layer grayscale image, then it silently converted my image on save to an RGB with alpha image. Check the channels tab if you are ever in doubt.
Hope it helps.


text:
Q: Change the suffix of column name after merging I am merging two datasets using join commands however, I get .x & .y as the suffix of merged dataframe.
Required output is to have "_1" & "_2" as the suffix in the final merged dataframe.
Example using mtcars what I am trying
mt2 <- mtcars %>%
  rownames_to_column(var="id")

  mt2 %>%
  inner_join(mt2, by="id") %>%
  head()

Output of column name
id, mpg.x, cyl.x ...... mpg.y, cyl.y

Required output
id, mpg_1, cyl_1........mpg_2, cyl_2

A: You were so close to get this done (If I understood your question right)
Just try suffix argument from join function (from dplyr package)
library(dplyr)
data("mtcars")
mt2 <- mtcars %>%
rownames_to_column(var="id")

mt2 %>%
inner_join(mt2, by="id",suffix=c("_1","_2")) %>%
names() %>%
  dput()

Output of column names
    c("id", "mpg_1", "cyl_1", "disp_1", "hp_1", "drat_1", "wt_1",
"qsec_1", "vs_1", "am_1", "gear_1", "carb_1", "mpg_2", "cyl_2",
"disp_2", "hp_2", "drat_2", "wt_2", "qsec_2", "vs_2", "am_2",
"gear_2", "carb_2")


text:
Q: Devise invitable custom message not working - rails I'm using devise_invitable to allow for user invites.
Here is what I have in my user model:
attr_accessor :custom_message

I created a new controller called invitations_controller.rb and here is what I have inside it:
class InvitationsController < Devise::InvitationsController
    def create
         User.invite!({email: email}, current_user) do |user|
           user.message = params[:custom_message]
     end
end

And here is what is inside my new invite form:
<%= t "devise.invitations.new.header" %>

<%= simple_form_for resource, :as => resource_name, :url => invitation_path(resource_name), :html => {:method => :post} do |f| %>

<% resource.class.invite_key_fields.each do |field| -%>
  <%= f.input field  %>
<% end -%>

<%= f.input :custom_message  %>

<%= f.submit t("devise.invitations.new.submit_button") %>
<% end %>

And this is what I have in my invitation mailer:
<%= @resource.email %>

<%= @resource.custom_message %>

<%= link_to 'Accept this invitation', accept_invitation_url(@resource, :invitation_token => @token) %>

When I enter the email address, and the custom message and click send, this is what I see in the log:
Started POST "/users/invitation" for 127.0.0.1 at 2014-04-15 15:30:18 -0400
Processing by Devise::InvitationsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"x4Mb6AkF1GnZ5bHlipBbLh/X/T0zcHkkkxrtkHW7Y0U=",
"user"=>{"email"=>"email@gmail.com", "custom_message"=>"Test message"}, "commit"=>"Send an invitation"}

The email sends out successfully, I see no errors, but nothing shows up were the custom message is supposed to be, the custom message is blank from within the email that is received. What is causing this? How can I fix it?
Edit: I am getting an unpermitted parameter error on the custom_message
This is what I have in my application controller:
before_filter :configure_permitted_parameters, if: :devise_controller?

 protected

  def configure_permitted_parameters
 devise_parameter_sanitizer.for(:accept_invitation) do |u| u.permit(:username,:validate_username,  :password,:password_confirmation, :invitation_token)
devise_parameter_sanitizer.for(:accept_invitation).concat [:custom_message]
 end
 end

A: Might be this will work.
 User.invite!({email: email, message: params[:user][:custom_message] }, current_user)

If you are getting Un permitted error, you should do something like in either application or User controller.
before_filter :configure_permitted_parameters, if: :devise_controller?

def configure_permitted_parameters
    devise_parameter_sanitizer.for(:invite).concat [:custom_message]
end

You also have to edit invitation mailer, since you are using custom_message attribute which has no value . You should use message since you are assigning data into it. So
<%= @resource.custom_message %>

changes to
<%= @resource.message %>

A: Look closely at your log, it has the answer. Your parameter value is at
params[:user][:custom_message]

not
params[:custom_message]


text:
Q: Declare a functional component as "pure" How to signal to React that a functional component is "pure", as an equivalent of React.PureComponent for component classes?
function C(props) {
  return <var>{props.n}</var>
}

without making it a class
class C extends React.PureComponent {
  render() {
     return <var>{this.props.n}</var>
  }
}

A: Based on the concept of purity in functional programming paradigms, a function is pure if:

*

*Its return value is only determined by its input values

*Its return value is always the same for the same input values

There seem two ways to do it for React functional components:

*

*Using memo from react:
import React, { memo } from 'react';

const Component = (props) {
  return (
    // Component code
  )
}

// Wrap component using "memo" HOC
export default memo(Component);

*Using pure from recompose:
import React from 'react';
import { pure } from 'recompose';

const Component = (props) {
  return (
    // Component code
  )
}

// Wrap component using "pure" HOC
export default pure(Component);

A: To @Shubham and @Andrew:
No, functional components are not PureComponents. Functional components will always get re-render if the parent component re-renders. A PureComponent contains a default shouldComponentUpdate() and I think that's what OP wants.

You can use pure provided by recompose to wrap and optimize your functional components:
import pure from 'recompose/pure'

const YourFunctionalComponent = (props) => {
  ...
}

export default pure(YourFunctionalComponent)

A: As of React 16.6.0, memo has been added, so the answer is now:
const C = React.memo(props => {
  return <var>{props.n}</var>
})

A: In addition to CodinCat answer.
The author of the library, recomponse, wrote a note on 25th Oct of 2018, where he stated, that what he tried to solve by the library was solved by the React Team through introducing hooks. Not only that, React team added optimization feature like React.memo(), which was named as React.pure() earlier. So, it's time to use React.memo(). Read Official Docs about it


text:
Q: Most efficient way to find every max number in a set of a numbers I have 3 int values:
int value1;
int value2;
int value3;

And 3 bool values:
bool maxIs1;
bool maxIs2;
bool maxIs3;

Input values have to be separate variables.
maxIs1 = True means that value1 must have maximum value and so on.
I need method to compare this set of numbers with set of conditions.
For example:
int value1 = 10;
int value2 = 1;
int value3 = 10;

bool maxIs1 = True;
bool maxIs2 = False;
bool maxIs3 = True;

bool result = compareValues(); //true

Or:
int value1 = 1;
int value2 = 1;
int value3 = 10;

bool maxIs1 = True;
bool maxIs2 = False;
bool maxIs3 = True;

bool result = compareValues(); //false

What is the most efficient way to do so?

A: This was fun. If you can put them into an array you can use linq to cleanly check if they all satisfy the condition:
var values = new[] { value1, value2, value3 };
var maxes = new[] { maxIs1, maxIs2, maxIs3 };
var max = values.Max();

var result = values
    .Zip(maxes, (f, s) => new { value = f, isMax = s })
    .All(c => !c.isMax || (c.value == max));

A: I don't think you have to care about efficiency in case of 3 values
int value1 = 10;
int value2 = 1;
int value3 = 1;

bool maxIs1 = true;
bool maxIs2 = false;
bool maxIs3 = true;

int max = new[] { value1, value2, value3 }.Max();
bool result = (!maxIs1 || value1 == max) && (!maxIs2 || value2 == max) && (!maxIs3 || value3 == max);

A: Try this solution if you want different number of value :
static void Main()
    {
        List<int> listOfInts = new List<int>();
        List<bool> listOfBools = new List<bool>();

        listOfInts.Add(1);
        listOfInts.Add(2);
        listOfInts.Add(1);

        listOfBools.Add(false);
        listOfBools.Add(false);
        listOfBools.Add(false);

        Console.WriteLine("value = " + Compare(listOfInts,listOfBools));

    }

and Compare() should be like this :
static bool Compare(List<int> listOfInts, List<bool> listOfBools)
    {
        int max = listOfInts.Max();
        bool isCorrect = true;

        var maxList = listOfInts.Where(value => value == max);
        var indicesOfMax = GetIndeciesOfMax(maxList, listOfInts);

        for (int i = 0; i < listOfInts.Count; i++)
        {
            if (indicesOfMax.Contains(i) && listOfInts[i] == max && listOfBools[i])
            {
                isCorrect = true;
            }
            else if (!indicesOfMax.Contains(i) && listOfInts[i] != max && !listOfBools[i])
            {
                isCorrect = true;
            }
            else
            {
                isCorrect = false;
                break;
            }
        }

        return isCorrect;
    }

    static List<int> GetIndeciesOfMax(IEnumerable<int> maxList, List<int> list)
    {
        List<int> indecies = new List<int>();

        foreach (var m in maxList)
        {
            indecies.Add(list.IndexOf(m));
        }

        return indecies;
    }


text:
Q: looping through product collection and saving products is changing attribute values unintended changes I am running a loop through a product collection like the following
$productCollection = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('small_image')
    ->addAttributeToSelect('thumbnail')
    ->addAttributeToSelect('image')
    ->addAttributeToSelect('sku');

foreach($productCollection as $product){
    $product->setSmallImage($product->getImage());
    $product->setThumbnail($product->getImage());
    $product->save();
}

I am setting the other image types to the same as the base image because the client forgot to set those in the import sheet. For some reason when doing this it is setting the visibility of all products to Catalog, Search. A lot of my products are suppose to be "Not Visible Individually", so of course this messes stuff up.
Any Idea why this value would change, and are there other values that might change based on how I looped through the product collection?
I think it is because i removed the addAttributeToSelect(*) and did it specific to the two attributes but when trying to do the product collection over 18k products it was crapping out

A: Ok so this is what I found. When saving an object in Magento, it will call the normal Model abstract save method, this then calls $this->_getResource()->save($this); which will call the entity abstract save method, which eventually gets to /app/code/core/Mage/Eav/Model/Entity/Abstract.php and its _beforeSave() method which calls the walkAttributes($partMethod, array $args=array()) method.
A long the way all the attributes are loaded the the Resource object of the entity. The walkAttributes method will go through all attributes associated to the entity and calls this method call_user_func_array(array($instance, $method), $args); and in my case it is calling the beforeSave method for an attribute, as you can see here
/app/code/core/Mage/Eav/Model/Entity/Attribute/Backend/Abstract.php
public function beforeSave($object)
    {
        $attrCode = $this->getAttribute()->getAttributeCode();
        if (!$object->hasData($attrCode) && $this->getDefaultValue()) {
            $object->setData($attrCode, $this->getDefaultValue());
        }
    }

So any attribute that does not have any data and has a default value, that default value is applied to the object, in sense overwriting my data that is really set just not loaded to my object. I am guessing the best way to loop over thousands of products is to set the pageSize to a number that your server can handle loading and then you can set addAttributeToSelect('*'). However I am not aware of the best way to loop over this correctly, so for me I might just load the product in the for loop and not set the attribute to select all.
Here is my attempt at looping over the whole collection, please post any improvements
$productCollection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*')->setPageSize(200);
for ($i = 1; $i <= $productCollection->getLastPageNumber(); $i++) {
    if ($productCollection->isLoaded()) {
        $productCollection->clear();
        $productCollection->setPage($i);
        $productCollection->setPageSize(200);
    }
    foreach ($productCollection as $product) {
        echo $product->getId() . "\n\n";
    }
    echo $i . "\n\n";
}

I would like to still hear any other input on this as to whether this is the right thinking or explanation of the problem.

A: I actually found a better way to loop over a large collection, which is to use the resource iterator model and here is a tutorial on how to do so from the Fontis guys
http://www.fontis.com.au/blog/magento/loading-large-collections


text:
Q: Continuous nodes in Bayes net toolbox for Matlab I have a node representing a random variable whith 3314 realizations and 49 dimensions each, can it be treated as a discrete variable? Each realization is a binary vector of 49 dimensions, the other nodes are observable therefore the network training is performed with learn_params. This function transforms data as follows:
local_data = data(fam, :);
if iscell(local_data)
  local_data = cell2num(local_data);
end

When this transformation takes place, the data lose their structure and become just an array of 162386 = (49 * 3314) so every vector of 49 dimensions cannot be seen as an embodiment of the variable, now will be 162386 realizations and the training on network node will not be correct.
I want to know if it is really possible (right?) take this variable as discrete and what training alternative I have for not modifying the data structure.


text:
Q: How to Predict Future values Using LSTM? I am kind of new in time series forecasting and deep learning. I have a dataset regarding Solar Irradiation and I am using Jupyter Notebook. I have divided data into 3 parts train, val and test. Trained the model and got the predictions on the test dataset. The dataset is from 2010 to 2020 consisting of each hour. I want to make future prediction like from 2021 to 2024.
This is how dataset and current plot looks like:
These are the prediction that I made on the train, val and test dataset.  .
But I am unable to make future predictions.
I extended the dataset for future prediction
but not able to make the prediction. Also, how to handle these NaN values?
## Made a function for window size took the window size as 24

def df_to_X_y(df, window_size=24):
    df_as_np = df.to_numpy()
     X = []
     y = []
     for i in range(len(df_as_np)-window_size):
         row = [[a] for a in df_as_np[i:i+window_size]]
         X.append(row)
         label = df_as_np[i+window_size]
         y.append(label)
     return np.array(X), np.array(y)`

WINDOW_SIZE = 24
x,y = df_to_X_y(Irr,WINDOW_SIZE)
x.shape,y.shape

## Splitted the Data

X_train, y_train = x[:80000], y[:80000]
X_val , y_val = x[80000:90000] , y[80000:90000]
X_test , y_test = x[90000:] , y[90000:]

## Model
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import *
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.losses import MeanSquaredError
from tensorflow.keras.metrics import RootMeanSquaredError
from tensorflow.keras.optimizers import Adam

model1 = Sequential()
model1.add(InputLayer((24, 1)))
model1.add(LSTM(64))
model1.add(Dense(8, 'relu'))
model1.add(Dense(1, 'linear'))

model1.summary()

model1.fit(X_train, y_train,
validation_data(X_val,y_val),epochs=50,callbacks=[cp])

train_predictions = model1.predict(X_train).flatten()
train_results = pd.DataFrame(data={'Train Predictions':train_predictions, 'Actuals':y_train})
train_results.index = pd.to_datetime(df['Date'][:80000], format='%Y-%m-%d %H:%M:%S')
train_results.head(125)

## Val predictions
val_predictions = model1.predict(X_val).flatten()
val_results = pd.DataFrame(data={'Val Predictions':val_predictions, 'Actuals':y_val})
val_results.index = pd.to_datetime(df['Date'][80000:90000], format='%Y-%m-%d %H:%M:%S')
val_results

## Now Testing on the Test dataset

test_predictions = model1.predict(X_test).flatten()
test_results = pd.DataFrame(data={'Predictions':test_predictions, 'Actuals':y_test})
test_results.index = pd.to_datetime(df['Date'][90000:96408], format='%Y-%m-%d %H:%M:%S')

test_results

## Future Predictions
test_results_last_24 = test_results['Test Predictions'][-24:] ## Taking last 24 values
test_results_last_24

x_input = array(test_results_last_24)

temp_input=list(x_input)
lst_output=[]
i=0
while(i<10):

    if(len(temp_input)>24:
        x_input=array(temp_input[1:])
        print("{} day input {}".format(i,x_input))
        #print(x_input)
        x_input = x_input.reshape((1, n_steps, n_features))
        #print(x_input)
        yhat = model.predict(x_input, verbose=0)
        print("{} day output {}".format(i,yhat))
        temp_input.append(yhat[0][0])
        temp_input=temp_input[1:]
        #print(temp_input)
        lst_output.append(yhat[0][0])
        i=i+1
    else:
        x_input = x_input.reshape((1, n_steps, n_features))
        yhat = model.predict(x_input, verbose=0)
        print(yhat[0])
        temp_input.append(yhat[0][0])
        lst_output.append(yhat[0][0])
        i=i+1

print(lst_output)

Getting The Error
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_13296/1377391710.py in <module>
----> 1 x_input = array(test_results_last_24)
  2 temp_input=list(x_input)
  3 lst_output=[]
  4 i=0
  5 n_features = 1

TypeError: array() argument 1 must be a unicode character, not Series
This is what I have used

A: I don't know how you extended the dataset, but I think it should be like this: in the existing data, suppose the solar irradiation data of the previous 24 hours is used to predict the solar irradiation data of the next hour. Your data is from 2010 to 2020. Then you can use the data of the last day of 2020 to predict the data of the first hour of January 1, 2021, and then you can use the data of the last 23 hours of 2020(true value) and the data of the first hour of January 1, 2021(predicted value) to predict the data at the second hour, and so on. In general, NaN do not appear in your model's predictions, and if they do, you need to retrain your model.


text:
Q: Ubuntu 11.04: Running MARS simulator I am trying to run the MARS simulator in order to do some Assembly homework in Ubutnu 11.04. MARS(jar file) requires Java to be installed and so I did install Java.
After that I typed
java -jar .jar

and as a result I got:

Failed to load Main-Class manifest attribute from .jar

What must I do in order to run this file properly?

A: There are different Java implementations and you are not using the "official" one. (As is clear from the libgcj.so that appears on your error) and that one tends to be the most reliable.
Ubuntu 11.04 might still have the java-6-sun package (it was deprecated on newer Ubuntu releases because of license conflicts), so you should try with that one.
If that java is not in Ubuntu, then you can try downloading and installing Java from the Oracle site.