How can I custom format the top bar clock in Ubuntu 20.04 without extensions?

Question: I wanted to format the clock without the use of extensions...
Answer: BLUF: This is a permanent and clean way to alter formatting of the Gnome top bar clock to your liking without the use of extensions.
My goal was to simply do this without any extension so the custom time format would be seen consistently at the initial gdm login screen upon boot, while in active logged-in sessions, and on the session unlock screen.  It took some digging but the key lies in how Gnome handles localization/internationalization and how the Gnome wall clock, as it's called, obtains the string to actually display in the top bar.
First, a bit of background on the use of .po and .mo files in Gnome localization/internationalization can be found here:
https://wiki.gnome.org/TranslationProject/LocalisationGuide
Basically, at runtime, Gnome wall clock takes the current time and applies localization/internationalization string formatting.  It uses a string key to look up a formatting string to use for a given locale to determine what to actually display -- it does not rely on the locale file formatting strings.  If you modify the value returned for a given key in the localization/internationalization file, the clock display will reflect the change.  Localization/internationalization uses two files.  The first is the human-readable .po file that translators populate for each locale and this is where the mapping from lookup keys to formatting strings can be found.  The second is the .mo file that is generated from the .po file... more on this and how it relates in just a bit...
Below is a link to the source for the Gnome wall clock version used in Ubuntu 20.04:
https://github.com/GNOME/gnome-desktop/blob/gnome-3-36/libgnome-desktop/gnome-wall-clock.c
If you examine the function 'gnome_wall_clock_string_for_datetime' beginning at line 310, you'll see the localization/internationalization lookup keys in use.  There are several.  Ubuntu has various display settings for the wall clock depending on whether you want to display just the time, time with day, time with day and date, etc.  Each of these corresponds to a given localization/internationalization lookup key that wall clock uses.  What you see in quotations below is not the formatting string itself but rather the key to look up the actual formatting string.  The N_( that surrounds each key performs the lookup:
char *
gnome_wall_clock_string_for_datetime (GnomeWallClock      *self,
                      GDateTime           *now,
                      GDesktopClockFormat  clock_format,
                      gboolean             show_weekday,
                      gboolean             show_full_date,
                      gboolean             show_seconds)
{
    const char *format_string;

    g_debug ("clock_format: %s", clock_format == G_DESKTOP_CLOCK_FORMAT_24H ? "24h" : "12h");
    g_debug ("show_weekday: %s", show_weekday ? "TRUE" : "FALSE");
    g_debug ("show_full_date: %s", show_full_date ? "TRUE" : "FALSE");
    g_debug ("show_seconds: %s", show_seconds ? "TRUE" : "FALSE");

    if (clock_format == G_DESKTOP_CLOCK_FORMAT_24H) {
        if (show_full_date) {
            if (show_weekday)
                /* Translators: This is the time format with full date
                   plus day used in 24-hour mode. Please keep the under-
                   score to separate the date from the time. */
                format_string = show_seconds ? T_(N_("%a %b %-e_%R:%S"))
                    : T_(N_("%a %b %-e_%R"));
            else
                /* Translators: This is the time format with full date
                   used in 24-hour mode. Please keep the underscore to
                   separate the date from the time. */
                format_string = show_seconds ? T_(N_("%b %-e_%R:%S"))
                    : T_(N_("%b %-e_%R"));
        } else if (show_weekday) {
            /* Translators: This is the time format with day used
               in 24-hour mode. */
            format_string = show_seconds ? T_(N_("%a %R:%S"))
                : T_(N_("%a %R"));
        } else {
            /* Translators: This is the time format without date used
               in 24-hour mode. */
            format_string = show_seconds ? T_(N_("%R:%S"))
                                : T_(N_("%R"));
        }
    } else {
        if (show_full_date) {
            if (show_weekday)
                /* Translators: This is a time format with full date
                   plus day used for AM/PM. Please keep the under-
                   score to separate the date from the time. */
                format_string = show_seconds ? T_(N_("%a %b %-e_%l:%M:%S %p"))
                    : T_(N_("%a %b %-e_%l:%M %p"));
            else
                /* Translators: This is a time format with full date
                   used for AM/PM. Please keep the underscore to
                   separate the date from the time. */
                format_string = show_seconds ? T_(N_("%b %-e_%l:%M:%S %p"))
                    : T_(N_("%b %-e_%l:%M %p"));
        } else if (show_weekday) {
            /* Translators: This is a time format with day used
               for AM/PM. */
            format_string = show_seconds ? T_(N_("%a %l:%M:%S %p"))
                : T_(N_("%a %l:%M %p"));
        } else {
            /* Translators: This is a time format without date used
               for AM/PM. */
            format_string = show_seconds ? T_(N_("%l:%M:%S %p"))
                : T_(N_("%l:%M %p"));
        }
    }

    g_debug ("format_string: %s", format_string);

    return date_time_format (now, format_string);
}
For instance, I wanted a custom format string for displaying day, date, and time in 12 hour(AM/PM) format.  That is in Ubuntu, I had set the clock to display the day, date, and time in 12 hour format which corresponds to the 'full date' in the above code.  Examining the function, I was able to determine that this 'full date' lookup key occurred at line 361:
/* Translators: This is a time format with full date
                   used for AM/PM. Please keep the underscore to
                   separate the date from the time. */
                format_string = show_seconds ? T_(N_("%b %-e_%l:%M:%S %p"))
                    : T_(N_("%b %-e_%l:%M %p"));

I wasn't interested in seconds so the key I needed to find in the localization/internationalization .po file was:
'%b %-e_%l:%M %p'
Unfortunately, I couldn't locate this particular key in the en.po for my locale.  Since the 18.04 LTS release it appears that the Gnome folks have replaced the commas with underscores in the formatting string but the locale file -- at least for en -- has not been updated to reflect this change.
https://github.com/GNOME/gnome-desktop/blob/gnome-3-36/po/en.po
So, I needed to add it as well as the mapping to the formatting I wanted.
msgid "%a %b %-e_%l:%M %p"
msgstr "%A %b %-d, %l:%M %p"

The localization/internationalization .mo files are binary in format but easily generated from a human-readable plain-text mapping .po files that maps a given lookup key to formatting string.  Gnome wall clock uses a file with the specific name of gnome-desktop-3.0.mo for localization/internationalization.  It was not present on my system under the prescribed location for any locale:
/usr/share/locale/XX/LC_MESSAGES
So, I didn't need to worry about replacing it but rather creating it anew.  Regardless, you need to first obtain the .po file for your locale:
https://github.com/GNOME/gnome-desktop/tree/gnome-3-36/po
Again, many of the clock formatting strings are not present for the 'en' locale and I needed to add the one I was interested in.
Prior to the change reflected in the above 'msgstr' the clock would have displayed:
Mon Feb 4  12:22 PM
But after the above change the day is no longer abbreviated and the space separating the date and time has been replaced with a comma(see the end of this answer for the formatting specifiers):
Monday Feb 4, 12:22 PM
Next, take this .po file and run it through the following on the command line to obtain the messages.mo file where XX is your locale.  The binary msgfmt can be installed via 'sudo apt install gettext' in 20.04:
msgfmt -cv XX.po
Next, rename the resulting messages.mo file to gnome-desktop-3.0.mo and copy it to your specific locale LC_MESSAGE directory:
/usr/share/locale/XX/LC_MESSAGES/gnome-desktop-3.0.mo
Then, to effect the change, log out and log back in.  If you find that the formatting did not change then double check that your current clock settings truly correspond to the key for which you changed the formatting string.
Finally, here are some formatting string specifiers to help you along.  I borrowed these from another site so no guarantees that these all work in Gnome:
The % sign indicating a directive may be immediately followed by a padding modifier, e.g. %-d:

0 - zero-padding
_ - space-padding
- - disable padding

%a - abbreviated weekday name.*
%A - full weekday name.*
%b - abbreviated month name.*
%B - full month name.*
%d - zero-padded day of the month as a decimal number [01,31].
%e - space-padded day of the month as a decimal number [ 1,31]; equivalent to %_d.
%f - microseconds as a decimal number [000000, 999999].
%H - hour (24-hour clock) as a decimal number [00,23].
%I - hour (12-hour clock) as a decimal number [01,12].
%j - day of the year as a decimal number [001,366].
%m - month as a decimal number [01,12].
%M - minute as a decimal number [00,59].
%L - milliseconds as a decimal number [000, 999].
%p - either AM or PM.*
%Q - milliseconds since UNIX epoch.
%s - seconds since UNIX epoch.
%S - second as a decimal number [00,61].
%u - Monday-based (ISO 8601) weekday as a decimal number [1,7].
%U - Sunday-based week of the year as a decimal number [00,53].
%V - ISO 8601 week of the year as a decimal number [01, 53].
%w - Sunday-based weekday as a decimal number [0,6].
%W - Monday-based week of the year as a decimal number [00,53].
%x - the locale's date, such as %-m/%-d/%Y.*
%X - the locale's time, such as %-I:%M:%S %p.*
%y - year without century as a decimal number [00,99].
%Y - year with century as a decimal number.
%Z - time zone offset, such as -0700, -07:00, -07, or Z.
%% - a literal percent sign (%).

Comment: @Skillzone So noted.  I haven't explored this yet but you are correct.  I'm happy to have the gdm and desktop looking consistent at least.  I'm running vanilla gnome and have a bit of customizing to do to the Adwaita theme gresource file(including the font boldness of the clock on the lock screen aka screen shield) so I'll have a look in there while I'm at it... I might know of a few other locations that could influence the clock on the lock screen as well... I'll report back if I find anything
Comment: Awesome answer! I have my Ubuntu set to English (United States) language but with Sweden Formats. Thus I was expecting my Ubuntu to look for the gnome-desktop-3.0.mo in /usr/share/locale/sv/LC_MESSAGES, but apparently it is the /usr/share/locale/en/LC_MESSAGES it uses.  Then what effects do the Formats setting even have?
Comment: This does not affect the date on the lock screen, do you have a solution for that as well? I have just posted a question about it here: https://askubuntu.com/questions/1343639/how-can-i-custom-format-the-lock-screen-date-in-ubuntu-20-04-without-extensions
Answer: As the source code in Steve's well-researched answer shows, there are four settings that are supported by the clock, which can be changed without having to make changes to l10n/i18n files:

use 12/24h format
show the weekday
show the full date
show the seconds

They can be done through gsettings, e.g.
gsettings set  org.gnome.desktop.interface clock-show-seconds false
gsettings set  org.gnome.desktop.interface clock-show-date    true
gsettings set  org.gnome.desktop.interface clock-show-weekday true
gsettings set  org.gnome.desktop.interface clock-format       '24h'

(You can use gsettings get to check the values, or gsettings reset to put them back to the default setting.)
Comment: these four properties can also be changed through Gnome Tweaks


How to retrieve only those records that have at least one associated record?

Question: The data should show only the tenancies that contains data. In normal query normally I do this be right join.
I know contain() is left join on default but can contain be right join at all?
My query:
$properties = $this->find()
                ->select([
                    'Property.id', 'Property.company_id', 'Property.address1', 'Property.postcode',
                ])
                ->contain([
                    'Tenancies' => function($q) {
                        return $q
                            ->select([
                                'Tenancies.id','Tenancies.property_id','Tenancies.created',
                                'Tenancies.stage', 'Tenancies.landlord_offer_sent', 'Tenancies.offer_letter_contract_id',
                            ])
                            ->contain([
                                'Tenants' => function($q) {
                                    return $q
                                        ->select([
                                            'Tenants.id', 'Tenants.stage', 'Tenants.tenancy_id', 'Tenants.holding_fee',
                                        ])
                                        ->where([
                                            'active = 1',
                                        ]);
                                    }
                            ])
                            ->where([
                                'Tenancies.active = 1',
                            ]);
                    }
                ])
                ->where(['Property.active = 1', $conditions])
                ->toArray();

e.g. I need to get read of nodes that tenancies that are null 'tenancies' => [], and it should show only node 1.
Prints=>
(int) 0 => object(App\Model\Entity\Property) {

        'id' => (int) 95,
        'company_id' => (int) 3,
        'address1' => '40 Arthur Street',
        'postcode' => 'LE11 3AY',
        'tenancies' => [],
        '[new]' => false,
        '[accessible]' => [
            '*' => true
        ],
        '[dirty]' => [],
        '[original]' => [],
        '[virtual]' => [],
        '[errors]' => [],
        '[invalid]' => [],
        '[repository]' => 'Property'

    },
    (int) 1 => object(App\Model\Entity\Property) {

        'id' => (int) 102,
        'company_id' => (int) 3,
        'address1' => 'Grace Dieu Court',
        'postcode' => 'LE11 4QH',
        'tenancies' => [
            (int) 0 => object(App\Model\Entity\Tenancy) {

                'id' => (int) 16,
                'property_id' => (int) 102,
                'created' => object(Cake\I18n\FrozenTime) {

                    'time' => '2015-05-08T09:30:41+00:00',
                    'timezone' => 'UTC',
                    'fixedNowTime' => false

                },
                'stage' => (int) 6,
                'landlord_offer_sent' => false,
                'offer_letter_contract_id' => (int) 37,
                'tenants' => [
                    (int) 0 => object(Cake\ORM\Entity) {

                        'id' => (int) 16,
                        'stage' => (int) 7,
                        'tenancy_id' => (int) 16,
                        'holding_fee' => (float) 50,
                        '[new]' => false,
                        '[accessible]' => [
                            '*' => true
                        ],
                        '[dirty]' => [],
                        '[original]' => [],
                        '[virtual]' => [],
                        '[errors]' => [],
                        '[invalid]' => [],
                        '[repository]' => 'Tenants'

                    },
                    (int) 1 => object(Cake\ORM\Entity) {
                    ...
                    ...
                    ...

I have tried inner join 'joinType' => 'INNER' but no luck:
class TenancyTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('tenancy');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('Properties', [
            'foreignKey' => 'property_id',
            'className' => 'property',
            'joinType' => 'INNER'
        ]);

Answer: Not possible via containments for hasMany associations
This cannot be done with containments, as hasMany ones are being retrieved via a separate query. Instead you'll have to add a proper join yourself, an INNER join (more portable than a RIGHT join) could do it if you want to restrict the results to only those that have associated Tenancies.
A simple Query::innerJoinWith() without conditions, and some grouping to avoid duplicates
$properties = $this
    ->find()
    // ...
    ->innerJoinWith('Tenancies')
    ->group('Property.id');

... and you're done, this will add a join like
INNER JOIN tenancies Tenancies ON Property.id = Tenancies.property_id

innerJoinWith() works for all other types of associations too
For belongsTo and hasOne associations however, it could be done via containments, as for these types of associations, all data is being retrieved in the same query. To filter by those that have an associated record, just change the join type to INNER, like
$this
    ->find()
    ->contain([
        'BelongsToAssociated' => [
            'joinType' => 'INNER'
        ]
    ]);

See also

Cookbook > Database Access & ORM > Query Builder > Filtering by Associated Data
Cookbook > Database Access & ORM > Query Builder > Using innerJoinWith
Answer: This worked when I simply changed contains to matching.
It seems to be possible, see Filtering By Associated Data


Is it worth encrypting files being stored on a server for distribution?

Question: I'm creating a site for distributing software to clients. We're implementing lots of security bells and whistles on it to reasure the clients that software they're running wont have been tampered with.
I'm toying with the idea of encrypting the files we upload to the server, but I'm not sure if there's much point conisdering the overhead it entails. The files are decrypted anyway when being transmitted to the client. As well as this, if a hacker gets into the server and replaces the encrypted files, they can also change any hashes we made of the files to check they havnt been manipulated.
So... is it worth encrypting the uploaded files?
Answer: You should sign rather then encrypt your files.
When using PKI, it is the act of encrypt (or encrypt a hash of) your file with your private key, instead of doing so with the receiver's public key.
Then everybody that download the file can verify that the file was not tampered with.
File encryption is useful when either you share a secret with your
receivers, or that you have their public key available. Typically it
is not useful in case of file distribution as you describe it.
Comment: I agree completely with this answer.  Get a code-signing cert from a vendor with certs built into your target platform, protect it, use it to sign your deliverables, and then you can deliver your software from anywhere and the client can be satisfied of the security.
Answer: I will answer with a question: what is the point in encypting files on the server when you don't have any control over what the clients will do with the decrypted versions anyway?
Answer: Oh security.
How can the client be sure they're talking to the correct server.
How can the server be sure they're talking to a legal client.
How can the user be sure they're not using a compromised client etc.
Is the server in your custody or is it a shared server. How volatile is the data and is datatheft an acceptable risk or not.
Please expand your current situation. Do you use encrypted communcation. Is the communcation over internal or external lines. Do you thrust the server support team.


How do I make include files execute inclusively in php?

Question: I've been looking at some example php code to make a members area on a website. In the examples the tutor says that you can just put <?php include 'members_area_protection.php'; ?> at the beginning of whatever the page is at that will execute and then the rest of the members area stuff will execute. I tried to test the theory of this by writing a php file:
<?php
    $name = 'Stack Overflow';
    echo $name;
?>

and then including it in:
<?php include 'namefile.php'; ?>

  <title> Members-Only Page </title>
  <meta http-equiv="Content-Type"
    content="text/html; charset=iso-8859-1

Welcome, <?=$name?>! You have entered a members-only area
   of the site. Don't you feel special?

However, when I run the php the include file executes and echoes the name. But none of the other stuff happens. Is there a trick to getting it to carry onto the rest of the file? From my examples it doesn't look like it.
Thanks! (Sorry for the basic question I only just started using php)
Comment: What "other stuff" do you expect to happen?
Comment: Additionally to the unfinished meta-equiv line, please note that in your included file you echo a string, on top of the HTML you define in the including file. Use right-click and show-html-source in your browser to see what happens.
Answer: You have problem in this line
  <meta http-equiv="Content-Type"
    content="text/html; charset=iso-8859-1

Replace this with
<meta http-equiv="Content-Type"
    content="text/html; charset=iso-8859-1">

Or
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Otherwise code is fine.
Answer: Your meta tag isn't closed. You're missing ">
Try:
<meta http-equiv="Content-Type"
    content="text/html; charset=iso-8859-1">


$k[x,y,z]/(y-x^2,z-x^3)\cong k[x]$, where $k$ is a field

Question: This is generalizing from a previous question, which asks to prove that $k[x,y]/(y-x^2)\cong k[x]$. The way I proved that was by using the homomorphism $\phi:k[x,y]/(y-x^2)\to k[x]$, $\phi(\overline{f(x,y)})=f(x,x^2)$, which is well defined, since $$f(x,y)\in (y-x^2)\implies y-x^2\mid f(x,y) \implies 0\mid f(x,x^2) \implies f(x,x^2)=0$$ is trivially a surjective homomorphism, and is injective, since $$f(x,x^2) = 0\implies x^2 \mathrm{\,is\,a\,root\,of\,} f(x,y)\mathrm{\,in\,} k[x][y] \implies y-x^2\mid f(x,y)\mathrm{\,in\,} k[x][y]=k[x,y]$$ However, when I try to generalize this to $k[x,y,z]/(y-x^2,z-x^3)$, by defining $\phi:k[x,y,z]/(y-x^2,z-x^3)\to k[x]$, $\phi(\overline{f(x,y,z)})=f(x,x^2,x^3)$, I can show everything except injectivity. What I get is that $$f(x,x^2,x^3)=0\implies x^3 \mathrm{\,is\,a\,root\,of\,} f(x,x^2,z)\mathrm{\,in\,} k[x][z] \implies z-x^3\mid f(x, x^2,z)\mathrm{\,in\,} k[x][z]$$ or that $$f(x,x^2,x^3)=0\implies x^2 \mathrm{\,is\,a\,root\,of\,} f(x,y,x^3)\mathrm{\,in\,} k[x][y] \implies y-x^2\mid f(x, x^2,z)\mathrm{\,in\,} k[x][z]$$
Assuming the result, that $f=g+h$, where $y-x^2\mid g$ and $z-x^3\mid h$, the problem with my previous approach is that it is impossible to isolate either $g$ or $h$ without destroying some of the structure necessary to prove divisibility. How might it be possible to fix this?
Comment: Are you also interested in a simpler approach to show isomorphisms of this sort? or are you primary interested in fixing your own approach?
Comment: I think there's a typo in your last display. Anyway, in the older problem how did you know that $f(x,x^2) = 0$ implied this divisibility statement? I think this technique needs to be upgraded somewhat.
Comment: I used the euclidean algorithm over the field of fractions of $k[x]$.
Comment: Okay, that allows you to write $f(x,y) = (y-x^2)g$. But now $g$ is an element of $g(x)[y]$. What then?
Comment: I know already (and have been asked to prove) that if $R$ is a UFD then so is $R[X]$, and therefore, since $f$ has a prime factorization, one of those irreducible elements must have root $x^2$, since we are working over a domain. Then you apply Gauss's lemma – a polynomial is irreducible over the ring iff it is irreducible over the field of fractions.
Answer: Assume there are polynomials $f$ with $\phi(\overline f)=0$ and $f\notin (y-x^2,z-x^3)$.
Among these. let $f_0$ have minimal degree in $z$. If $f_0$ has positive degree $k$ in $z$, say $f(x,y,z)=p_0(x,y)+p_1(x,y)z+\ldots +p_k(x,y)z^k$, then $f_0(x,y,z)-p(x,y)z^{k-1}x^3$ is equivalent to $f_0$ but of lower degree in $z$. We conclude that $f_0$ has degree $0$ in $z$, i.e., is only a polynomial in $x$ and $y$. Again, among all polynomials with $\phi(\overline f)$ and $f\notin(y-x^2,z-x^3)$ and degree zero in $z$ let $f_1$ be of moinimal degree in $y$. By a similar argument, we conclude that $f_1$ is a polynomial in $x$ alone. As it is mapped to the zero polynomial, we conclude that $f_1=0$, i.e., our polynomilas were in $(y-x^2,z-x^3)$ to begin with.
This simple method works more generally when we consider $k[x_1,x_2,\ldots, x_n]/(x_2-f_2(x_1), x_3-f_3(x_1,x_2),\ldots,x_n-f_n(x_1,\ldots,x_{n.1}))$.
Comment: That generalizes very nicely to an induction argument. Thanks.


Algorithm for Cutting Patterns

Question: Let's say I have a given length c and I need to cut out several pieces of different lengths a{i}, where i is the index of a specific piece. The length of every piece is smaller or equal to the length c. I need to find all possible permutations of cutting patterns.
Does someone has a smart approach for such tasks or an algorithm to solve this?
The function could look something similar to this:
Pattern[] getPatternList(double.. a, double c);

The input is hence a list of different sizes and the total available space. My goal is to optimize/minimize the trim loss.
I'll use the simplex algorithm for that but to create an linear programming model, I need a smart way to determine all the cutting patterns.
Comment: You really need all of them? Typically only cutting patterns that "help" given the current reduced prices are necessary (if you're doing Cutting Stock with column generation). You'd only need one at the time and you can use the usual Knapsack tricks.
Comment: Please add input and output examples
Comment: @BastianSchoettle I added the integer-programming approach to my answer.
Comment: @harold: All relevant ones. Since it's hard to determine the quality of a pattern, I would prefer to have too much instead of missing a good one.
Comment: @Ohad: I updated my question according to your requirement.
Comment: It's not really clear what you want to do. Using simplex, but needing all the cutting-patterns for that? What do you want to do? What is a cutting-pattern for you? If it's a subset of selected items, it's just space - sum(subset) to determine the trim-loss (no simplex needed). Why not just use integer-programming to select this subset while minimizing trim-loss (you would not need to think about these cuts before).
Comment: @sascha: Let's say I have 3 different pieces {a,b,c}, where a=5cm, b=3cm and c=2cm. One piece of resources material is 10cm. One cutting pattern would hence be 1 a, 1 b and 1c. And another could be 2b and 1c. So, I would than for example need at least 10 pieces of a and 4 of c. To minimize usage of resources material under given constraints, I would of course use an linear integer programming approach. But do you know another way to model it as such without the patterns?
Comment: @BastianSchoettle (1) Your question did not say, that items can be picked multiple times. You should have been more clear about that (2) Reading your comment above, the problem you want to solve is nowhere near that, which you describe. You **now** describe somewhat the cutting-stock problem in one dimension. So just read up on that. It's common to use column-generation, but this concept is a bit different to *generate all possible patterns before*.
Comment: @sascha: Yes, you are right about your advice. I will keep it in my mind for the future. Thank you very much for your answer and the code. I'll have a look at the column-generator and try that approach. It seemed also to me a bit inefficient to determine the cutting patterns upfront but this approach was somehow intuitive:) Thank you very much!
Answer:
There are exponentially many cutting-patterns in general. So it might not be feasible to construct them all (time and memory)
If you need to optimize some cutting based on some objective, enumerating all possible cuttings is a bad approach (like @harold mentioned)

A bad analogy (which does not exactly apply here as your base-problem is np-hard):
solving 2-SAT is possible in polynomial-time
enumerating all 2-SAT solutions is Sharp-P-complete (an efficient algorithm would imply P=NP, so there might be none!)

A simple approach (to generate all valid cutting-patterns):

Generate all permutations if items = ordering of items (bounded by !n)
Place them one after another and stop if c is exceeded
(It would be a good idea to do this incrementally; build one permutation after another)
Assumption: each item can only be selected once
Assumption: moving/shifting a cut within a free range does not generate a new solution. It it would: solution-space is possibly an uncountably infinite set

edit
Code
Here is a more powerful approach handling the problem with the same assumptions as described above. It uses integer-programming to minimize the trim-loss, implemented in python with the use of cvxpy (and a commercial-solver; can be replaced by an open-source solver like cbc):
import numpy as np
from cvxpy import *
np.random.seed(1)

# random problem
SPACE = 25000
N_ITEMS = 10000
items = np.random.randint(0, 10, size=N_ITEMS)

def minimize_loss(items, space):
    N = items.shape[0]
    X = Bool(N)
    constraint = [sum_entries(mul_elemwise(items, X)) <= space]
    objective = Minimize(space - sum_entries(mul_elemwise(items, X)))
    problem = Problem(objective, constraint)
    problem.solve(solver=GUROBI, verbose=True)

    print('trim-loss: ', problem.value)
    print('validated trim-loss: ', space - sum(np.dot(X.value.flatten(), items)))
    print('# selected items: ', np.count_nonzero(np.round(X.value)))

print('items: ', items)
print('space: ', SPACE)
minimize_loss(items, SPACE)

Output
items:  [5 8 9 ..., 5 3 5]
space:  25000
Parameter OutputFlag unchanged
   Value: 1  Min: 0  Max: 1  Default: 1
Changed value of parameter QCPDual to 1
   Prev: 0  Min: 0  Max: 1  Default: 0
Optimize a model with 1 rows, 10000 columns and 8987 nonzeros
Coefficient statistics:
  Matrix range    [1e+00, 9e+00]
  Objective range [1e+00, 9e+00]
  Bounds range    [1e+00, 1e+00]
  RHS range       [2e+04, 2e+04]
Found heuristic solution: objective -25000
Presolve removed 1 rows and 10000 columns
Presolve time: 0.01s
Presolve: All rows and columns removed

Explored 0 nodes (0 simplex iterations) in 0.01 seconds
Thread count was 1 (of 4 available processors)

Optimal solution found (tolerance 1.00e-04)
Best objective -2.500000000000e+04, best bound -2.500000000000e+04, gap 0.0%
trim-loss:  0.0
validated trim-loss:  [[ 0.]]
# selected items:  6516

edit v2
After read your new comments, it is clear, that your model-description was incomplete/imprecise and nothing above tackles the problem you want to solve. It's a bit sad.
Answer: You will need to enumerate all permutations of a, and then take the longest prefix that has length less than or equal to c.
This sounds like a version of the knapsack problem (https://en.wikipedia.org/wiki/Knapsack_problem), and nobody knows an efficient way to do this.
Comment: There's actually a much more specific name for the problem, although it's a variant of (and reducible to) the knapsack problem: [Stock Cutting Problem](https://en.wikipedia.org/wiki/Cutting_stock_problem)
Comment: @jedwards: Thanks.

Algorithm for Cutting Patterns


Improper triple integral bounds of integration in cylindrical coordinates

Question: Regrettably I don't understand the process of change of coordinates and change of bounds very well.
Cartesian coordinates may be retrieved from cylindrical coordinates by
$x = r \, \cos \, \theta \\ y = r \, \sin \, \theta \\ z=z$
where
$\displaystyle {r  \ge 0,\;\;\;}\kern-0.3pt {0 \le \theta \le 2\pi ,\;\;\;}\kern-0.3pt  {- \infty  \lt z \lt \infty .}$
In case we have a triple integral of the form
$\displaystyle \int _0^{\infty }\int _0^{\infty }\int _0^{\infty }f(x,y,z)dxdydz$
the corresponding integral in cylindrical coordinates will be
$\displaystyle  \int_c^d \int_{\beta}^{\alpha} \int_a^b f(r, \theta, z) r \, dr \, d\theta \, dz.$
For the bounds of integration of $(x,y,z)$ going from zero to infinity, what would be the values of $a,b,c,d,\alpha,\beta$ ?
Answer: The variable $z$ has not changed, so that one is easy: $c=0, d = \infty$.
For the rest, use this approach: sketch the region that you are integrating over. It's as simple as representing that region in terms of your new coordinates. In this case, the region is just the octant of the $3$-dimensional plane with positive $x$, $y$, and $z$ coordinates. Since we already took care of $z$, let's look at where $x$ and $y$ can lie. In the two-dimensional $xy$ plane, they must lie in the first quadrant. How can we represent this in terms of a radius ($r$), and a central angle ($\theta$)?
Since we can have a point in the first quadrant arbitrarily far from the origin, we know $r$ goes from $0$ to $\infty$. But what about $\theta$? Well, the first quadrant only has $0 \leq \theta \leq \pi/2$, so we have our answer.
In general, it may not be easy to have this "visual intuition" that cylindrical coordinates may have. But when faced with an arbitrary change of variables, just draw out the region you are integrating over, and determine the ranges that each of your new variables can take.


VIM Adventures Level 9 - Getting out of the PI puzzle?

Question:
So, I'm playing VIM adventures to get a grasp on basic VIM.  In this case, the game is asking me to reach that key in the bottom right.  The cursor is currently sitting on the darkened "8" block.  I cannot move the cursor onto the numbers sitting over the bottomless pit.  Once a block is passed over, it disappears, which is how I ended up in this situation.
The game introduces various VIM keys over time- as of now, this is what I have available to me:

Essentially, I need to either find a set of keystrokes which would land the cursor on that block with the key or restart the game.  Restarting wouldn't be too much of a hassle, just good review if anything, but I figured someone here might enjoy looking for a solution.
Comment: What's' your question?  Are you asking us to play the game?
Comment: @Nelson        I'm just asking whether or not there would be a way, using VIM inputs, to solve this little puzzle. You don't need to play the game to understand, but you do need to understand VIM.
Answer: I can imagine 2 possible solutions for now:
1. **
2. 10k l 7j 2l 4j 3l
Comment: I'm not sure why your answer got downvoted.  Solution #1 will not work -- on the first `*` Vim will try to find all the text in the "word" (so, **5058223172**), and since there's only one instance, the cursor will fall through the first non-blank character (5) and "die".  But, I've just confirmed that  Answer #2 works fine.  If you edit out the first (non-working) answer, I'll upvote.


Insertion of NM electrical cable into plastic boxes

Question: Some installers routinely completely knock out the rectangular flap to create an open rectangle for passage of NM cable into a plastic box. I was under the impression that was to be left attached on one side to act as a clamp and a seal. What is the official requirement? Is this widely done?
The Carlon new work single gang blue plastic box I have in front of me (possibly 20 years old but don't actually know) has the flaps symmetrically and flimsily attached. I thought one side would be strongly attached and the other weakly. Are there better quality plastic boxes in which the flaps are asymmetrical?
EDIT
It seems that only the standard small size of single gang plastic new work box allows the total removal of the flap, right? So the multi-gang new work plastic boxes require leaving the flap attached on one side? And all old work plastic boxes require some attachment of NM cable to the box? E.g., installation of old work boxes require leaving the flap as a clamp?
Comment: When UL approves the box, they also approve the labeling on the box, and the instruction sheet intended to go with the box.  Of course, big-box stores buy by the carton, sell them loose in bins, and don't give you the instruction sheet.  But it should be on the Internet.

The labeling and instructions define the conditions under which UL tested and certified the device.
Answer: Products vary widely. Some have tensioned flaps that are obviously designed to retain the cable. Some are just flimsy knockouts. You can use them or not depending on your particular level of workpersonship.
The critical point may be that none are rated as complete retention devices anyway, meaning that cable must be fastened (stapled) within 12" of the box with any of them, and within 8" for boxes that don't have clamps.
Related discussion: I broke the knockouts on the blue receptacle boxes while doing electrical rough in. Now what?


SQL Server 2008 Stored Precedure

Question: This stored procedure is giving me an error due to truncation on the customerAddress.
Here is my code:
CREATE PROCEDURE insertNewCustomer
-- Add the parameters for the stored procedure here
@customerId char(8),
@customerName varChar(20),
@customerAddress varChar(18),
@zipCode integer
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
INSERT INTO customer (customerId, customerName, customerAddress, zipCode)
VALUES ('Z0999999', 'Larisa Preiser', '3801 W. Temple Avenue', '92335')
END
GO

EXEC insertNewCustomer 1, '', '', 0

Any ideas on how to make it truncate it?
Comment: Can you show use how you're testing and what the results are before and after
Comment: Have you executed the procedure using the EXEC statement?
Comment: Yes it says the command completed successfully. Also the results are no rows both times!
Comment: @dctucker No I have not put any EXEC anywhere nor know what that is.
Comment: @JonathanWood I have been writing a query on my customer table to see if the new customer appears.
Comment: I dont have the EXEC command I guess. Would I put @customerId after EXEC?
Answer: Have you executed the procedure using the EXEC statement?
You must first create the procedure by running the CREATE PROCEDURE command, and then execute it with the EXECUTE command. Please read this tutorial.
http://databases.about.com/od/sqlserver/a/storedprocedure.htm
Try running
EXECUTE insertNewCustomer 1, '', '', 0

Modify your procedure as follows
CREATE PROCEDURE insertNewCustomer
-- Add the parameters for the stored procedure here
@customerId char(8),
@customerName varChar(20),
@customerAddress varChar(18),
@zipCode integer
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
INSERT INTO customer (customerId, customerName, customerAddress, zipCode)
VALUES (@customerId, @customerName, @customerAddress, @zipCode)
END
GO

Comment: @PrettSangda I'm attempting to provide direction please unflag
Comment: I says that my line 19 string or binary data would be truncated.
Comment: Ah, this is good, means it's attempting to INSERT. You should make sure the table can hold all of the data you're throwing at it though your INSERT command there.

Also, if you want to bind the inputs (@customerID etc) you should put them into the INSERT statement within the CREATE OR ALTER PROCEDURE sequence.
Comment: I know that the customerAddress is larger than my varChar(18) but can't I force it to truncate it?
Comment: Sure use LEFT(@whatever,18) ... [link](http://msdn.microsoft.com/en-us/library/ms177601.aspx)
Comment: Why would I want to remove the VALUES for the @ things? I am trying to use the input parameters to put that certain data in. (Even if its redundant to use it again)
Comment: It's really not clear what you're trying to accomplish. Perhaps you could describe it more thoroughly in your original question.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/20426/discussion-between-dctucker-and-dddd)
Comment: Thank you all! I needed to add the EXEC cmd.
Answer: When you run the above script is for create your stored procedure in the database.
To execute your stored procedure after created.
E.g
exec insertNewCustomer  'xxx','xxx','xxx',0

please take noted, your sample query not take the input arguments as the input to insert to your table
Answer: If you run the SQL Server code you've posted, it will create a stored procedure. It will not run the stored procedure or insert any rows into your customer table.
After you have created the stored procedure, it is available to call. Most people would call stored procedures using a language such as C#. I have no idea what, if any, other language you are using.
You can also run the stored procedure directly in SQL Server Management Studio using the EXECUTE command. (If you have SQL Server, you have the EXECUTE command.)
Comment: My answer contained a link. Did you click it?
Comment: There are examples near the bottom. Your stored procedure requires several arguments; however, it doesn't use them.

SQL Server 2008 Stored Precedure


disable clicks and mouseevents in javascript for a flash embed/object tag

Question: I have a flash object on my page and I want to disable clicks on it using Javascript. I tried to use the following code:
document.getElementById('flash-obj').onclick = function(){return false;};
document.getElementById('flash-obj').onmouseup = function(){return false;};
document.getElementById('flash-obj').onmousedown = function(){return false;};

It doesn't work. Is there any other alternative? Any examples would be appreciated.
Cheers
Nyo
Answer: I think the only way to achieve what you want is using absolutely positioned  element on top of the flash-object. The same technic is used to prevent mouse events to fire in iframe instead of main document.
Comment: Yes, you are correct. Although my described code works in some cases, it still doesn't work in all cases. The only (javascript only) way is with a transparent absolutely positioned div. Therefore, I accept your solution.
Answer: You could use ExternalInterface, something like this:
In flash, register a callback:
if (ExternalInterface.available)
{
    flash.external.ExternalInterface.addCallback("myExternalMethod", myFunction);
}

function myFunction():void
{
    myObj.removeEventListener(MouseEvent.CLICK, someFunction);
}

in JS, call the Flash method:
document.getElementById('flash-obj').myExternalMethod();

Comment: Yes, that is a correct solution, but only if I had access to the flash code. However, I don't and I was looking for a dirty only Javascript solution. Thanks for the answer anyway, your way is the correct way to go in any other situation.


Force a reload of Listbox items(usercontrols) on ListBox Visibility Changed

Question: I have a ListBox that is bound to a List of UserControls.
The uc has a TextBlock that has an animation that fires OnLoad.
<code> <TextBlock.Style>
            <Style TargetType="TextBlock">
                <Style.Triggers>
                    <EventTrigger RoutedEvent="Loaded">
                        <EventTrigger.Actions>
                            <BeginStoryboard>
                                <Storyboard>
                                    <DoubleAnimation Duration="0:0:0.8"      Storyboard.TargetProperty="FontSize" To="16" />
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger.Actions>
                    </EventTrigger>
                 </Style.Triggers>
            </Style>
        </TextBlock.Style
</code>
Works fine. My problem is the List can be Collapsed by the user. When the user unCollapses the List I need the aanimation to fire again (it doesn't, of course -  because they are already loaded). Doesn't seem to be any other event that would work. Soo..I'm trying to dump the ItemSource and reload them. It won't hurt as there are only up to 10 or 12 items. I have an ICommand in the ViewModel that catches the Visibility Collapse...but I'm stuck there. Thanks
Answer: What I ended up doing is copying the Collection on Collapse...then Clearing. Now I reload the copy when Visibility becomes Visible. Thanks


replace text hyperlink with id attribute value and make it unclickable

Question: What am I trying to accomplish is to display a text message on a web page after I click a text. The new text should replace the text that I clicked. The new text should be the value of the id attribute. The hyperlink is meant to go away after the first click (and become unclickable).
Here is one of my attempts:
 Apasa textul 1

The tag that should be used to replace the  tag is .
I expect to display Ana after I click  Apasa textul 1
Any help will be appreciated, thanks.
Comment: Do you _actually_ need an ajax request?  By your post, you just want to append the `id` attribute's value to the end of the hyperlink text.  ...or do you want it _after_ the hyperlink?  Do we need to see more of the html here?
Comment: Please update your post to show your exact expected source code.  ` Apasa texul 1 Ana` or ` Apasa texul 1 Ana`  (I only understand English.)  What is the desired behavior if the hyperlink is clicked a second time?  Is the hyperlink meant to go away after the first click (and become unclickable)?
Comment: When the new html looks like ` Apasa texul 1 Ana` and the user clicks the link, should it become ` Apasa texul 1 Ana Ana` ?  Does the tag need to remain as a hyperlink for any reason?
Comment: You should add this requirement to your question as well, so that you don't continue to receive incorrect answers.
Comment: Display where? and look like what?  You want a tooltip? a modal? another page? a text replacement? You want the new text appended to the old text?  Your question is Unclear, I completely understand the downvotes.  It doesn't look like you need ajax here.  Is there some requirement that requires ajax in your actual project?
Comment: I want the new text appended to the old text
Comment: Ajax request is not necessary, I want to append the ID attribute value to the end of the hyperlink text, thx you
Comment: What tag should be use to replace the `` tag?  A `` perhaps?
Comment: Thx for helping me, yes
Comment: even though I  simplify the question as much as I could not so many ppl like the question
Comment: People don't often return to a question after downvoting.  It was initially a downvote worthy question.  The inclusion of ajax was unnecessary and added confusion to the requirements.  Now you have removed your coding attempt, but some upvoters (including myself) expect a coding attempt to be posted in every question.  Like you, I am very surprised that my post isn't receiving more love.  Is there anything about my answer that doesn't satisfy or that needs further explanation? @rusu
Comment: your post is great (the best I will say), just waiting for a little more :)
Answer: There will be quite a few different ways to do this, but if you want to employ an inline function call, you could declare a custom function called swapTag() (or whatever you like) which will generate a new  tag, then fill it with the original tags id value, then replace the original dom element with the newly generated element.

function swapTag(el) {
  let newEl = document.createElement('span');
  newEl.innerHTML = el.id;
  el.parentNode.replaceChild(newEl, el);
}
Apasa texul 1

Although you have stated that you wish to replace the  tag with a  tag, if you want to replace the  with pure text, this will work too:
Apasa texul 1

There isn't a great deal of context to the question, so I don't know how much utility your project actually requires.  Inline function calls may be an ugly choice -- using a listener may be a cleaner way.

I'll add an alternative that will use Jquery and an event listener (so that you you aren't muddying up your dom with inline function calls ...again, it is hard to give you a "perfect" answer because we don't know much about your application).

$(document).ready(function() {
    $('a[href="#"][id]').click(function(){
        let oldEl = this,
            newEl = document.createElement('span');
        newEl.innerHTML = oldEl.id;
        oldEl.parentNode.replaceChild(newEl, oldEl);
    });
});

Apasa texul 1
Apasa texul 1
Apasa texul 1

And again, if you want to just swap the  tag for text, this is the jquery-listener version  (listening for the click of an  tag with an href value of # and an id attribute containing anything):
$(document).ready(function() {
    $('a[href="#"][id]').click(function(){
        this.outerHTML = this.id;
    });
});

Answer: On you PHP you must do this (put this code in the top of the page):
 <?php
  if(isset($_POST['name']))
  {
    echo $_POST['name'];
    exit;
  }
 ?>

On JS:
$('#Ana').click(function()
{
    var name = $(this).attr('id');
     $.ajax(
                {
                    type: "POST",
                    url: "index.php",
                    cache: false,
                    data:  {'name':name},
                    dataType: 'text',
                    success:function(result)
                    {
                        alert(result);
                    }
                }
            )
});

The alert will show you the echoed value by PHP. From there do as you please... something like $('p').html(result);
Because you are doing an ajax call, you cannot rely on that inline code you wrote, since the page is not being entirely refreshed. That code executes when you first load the page, but because when that happens you are not passing parameters via POST (normally) in the initial statements "else" is always executed.
When calling ajax if you do not perform "exit;" in my code above, you would receive the entire page in the result. That's why the code must be at the top of the page, and an exit must be called after.
Comment: even i perform "exit"i still recevie the entire page :(
Comment: try add dataType: "text" to the ajax call
Comment: humm.. pass the data like this  data:  {'name':name},
Comment: the if(isset... is at the very top of the index.php?
Comment: set cache:false, this is strange, must be cache.
Comment: try doing var_dump($_POST) outside and prior to the if statement to see whats inside $_POST.
Comment: i try it just display array(0) { }..and still return the entire page :(
Comment: are you sure your code "isset" in on your index.php ?! aren't you targeting the wrong page?
Answer: You don't need all those stuff.
If i understand the whole, you want, when the link is clicked, to:

perform an AJAX call
replace the whole link by its ID property, no matter the call does

 Apasa texul 1

is the fastest way, considering your AJAX call would be in performAjaxCall() .
Answer:  Apasa texul 1

<?php if(isset($_POST['name']))echo $_POST['name'];else echo 'rusu';?>
 /** 2nd line **/

The 2nd line isn't meant to be executed after an AJAX request, it only gets executed when the entire page is requested normally.
To have the wanted results you may :

In the JavaScript part, when attaching the click handler you'll need to prevent the default behavior of the a element (redirects to wathever the href attribute is, if it's # the page gets scrolled to the top in most cases). Also, to distinguish that the request is an AJAx request you may use a POST variable, set to 1 for example, to check it in the server side.
In the PHP part, check if the $_POST['isajax'] (the variable that should tell us we have an AJAX request) and $_POST['name'] are set and $_POST['isajax'] equals 1 then echo the $_POST['name'] and halt the script. Also, these checks are likely to be the put in the top of the PHP file.

The JavaScript part may look like :
$('#Ana').click(function(e) {
  e.preventDefault(); /** prevents the link's default behavior **/
  var name = $(this).attr('id');
  $.ajax({
    type: "POST",
    url: "index.php",
    data: {
      isajax: 1, /** means we have an ajax request, it's not that  **/
      name: name
    },
    success: function(response) {
      alert(response)
    }
  })
});

and the PHP part (top of index.php page) ould look like :
if(isset($_POST['isajax'], $_POST['name']) && $_POST['isajax'] == 1) {
    echo $_POST['name'];
    exit; /** no further lines are executed **/
}


Finding the height of a trough through root finding methods

Question: In my computer-aided-problem-solving class, I am asked to determine the height of a trough, through a root-finding method. I can choose between the bisection method, Newton's method or successive substitution.
Whichever method I choose, I should determine the height via the method in MATLAB.
I have no idea how one of these methods is going to help me find the depth of the trough?
The following formula is given:
$$V = L \left( r^2  \arccos\left(\frac{h}{r}\right) -h \sqrt{r^2-h^2}\right)$$
Where V is the volume of the trough, which has a value of $0.35\,\text{m}^3$.
$L$ is the length, which has the value of $3\,\text{m}$.
Finally the "radius" of the trough is $r=0.3\,\text{m}$.
I should give an answers with an accuracy of 6 digits.
I attached a picture of the trough.
Can someone help me with this?? Thanks
Comment: finally you have to solve $$0.35=3\cdot 0.3^2\arccos\left(\frac{h}{0.3}\right)-h\sqrt{0.3^2-h^2}$$  is this right?
Answer: One approach would be to do it using Newton's method. We want to solve the equation $f(h)=0$, with
$$
f(h) = L\left( r^2 \arccos \left(\frac{h}{r}\right) - h\sqrt{r^2-h^2} \right) - V
$$
With Newton's method, we start out with an initial value (e.g., $h_0 = 0$), and then iterate, until we converge:
$$
h_{n+1} = h_n - \frac{f(h_n)}{f'(h_n)}.
$$
Here, $f'(h)$ represents the derivative, which happens to be
$$
f'(h) = -2L\sqrt{r^2-h^2},
$$
in your case. If you will do this, you'll find $h=0.041306\,\text{m}$.
Here is the code:
<code>% Parameters
V = 0.35;       % [m^3]
L = 3;          % [m]
r = 0.3;        % [m]

% Initial guess
h = 0;          % [m]

% Loop until convergence
hold = 1;
iter = 0; % Counter to limit # of iterations, in case of no convergence
while abs(h - hold) > 1e-7 && iter < 100
    % Compute the value of the function
    f = L*(r^2*acos(h/r) - h*sqrt(r^2-h^2)) - V;

    % Compute the derivative of the function
    fderiv = -2*L*sqrt(r^2-h^2);

    % Compute the Newton update
    hold = h;  % Remember old value for comparison
    h = h - f / fderiv;

    % Increase the counter for the number of iterations
    iter = iter + 1;

    % Show progress
    fprintf('Iteration %i, h = %.6f\n', iter, h);
end;

% Display result with an accuracy of 6 digits
fprintf('h = %.6f\n', h);  % h = 0.041306
</code>
Comment: Thankyou so much for the reaction! It indeed looks like a good idea to use Newton's method. Indeed when I type the code in matlab, I get the same answer, however, I only get to see 4 digits... how can I get 6 digits?
Also, is there a possibility that I can get the iterations vs. the outcomes in a table? So that I can study the convergence behaviour? Thanks!
Comment: @R3E1W4 You're welcome. I added a line within the loop such that you can see the convergence. I don't understand why you only see 4 digits. The `6` in `fprintf('h = %.6f\n', h);` controls the number of digits, so if you need more digits, just change the `6` into a higher number.
Comment: It worked, thank you very much. I can complete my assignment now!


Writing Fourier transform integral in terms of real-valued functions

Question: I am interested in the following integral.
$$ f(x,t) = \int \limits_{-\infty}^{\infty} \mathrm{d}k e^{-k^2}\left( e^{i(kx-pt-qk^2t)}+e^{i(kx+pt+qk^2t)} \right)$$
One way (for example, by using Mathematica) to solve it is in the following way.
$$ f(x,t) = \frac{\sqrt{\pi}}{2} \frac{(e^{-ipt}e^{\frac{ix^2}{-4i+4qt}}\sqrt{1-iqt}+e^{ipt}e^{\frac{-ix^2}{4i+4qt}}\sqrt{1+iqt})}{\sqrt{1+q^2t^2}} $$
I believe that $f(x,t)$ should be real valued, but it is not clear to me how to simplify given expression so that it consists only of real valued functions.
Comment: I think this can be simplified to a real-valued function. Let me try to type this up...
Comment: @RachidAtmai Thanks, I would appreciate it. I think I am a little confused about branch cuts of square root and how to deal with that.
Comment: yeah, this is quite a lengthy computation!
Answer: The exponential term can be recast as $2cos(kx)cos(pt+qk^2t)$
a)$e^{ikx}=cos(kx)+isin(kx)$.  The rest of the integrand is a function of $k^2$, so integrating over the real line eliminates the $sin(kx)$ term.
b) $e^{-i(pt+qk^2t)}+e^{i(pt+qk^2t)}=2cos(pt+qk^2t)$.  Note the $sin$ terms cancel.
Comment: OK, this is a lot better than the absurd computation I produced below!
Answer: First observe that we have: $$\displaystyle e^{ix^2/(-4i+4qt)}$$ is the same as $$e^{ix^2(4qt+4i)/(16(q^2t^2+1))}$$ which then becomes $$e^{-4x^2/(16(q^2t^2+1))}e^{i4x^2qt/(16(q^2t^2+1))}$$
Similarly $$\displaystyle e^{-ix^2/(4i+4qt)}$$ really is just $$e^{4x^2/(16(q^2t^2+1))}e^{i4x^2qt/(16(q^2t^2+1))}$$
Next observe that $$\sqrt{1-iqt}=\left(\sqrt{1+q^2t^2}\right)e^{-i\theta}e^{-i\pi n}$$ where $\theta=2\arctan(qt)$. Similarly observe that $$\sqrt{1+iqt}=\left(\sqrt{1+q^2t^2}\right)e^{i\theta}e^{i\pi n}$$ with again $\theta$ as above.
At any rate we then have $f(x,t)= \displaystyle \frac{\sqrt{\pi}}{2\sqrt{1+q^2t^2}}\left[e^{-ipt}e^{i4x^2qt/(16(q^2t^2+1))}e^{-4x^2/(16(q^2t^2+1))}\sqrt{1+q^2t^2}e^{-i\theta}e^{-i\pi n}+e^{ipt}e^{-i4x^2qt/(16(q^2t^2+1))}e^{4x^2/(16(q^2t^2+1))}\sqrt{1+q^2t^2}e^{i\theta}e^{i\pi n}\right]$ which then reduces to:
$f(x,t)= \displaystyle \frac{\sqrt{\pi}}{2}\left[e^{-ipt}e^{i4x^2qt/(16(q^2t^2+1))}e^{-4x^2/(16(q^2t^2+1))}e^{-i\theta}e^{-i\pi n}+e^{ipt}e^{-i4x^2qt/(16(q^2t^2+1))}e^{4x^2/(16(q^2t^2+1))}e^{i\theta}e^{i\pi n}\right]$
This expression is absurd, thus let $$A=\frac{4x^2}{16(q^2t^2+1)}$$
We thus have: $$f(x,t)= \displaystyle \frac{\sqrt{\pi}}{2}\left[e^{-i(pt+\theta+\pi n)}e^{i4x^2qt/(16(q^2t^2+1))}e^{-A}+e^{i(pt+\theta+\pi
 n)}e^{-i4x^2qt/(16(q^2t^2+1))}e^A\right]$$
I'll let you maybe take it from here using Euler's formula....lol. I'm sure there's a faster way of doing this...smh
Answer: The two parts of your answer are obviously a complex conjugate pair.
Let's just take one of the terms and double its real part:
$$\begin{align*}f(x,t) &= \frac{\sqrt{\pi}}{2} \frac{(e^{-ipt}e^{\frac{ix^2}{-4i+4qt}}\sqrt{1-iqt}+e^{ipt}e^{\frac{-ix^2}{4i+4qt}}\sqrt{1+iqt})}{\sqrt{1+q^2t^2}}\\
\\
&= \sqrt{\pi}\;\Re\left[\frac{e^{-ipt}e^{-\frac{x^2}{4}\frac{1}{1+iqt}}}{\sqrt{1+iqt}}\right]\\
\\
&= \dfrac{\sqrt{\pi}}{\sqrt{1+q^2t^2}}\;\Re\left[\sqrt{1-iqt}\cdot e^{-ipt}e^{-\frac{x^2}{4}\frac{1-iqt}{1+q^2t^2}}\right] \\
\\
&= \dfrac{\sqrt{\pi}}{\sqrt{1+q^2t^2}}e^{-\frac{x^2}{4}\frac{1}{1+q^2t^2}}\;\Re\left[\sqrt{1-iqt}\cdot e^{-ipt}e^{-\frac{x^2}{4}\frac{-iqt}{1+q^2t^2}}\right] \\
\\
&= \dfrac{\sqrt{\pi}}{\sqrt{1+q^2t^2}}e^{-\frac{x^2}{4}\frac{1}{1+q^2t^2}}\;\Re\left[\sqrt{re^{i(\theta +2n\pi)}}\cdot e^{i\left(\frac{x^2}{4}\frac{qt}{1+q^2t^2}-pt\right)}\right] \\
\\
&= \dfrac{\sqrt{\pi}}{\sqrt{1+q^2t^2}}e^{-\frac{x^2}{4}\frac{1}{1+q^2t^2}}\;\Re\left[{\sqrt[4]{1+q^2t^2}e^{i(\theta/2 +n\pi)}}\cdot e^{i\left(\frac{x^2}{4}\frac{qt}{1+q^2t^2}-pt\right)}\right] \\
\\
&= \dfrac{\sqrt{\pi}}{\sqrt[4]{1+q^2t^2}}e^{-\frac{x^2}{4}\frac{1}{1+q^2t^2}}\;\Re\left[e^{i\left(\frac{\theta}{2}+n\pi+\frac{x^2}{4}\frac{qt}{1+q^2t^2}-pt\right)}\right] \\
\\
&= \dfrac{\sqrt{\pi}}{\sqrt[4]{1+q^2t^2}}e^{-\frac{x^2}{4}\frac{1}{1+q^2t^2}}\;\cos\left(\frac{\theta}{2}+n\pi+\frac{x^2}{4}\frac{qt}{1+q^2t^2}-pt\right) \\
\\
&= \dfrac{\sqrt{\pi}}{\sqrt[4]{1+q^2t^2}}e^{-\frac{x^2}{4}\frac{1}{1+q^2t^2}}\;\cos\left(\frac{\mathrm{arctan2}(-qt,1)}{2}+n\pi+\frac{x^2}{4}\frac{qt}{1+q^2t^2}-pt\right) \\
\\
\end{align*}$$
You can take $n=0$ for the principal value of the square root.  Or you can take $n=1$ and effectively just change the sign of the answer.


Ajax.beginform does a full postback

Question: I am using Ajax,beginform to get partial postback, have install the Microsoft.jQuery.Unobtrusive.Ajax package, set up the bundle and added the keys in config files. With all this done when i click my submit button i get full postback. Have gone though tones of post and tried all suggested solutions, still seems to not work. is there anything i am still missing.
@using (Ajax.BeginForm("MyAction", "MyController", new AjaxOptions()
 {
       HttpMethod = "GET",
       UpdateTargetId = "divList",
       InsertionMode = InsertionMode.Replace
  }))
  {
       <button type="submit">Show more List</button>
  }

     @Html.Partial("_MyList.cshtml", Model.List)

In my controller
    public ActionResult MyAction()
    {
        .....
        return PartialView("_MyList", list);
    }

Added in the bundle
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                          "~/Scripts/jquery.unobtrusive*",
                          "~/Scripts/jquery.validate*"));

In web.config
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

Have even tried setting the section script in my view
@section Scripts {
  @Scripts.Render("~/bundles/jquery")
  @Scripts.Render("~/bundles/bootstrap")
  @Scripts.Render("~/bundles/jqueryval")
}

Comment: Its definitely an issue with the scripts if its redirecting. But `Ajax.BeginForm()` is awful and has been dropped in the latest MVC so better to use the jquery ajax methods anyway. - `Show more List` and `$('#show").click(function() { $('#divList').load('@Url.Action("MyAction", "MyController")'); })`
Comment: If you doing a redirect, then it means `jquery.unobtrusive-ajax.js` is not loaded. Check for any errors in the browser console. Also check that you do not have any duplicate scripts (e.g. loading `jquery-{version}.js` again after `jquery.unobtrusive-ajax.js`)
Comment: @Stephen, I do not get any error on the console, i even registered jquery.unobtrusive-ajax.js directly and made sure jquery duplicated. still it does not work.
Answer: Another best way to handle the scenario is, instead of Ajax.BeginForm use Html.BeginForm
Use JQuery form submit, this will help you to stay away from jquery.unobtrusive
In .cshtml
@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { id = "form_" + @Model.Id }))
    {

            @Html.HiddenFor(m => m.AntiForgeryToken, new { @class = "form-control" })
            @Html.HiddenFor(m => m.Id, new { @class = "form-control" })

            <button onclick='onClickFormButton("email@example.com")' type="button">Submit</button>

    }

Javascript
window.onClickFormButton = function (formId) {
    //validate the form clientside
    var validateResult = OnValidateForm(formId);
    if (!validateResult) return false;

    var form = $('#' + formId);
    $.ajax({
        url: form.attr('action'),
        type: form.attr('method'),
        data: form.serialize(),
        success: function (result) {
            // process the result
            processSuccessResult(result)
        },
        fail: function (result) {
            // process the result
            processFailResult(result)
        }
    });
    return false;
}

Controller/Action
[HttpPost]
public JsonResult ActionName(FormCollection model)
{
    // Get  id
    var idKey = model.AllKeys.FirstOrDefault(x => x.Contains("Id"));
    var id = model[idKey];

    return new ProcessedResult(id);
}

Ajax.beginform does a full postback


What are the differences between different platforms in Dungeon Defenders?

Question: I have both the PC version, through Steam, and the PS3 version of Dungeon Defenders.
I have maxed out the level of my Squire on PS3, and was surprised to find that on the PC I could raise skill points to a base level of 100 on my Apprentice on the PC version (the PS3 version seems to cap the skill points at a base of 70).
What other differences exist between platforms? Are the level caps the same?
Answer: There are a large number of differences between the versions for PC, PS3, and Xbox. It all depends on when they release patches for the respective platforms. They made the change for stat points in a few patches (can't remember which one). But they made the point cap raised from 70 to 100, and then more recently from 100 to 120 as you've noticed.
They tend to upgrade the PC version a lot quicker and you will find the most up-to-date information in this forum.
A comprehensive list for the differences between the two would be a very large post.
The current PC patch information can be found here.


Fresh Ubuntu Install Being Extremely Slow

Question: Ubuntu has become a bit of a nightmare for me.
I have a brand new desktop (i3-8100 – 8th gen, Ripjaws V 16gb DDR4, Z370 Aorus Gaming 5 chipset, 2x 4TB hard drives + 1x 1TB hard drive). I had installed Ubuntu 16.04 LTS and everything was working perfectly.
Randomly about a month ago I couldn't log in. I'd get stuck on the login screen. I tried to debug but no success, so I thought forget it I'll format and create a fresh install. Ubuntu loads up and it's slow to the point of being unusable. Typing the word terminal takes 10 seconds. If I want to move a window it is super laggy. Again, please keep in mind everything was perfect a month ago and this machine is new.
It's a fresh install, so no processes or anything else. This has been a nightmare, would really appreciate some help.
Output from systemd-analyze blame
On my first attempt about 2-3 minutes in:
Bootup is not yet finished. Please try again later.
On my second attempt:
8min 19.825s apt-daily-upgrade.service
1min 58.770s apt-daily.service
1min 11.176s systemd-fsck@dev-disk-by\x2duuid-4479ee04\x2df118\x2d4da6\x2d99ef\x2d2735ef7460e0.service
      8.118s dev-sdb2.device
      7.252s NetworkManager-wait-online.service
      5.868s systemd-tmpfiles-setup-dev.service
      5.397s systemd-sysctl.service
      2.024s keyboard-setup.service
      1.891s ModemManager.service
      1.868s accounts-daemon.service
      1.836s grub-common.service
      1.783s NetworkManager.service
      1.578s lightdm.service
      1.551s upower.service
      1.450s thermald.service
      1.036s systemd-journald.service
       895ms polkitd.service
       854ms systemd-modules-load.service
       781ms systemd-rfkill.service
       748ms sys-kernel-debug.mount
       748ms dev-mqueue.mount
       745ms dev-hugepages.mount
       510ms irqbalance.service
       411ms kmod-static-nodes.service
       275ms console-setup.service
       259ms ufw.service
       249ms apparmor.service
       242ms networking.service
       235ms avahi-daemon.service
       204ms ondemand.service
       204ms home.mount
       196ms rsyslog.service
       195ms gpu-manager.service
       194ms pppd-dns.service
       141ms udisks2.service
       126ms plymouth-start.service
       124ms dev-sdb1.swap
       124ms systemd-tmpfiles-setup.service
       117ms wpa_supplicant.service
       110ms systemd-update-utmp.service
        93ms systemd-udevd.service
        66ms systemd-journal-flush.service
        64ms email@example.com
        57ms setvtrgb.service
        37ms colord.service
        36ms systemd-random-seed.service
        32ms systemd-udev-trigger.service
        30ms systemd-remount-fs.service
        28ms plymouth-read-write.service
        23ms systemd-timesyncd.service
        23ms systemd-logind.service
        21ms speech-dispatcher.service
        14ms apport.service
        12ms bluetooth.service
        10ms alsa-restore.service
         8ms snapd.autoimport.service
         5ms systemd-user-sessions.service
         3ms dns-clean.service
         3ms plymouth-quit-wait.service
         2ms rtkit-daemon.service
         2ms ureadahead-stop.service
         2ms systemd-update-utmp-runlevel.service
         1ms resolvconf.service
         1ms rc-local.service
         1ms sys-fs-fuse-connections.mount
       352us snapd.socket

Comment: If it is slow booting, run `systemd-analyze blame` from the terminal. Copy the output and paste it into your question.
Comment: What is it doing slowly?  Is boot slow, or is doing other particular things slow?
Comment: One of the disks beginning to fail?
Comment: @thomasrutter typing the word terminal takes 10 seconds. If I want to move a window it is super laggy. Also updated my answer to include this. Again, please just keep in mind everything was perfect a month ago and this machine is new. Thanks.
Comment: @WinEunuuchs2Unix thanks, I didn't know about this command. I've updated my question above.
Comment: I'm on my phone so can't link one but there are various articles on speeding up `systemd` boot and I'm pretty sure apt daily can be relocated.
Comment: The dev/disk is a concern too.
Comment: @WinEunuuchs2Unix I didn't know what "systemd-analyze blame" does but I learnt it prints a list of all running units which can help optimize boot-up times. So before I go down that road, (1) Should we not assume that if I waited 10-30 minutes that the system would then be perfectly fast? Since it does not speed up I doubt it's the boot. Or am I missing something? (2) Why would I need to optimize the boot if it was working find before, and still works fine booting off a thumb drive? It makes no sense to me why everything was fine and is fine when loading the OS off a thumbdrive.
Answer: I found a solution but I'm not satisfied with the answer.
The ONLY difference between the nearly 10 unsuccessful Ubuntu installs I had and the one that did work was this:
ubuntu install options
I went back and re-installed with these options for "Encrypt..." and "Use LVM..." checked and now everything works fine. Can someone explain why this impacts system performance? I'd really like to understand.
Comment: Encryption and Logical Volume Management sound like using a sledge hammer on a thumb tack. But if it works you might as well keep it that way. Just remember to backup your documents. In two days time sign back on and accept your answer as the solution so others know it works now.
Comment: @WinEunuuchs2Unix I definitely will. Still curious to see if people have an answer as to why this worked though. I hate doing stuff without knowing why :P


How to move points of a line to specific locations?

Question: I'm trying visualise the sine waves addition in python using tkinter, and I'm trying to build lines between each circles center, but what I've tried so far didnt work as I thought it would. is there a way to fix what I've tried (see code), or a way to move only one coordinates point of a line independantly from the other?
As you'll see in the code if you run it, I've tried a method where each iteration the previous line is erased and a new one is created. When I run the code there is actually a line between each center of the circles just like I want, but facts are those lines persist and won't erase themselves; for some reason it seems like the canvas.delete(line) doesnt work as I expected it to.
here's the full code. The interesting part is in the 'updateline' fonction, into 'act()' func.
import math
import tkinter as tk

##important to know! -- the way I'm creating the circles is by setting an object, the bounds of the circle, depending on amplitude asked by user.
##then the programs calculates the path of these bounds, depending on circles, amplitude, phase and frequency of the sine waves asked by the user from the tkinter GUI.
##finally, the program creates and moves along this path a circle, representing visually the sine wave.

top = tk.Tk()
top.title('Superposition')
choice = tk.Tk()
choice.title('Parametres')

f = tk.Frame(choice,bd=3)
f.pack(side='top')

g = tk.Frame(choice,bd=3)
g.pack(side='bottom')

tk.Label(f,text="nbre ondes:",width = 10).grid(row=0,column=0)
sines = tk.Spinbox(f,from_=1,to=50,width=10,textvariable=tk.DoubleVar(value=2))
sines.grid(row=0,column=1)
sines.delete(0,5)
sines.insert(0,2)

delai = tk.Scale(g, orient='vertical', from_=100, to=1,resolution=1, length=100,label='delai')
delai.grid(row=0,column=0)
hauteur = tk.Scale(g, orient='vertical', from_=1100, to=100,resolution=100, length=100,label='fenetre')
hauteur.grid(row=0,column=1)
taillec1 = tk.Scale(g, orient='vertical', from_=3.5, to=0.1,resolution=0.1, length=100,label='taille')
taillec1.grid(row=0,column=2)
delai.set(20)
hauteur.set(600)
taillec1.set(1.5)

def grilledechoix():
    numberofsines = int(sines.get())
    for i in f.grid_slaves():
        if int(i.grid_info()["row"]) > numberofsines+2:
            i.grid_forget()

    for i in range(1,numberofsines+1):
        tk.Label(f,text="phase n."+str(i),width = 10).grid(row=i+2,column=4)
        phase = tk.Spinbox(f,from_=-180,to=180,width=10)
        phase.grid(row=i+2,column=5)
        phase.delete(0,5)
        phase.insert(0, 0)
    for i in range(1,numberofsines+1):
        tk.Label(f,text="amp. n."+str(i),width = 10).grid(row=i+2,column=0)
        ampli = tk.Spinbox(f,from_=1,to=10000000,width=10)
        ampli.grid(row=i+2,column=1)
        ampli.delete(0,5)
        ampli.insert(0,10)
    for i in range(1,numberofsines+1):
        tk.Label(f,text="freq n."+str(i),width = 10).grid(row=i+2,column=2)
        freq = tk.Spinbox(f,from_=-1000,to=1000,width=10)
        freq.grid(row=i+2,column=3)
        freq.delete(0,5)
        freq.insert(0,5)

def act():
    h = g.grid_slaves()[1].get()
    delai = g.grid_slaves()[2].get()
    taillec1 = g.grid_slaves()[0].get()
    w = h

    ampdict = {'box1':100 * ((h/700)*taillec1)}
    frqdict = {}
    aaadict = {}
    fffdict = {}
    phadict = {}

    numberofsines = int(sines.get())

    sin = lambda degs: math.sin(math.radians(degs))
    cos = lambda degs: math.cos(math.radians(degs))

    for i in range(1,numberofsines+1):
        fffdict['box'+str(numberofsines-i+1)] = f.grid_slaves()[(2*i)-2].get()
        aaadict['box'+str(numberofsines-i+1)] = f.grid_slaves()[(2*i)-2+2*numberofsines].get()
        phadict['box'+str(numberofsines-i+1)] = f.grid_slaves()[(2*i)-2+4*numberofsines].get()
    for i in range(1,numberofsines+1):
        ampdict['box'+str(i)] = (float(ampdict['box1'])/float(aaadict['box1'])) * float(aaadict['box'+str(i)])
        frqdict['box'+str(i)] = float(fffdict['box'+str(i)])/float(fffdict['box1'])

    class obj(object):
        cos0, cos180 = cos(0), cos(180)
        sin90, sin270 = sin(90), sin(270)

        def __init__(i, x, y, rayon):
            i.x, i.y = x, y
            i.rayon = rayon

        def bounds(i):
            return (i.x + i.rayon*i.cos0,   i.y + i.rayon*i.sin270,
                    i.x + i.rayon*i.cos180, i.y + i.rayon*i.sin90)

    def updateposition(canvas, id, cent, obj, path):
        obj.x, obj.y = next(path)
        x0, y0, x1, y1 = canvas.coords(id)
        oldx, oldy = (x0+x1) // 2, (y0+y1) // 2
        dx, dy = obj.x - oldx, obj.y - oldy
        canvas.move(id, dx, dy)
        canvas.move(cent, dx, dy)
        canvas.after(delai, updateposition, canvas, id, cent, obj, path)

    def updateline(canvas, line, robj0, cent0, robj1, cent1):
        x00, y00, x01, y01 = canvas.coords(cent0)  ##defining coords of the two ovals asked, representing centers of circles
        x10, y10, x11, y11 = canvas.coords(cent1)
        oldx0, oldy0 = (x00+x01) // 2, (y00+y01) // 2 ##defining center coords of the two ovals
        oldx1, oldy1 = (x10+x11) // 2, (y10+y11) // 2
        dx0, dy0 = robj0.x - oldx0, robj0.y - oldy0 ##defining the deltax and deltay, difference of movements between frames, of the two ovals
        dx1, dy1 = robj1.x - oldx1, robj1.y - oldy1
        canvas.after(delai, canvas.delete, line) ##deleting previous line, does not work and I don't know why. I've also tried 'canvas.delete(line)', giving same results
        canvas.create_line(oldx0+dx0, oldy0+dy0, oldx1+dx1, oldy1+dy1) ##creating new line
        canvas.after(delai, updateline, canvas, line, robj0, cent0, robj1, cent1) ##function invoking itself after delay 'delai'

    def posobj(pt,ang,deltang):
        while True:
            yield pt.x + pt.rayon*cos(ang), pt.y + pt.rayon*sin(ang)
            ang = (ang+deltang)%360

    try:
        top.pack_slaves()[0].destroy()
    except:
        pass

    canvas = tk.Canvas(top, bg='white', height=h, width=w)
    canvas.pack(side='right')

    robj = {}
    r = {}
    posobjet = {}
    line = {}
    cent = {}

## the following 'for' loop creates a number of circles corresponding to sine waves, as much as the user asked.
    for i in range(1,int(sines.get())+2):
        if i != int(sines.get())+1:
            if i == 1:
                robj[str(i)] = obj(h/2,h/2,float(ampdict['box'+str(i)]))
                r[str(i)] = canvas.create_oval(robj[str(i)].bounds(),fill='',outline='black')
                cent[str(i)] = canvas.create_oval(h/2+h/200,h/2+h/200.,h/2-h/200,h/2-h/200, fill='white', outline='red')
                posobjet[str(i)] = posobj(robj[str(i)],float(phadict['box'+str(i)]),float(frqdict['box'+str(i)]))
            else:
                robj[str(i)] = obj(robj[str(i-1)].x,robj[str(i-1)].y,float(ampdict['box'+str(i)]))
                r[str(i)] = canvas.create_oval(robj[str(i)].bounds(),fill='',outline='black')
                cent[str(i)] = canvas.create_oval(robj[str(i)].x+h/200,robj[str(i)].y+h/200,robj[str(i)].x-h/200,robj[str(i)].y-h/200, fill='white', outline='blue')
                line[str(i)] = canvas.create_line(0,0,0,0)
                posobjet[str(i)] = posobj(robj[str(i)],float(phadict['box'+str(i)]),float(frqdict['box'+str(i)]))
                top.after(delai, updateposition, canvas, r[str(i)], cent[str(i)], robj[str(i)], posobjet[str(i-1)])
                ##here I'm invoking the updateline function using the constant 'delai', the line i, and objects defining the bounds of the center objects, the little blue/red dots appearing as the center of each circles(run the code, it'll be easier to understand)
                top.after(delai, updateline, canvas, line[str(i)], robj[str(i-1)], cent[str(i-1)], robj[str(i)], cent[str(i)])
        else:
            robj[str(i)] = obj(robj[str(i-1)].x,robj[str(i-1)].y,h/200)
            r[str(i)] = canvas.create_oval(robj[str(i)].bounds(),fill='white',outline='red')
            cent[str(i)] = canvas.create_oval(robj[str(i)].x+h/200,robj[str(i)].y+h/200,robj[str(i)].x-h/200,robj[str(i)].y-h/200, fill='white', outline='red')
            line[str(i)] = canvas.create_line(0,0,0,0)
            top.after(delai, updateposition, canvas, r[str(i)], cent[str(i)], robj[str(i)], posobjet[str(i-1)])
            ##2nd and last time invoking the updateline function, for the line between the last circle's point and the final red point.
            top.after(delai, updateline, canvas, line[str(i)], robj[str(i-1)], cent[str(i-1)], robj[str(i)], cent[str(i)])
    top.mainloop()

ok = tk.Button(f,text='NBRE',command=grilledechoix)
ok.grid(row=0,column=2)
ac = tk.Button(f,text='APPLY',command=act)
ac.grid(row=0,column=3)
grilledechoix()
act()

I expected the lines to disappear once the updateline function called itself again, because of that 'canvas.delete(line)' line into updateline, and I can't really understand why it does that.
anyway if you have a solution to make the lines move, without creating and deleting them each time the function is called, feel free to tell me.
Thanks!
Comment: sure, sorry. I've edited so that the function where there's the problem is fully explained and the 2 moments where I invoke the function updateline are commented.
Comment: Your code seems complete and reproducible, which is is not frequent for new users - thank you! But there's hardly any comments and the codebase is pretty large... Can you edit your code block and add comments?
Answer: If I understand the problem correctly, I believe the issue is with this code:
canvas.after(delai, canvas.delete, line)
canvas.create_line(oldx0+dx0, oldy0+dy0, oldx1+dx1, oldy1+dy1)
canvas.after(delai, updateline, canvas, line, robj0, cent0, robj1, cent1)

It fails to reassign the new line to the line variable for the next call.  Instead try:
canvas.after(delai, canvas.delete, line)
line = canvas.create_line(oldx0+dx0, oldy0+dy0, oldx1+dx1, oldy1+dy1)
canvas.after(delai, updateline, canvas, line, robj0, cent0, robj1, cent1)

Which gets rid of the extra lines when I run it.  Let me know if I've missed the point.
Comment: thanks! You totally didn't miss the point, that was exactly what was I searching. I'm 'coding' since only 1 month and a half, and I can't understand the logic behind it, why does the call of a lambda function solves the problem?
Comment: I thought the arguments after the function were taken in count with the function, from what my tests with after() resulted in.
Comment: @foriinme, you appear to be correct about `after()` -- the references I checked were inconsistent about this.  I've updated my code accordingly.  It was likely primarily the issue of not reassigning the `line` variable.  But do confirm!
Comment: this explains why it did actualize the other point of the line's coordinates, the problem may come from the function deleting a variable - line - and creating another but trying to re-delete that same it deleted. thanks a lot, you really enlighted me on my own code :)
Comment: btw, I have no clue why it does that as the previous line is deleted before, but the code you edited, without the lambda function call, makes two lines instead of one


Dirac Delta of a Function When the Derivative of the Function is Discontinuous at its Roots

Question: We know that the Dirac delta function of a function can be written as
$$ \delta(f(x))=\sum_i\frac{\delta(x-x_i)}{|f'(x_i)|}, $$
where $x_i$ are roots of function $f(x_i)$.
Now my question is the following: how can we write a same expression for $\delta(f(x))$ if we have $f'(x_i^+)\neq f'(x_i^-)$?
Answer: Split the integral into regions around $a_i$, the zeros of $f$ (as integration of a delta function only gives nonzero results in regions where its argument is zero)
$$
\int_{-\infty}^{\infty}\delta\big(f(x)\big)g(x)\,\mathrm{d}x = \sum_{i}\int_{a_i-\epsilon}^{a_i}\delta(f(x))g(x)\,\mathrm{d}x+\int_{a_i}^{a_i+\epsilon}\delta(f(x))g(x)\,\mathrm{d}x\ .
$$
Write out the Taylor expansion of $f$ for $x$ near some $a_i$ (ie. different for each term in the summation) to the right
$$
f(x) =f(a_i) + f_+'(a_i)(x-a_i) + \mathcal{O}((x-a_i)^2) =f_+'(a_i)(x-a_i) + \mathcal{O}((x-a_i)^2)
$$
and to the left
$$
f(x) =f(a_i) + f_-'(a_i)(a_i-x) + \mathcal{O}((a_i-x)^2)=f_-'(a_i)(a_i-x) + \mathcal{O}((a_i-x)^2)\ .
$$
Therefore
$$
\int_{-\infty}^{\infty}\delta\big(f(x)\big)g(x)\,\mathrm{d}x \simeq \sum_{i}\int_{a_i-\epsilon}^{a_i}\delta( f_-'(a_i)(a_i-x))g(x)\,\mathrm{d}x+\int_{a_i}^{a_i+\epsilon}\delta(f_+'(a_i)(x-a_i))g(x)\,\mathrm{d}x\ .
$$
Changing variables $a_i-x=y$ and $x-a_i=z$ in the two integrals, we get
$$
\int_{-\infty}^{\infty}\delta\big(f(x)\big)g(x)\,\mathrm{d}x \simeq \sum_{i}\int_{0}^{\epsilon}\delta( f_-'(a_i)y)g(a_i-y)\,\mathrm{d}y+\int_{0}^{\epsilon}\delta(f_+'(a_i)z)g(a_i+z)\,\mathrm{d}z\ .
$$
Now, for each term, it is tempting to use the following property
$$
\int_{-\infty}^\infty\delta(kx)g(x)\,\mathrm{d}x = \frac{1}{|k|}g(0) = \int_{-\infty}^\infty\frac{1}{|k|}\delta(x)g(x)\,\mathrm{d}x\ ,
$$
however it should be noted that the integration range is truncated, and the argument of the deltas vanishes at one of the integration bounds. The best way to handle this situation seems to include a factor of $1/2$ in front (see this thread). Therefore in the end
$$
\boxed{\delta(f(x))=\frac{1}{2}\sum_{i}\left(\frac{1}{|f'(a^+_i)|}+\frac{1}{|f'(a^-_i)|} \right)\delta(x-a_i)}\ ,
$$
i.e. the factor in front of the simple delta is now the arithmetic average of the inverse of left and right derivatives. Note that, if such derivatives are equal, we recover the 'standard' formula.
Answer: $$\delta(f(x))~=~\frac{1}{2}\sum_{i}^{f(x_i)=0}\left(\frac{1}{|f'(x^+_i)|}+\frac{1}{|f'(x^-_i)|} \right)\delta(x-x_i).$$


How to use pip install where one requirement has dependency on version on gcc-4.5

Question: I am installing an egg packaged for pip, inside my virtualenv, under Python 2.7.2.
The egg has 16 requirements, one of which (pycryptopp 0.5.29) is known to fail with gcc-4.6 and hence must be compiled with 4.5. The system has both gcc-4.6 (default) and gcc-4.5 installed.
How do I configure/hack pip install to build this package specially? (or do I just temporarily kludge the link /usr/bin/gcc while installing this package)
Do I need to clean up the existing (virtualenv)/build directory where it broke, and if so how?
(I already read the pip documentation and searched SO + SU)
Comment: (pycryptopp 0.5.29-2 might fix the compile breakage)
Answer: No need to fiddle around with symlinks here. On most Linux systems you can set the compiler to use with the CC env var. In case of pycryptopp and pip the following might help:
$ CC=/usr/bin/gcc-4.5 pip install pycryptopp

given that you have GCC 4.5 installed in that location. This worked fine for me on Ubuntu 11.10 (oneiric) with packages gcc-4.5 and g++-4.5 installed.
Comment: A note that saved me: sometimes you need c++ as well, which is g++ instead of gcc.  Make sure you have it installed with apt install g++-4.5 (or whatever version you need)
Answer: (I retitled the question from "How to use pip install where one requirement must be compiled with gcc-4.5?")
1) The correct method is to build with "--disable-embedded-cryptopp" which links to libcryptopp. Some people report runtime issue but It Works For Me.
pip install --install-option="--disable-embedded-cryptopp" pycryptopp

2.) A truly ugly workaround which I used (and which ulif helpfully points out can be obviated by using CC=.. ) is to invoke pip install specifically for the problem package, and temporarily kludge the link to gcc.
pushd /usr/bin; sudo rm gcc-4.6; ln -s gcc-4.5 gcc; popd;
pip install pycryptopp
pushd /usr/bin; sudo rm gcc-4.5; ln -s gcc-4.6 gcc; popd;

Further reasons this is bad: it requires root access and messing with the link to gcc binary. It certainly can't be Makefile'd.
Answer: Adding this for completeness to extend upon the existing good answers; if you are on apt based distribution such as Ubuntu or Debian, you can do the following:
Step 1: Install the versions of gcc/g++ you need
sudo apt install gcc-7 gcc-8 g++-7 g++-8

Step2: Install your gcc/g++ versions into "alternatives" system of your OS:
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-7 70
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-8 80
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-7 70
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-8 80

Step 3: Select your active gcc/g++ versions
sudo update-alternatives --config gcc

sudo update-alternatives --config g++

It will in each case ask you which version you want, or use the "weight" you provided to select automatically for you:
Selection    path               Priority    Status
--------------------------------------------------------------------
* 0          /usr/bin/gcc-8     80          auto mode
  1          /usr/bin/gcc-8     80          manual mode
  2          /usr/bin/gcc-7     70          manual mode

Press ENTER to maintain, or type the selection number to the corresponding version.

TIP: If you want to delete a version, simply use this:
sudo update-alternatives --remove gcc /usr/bin/gcc-7

You will still use root/sudo access to do this, but it is much cleaner than dealing with manually deleting/creating links, or specifying environment variables on the commandline. It is the recommended way of selecting versions for all kinds of things in arpt based distributions.


Pandas How to group by month and year using dt

Question: I am just wondering how to group by both year and month using pandas.series.dt.
The code below groups by just year, but how would I add a further filter to group by month as well.
Data = {'Date':['21.10.1999','30.10.1999','02.11.1999','17.08.2000','09.10.2001','14.07.2000'],'X': [10,20,30,40,50,60],'Y': [5,10,15,20,25,30]}

df = pd.DataFrame(Data)

#Convert to pandas date time
df['Date'] = pd.to_datetime(df['Date'])

#Obtain dataframe dtypes
print(df.dtypes)

print(df)
print(df.groupby(df['Date'].dt.year).sum())

Answer:
am just wondering how to group by both year and month using pandas.series.dt.

You can pass Series.dt.year and
Series.dt.month with rename to groupby, new columns are not necessary:
print(df.groupby([df['Date'].dt.year.rename('y'), df['Date'].dt.month.rename('m')]).sum())
          X   Y
y    m
1999 2   30  15
     10  30  15
2000 7   60  30
     8   40  20
2001 9   50  25

Another solutions:
If use DataFrame.resample or Grouper then are added all missing datetimes between (what should be nice or not):
print(df.resample('MS', on='Date').sum())

print(df.groupby(pd.Grouper(freq='MS', key='Date')).sum())

Or convert datetimes to month periods by Series.dt.to_period:
print(df.groupby(df['Date'].dt.to_period('m')).sum())
          X   Y
Date
1999-02  30  15
1999-10  30  15
2000-07  60  30
2000-08  40  20
2001-09  50  25

Comment: @imantha I am on phone only, so not tested `mean_df = df.groupby([df['Date'].dt.year.rename('y'), df['Date'].dt.month.rename('m')])transform('mean') ; (EQ2:) std_df = df.groupby([df['Date'].dt.year.rename('y'), df['Date'].dt.month.rename('m')]).transform('std'); (EQ3:) df['z_sco'] = (df['X'] - mean_df) / std_df `
Comment: tried it and it works. Thanks, heaps, this is what I was looking for.
Comment: is it possible to have the sum in another column, and have the sum repeated for values of the same group? What I mean by that is, the original table has 6 entries of which 3 entries are for October 1999. So instead of having 80 (10+20+50) as a grouped value. Have 80 repeated for each entry of october 1999. I am asking this since I want to follow your logic to calculate the Z score. I am planning to do that by calculating the mean and standard deviation separately and then computing the z score for each entry. However, I am unable to that when the tables have different dimensions
Comment: (EQ1:) mean_df = df.groupby([df['Date'].dt.year.rename('y'), df['Date'].dt.month.rename('m')]).mean() ;
(EQ2:) std_df = df.groupby([df['Date'].dt.year.rename('y'), df['Date'].dt.month.rename('m')]).std();
(EQ3:) df['z_sco'] = (df['X'] - mean_df['X']) / std_df['X']
Comment: @imantha check transform from [this](https://stackoverflow.com/q/54907933/2901002)
Answer: df.assign(yr = df['Date'].dt.year, mnth = df['Date'].dt.month).groupby(['yr', 'mnth']).sum()

    Out[1]:

            X   Y
yr  mnth
1999    2   30  15
        10  30  15
2000    7   60  30
        8   40  20
2001    9   50  25


Overflow and css3 columns

Question: I am unable to make a css3 column layout work with scrolls in a defined-height container area. Here is an example link:
http://codepen.io/anon/pen/WQNeVX
All I do in css is to define this to the container area -
#container {
  width: 500px;
  height: 200px;
  overflow-y: scroll;
  overflow-x: hidden;
  -webkit-column-count: 4;
  -moz-column-count: 4;
  column-count: 4;
}

What should I do in this case to make overflow-y work as a scroll?
Thank you.
Answer: You need to set height to max-height
body {
 margin: 0;
 padding: 0;
}
#container {
  width: 500px;
  max-height: 200px; /* like this*/
  overflow-y: scroll;
  overflow-x: hidden;
  -webkit-column-count: 4;
  -moz-column-count: 4;
  column-count: 4;
}

The second method is to do so, for Moz, Opera , IE-9 and Chrome is like this:
Updated CSS
body {
  margin: 0;
  padding: 0;
}
#container-wrapper{
  width: 500px;
  max-height: 200px;
  overflow-y: scroll!important;
  overflow-x: hidden;
}
#container {
  -webkit-column-count: 4;
  -moz-column-count: 4;
  column-count: 4;
}

Updated HTML

Do come back if you still face any issues.
Comment: I just realized this does not work in firefox or safari
Comment: Oh.. let me check.! I  will update my answer with the modification.

Overflow and css3 columns


Can you split up expectation over multiplication?

Question: I was wondering if the property exists where if you have $\ E[(Y- \mu)^3]$ you can write it as $\ E[(Y- \mu)^2] E[(Y- \mu)] $ ?
Comment: Well, it CAN happen that E(Y^3)=E(Y)E(Y^2), for example if Y is symmetric, but this is not a general fact at all.
Comment: No, $E[(Y-\mu)^3]=0$ does not imply that $Y$ is symmetric around $\mu$.
Comment: My question says that  when $\ \dfrac{E[(Y - \mu)^3]}{ \sigma ^3} = 0 $ then Y is symmetric. So does that mean I can't use it?? Since it may not be zero all the time?
Answer: Unfortunately, this is not generally true.
It is true that if $X$ and $Y$ are independent random variables, then
$$
\mathbb{E}[XY]=\mathbb{E}[X]\cdot\mathbb{E}[Y].
$$
There are certainly pairs of non-independent random variables for which you can do this; two random variables $X$ and $Y$ so that this property holds are called uncorrelated.
Unfortunately, it is not generally true that $Y-\mu$ and $(Y-\mu)^2$ are uncorrelated.
Answer: Is $Y$ normally distributed by any chance? If it is then Stein's Lemma can be useful for calculating higher order moments.
Stein's Lemma:
Let $Y\sim N(\mu,\sigma^{2})$ and let $g$ be a differentiable function satisfying $\mathbb{E}|g\prime(Y)|<\infty$ then
$\mathbb{E}[g(Y)(Y-\mu)]=\sigma^{2}\mathbb{E}[g\prime(Y)]$
in your case $g(Y)=(Y-\mu)^{2}$ and so $g\prime (Y)=2(Y-\mu)$, for which $\mathbb{E}[...]=0$
and so $\mathbb{E}[(Y-\mu)^3]=0$
!but only works for normally distributed Y.


Why is Dell XPS 15 9500 wifi card not recognized on Ubuntu 21.04 Hirsute?

Question: After reading many contributions about the support of the Killer wifi card of the Dell XPS 15 9500 with the 5.10/5.11 kernels, I decided to install Ubuntu 21.04 Hirsute which provides the 5.11 kernel by default.
Everything on the laptop is working fine, great!
But not the wifi card :-(

lspci shows the wifi card
lsmod shows the various ath11k modules loaded
ifconfig or ip show only the lo interface

What is missing on this installation to recognize the wifi card?
Comment: Let's have a look at the message log for clues. Please edit your question to show the result of the terminal command: `dmesg | grep ath` I suspect that you lack the needed firmware.
Answer: New XPS 15 with fresh 21.04 install two weeks ago.
I'm having issues, twice in the past 2 weeks, on my new XPS 15 9500 and 21.04 with wifi working fine initially then not available.  lspci shows the card.
After trying numerous troubleshooting options found online in desperation I usb boot back to 20.10.  wifi isn't available there either.
Reboot to installed 21.04 and mysteriously wifi is back on.
I have no idea if booting into trial 20.10 fixed it or if it is incidental???


Example of functions where limits don't commute

Question: Can we have a function $f(h,k)$ such that $$\lim_{h\to 0}\lim_{k\to 0}f(h,k)\neq \lim_{k\to 0}\lim_{h\to 0}f(h,k)?$$
Comment: $f(h,\,k) = \frac{h^{2} - k^{2}}{h^{2} + k^{2}}.$
Answer: Say $$f(x,y)=\frac {x-y}{x+y}\quad(x+y\neq0).$$You can extend the domain to $\Bbb R^2$ by defining $f(x,y)=0$ when $x+y=0$.
Answer: Moore-Osgood theorem deals with interchange iterated limits like this, See here and here
Simple counter example from the wiki:
$$ \lim_{x,y \to 0,0} f(x,y) = \lim_{x \to 0 } \lim_{ y \to 0} \frac{x^2}{x^2 +y^2}$$
More detailed discussion about this here
Comment: *wayy beyond my current level* --- I thought as much (I'm older is all), but I was thinking others might be interested (or you or the OP in time).
Comment: p.s: I have no idea about the technicalities of the theorem because my knowledge of it is from a time where I found a limit interchanging problem xD
Comment: @mithusengupta123: For some strong counterexamples and more refined theorems, see the two links given in my answer to [Functions continuous in each variable](https://math.stackexchange.com/a/51308/13130) (my 5th Stack Exchange answer; the July 2011 date had me curious, so I checked with my earliest answers). This non-commutativity of limits was an especially motivating issue for many significant developments in the late 1800s and early 1900s (e.g. the [Baire category theorem](https://www.google.com/search?q=%22baire+category%22), among other things).
Comment: Those papers are wayy beyond my current level but I have added that answer into mine :D


Auto config netplan for specific interface

Question: After removing or adding graphic cards ( I assume it's true for any PCIe device ) my network interface always changes name. From something like enp4s0 to enp3s0. Tested on multiple devices, with 18.04 and 19.04, same thing. After doing some research I found out this might be normal ? (confirmation required)
Anyways if it's not a bug, I have to reconfigure my netplan every time I boot up. I never had such a problem in past with good old networking. Either it always recognized my Ethernet card or name didn't change, but it worked.
I edited my netplan config to this :
network:
ethernets:
    enp4s0:
        dhcp4: true
    enp3s0:
        dhcp4: true
    enp2s0:
        dhcp4: true
    enp1s0:
        dhcp4: true
    enp0s0:
        dhcp4: true
version: 2

It works for configurations I can get, but this definitely is not the solution, more of a workaround.
Answer: In theory you can configure your networking based on macaddress matching and specify the name for the interface that way.
This is a potential configuration that might work for your needs, assuming you can get the MAC Address for your interface and put it in for the mac address below:
network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      match:
        macaddress: "de:ad:be:ef:ca:fe"
      dhcp4: true

This will define the network interface name as eth0 which is the old naming convention, but should work regardless of the name set up by predictive interface naming.
This configuration is partially based off of this example in the Netplan examples documentation but with dhcp4 spin on it (and no VLANs).  (This is an untested solution on my part, however, so if this does not solve the issue for you I will remove this answer.)
Comment: I think it's working - I didn't test with moving around any PCIe cards, but after rebooting it connected to network just fine and the interface shows up as eth0. Thanks
Comment: @John Glad to hear it!  Let me know when you test moving cards around, see if the ifname stays `eth0` and networking still works.  As configured it should "Just Work" per my understanding of the Netplan system, but your mileage with this may vary which is why I still state the solution is 'untested'
Comment: Done some testing with moving cards, multiple devices ... All works really good. Wondering why this isn't default configuration for netplan, much harder to screw it up. I guess this was default for ifupdown since I never run into this on older Ubuntu versions ?
Comment: `set-name` is not needed in order to match (you can call your interface 'eth0' in netplan just fine without changing the interface name in the kernel, it's just a label), and I would discourage this unless you are layering other software on top of it (firewall tools, etc) which needs the interface name to not change.
Comment: @slangasek Edited