Average time on page includes the video view time in Google analytics

Question: Google Analytics has one of the metric which is "average time on page", which is how long user stays on a certain page. I'm trying to figure out if someone watched the video on same page, would the time they viewed count towards this "average time on page" or not ?
FYI- Video is hosted on Brightcove and analytics information for page is extracted from Google Analytics.
Example :- The avg time spent on the landing page is ~2.5 minutes, which is very similar to the average 'video seconds viewed' (39010 seconds played / 290 views = 2.5 min per view on avg). We want to understand if people went to the site and only watched the video (if the video seconds played counts towards average time on page, then the answer is yes); or if people watched the video and spent an additional 2.5 minutes on the site which means 2.5 min +2.5 min = 5 min.
Google Analytics is implemented on Page only and in video we have video analytics.
Any link would be helpful ?
Thanks in advance
Comment: If you embed video on your page, then yes.
Comment: google analytics is not implemented in video, its only there in page
Answer: The average time on a page is calculated from the difference between a hit sent to Google Analytics and the next hit sent.
If you are not tracking the video and a user lands in the page, watch the video and then exit, you will not have average time for that page.
Otherwise if you are tracking the video and for example sending an event to Analytics when the user has reached 25% of viewing it (non-interaction: false) the average time is calculated from the time difference between the event was sent to Analytics and when the user has landed on the page (and so on for the events of viewing 50%, 75%, 100%).
Tracking Brighcove Videos with Gooogle Analytics:
http://www.analytics-ninja.com/blog/2016/03/tracking-brighcove-videos-with-gooogle-analytics.html
Comment: thank you @michele for the reply. I understood completely, let me take and exmaple to understand :- The avg time spent on the landing page is ~2.5 minutes, which is very similar to the average 'video seconds viewed' (39010 seconds played / 290 views = 2.5 min per view on avg). We want to understand if people went to the site and only watched the video (if the video seconds played counts towards average time on page, then the answer is yes); or if people watched the video and spent an additional 2.5 minutes on the site which means 2.5 min +2.5 min = 5 min.
Comment: if there are no interactions (pageviews or events) after the last interaction sent to Analytics, the extra seconds are not counted in the calculation of the average (for example if the user accesses the site and does nothing for 30 minutes or if the user browse the page but nothing is tracked except the pageview of the landing page and then he leaves the website or exceeds 30 minutes, the extra seconds are not counted in the calculation of the average).

You can't know if the user stay on the page for another 2.5 minutes if you do not send an hit to Analytics.


Oracle REST Handler Split Payload

Question: I've installed Oracle DB/ORDS and created all the handlers and related procedures by following Oracle-base guides. There is one issue which I was not able to solve, which seems simple but my lack of understanding SQL hinders me.
When I send JSON documents in bulk such as below;
{"tenantId":"wjg79702","userSessionId":"JAFLA....\n
{"tenantId":"wjg79702","userSessionId":"SLPW....\n
\n

This inserts all the records as expected. But I would like to insert every record one by one into individual CLOB columns. There is line break at the end of every record. How can I split them by incorporating additional functionality into my handler or procedure?
Handler
BEGIN
      create_kayit(p_kayit => :body_text);
END;

Procedure
create or replace PROCEDURE create_kayit (
p_kayit IN CLOB
)
AS
BEGIN
    INSERT INTO uemtest (kayit) VALUES (p_kayit);
EXCEPTION
    WHEN OTHERS THEN
        HTP.print(SQLERRM);
END;

EDIT
Solution has worked. I am sharing the final code for future refences.
CREATE OR REPLACE PROCEDURE create_kayit (p_kayit IN CLOB) AS
BEGIN
        INSERT INTO UEMTEST (KAYIT)
        SELECT
        REGEXP_SUBSTR(p_kayit, '.+', 1, level, 'm') KAYIT
        FROM DUAL connect by level <= length(REGEXP_REPLACE(p_kayit,'.+'));
EXCEPTION
    WHEN OTHERS THEN
        HTP.print(SQLERRM);
END;

Comment: are you storing json docs as clobs, in what version of oracle database? We have a simple oracle document access api (SODA) that makes this trivial - you POST your array of json, and we automatically create the documents for you https://www.thatjeffsmith.com/archive/2020/10/fastest-way-to-upload-a-bunch-of-documents-to-your-oracle-json-collection/
Comment: Yes I am storing them as CLOBS. Right now I am looking at how to go through the :body_text and use substring_regex to loop through these multiple records by carriage return and then insert them line by line. How can I define carriage return in substrin_regex function? I am using latest express edition of oracle, and standalone ORDS.
Comment: CLOBs will be less efficient to read back out, suggest you look at both SODA and BLOBS - faster, easier, way less code for you.
Answer: Answer your comment, if you want to do split by return carriage, one option might be regexp_substr and connect by
Example
SQL> select  regexp_substr(to_clob('line 1
  2  line 2
  3  line 3') , '.+',1,level,'m') from  dual
  4  connect by level <= regexp_count( to_clob('line 1
  5  line 2
  6* line 3'), '.+',1,'m')
  7  /

REGEXP_SUBSTR(TO_CLOB('LINE1LINE2LINE3'),'.+',1,LEVEL,'M')
--------------------------------------------------------------------------------
line 1
line 2
line 3

You just need to incorporate this logic into your procedure.
Comment: Yes, your suggestion has worked. I wanted to share the final code for reference but I don't know how to do it in the comments section. Thank you very much.
Comment: @serhatbalik, you can always edit the question and post the code.

Oracle REST Handler Split Payload


How do I make a WPF ListBox with a TextBox stretch inside a ScrollViewer?

Question: I have a ListBox that contains a single TextBox with a lot of text, which should be wrapped when possible. The ListBox is inside a ScrollViewer along with other controls (in the example below, it's a Button). I would like the ListBox to stretch horizontally with the ScrollViewer, and only show a horizontal scroll bar when the ListBox is smaller than a certain width. Here's the XAML I've got:
<StackPanel>
    <ScrollViewer
        VerticalScrollBarVisibility="Auto"
        HorizontalScrollBarVisibility="Auto"
        >
        <StackPanel>
            <Button Content="Test" />
            <ListBox MinWidth="500">
                <ListBoxItem>
                    <TextBox
                        Text="This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test."
                        TextWrapping="Wrap"
                        />
                </ListBoxItem>
            </ListBox>
        </StackPanel>
    </ScrollViewer>
</StackPanel>

The problem is that the ListBox (and therefore the TextBox) go to their maximum width no matter the width of the ScrollViewer. The horizontal bar always shows up (unless, of course, the width of the ScrollViewer is past the width of the ListBox). I want the horizontal bar to show up only when the ListBox is smaller than a certain size.
Comment: Do you need that outside StackPanel?  It only contains one item.
Comment: @RobertHarvey Not really. It's the topmost panel inside a `Window`, but I suppose that for this example the `ScrollViewer` could be the topmost element.
Answer: I don´t know  why do you need the ListBox i think that you can use this
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <Button Content="Test" />
    <TextBox Text="This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test.This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test.This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test.This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a"
             TextWrapping="Wrap"
             Grid.Row="1"
             VerticalScrollBarVisibility="Auto"/>
</Grid>

Comment: The code I posted is a minimal problem for the sake of simplifying the question. My actual problem uses a ListBox to hold a list of items bound via ItemsSource.
Comment: If you wanna modify the listbox i recommed `ListBox.ItemTemplate` there you can create your custom design
Answer: After a lot of trial-and-error and other answers on StackOverflow, I arrived at the following solution:
<StackPanel>
    <ScrollViewer
        VerticalScrollBarVisibility="Auto"
        HorizontalScrollBarVisibility="Auto"
        >
        <StackPanel>
            <Button Content="Test" />
            <ListBox
                ScrollViewer.HorizontalScrollBarVisibility="Disabled"
                HorizontalContentAlignment="Stretch"
                Width="{Binding ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ScrollViewer}}"
                MinWidth="500"
                >
                <ListBoxItem>
                    <Grid>
                        <TextBox
                            Text="This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test."
                            TextWrapping="Wrap"
                            />
                    </Grid>
                </ListBoxItem>
            </ListBox>
        </StackPanel>
    </ScrollViewer>
</StackPanel>

The only changes are the additional properties on the ListBox.


Ecto - migrate table column into its own join table (shifting the DATA to the new tables)

Question: I would like to go from this:
  schema "products" do
    field :name, :string
    field :brand, :string
    ...more fields...
  end

To this:
  schema "products" do
    field :name, :string
    ...more fields...
  end

  schema "brands" do
    field :name, :string
    ...more fields...
  end

  schema "product_brand_joins" do
    field :p_id, :integer
    field :b_id, :integer
    ...more fields...
  end

Without losing my current data which has products with a string :brand field.
I understand how to create the new brands table and product_brand_joins tables and remove ":brand" from products table, with an ecto migration. But is there a way to manipulate my current data into the new tables?
Comment: Steps should be
1. Create new `brands` table and `product_brand_joins` table.
2. Migrate data from `products` table to the new tables.
3. Delete the field in `products` table.
Your data stay safe!
Comment: Thanks @TheAnh, I am just unsure how to do the migrate data to new tables part. I have only migrated tables, not data.
Answer: You can execute SQL statements using the execute/1 or execute/2 functions, the one that accepts two arguments is a rollbackable version of the first one, which expects a statement to execute when migrating and one to execute when rolling back.
So, you can use that to define what should happen when migrating and it becomes a matter of defining your statement. At the end of this docs page from PostgreSQL there's an example of inserting based on a subquery, which we'll use here.
In your migration .exs file:
use Ecto.Migration

def up do
  create table(:brands) do
    add :name, :string,
    # add other fields
  end

  create table("product_brand_joins") do
    add :product_id, references: :products
    add :brand_id, references: :brands
  end

  # Insert into the brands table a brand with each name found in products
  execute(
    "INSERT INTO brands(name)
      SELECT DISTINCT(brand) FROM products"
  )

  # Insert into the joined table the product and brand ids
  execute(
    "INSERT INTO product_brand_joins(product_id, brand_id)
      SELECT p.id, b.id FROM products p LEFT JOIN brands b ON p.brand = b.name"
  )

  # And finally delete the column from products
  alter table(:products) do
    remove :brand
  end
end

And then for the rollback you would implement the down function in the migration to revert the process using similar logic: creating the brand column in products, filling it with the name of the corresponding brand depending on the product id, and removing the new tables.


How do I evaluate the following integral $\int_{-\infty}^\infty\mathop{dx} \frac{x^n}{(x^2+a^2)^m}$?

Question: I am interested in the following integral $$\int_{-\infty}^\infty\mathop{dx} \frac{x^n}{(x^2+a^2)^m},$$ given that $m>n/2$ (this is just what I wrote so that the integral converges. If this is not exactly true, just assume that $m$ and $n$ are such that the integral converges.) It is known that $m$ and $n$ are rational numbers and $a$ is a real constant. Any body has any idea? I felt that contour integral might be a good bet. However, the problem is that for non integer $m$, there are branch points.
Comment: have you tried trigonometric substitution of x = a*tan(u)? this gives an integrand in terms of a power of sine of u over a power of cosine of u multiplied by a constant of a
Comment: The problem is that 1/cos will be divergent at end points, -pi/2 and pi/2.
Comment: If $-m\not\in\Bbb Z, \frac{n+1}{2}\not\in\Bbb Z, -m+\frac{n+1}{2}\not\in\Bbb Z$, then $\int x^n\left(x^2+a^2\right)^{-m}\, dx$ (if $m,n$ are rational) is not integrable in elementary functions.
Comment: To be more precise, $n$ is an integer, however $m$ is just a rational number.
Comment: A [related](http://math.stackexchange.com/questions/1494128) question.
Answer: Assume $a\neq0$, $m-\frac{n+1}2>0 $ and $n>-1$. Then

$$
\int_{-\infty}^\infty \frac{x^n}{(x^2+a^2)^m}\mathop{dx}=\frac{(e^{i\pi n}+1)}2\:|a|^{n-2m-1}\:\frac{\Gamma\left(m-\frac{n+1}2\right)\Gamma\left(\frac{n+1}2\right)}{\Gamma\left(m\right)}. \tag1
$$

Proof.
Using the Euler beta function $B$, you may write
$$
\begin{align}
&\int_{-\infty}^\infty \frac{x^n}{(x^2+a^2)^m}\mathop{dx}\\\\
&=\int_{-\infty}^0 \frac{x^n}{(x^2+a^2)^m}\mathop{dx}+\int_0^\infty \frac{x^n}{(x^2+a^2)^m}\mathop{dx}\\\\
&=\int_0^{\infty} \frac{(-x)^n}{(x^2+a^2)^m}\mathop{dx}+\int_0^\infty \frac{x^n}{(x^2+a^2)^m}\mathop{dx}\\\\
& =(e^{i\pi n}+1)\int_0^\infty \frac{x^n}{(x^2+a^2)^m}\mathop{dx}\\\\
&=(e^{i\pi n}+1)\:|a|^{n-2m-1}\int_0^\infty \frac{v^n}{(v^2+1)^m}\mathop{dv}\qquad (x=|a|\times v)\\\\
&=\frac{(e^{i\pi n}+1)}2\:|a|^{n-2m-1}\int_0^1 u^{\large m-\frac{n+1}2-1}(1-u)^{\large \frac{n+1}2-1}\mathop{du}\quad \left(u=\frac1{v^2+1}\right)\\\\
&=\frac{(e^{i\pi n}+1)}2\:|a|^{n-2m-1}B\left(m-\frac{n+1}2,\frac{n+1}2\right)
\end{align}
$$ giving $(1)$.
Answer: It looks very like a loop integral in physics, that we do it like this(I hope it wll help): when n is odd, it is 0, when n is even, then $$\int _{-\infty}^{\infty}dx\frac{x^n}{(x^2+a)^m}=\int _0^{\infty}d(x^2)\frac{(x^2)^{\frac{n-1}{2}}}{(x^2+a)^m}$$ then, let $y=\frac{a}{x^2+a}$, it is $$\int _0^1 a y^{-2}dy\frac{(\frac{a}{y}(1-y))^{\frac{n-1}{2}}}{(\frac{a}{y})^m}=a^{\frac{n-1}{2}+1-m}\int _0^1 dy^{m-2-\frac{n-1}{2}}(1-y)^{\frac{n-1}{2}}$$ it is a beta-function so is $$a^{\frac{n-1}{2}+1-m} \frac{\Gamma (m-1-\frac{n-1}{2}) \Gamma (\frac{n-1}{2}+1)}{\Gamma (m)}$$, I hope I don't make mistakes.
Comment: Thanks. Does this apply apply to non integer (but rational) $m$?
Comment: Yes, rational m is OK
Comment: I think ratinal n is also OK, then it is $$\int _{-\infty}^{\infty}dx \frac{x^{n}}{(x^2+a)^m}=\int _{-\infty}^0dx  \frac{x^{n}}{(x^2+a)^m} + \int _{0}^{\infty}  dx\frac{x^{n}}{(x^2+a)^m} =((-1)^n+1)\int _0^{\infty}dx \frac{x^{n}}{(x^2+a)^m} $$


Is there really a benefit to using modules in Factorio?

Question: I've been playing Factorio quite a while now, but I've never really gotten into modules much. They don't seem to really add anything, when you look rationally at the math.
For example. Lets say I am producing green circuits, and I want to increase production. If I pop in 4x speed3 modules in a machine and surround it with beacons (lets say 6) with 2x speed3 modules, I can now produce 4*3*50=600 + 6*2*50/2 = 900% faster. But it also takes 1260% more power.
If I were to increase production by simply adding more machines, I could get 900% increase by adding 9 more machines, and it would only cost me 900% increase in power. Basically with modules I would be "paying" an extra 360% power for no benefit.
So why would I want to spend more power than I need to? I cannot see any way around the basic math here, and I suspect modules are "for suckers", and for people who like the additional layer of complexity. There is also the fact that modules are expensive.
If I came to your home and told you "Hey, I can install this gadget in your coffee machine so it will make your coffee 900% faster, but it will take 1260% more energy!" I assume most rational people would just throw me out. But not in Factorio.
Now, I can see some instances where they can have a true use. For example:
Efficiency modules that reduce pollution and energy. Not incredibly useful, but still a usage that actually works as intended.
Getting more oil. Adding speed modules to oil jacks. Since oil wells are infinite, it can be a way to create a viable oil source from a depleted well.
Technically you could do the same for any ore, but they are 1) not infinite, 2) more abundant. You could add speed modules to an ore field, but then, you could just find another field and double production without spending more power. You could add productivity modules to squeeze more ore out, but it would also slow down the mining. Again, on an infinite map, you could just find another field and modules are useless again.
Productivity modules could save you precious resources, if you are particularly low on something. Again, on an infinite map it should not be an issue, but at least it is an effect that DOES something, as opposed to just pretend to do something.
So am I wrong here? I see very experienced Factorio players like Nilaus talk about how modules are ESSENTIAL for the mega base. But I just don't see it. Unless space is a limited resource. But again... infinite map?
Comment: "4*3*50=600"?  Where the heck did you take that 3 from?  It's 4*50=200.
Answer: Something none of the answers have really spelled out yet is the true effect of combining speed modules with productivity modules.
The effects
The key observation is that the effects stack additively. This means that, e.g. an Assembler 3 with 4x Productivity 3 modules will produce 40% more items per input, while working at 40% speed (-60% malus). And consuming 320% more power for 420% total, but more on that later.
Meanwhile a single Speed 3 increases speed by 50%. Your assembler has all its slots taken up by Prod mods, and beacons only transmit half the effect, so it's 25% per module. Place four beacons in range of your assembler, and the modules give it a +100% bonus. Summed with the malus from the prods, it totals 140% speed. While also having 40% extra output (for free).
The result is that you need way fewer machines to make way more output with way less input.
Let's visualise it.

Here's a calculator output for one yellow belt of red circuits. Notice how it needs 2 input belts of iron, 5 input belts of copper, and 114 assemblers total (plus miscellanea for oil products). And uses 107 MW of power.
And now here's the same assembly line, heavily moduled (with four speed-3 beacons in range of each assembler): we're using 36% as much copper, ~36% as much oil, 45% as much iron, and only 31 assemblers. And the assemblers themselvers are only using about 22% extra power (this doesn't take into account beacon power draw, but again, more on that later).

But why bother?
The effects are absolutely drastic for large-scale builds.

Four blue belts of iron using 65 heavily moduled electric furnaces.

The same using 288 non-moduled furnaces.

Here's 1000 yellow science per minute needing 2800 miners to feed (and needing enough patches to place them all), not to mention over 1000 assemblers and 2200 furnaces...

...and here's the same production being fed by just over 1000 miners, only 136 assemblers and 219 furnaces.

The poster child of the effect of modules is probably rocket science, which I will leave for you to peruse yourself in

unmoduled...
...and moduled flavours.

What does this mean? Everything is smaller and easier. Sure, you can always just build a larger factory. Place 10x more assemblers and furnaces, 3x more miners (on 3x more patches), and get the same output. But why not place 3x more miners, then only 3x more assemblers and furnaces, and get 3x the output?
Because space is free (and infinite), but logistics aren't. Your items need to get from point A to point B, and your factory has a large amount of different processing lines all feeding into each other. It's just that much more effort to connect 10x bigger assembly lines to each other. It's just wasting your play time with needless complexity. Not that it trivialises the game or anything: if you want the extra logistical complexity, just build even bigger while reaping the advantages of modules!
Some of the other answers have mentioned UPS/lag, which becomes relevant for pushing the game to its limits (or if you're playing on a weaker machine). Beacons do not take any processing power - they just apply an attribute to nearby machines - so being able to build the same factory with 5x-10x fewer machines means you get that much less lag. Or conversely, you can build a 5x-10x bigger factory before the game slows down.
A note on mining speed, late-game
Mining productivity research essentially gives you free ores per ore. It's also the only infinitely repeatable research whose costs grow linearly rather than exponentially, so it's realistic to reach very high levels when going for endgame builds. At minining productivity 10 you have a 100% bonus, meaning two ores per ore; at mining productivity 100 you have a 1000% bonus, meaning you get ten free ores for every ore mined (or 11 ores per ore).
At those levels, ore patches start lasting for a very long time indeed. And so it starts making sense to add speed modules to miners, to get more output from the mine. It's not gonna run out for dozens of hours anyway, and it's just faster to stick some modules than it is to run out, find another patch, lay more miners, lay your train tracks to it, hook it up to your train schedules...
But what about power?
Beacons take a lot of power to run. Especially if you're going to be building a factory containing thousands of the things.
Here's the thing, though: power generation in Factorio is really cheap and easy. Usually, a power plant will take up about 5% of a typical factory*. So think of it this way: it's much easier to quadruple your power production while building a 5x-10x smaller factory, than it would be to quintuple your entire factory. If you were willing to put down 1000 extra assembly machines and 2000 extra furnaces - it's much much easier to, instead, simply plop down 8 extra nuclear reactors and the few dozen heat exchangers and turbines around them.
Oh, and pollution is worth mentioning here. Beacons don't generate pollution either, so funnily enough despite both speeds and prods having large pollution penalties, because you'll be using just that much fewer machines, I don't remember the maths but I think moduled factories are either actually greener than unmoduled ones, or at the very least barely any more polluting.
*The elephant in the room here is solar power, which is notorious for requiring vast tracts of land to get covered in solar panels to give reasonable outputs. But here's the thing, you need so many solar panels that you're probably going to automate its construction (with expandable roboported blueprints) already anyway. And solar fields simply... exist; they require absolutely zero logistics to set up, once you've got the blueprint designed and kicked off - so in their case, space really is infinite and building large is completely free.
But what if I'm not building giant endgame bases
Well then modules aren't essentials. You can easily launch the rocket without ever touching a module.
The tl;dr is that modules drastically cut down the time and effort to build huge megabases; and make it possible to build far bigger ones without lagging than could be done otherwise. But they're definitely not necessary or essential when building at small scales, like just enough to launch one rocket in vanilla.
What about efficiency?
I've focused this answer on speed and prod, because ultra-end-game, these are the ones that matter, and they are the ones that are truly essential. Efficiency is mainly useful in other scenarios - namely, when you want to reduce pollution. But when you do want to reduce pollution, they're absolutely cracked - the maximum you can get on any machine is -80% power consumption (and pollution), and you can easily reach that on most machines with just tier 1 greens.
As a result they can be a good candidate for sticking into miners, which normally generate a huge amount of pollution, provided you're not ultra end game yet and don't have huge mining productivity bonuses (at which point you'll be wanting to switch to speed 3s as mentioned earlier). But in general, tier 1 greens are a very cheap way to cut down your pollution and power consumption if you ever need to for any reason.
Comment: You might slightly improve this great answer by mentioning that beacons don't just cover one machine, so the beacon:assembler ratio is closer to 1:1 than the 4:1 often mentioned in Prod + Speed examples.
Comment: +1 for the key **"space is free (and infinite), but logistics aren't"**. When building a centralized 10K SPM base, train logistics are non-trivial _even_ with productivity modules all the way cutting down material requirements by 3x or 4x. Even with nuclear fuel, maximized breaking distance and good signalling you still need to optimize your train network to minimize crossings (or make them efficient). And of course unloading the trains (in vanilla) at that scale is non-trivial. That 128x128 balancer requires _quite a bit_ of material, after all.
Comment: With regard to efficiency modules: one excellent reason to use them is playing on a "Death World" (ie, with bugs settings cranked up to the max).
Answer: The most important module for most players is the productivity module, because it increases the output you get per input. This means that for a given raw material production rate, you can produce more processed items with modules than without them. This effect is particularly strong on recipes that require ingredients that are late in the production tree and represent large amounts of raw materials, such as rockets, labs, and satellites. As other answers have noted, speed beacons are primarily useful to offset the speed loss from productivity modules. Efficiency modules are more niche, and are primarily used on death worlds to minimize pollution to avoid aggroing the biters. Power is generally not a concern; it is fairly easy to over-produce power by the time you get to modules.
In addition, as this reddit post describes, speed modules are actually fairly efficient in terms of increased energy consumption per item produced, because the energy consumption penalty is per unit time, but the machine is producing more items in that same amount of time. In the limit, as that post says

Furthermore, stacking speed modules has an even more dramatic effect, 4x Speed 3 Modules, with a combined +200% speed and +280% consumption, only increase energy per item by +27% - a mere 10% of the +280%.

The Module wiki page also says this about speed and productivity modules:

There is however synergy between productivity modules and speed modules, productivity modules reduce crafting speed which lowers the production rate of items and increases the energy consumed per item, the speed bonus from speed modules increases production rate of items and lowers the energy consumed per item - in fact when dealing with productivity modules, the reduction in energy consumption from the increased speed from speed modules can be greater than the increased energy consumption. For detailed calculations on the synergy between productivity modules and speed modules refer to this discussion as well as this warning.

At megabase scale, things change because the main concern becomes UPS (updates per second). This number generally stays at 60 for normal play, but if there is a very large number of active entities on the map, it can decrease. That can make the game more unpleasant to play, and the decrease in the rate at which the game plays can offset increases in production. Modules and beacons maximize the amount of production you can get per active entity, so they are essential to building at megabase scale.
At megabase scale, when trying to minimize active entities as much as possible, it is more worthwhile to use modules and beacons on earlier intermediate products, and as a result you also get the benefit of compounding productivity. For example, looking at one line through a production tree:

With productivity modules in a rocket silo, you need ~30% less of all input items per rocket.
With productivity modules in blue circuit production, you need ~30% less red circuits to make enough blue circuits to launch a rocket.
With productivity modules in red circuit production, you need about ~30% less green circuits to make enough red circuits to launch a rocket.

So, using productivity circuits in that whole chain means that you need 0.7 * 0.7 * 0.7 = 0.343 times as many green circuits to launch one rocket as you would need with no productivity modules.
Comment: I added some more information about power consumption and about productivity compounding, with numbers.
Comment: So you are talking late game products, and computer power. I still don't get the ESSENTIAL side of it. Sure, 30% bonus to expensive products is nice, but is it game changing? You may be right, but I was looking for numbers.
Comment: @TLP think about this: if you put a couple of Prod modules in the rocket silo, you only need to make 70 parts to launch a rocket. That's a huge difference for relatively little investment. Research is also a good candidate for them you literally research at 1.3x speed.
Comment: @TLP It compounds. Prod in science assembly and labs gives you a 68% bonus
Answer: Because power logistics is easy. Throw power on the net, and it's anywhere you need it to be, instantly, as much as you want.
You don't need more belts, bigger belts, faster belts, trains, tunnels, splitters. You throw it on the net, and it's done.
Copy paste some solar+battery arrays, bots install it, and you got your power. Done.
Now compare that to copy-pasting factories. Especially with oil. In comparison, that's a lot of work. And the belts don't just scale as easily, nor do the trains.
Answer: On power efficiency, modules never beat building more machines - but power is cheap and easy to scale up with no regard for location, while factories and belt networks need to be more carefully planned.
Modules stack additively, so four speed module 3 gives +50% * 4 = +200% = 300% speed and +70% * 4 = +280% = 380% power consumpton.
So you have the choice between boosting 1 machine with modules to 3x speed and barely 4x power consumption, or building 3 machines to get 3x speed and 3x power consumption. The trade-off is having to triple the complicated part of your factory, or copy-paste some of your solar arrays a few more times.
Comment: You could just copy paste your production array a few more times too. Or? That does not explain how it is considered "essential" for mega base construction. Not a bad argument for adding modules to existing buildings, but what about beacons? Have you seen some of the beacon modified stuff where they use more beacons than assembly machines?
Answer: It's tricky to look at the benefits of a module vs an extra production building in a vacuum. Yeah, the map is infinite, and the resources are infinite, but let's look at what happens when you decide to add zero modules and compensate by just building more assemblers:

Now your base is bigger, so you need more belts, inserters, roboports, cables, etc
Your bots need to fly further, so you both need a larger cloud of them and have more overhead & waiting time whenever something changes
Your base is bigger, so you need more walls, more turrets to cover it, more ammo/power to feed them
Also you make more pollution, so you need even more turrets everywhere to deal with the larger waves of bugs
Also you need more patches being mined, because your base uses more resources (for both your extra factories since you don't have productivity boosters and for all the extra infrastructure you need to build)
This means you need more rails, more trains, more mines, and then even more walls and turrets to protect all of them (and it produces even more pollution)

And of course, you need to actually manage all these things, so it's also additional overhead on you as the engineer to set all of it up.
That is not to say you can't build without modules, but I'm assuming the really experienced guys tried both and realized that all the little bonuses from modules, including the not so obvious one, really do add up to more usefulness than just slapping down more assemblers.
I'm not super good at Factorio, but from personal experience, the first time I decided to use modules and put Efficiency Modules into every mining outpost I had, pollution there dropped by 80% and bug attacks went from "constant annoyance" to "almost non-existent". The time and resources saved by not constantly having to think about protecting or repairing them was huge, and that wasn't even a mega-base or high level modules.
Comment: I'm not sure you added anything new, but thanks for your answer.
Answer: Speed modules are mainly used to offset speed penalty from productivity modules.
The benefit of productivity modules is huge, as they apply on all the prereq of what you are building. Prod module in rocket silo and labs --> you need to build less of everything.
This table sums up payoffs : https://factoriocheatsheet.com/#productivity-module-payoffs
Comment: I hear what you are saying, but still, I don't see any numbers contradicting mine. 30% extra products for 310% more power, on maps with endless resources still makes me think I would be better off just adding more production buildings.
Answer: Since you used the word "essential" in a comment: There is nothing essential about modules, they are totally optional in all stages of the game. If all the positive points listed in this and other answers are low on your priority list, or not on it at all, then you personally won't get benefits from modules. There are people playing without modules as a matter of fact, and that is a perfectly valid play-style, even for large factories.
That said, in my factories, modules are excellent in these aspects:

They allow me to achieve the same amount of output with less space usage.
(Totally subjective) they give me another puzzle to solve.
They reduce the amount of source items (for intermediate recipes, not finished products, obviously).

The first part is mostly relevant (to me, subjectively) because I love compact(er) designs; and secondarily because this then requires less of the supporting items (belts etc.).
The second part is important to me because I have done soooo many factories; there is little challenge in clicking together yet another line with only assemblers. But optimizing beacon layouts seems to be fun for me every time. I play primarily for fun, so the actual activity I am doing is meaningful as well, not only the raw maths.
But the last one is the big one. By using productivity and speed modules, you  reduce the required source materials not just for this particular assembler, but all the way down to raw materials. If you have productivity modules on, say, the rocket silo, then all those savings go down recursively through the whole production line. And of course also for the productivity modules on the items before that. This effect adds up enormously, and you have to build much fewer mining outposts, less trains, less belts, less congestion, etc. etc.
For context, I have finished several 1kspm vanilla factories, have played most of the big mods out there (i.e. full Pyanodon, SeaBlockPack, Space Exploration and many more), and am currently in the finishing touches of a vanilla 10kspm (which would be nearly impossible without modules, at the very least psychologically). I totally get where you are coming from (for example, I had given myself a limit of "no modules" at all in my SeaBlockPack just for fun), but if your maths says that they don't have a benefit, then the math isn't quite right.
To make sure, you can fire up one of those in-game or website-based recipe calculators, click together a complete recipe for the rocket with all ingredients down to raw ores, and then compare "no modules" vs. "full productivity + speed beacons" (you can use an average of 8 beacons per assembler if you're not sure). You will most definitely see a noticeable difference.
Answer: About modules I have a specific approach linked with some OCD on my side:
Power modules : reduce biter attacks
I play on peaceful and the few times I played "normal" (to unlock some achievements for example) I used a lot of green modules to reduce pollution and make the biters less angry. It goes slower? Nah I'm not in a hurry.
Production modules : less ore depletion or saving rare ore/components.
In short: rocket construction, kovarex enrichment or very expensive parts (blue circuits). I know it won't do much of a change especially with level 1 modules but in my head I know that free item costed nothing but a little more electricity and time instead of resources.
(sidenote, solar is infinite so I personnaly don't consider electricity as "expensive" and simply adapt)
Speed modules : gimme part quick!
When I see machines clogging that could go faster and I want things to arrive quicker on my belts I use speed modules, especially when idleing.
Answer: Efficiency Modules
reduce power consumption and pollution. They are cumulative, but the max reduction is 80%, i.e. 20% pollution will remain.
Of these effects, energy tends to be quite irrelevant, because by the time you research modules, you have access to clean power, and building more power is cheaper than modules.
That leaves pollution. Pollution drives the intensity of biter attacks, and is a major driver for their evolution. Equipping your factory with efficiency modules may increase its construction cost, but it will allow to produce over twice as quickly at the same pollution level (or produce at the same speed at less than half pollution).
Productivity Modules
produce more output at greater pollution and much less speed. They make a manufacturing step need more assembly machines, and cause these to emit much more pollution per product made. However, they make more products out of the same quantity of raw materials.
Productivity modules are therefore best used where expensive raw materials flow through a cheap (i.e. quick) production step. A prime example is assembling electronic circuits (whose 0.5 second manufacturing time means that the pollution of the assembling machine is negligible compared to the pollution emitted by extracting and refining the raw materials), or sulfuric acid. Some advanced science packs are also prime candidates.
However, productivity modules remain a very situational pick. The main problem is that their disadvantages combine multiplicatively. As the assembly machines grind to a near halt due to the speed debuffs, the amount of assembly machines, and the pollution caused by each machine, explodes.
That changes with the invention of the beacon, and that brings us to
Speed Modules
which allow to increase the speed and energy (and therefore pollution) of an assembling machine. As you rightly observe, speed modules are mostly useless if used on their own.
But what happens if we combine modules of different types? After all, beacons allow us to add a lot more module effects to an assembly machine than its slots would seem to indicate.
Adding more than 3 efficiency modules is useless, because we hit the maximum reduction of 80%. But if we add a speed module to increase speed and energy, and then further efficiency modules until we hit the max reduction again, we can produce with increased speed at the same, minimal, energy and pollution output, reducing the pollution per item :-)
Likewise, as described above, adding several productivity modules causes a prohibitive slowdown of the machine. But if we add speed modules to compensate, we can have a machine that produces more output at the same speed, and if we add sufficient efficiency modules, at the same, minimal pollution output.
Put differently, speed modules are for creating synergies once beacons allow you to bring many effect sources to bear. The disadvantage of such a setup is of course the cost of all those modules, and the electricity consumption of all those beacons. But the benefit is a factory that produces far less pollution per item made.
Answer: First of all, let's get the obvious out of the way. You've probably read https://wiki.factorio.com/Module#Usage_tips but to quickly summarise:

Filling devices with productivity modules is recommended when resources are scarce.
Filling devices with efficiency modules is recommended for electric furnaces as these use a lot of power.
(And as you stated, speed modules on oil)

Outside of these scenarios, all three types of module are a temporary option, a quick and dirty fix for a production imbalance or power consumption imbalance. They have situational benefits. They are not a gimmick, but they are also not a permanent solution, and it is easy to fall into a bad habit of using them.
You are right to say that modules are not ESSENTIAL. If you need production of an item to be improved and to remain scalable, the permanent solution is more mines/assemblers/belts, not modules. This does require you to have materials, space and a plan including transport links.
For some number crunching, see https://forums.factorio.com/viewtopic.php?f=5&t=5705. If, in your opinion, this does not add anything to previous answers, then please clarify your question OR mark one of the previous answers as the solution so that you don't get more and more answers all blindly saying the same thing.
Comment: "bad habit of using them" Yes, let's tell people how they must play this game.


How do I filter my XML list to not get duplicate letters returned case insensitively

Question: I've got some XML that has an Alphabetically ordered list of strings. I want to generate a set of Divs containing the first letter of each set with no duplicate first letters.
XML
<?xml version="1.0" encoding="UTF-8"?>
<textstring>
  <example>Delta</example>
  <example>delta2</example>
  <example>harmony</example>
  <example>incognito</example>
  <example>Inconvenient</example>
</textstring>

XSL
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="textstring">
      <xsl:apply-templates mode="trick" select="/textstring/example"/>
    </xsl:template>

    <xsl:template match="/textstring/example" mode="trick">
      <xsl:variable name="firstLetter" select="substring(text(),1,1)"/>

            <xsl:copy-of select="$firstLetter"/>

    </xsl:template>
</xsl:stylesheet>

Output
D
d
h
i
I

Desired Output
D
H
I

I was thinking of something that would add to the select such as
<xsl:template match="textstring">
  <xsl:apply-templates mode="trick" select="/textstring/example[not(starts-with(
         substring(
           translate(text(),
             'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') ,1,1),
         substring(following-sibling::example[
           translate(text(),
             'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') ],1,1)
    ))]"/>
</xsl:template>

But that results in
D
d
h

Am I completely off base?  I didn't really want to switch to a for-each loop since it is somewhat resource intensive, but is checking preceding sibling really any less so?
Comment: IMHO, you should use [Muenchian grouping](http://www.jenitennison.com/xslt/grouping/muenchian.html).
Answer: As told in the comment you should use the Muenchian Method. See the next XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" encoding="UTF-8" indent="yes"/>

    <xsl:key name="first-letters" match="example" use="substring(translate(., 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 1, 1)" />

    <xsl:template match="@*|node()">
        <xsl:apply-templates select="@*|node()" />
    </xsl:template>

    <xsl:template match="textstring">
        <xsl:apply-templates select="example[generate-id() = generate-id(key('first-letters', substring(translate(., 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 1, 1))[1])]" />
    </xsl:template>

    <xsl:template match="example">

            <xsl:value-of select="substring(translate(., 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 1, 1)" />

    </xsl:template>
</xsl:stylesheet>

This will generate the required output:

D

H

I

Comment: A small nitpick: you should do substring() first, then translate().
Comment: Thanks, this is definitely a solution.  I'm curious about the impact on performance by grouping in this way. In the end I should only end up with something like 26 keys. So it shouldn't be too bad I'd think.  Any thoughts?
Comment: @Joshua: Using the Muenchian Method is the only and best way to go even for performance. If you are satisfied with this answer, don't forget to accept the answer (click the green tick beside the answer)
Comment: Yeah, it answers my question.  Not sure if it fits my exact non-example scenario (I do require the mode="trick" call) but if not I'll open a new question with more specific details. Thanks!
Comment: That was a modification I made to the final version :)


Map from continuous functions in $S^1$ to continuous functions in $\mathbb{R}$ injective subset of periodic functions

Question: Let $S^1 = \{ (x,y)\in \mathbb{R}^2 | x^2+y^2=1$. Let $z:\mathbb{R} \to S^1$ given by $z=(cos(\theta),sin(\theta))$. Define the map $z^* : C^0 (S^1) \to C^0 (\mathbb{R})$ by $z^* (f)= f \circ z$.
I am trying to prove the map $z^*$ is injective onto the subset of continuous periodic functions with period $2\pi$. I know how to prove surjectivity, however, I am not sure how to prove $z^*$ is injective and its image is a subset of the periodic functions with period of $2\pi$
Answer: Periodicity of the image of $z^*$ follows trivially from periodicity of $z$.
Let $z^*(f) = z^*(g)$.
Then, for all $x \in \mathbb{R}$, we have $f(z(x)) = g(z(x))$.  But then clearly $f = g$, so $z^*$ is injective.


Separate and display bitmap from a socket stream

Question: How do I separate and display bitmap images from a continuous socket stream of multiple images? Below codes will save and display a single image when there's only one bmp received. How can I separate and display images when the socket stream contains multiple bitmap images (e.g BM .... BM .... BM...) ?
<code>DWORD WINAPI CServerDlg::ThreadSocket( LPVOID lpParam )
{
    CServerDlg *pThis = (CServerDlg *)lpParam;

    SOCKET server;

    WSADATA wsaData;
    int wsaret = WSAStartup( MAKEWORD(2,2), &wsaData );
    if( wsaret != 0 )
    {
        return 0;
    }

    sockaddr_in local;
    local.sin_family = AF_INET; //Address family
    local.sin_addr.s_addr = INADDR_ANY; //Wild card IP address
    local.sin_port = htons((u_short)8888); //port to use

    server = socket( AF_INET, SOCK_STREAM, 0 );
    if( server == INVALID_SOCKET )
    {
        return 0;
    }

    if( bind( server, (sockaddr*)&local, sizeof(local) ) != 0 )
    {
        return 0;
    }
    if( listen( server, 10 ) != 0 )
    {
        return 0;
    }

    SOCKET_STREAM_FILE_INFO     StreamFileInfo;
    memset( &StreamFileInfo, 0, sizeof(SOCKET_STREAM_FILE_INFO) );
    SOCKET client;
    sockaddr_in from;
    int fromlen = sizeof( from );
    while( pThis->m_bListen )
    {
        char temp[1024];
        memset( temp, 0, 1024 );
        client = accept( server, (struct sockaddr*)&from, &fromlen );
        int iLen = recv( client, temp, sizeof(SOCKET_STREAM_FILE_INFO), 0 );
        if( iLen == sizeof(StreamFileInfo) )
        {
            memcpy( &StreamFileInfo, temp, sizeof(StreamFileInfo) );
            CFile destFile( StreamFileInfo.szFileTitle, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary);
            UINT dwRead = 0;
            while( dwRead < StreamFileInfo.nFileSizeLow )
            {
                memset(temp,0,1024);
                UINT dw = recv( client, temp, 1024, 0 );
                destFile.Write(temp, dw);
                dwRead += dw;
            }
            destFile.Close();

            pThis->LoadPicture( StreamFileInfo.szFileTitle );   // Display image in a dialog box
        }
        closesocket(client);
    }
    closesocket(server);
    WSACleanup();

    return 0;
}
</code>
Comment: You don't need the `memset` before receiving, as the `recv` call will write into it anyway. Also, you should always check for errors or closed connection when calling `recv`.
Answer: The Bitmap format described here
http://en.wikipedia.org/wiki/BMP_file_format
Includes a file size field in the header. You can read that for each bitmap and know where the end of the current bitmap is.
Comment: The length of each image is included in the header. The problem with the above code is all images will be saved continuously as one binary file.
Comment: i know bitmap binary starts with "BM" (0×42 0x4D), how can i locate it, then extract it from the stream? how do i read "0×42 0x4D"?
Answer: You need to design a protocol that differentiates between the different images.
A simple one that send a header (containing the size (in bytes) of the image, and possibly image type), followed by the actual image data is enough.
Comment: I am sending continuous stream with a fixed length of bitmap images. The length of each image is also sent to the server before each image is sent, and it's also included in the header of each image.
Comment: @boogiedoll Fixed size, or having the size being sent as a header, is enough. If all data in the stream is of a fixed length, you _know_ how much to read each time, and read exactly that.
Comment: how do I read that fixed length of file? do i read directly from the buffer? or save is as a file first then display?


How to use specific data from arrays - Example of click

Question: I have the following JQuery code:
var test = new Array();

    $(".quiz_list_row").each(function(index){
            // Gets the data necessary to show game chosen
            $quiz_list_id = $(this).data("quizlistId");
            $quiz_level_reached = $(this).data("quizlevelReached");

                test.push($quiz_list_id,$quiz_level_reached);

            $(this).click(function(){
                alert("test: "+test);
            });

    });

The divs (using html5 to send data):

Quiz 1

Current level: 5

Quiz 2

Current level: 7

The problem is that I need to find out how to use the data in the array test when the user clicks on a specific row (I want to use $quiz_list_id and $quiz_level_reached).
Comment: just so you know, you know that the items you're pushing into test is the id, then the quizlevel. I would assume you'd want them kept together instead of separate elements in the array. so your array would look like ['1','5','2','7'] in your example.
Comment: @kennypu, you're right! I decided to use david's answer, it's elegant and precise! hehe =) Thank you for the advice!
Answer: Unless there is a specific reason you're extracting the attributes and putting them into an array, I think you're taking some unecessary steps to achieving what you want. Take away the complexity from this, you have access to the data attributes with the .data() method at any time you have access to the elements jQuery object, one of those times is within the click handler itself.
var quizRows = $(".quiz_list_row");

quizRows.click(function(event) {

    var self = $(this);

    //As the element clicked on has it's data attributes defined
    //You would just need to retrieve it when the element is clicked on
    var id = self.data('quizlist-id'),
        level = self.data('quizlevel-reached');

    console.log("id is " + id);
    console.log("level is " + level);
}

Comment: It's funny that data('quizlist-id') should be data("quizlistId") to get the attributes, but it's like that. I haven't tried the method you spelled, though.
Anyway, that's an elegant way to solve the problem =) Thank you very much!!!


Why doesn't Patchwerk take fatigue damage?

Question: In the solo adventure Naxxramas the first boss on the fourth wing Patchwerk takes no fatigue damage. Was this intentional or just a bug? This happens on the normal and the Heroic version.
Answer: This is intentional. The bosses in Adventure Mode don't always play by the rules.
Patchwerk starts with no deck but he does not attempt to draw a card at the start of his turn. This means he won't normally take fatigue damage.
However, Patchwerk is not immune to fatigue. If an effect does cause him to draw cards, such as Coldlight Oracle's battlecry, he will attempt to draw them and take fatigue damage as a normal player would.
Comment: @freekvd Have you actually tested this? I've heard that it simply causes him to attempt to draw 3 cards. Still brutally effective of course- 21 damage over 2 turns and a kill at 3- but not instant.
Comment: A single Jeeves will cause Patchwerk to instantly die from fatigue.
Comment: Just tried it, and apparently you are right. That's weird though, considering his card text.


Get value of column content by row with Python/Pandas

Question: I have identified the row numbers of where I need to get within my excel file, with python pandas; using the below:
 row_numberd1 = df[df['Member Name'].str.contains(NameUp)].index.min()
 row_numberd12 = df[df['Member Address Line 3'].str.contains(Zip)].index.min()

i.e. when I print, the row numbers display:
 print(row_numberd1)
 print(row_numberd12)

Now, I am simply wondering how I can use the row number; to get a different columns value. So, get columns value by row number.
So, for instance, in the below sample:
   Age      City
1   34    Sydney
2   30     Delhi
3   16  New York

How could I use the row number; i.e. let's say Row 3, Column 'City' to get the 'New York' value?
Comment: df.loc[idx,'columns']
Comment: It is unclear to me
Comment: Can you create a [MCVE] ?
Answer: .loc for label based indexing
df.loc[3, 'City']
#'New_York'

# For a single value use `.at`
df.at[3, 'City']
#'New_York'

iloc for index based selection
df.iloc[2, 1]
#'New_York'

# For a single value use `.iat`
df.iat[2, 1]
#'New_York'

iloc + get_loc for a combination of both
(i.e. 3rd value in 'City')
df.iloc[2, df.columns.get_loc('City')]
#'New_York'

Answer: you can use
df[column_name][row_number]
Comment: This is called ["chained indexing"](https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy) and should be avoided.


plsql get particular sub string from givin string

Question: I have a input string like following
'"sadf asd " <firstname.lastname@example.com>'
'"email@example.com " <firstname.lastname@example.com>'

now i want to extract email address as following:
firstname.lastname@example.com
firstname.lastname@example.com

how can i get it ?
Comment: Is the email address always between < >?
Answer: Assuming that the address is always quoted by <...> and that there are no '<' or '>' in the first part of the string, you can use:
select regexp_replace('"email@example.com " <firstname.lastname@example.com>', '(.*)<(.*)>', '\2')
from dual

Answer: Here is a way:
select replace(replace(REGEXP_SUBSTR('"firstname.lastname@example.com " <email@example.com>','[<](\w+@(\w*.\w*)+)[>]'),'<',''),'>','')
from dual

This will return firstname.lastname@example.com


Add style to Docx in Novacode

Question: Using Novacode's DocX, I can add a paragraph with Heading 1 style like this:
var p = docX.InsertParagraph("My Heading");
p.StyleName = "Heading1";

But I can't add a "Title" style:
var p = docX.InsertParagraph("My Heading");
p.StyleName = "Title";

I looked in the generated Xml files, and I see the "Title" style is not in the Styles.xml file, whereas if I set it as Title style in Word and save, then the Title style appears in the styles Xml file.
So how do I either get DocX to include the Title style, or how do I go about adding a style to the DocX styles?
Answer: I meet this problem too. By comparing word\document.xml and word\styles.xml files in the docx(zipped)file. I found that the Paragraph.StyleName should be assigned with the style id not the style name !
for example:
one style in styles.xml:
<w:style w:type="paragraph" w:customStyle="1" w:styleId="a9">
    <w:name w:val="mystyle" />

You should assign "a9" not "mystyle" to Paragraph.StyleName to get the correct style.
Hope helpful.
Answer: I ran in to the same problem. I could solve it as follows:

create a .dotx Word template, and fill it with text/words in the styles you want to use (e.g. Title in the style 'Title', Heading 1 in 'style 'Heading 1', Heading 1 in 'style 'Heading 1', etc.
in VS, create a Novacode.DocX object and apply the .dotx as a template:
    static void Main(string[] args)
    {
    // Insert a paragrpah:
    string Title = "Hello World!";
    string Header1 = "Countries in Europe";
    string Header2 = "Belgium";
    string Header3 = "France";
    string Para1 = "Belgium, officially the Kingdom of Belgium, is a sovereign state in Western Europe bordered by France, the Netherlands, Germany, Luxembourg, and the North Sea. It is a small, densely populated country which covers an area of 30,528 square kilometres (11,787 sq mi) and has a population of about 11 million people. Straddling the cultural boundary between Germanic and Latin Europe, Belgium is home to two main linguistic groups: the Dutch-speaking, mostly Flemish community, which constitutes about 59% of the population, and the French-speaking, mostly Walloon population, which comprises 41% of all Belgians. Additionally, there is a small group of German-speakers who live in the East Cantons located around the High Fens area, and bordering Germany.";
    string Para2 = "France, is a country with territory in western Europe and several overseas regions and territories. The European, or metropolitan, area of France extends from the Mediterranean Sea to the English Channel and the North Sea, and from the Rhine to the Atlantic Ocean. Overseas France include French Guiana on the South American continent and several island territories in the Atlantic, Pacific and Indian oceans. France spans 643,801 square kilometres (248,573 sq mi) and had a total population of almost 67 million people as of January 2017. It is a unitary semi-presidential republic with the capital in Paris, the country's largest city and main cultural and commercial centre. Other major urban centres include Marseille[XVI], Lyon, Lille, Nice, Toulouse and Bordeaux.";

    using (MemoryStream docStream = new MemoryStream())
    {
        using (Novacode.DocX doc = Novacode.DocX.Create(docStream, Novacode.DocumentTypes.Document))
        {
            // Build the document
            // apply template
            doc.ApplyTemplate(@"C:\tmp\wordTemplate.dotx", false);
            // insert text with styles
            doc.InsertParagraph("Hello World", false).StyleName = "Titel";
            doc.InsertParagraph(Header1, false).StyleName = "Kop1";//dutch for Heading1
            doc.InsertParagraph(Header2, false).StyleName = "Kop2";//dutch for Heading2
            doc.InsertParagraph(Para1, false).StyleName = "Standaard";//dutch for 'Standard', style 'Normal' in an English Word version
            doc.InsertParagraph(Header3, false).StyleName = "Kop2";
            doc.InsertParagraph(Para2, false).StyleName = "Standaard";

            // Same the doc to MemoryStream
            doc.SaveAs(@"C:\tmp\ExampleDoc.docx");
        }

    }
}

Result: Screenshot of my word application
However, new problem: I had to add the styles in the native language of the Word application I want to use the document with (dutch). 'Kop1' is the equivalent of 'Heading1', 'Titel' is 'Title',  etc. When I use 'Heading1' or 'Title', this results in an error.
But, since you are in control of the .dotx document, this could be a solvable problem...
Answer: Turns our there are several Styles that are not implemented in this lib.  If you look in the source in the _Enumerations.cs file, there is a enum called HeadingType.  In this enum there are notes that Title and several others are not implemented as they are different than Headings.  It looks like the note says you can try yourself, but that would require a custom build of docx to be included in your project.
I would suggest that you find out what font characteristics are and set them manually or in a config file.  The simple example.
static void AddTitle()
{
    Console.WriteLine("\tAddTitle()");
    using (var document = DocX.Create(@"docs\Title.docx"))
    {
        var title = document.InsertParagraph("this should be a title");
        title.FontSize(28).Font(new FontFamily("Calibri Light"));
        document.InsertParagraph("title is above!");
        document.Save();
    }
}

Answer: I had a similar problem. I solved it by manually setting the Styles in a docx (Open the dialogue via STRG+SHIFT+ALT+S in Word) and used this docx file as a kind of template. This way, you can use the Paragraph.StyleName Attribute and the connected style.
Comment: i have a similar issue but cant seem to attach a style to a table, any ideaS?
Comment: I did like this, but when DocX is opened, styles seems assigned correctly but they're not applied (in other word, if you set for example a color in a style, it does not appear).

Add style to Docx in Novacode


Force browser to get last version of certain sources (CSS, JS, etc.)

Question: I would like, when someone is visiting my website, to make sure the browser has the last version of my files CSS, JS, etc. The idea I came with is to add an extra reference on my links:
Instead of using


Crontab job that compresses file with timestamp

Question: Ubuntu (Oracle VM virtual box)
I got an assignment to write 3 crontab jobs as follows:

logger - job that prints the date into /var/log/myDate.log every 30 minutes
archiver - job that compressed /var/log/myDate.log using gzip every day at 2:00 am with a timestamp (/var/log/2022_08_03.log.gz)
cleaner - job that cleans all gzip files except the 7 recent ones.

This is what I got so far:
<code>nevosmic@nevosmic-VirtualBox:~$ crontab -e
#
#
* /30 * * * * date >> /home/nevosmic/myDate.log
0 2 * * * gzip /home/nevosmic/myDate.log
</code>
This is working fine. Creates the myDate.log file in /home/nevosmic and prints the date every 30 min.Than creates myDate.log.gz in 02:00
The first problem I have is that /var/log/ directory has no permissions to write to other users (Sould I create the crontab job from inside root?)
UPDATE:
I did $ sudo crontab -e and it works.
I managed to create and write to the /var/log/myDate.log. But now, even when I try to store the zipped file in another directory : /home/my_userName/2022_08_03.log.gz the gzip is not working..
My command :
<code>#
#
*/30 * * * * date >> /var/log/myDate.log
0 2 * * * gzip /var/log/myDate.log > /home/my_userName/$(date+"%y_%m_%d").log.gz
</code>
It creates a zipped file /var/log/myDate.log.gz ... but this is NOT my intention.( I need it to be in /home/my_userName/ )
Any suggestions on how to do task 3?
Can I do this?:
<code># Every monday at 02:00 rm all files except the 7 most recent
0 2 * * 1 ls -t /home/nevosmic/logim/*.gz | tail -n 7 | xargs rm
</code>
Comment: ... as well, there is a typo in your time specs (`* /30 * * * *` needs to be `*/30 * * * *`) and also the `%` signs in the `date` command must be escaped - see for example [Unable to execute command in cron](https://askubuntu.com/questions/829818/unable-to-execute-command-in-cron)
Comment: Read `man gzip`. Use `gzip output`.
Comment: You can use the `-c`, `--stdout`, or `--to-stdout` option if you want to redirect gzip's output
Comment: and use /etc/crontab .., it lets you set a user.
Comment: /usr/gzip -c /var/log/myDate.log > /home/my_userName/$(date +"%y_%m_%d").log.gz is not working as well.
Comment: I guess all is remaining now is the "cleaner job" ... Work on it and show us your attempted solution and we will help.
Comment: Do you think I can use: 0 2 * * 1 ls -t /home/nevosmic/logim/.gz | tail -n 7 | xargs rm ?
Comment: Something like `find /full/path/diractory/ -type f -name "*.gz" -printf '%C@\t%p\n'| sort -nrk1 | awk 'NR > 7 {print $2}' | xargs rm` would be more accurate ... Also you might want to consider using [`logrotate`](https://manpages.ubuntu.com/manpages/xenial/man8/logrotate.8.html)
Answer: UPDATE:
Thanks to steeldriver,
This command works for me (I needed the '' before any '%') :
<code>#
*/30 * * * * date >> /var/log/myDate.log
0 2 * * * gzip -c /var/log/myDate.log > /home/my_userName/$(date +"\%y\%m\%d").log.gz
</code>
Comment: So it's working now ... Well done.


Django postgresql, filter on DateTime field with gt and lt lookups doesn't work

Question: I have problem with filtering on Datetime field with lt and gt lookups. I use following code:
timeout_range = timezone.now() - timezone.timedelta(seconds=settings.USER_ONLINE_TIMEOUT)
if friend_filter == "offline":
            friends.filter(friend__info__last_active__lt=timeout_range)
elif friend_filter == "online":
            friends.filter(friend__info__last_active__gt=timeout_range)

In both cases, it returns same result and seems like it doesn't filter anything at all.
Answer: Applying the filter to a queryset returns a new queryset and does not modify the existing queryset. Since you don't assign the new queryset to a variable, I am assuming that you simply access the friends variable afterwards which is still the original queryset. Assign the result of filter(...) to the friends variable to access it later.
if friend_filter == "offline":
    friends = friends.filter(friend__info__last_active__lt=timeout_range)
elif friend_filter == "online":
    friends = friends.filter(friend__info__last_active__gt=timeout_range)


html5 form validation - use pattern on optional field

Question: I have an optional form field that I want to use the new html5 pattern option.
But, when I add the pattern, the field becomes required even though I do not have the required attribute.  I have included the pattern below.  I want the user to be able to leave the field blank, but if the user enters something in the field, then I want the pattern applied.  How would I accomplish this?  Thanks in advance.
pattern="[-a-zA-Z '.,]{3,50}"

Answer: The problem is that {3,50} limiting quantifier requires at least 3 occurrences of the chars defined in the character class.
You need to make the pattern optional. Wrap it with an optional non-capturing group:
pattern="(?:[-a-zA-Z '.,]{3,50})?"
         ^^^                   ^^

HTML5 patterns are wrapped with the anchors automatically, i.e. the pattern above will be translated into ^(?:(?:[-a-zA-Z '.,]{3,50})?)$ and will match

^(?: - start of the string
(?:[-a-zA-Z '.,]{3,50})? - 1 or 0 occurrences of 3 to 50 hyphens, ASCII letters, spaces, ', . or ,
)$ - end of string.
Comment: Amazing.  Thanks.  You are HTML5 genius.  I simplified it by removing the ?: at the front.  And I didn't see the end of string in your pattern above.  The simplified version worked.  Is there a reason I need a start of string and end of string?
Comment: @XiVix: See [the docs](https://www.w3.org/TR/html5/single-page.html#the-pattern-attribute). The pattern you use in `pattern` attribute *must* match the entire string, and thus the `^` and `$` in leading/trailing positions are not necessary. That is why I did not include them into the pattern.


How to change the progress colour of SeekBar dynamically at runtime?

Question: I have tried to find a solution to this problem, but nothing i try seems to give the effect i want.
In my app, i have a SeekBar, that i want to change the colour of to match the current file being played (user can set different colours for different files).
My problem is that i am not able to find a way of setting the progress and thumb colour of the seekbar at runtime, as i dont know what colours will be used until the app runs, so i cant create XML drawables for each colour.
If someone knows of a way of changing the colour of the progress and thumb of the SeekBar at runtime, I would much appreciate their help.
Thanks, Corey B
Comment: like this? http://stackoverflow.com/q/9837843/2001247
Comment: Hi, I tried what was said in that link, but unfortuantely, it didnt work. After much trial and error however, i did manage to find a way to change the colour of the seekbar. Thanks anyway for your help, its much appreciated. Corey B :)
Answer: For those who have same problem. From above code i understand you want to change colour of SeekBar
i had same problem , after lot of search i made method of my own.
<code>public void changeSeekbarColor(SeekBar s,int colorp,int colors,int color b)
{
    PorterDuff.Mode mMode = PorterDuff.Mode.SRC_ATOP;

    LayerDrawable layerDrawable = (LayerDrawable) s.getProgressDrawable();
    Drawable progress = (Drawable) layerDrawable.findDrawableByLayerId(android.R.id.progress);
    Drawable secondary = (Drawable) layerDrawable.findDrawableByLayerId(android.R.id.secondaryProgress);
    Drawable background = (Drawable) layerDrawable.findDrawableByLayerId(android.R.id.background);
    Drawable th = s.getThumb();

    // Setting colors
    progress.setColorFilter(colorp,mMode);
    secondary.setColorFilter(colors,mMode);
    background.setColorFilter(colorb, mMode);
    th.setColorFilter(colorp,mMode);

    // Applying Tinted Drawables
    layerDrawable.setDrawableByLayerId(android.R.id.progress, progress);

    layerDrawable.setDrawableByLayerId(android.R.id.secondaryProgress, secondary);

    layerDrawable.setDrawableByLayerId(android.R.id.background, background);

}
</code>


Jquery Autocomplete close function

Question: I have a Jquery Autocomplete menu with an image at the bottom of it - added with the code below.
Is there a way to have Jquery Autocomplete menu close (disappear) after I click on the picture?
Thank you for your help.

Answer: On the click event, call $( "#tags" ).autocomplete( "close" );.
Here is how I'd do it...
$("#tags").autocomplete({
    source: availableTags,
    open: function(event, ui) {

        var nyc = $("", {
            src: "http://www.gravatar.com/avatar/8a3efc8be996c87da020df31e2416151?s=32&d=identicon&r=PG",
            alt: ""
        });

        nyc.click(function() {
            $(event.target).autocomplete("close");
        });

        $(this).autocomplete("widget").append(nyc);
    }
});

jsFiddle.
Comment: @Alex - sorry I completely missed the jsFiddle you posted initially.  My menu behaves now exactly as planned. Thanks much!
Comment: Actually, have you tested this? I've tried it out, and `ui.autocomplete("close")` doesn't actually close anything.
Comment: @AndrewShepherd No, I haven't.
Comment: @AndrewShepherd Thanks, I've modified the code and tested it.
Comment: Alex, please indicate where you've modified the code because Andrew's post shows that it doesn't work. Thanks.
Answer: Here's how I did it:
function closeAutocomplete() {
    $("#tags").next().hide();
}

$(function() {
       var availableTags = [
        "new york, ny",
        "new york city, ny",
        "manhattan, ny",
        "queens, ny",
        "brooklyn, ny",
        "bronx, ny",
        "staten island, ny",
        "kings county, ny",
        "richmond county, ny",
        "big apple, ny"
    ];
    $( "#tags" ).autocomplete({
        source: availableTags,
        open: function (event, ui) {
                     var nyc="";

                     $(this).autocomplete("widget").append(nyc);
                     $('#nycImage').click(closeAutocomplete);
            },
    });
});

Jquery Autocomplete close function


Open a message and select text

Question: I have used this code to open the selected message in a new window:

Dim olApp As Outlook.Application
  Dim Msg As Object
  Set olApp = Outlook.Application
  Set Msg = olApp.ActiveExplorer.Selection.Item(1)
  Msg.Display

I now want to go to the body and select the text "ERROR" inside the body, and then leave it for manual treatment.
I actually know the line number where this text appears (there is som more code). But my problem is how to get to the body of the message, go to the line, select the text - and then leave the routine.
Comment: The body is a property of a mail item.  Try `Msg.Body` for the text body or `Msg.HtmlBody` for the Html body.
Answer: Try using Word. Untested code
<code>Sub SearchString()
Dim myInspector As Outlook.Inspector
Dim myObject As Object
Dim myItem As Outlook.MailItem
Dim myDoc As Word.Document

Dim strItem As String

Set myInspector = Application.ActiveInspector
Set myObject = myInspector.CurrentItem

'The active inspector is displaying a mail item.
If myObject.MessageClass = "IPM.Note" And _
    myInspector.IsWordMail = True Then
    Set myItem = myInspector.CurrentItem
    'Grab the body of the message using a Word Document object.
    Set myDoc = myInspector.WordEditor
    myDoc.Range.Find.ClearFormatting
    Set mySelection = myDoc.Application.Selection
    With mySelection.Find
        .Text = "ERROR"
    End With
    If mySelection.Find.Execute = False Then
       MsgBox "There is no ERROR in this message."
    End If
End If
End Sub
</code>
Adapted from http://blogs.msdn.com/b/officedevdocs/archive/2011/03/15/how-to-search-for-a-string-in-an-email-message-and-automate-a-reply-that-contains-the-string.aspx

Open a message and select text


Plugging a kitchen sprayer that has a quick-connect fastener?

Question: TL;DR: Is there an easy way to properly plug a kitchen faucet sprayer when the sprayer uses a quick-connect instead of a threaded connection? Simply cutting the hose and plugging it isn't an option.
Full story: My wife and I currently rent our house, and we only have a sink with a sprayer in the kitchen, no dishwasher or in-sink garbage disposal. She managed to find a great deal on a portable dishwasher ($50 for a barely-used one that would have retailed for around $300), and snapped it up. We stashed it in the garage until I could get the time to hook it up.
Upon further research (hindsight is always 20/20), I found that hooking up a portable to a faucet with a sprayer can potentially cause the sprayer to blow. The obvious solution was to remove the sprayer and cap the feed to the sprayer hose. I figured it would be no big deal, as the guides I found online basically showed unscrewing the hose and capping it with a 3/8" brass cap, and we could just stash the sprayer under the sink & put it back when we move out. Easy-peasy, right? I popped over to the hardware store and got a cap, tape, and a plug for the sprayer hole in the sink, figuring that the faucet would have standard fittings.
Wrong again. Upon getting under the sink, I found that the faucet uses a quick-connect sprayer hose, rather than a standard threaded connection. The thing uses a Peerless/Delta RP54807 sprayer kit. This obviously torpedoed my plan to just cap the thing and be done with it, because there were no threads to screw anything on to.
This brings me to my question: Is there an easy, non-permanent way to remove the sprayer and cap that quick-connect barb, so we can hook up the dishwasher? If not, I'll happily just swap the faucet for one with standard connections, but I'd really rather not do that if I don't have to.
Answer: Home Depot carries caps for most quick connects. Go to the store and look at the RP40301 (cap for round) or the RP60295 (cap for square quick connect). Both are made for Delta to convert faucets from "with sprayer" to "without sprayer". These Delta numbers will work at other stores, too.
Hope this helps.
Comment: The RP60294 was exactly what I was looking for, given my faucet model. Unfortunately, it was unavailable locally (no-go at both Home Depot and Menards), but I was able to find it online. Thanks for your help!
Answer: Me i took the top off and removed the diverter, Squeezed silicon into the hole and put put a brass screw with threads smaller than the hole and a head a tiny bit bigger.  cleaned up excess silicon with long hemostats after it dried.  When i wanted it out i just pushed a dowel rod thru the bottom of the hole and pushed the screw and silicon out.  Put the diverter back in and hooked up a sprayer.    The things you do when you have to get inventive.  a rubber piece silicone down would do the same just don't cover the water inlets.
Comment: Welcome to [diy.se]. Please [edit] your answer to make it more readable. It's very hard to envision what you're trying to say, for example "Squeezed silicon into the hole and put put a brass screw with threads smaller than the hole and a head a tiny bit bigger". Maybe it's just me, but that's clear as mud.


OR-port $A\cdot B$: its conditional probabilities with zero working probability for each component? Reductio ad absurdum?

Question: I made this statement $P(T|A)=P(T|B)=0=P(T|\neg A)=P(T|\neg B)$ with a simple OR-gate where $P(A)=0$, $P(B)=0$ and $T=A\cdot B$ i.e. $P(T)=P(A\cup B)$.

What are the conditional probabilities of the system i.e. $P(T|A)$, $P(T|\neg A)$, $P(T|B)$ and $P(T|\neg B)$?
Answer: Suppose A works, what is the probability that the system works i.e. $P(T|A)$? Look A has 0% working probability i.e. $P(A)=0$ so what does the phrase "A works" mean here? The term "working" can mean at least two things: $P(A)=1$ or $P(A)>0$. The latter requires thinking probabilities with intervals.
The below threads address the aroused issues so far.
Sub-problems

Solved $P(T\cap \neg B)$ if $P(T)=P(A\cup B)$ where $P(A)=0$ and $P(B)=0$?
Solved Complement and Negation: $P(A)=0\rightarrow P(\neg A)=1$?
Conditional probabilties in the OR-gate $T=A\cdot B$ with zero-probabilities in $A$ and $B$?


What layout to choose for input fields with units?

Question: I'm currently in the wireframing stage of a project with a medical background. Nurses, Doctors and so on use the interface to enter captured patient data, mostly measured values in different units. My goal is to make the layout more efficient when you want to enter all the measured values into the input fields - the users  jump from field to field and quickly need to grasp the relevant input-information.
Some input fields provide maximum values, I want to use these to adjust the lengths of the input fields respectively so that the length of the input field acts as an affordance for the user. Some fields don't provide maximum values, so I need to resort to a default field-length. All input fields need to display the unit.
I came up with two versions:
Version A aligns with the standard model of NUMBER - UNIT, like 10 kg, 10 minutes, 10 cm. Nielsens heuristic »Match between system and real world« and »Consistency and standards« come to mind.
Version B offers a more structured approach. Users always find the unit in the exact same spot, eyes don't need to travel at the end of the input field only to go back straight afterwards. No matter how long the input field is, even if the entered value is just 2 characters long you still got the unit and value next to each other. Heuristics like »Flixibility and efficiency of use« come to mind.
What would you go for and why?
Answer: The best way I have found for this is to put them with the label (after the label in parenthesis) for example, label (unit) ________ This way the reading order is maintained in the sense that the user reads all instructions at once instead of reading the label at one end and looking for the unit at the other end then back to the middle to enter the value.
Comment: I guess this is perfect if your label is in line with the input field, but due to various lengths of the labels (questions) the unit would be somewhere else everytime. I want to establish a standard-position for the unit, because they change on nearly every question.
Comment: @Erik In that case, A/B won't matter as long as the input is not too wide for the user to move his or her head from left to right. It will be easier to compare numerical values if the input boxes are of equal width and all numbers are aligned to the right provided equal places of decimal values are displayed.
Comment: Yes, I did a quick visualization of the structure https://imgur.com/a/bhzUQZE I guess I will have to test both versions.
Answer: I hguess it depends on the country/region, but most western countries usually write it 100 cm or 500 €. It is pretty much just usual in the US to write $500.
So, go with a)
TL;DR:
X amount of Unit Y
1€
100ft
Simple test:
How do you speak out how much money you have left in your pockets? I am sure you say "I have 5 bucks with me" or "I have 20 pennies in my pockets". This is a good indicator to how to put it on your website and use it for forms.
Answer: Recognition is faster than recall, so go with what's typical or standard of similar forms.
Otherwise, if your users read top to bottom, left to right, it still makes sense to have the labels on the left because it identifies the following field, and that's important because tunnel vision and selective blindness might lead users to assume the label in a time-constrained environment.
Answer: My guess is version A is more natural to browse visually. However, I would recommend you showing this quickly to a doctor or nurse and see which version they like. Maybe the units are standardized across, so e.g. for measurement A it will always be in CM, so no need to check it says CM on the field.
Answer: Based on the scenario and users you described, I assume that the user of this app will probably repeat this task many times and do it frequently enough that the units aren't going to be the main focus every time they fill out this form.
It seems to me that having variations on input length is preventing the units from shifting positions without offering a big payoff for this loss of alignment. I'd go with option A and eliminate the width variations to have the units align nicely.
Answer: The design principle I like to follow in these situations is "See what Amazon does and copy it." Seriously though, if we see that a pattern is consistently used by companies that invest millions into UX, we're probably better off following it (unless of course our own user research and testing proves otherwise). There's lots of good reasons to follow established patterns which I won't get into now, but for now I'll try to figure out if there is an established pattern. A quick search shows that Amazon's placement of units corresponds with how things are normally written.
As marvinpoo mentioned, in the US dollar amounts are written as $###, so Amazon places the $ sign at the beginning:

But weight and dimensions are written as ##lbs, ##in, etc - so Amazon places them at the end:

I did a quick comparison with the only other UI I could think of at the moment with dimensions (Photoshop). Pixel sizes are written as ##px, so they place the unit at the end:

If it were my project, I'd probably check a couple more UI's (but only by companies that invest heavily in UX.. I wouldn't care about free online unit converters, etc). If you're convinced there's an established pattern I'd go with it, unless user testing revealed a reason to try something else.
Edit: I just reread your post and noticed your comment: "Nielsens heuristic »Match between system and real world« and »Consistency and standards« come to mind." So sounds like you are already well aware the benefits of following patterns, but were weighing those against the possible benefits of your alternative approach. My conclusions are still the same, I just may have worded my response differently :)
Comment: "See what Amazon does and copy it."  Do not. They have a very bad UX. Why they work is because of the amount of items and the prices. Their key to success is, that people will always search for products and use the spammy heavy loaded recommention modules. Amazone is like the sociopath that convinces you, cutting off your finger and letting him film it was your idea while the sociopath basically just made you do whatever he wanted.
Comment: Besides that, the rest of your answer is correct ;)
Comment: Hey thanks for the reply. Yes I know about the benefit of following standards. Biggest problem is, that some fields dont have max values and I it is important to have all the input values visible (so you dont have to move the cursor to the left or right). I did a visualization of my alternative here. But I guess I will resort to the standard way of Value:Unit. https://imgur.com/a/bhzUQZE


How to solve $\lim _{x\to \infty}\dfrac{x^5}{2^x} $ without L'Hospital's Rule

Question: Considering that asymptotically, $2^x$ grows faster than $x^5$ (in the beginning, $x^5$ grows faster than $2^x$, but there will be a point where $2^x$ outgrows $x^5$) then $\dfrac{x^5}{2^x} \rightarrow 0$ as $x \rightarrow \infty$. Therefore,
$$\lim _{x\to \infty}\dfrac{x^5}{2^x}  = 0$$
But in order to solve the limit, I applied  L'Hospital's Rule five times
\begin{align}
\lim _{x\to \infty}\dfrac{x^5}{2^x}  & =\lim _{x\to \infty}\dfrac{5x^4}{2^x\ln 2}\\
& = \lim _{x\to \infty}\frac{20x^3}{\ln^2(2)\cdot 2^x} \\
& = \lim _{x\to \infty}\frac{60x^2}{\ln^3(2)\cdot 2^x} \\
& = \lim _{x\to \infty}\frac{120x}{\ln^4(2)\cdot 2^x}  \\
& = \lim _{x\to \infty}\frac{120}{\ln^5(2)\cdot 2^x}   \\
& = \frac{120}{\ln^5(2)}\cdot\lim _{x\to \infty}\frac{1}{2^x} \\
& = 0
\end{align}
What would be a more elegant way solve it without using L'Hospital's Rule?
Edit
Even though, the Limit: $\lim_{n\to \infty} \frac{n^5}{3^n}$ is similar, I found the link provided by Axion004,  How to prove that exponential grows faster than polynomial? more interesting. Also, the answer provided by user trancelocation was very interesting and is what I was expecting.
Comment: I think [this answer](https://math.stackexchange.com/a/55477/258202) is the easiest way to see this. Your question is an abstract duplicate of that question.
Comment: There are many similar to your question. See [here](https://math.stackexchange.com/questions/571852/limit-lim-n-to-infty-fracn53n?noredirect=1)
Comment: @Axion004 Thank you, this link is really useful.
Answer: You can use the series expansion $e^t = \sum_{n=0}^{\infty}\frac{t^n}{n!}$ as follows:
For $x>0$ you have
$$\frac{x^5}{2^x}= \frac{x^5}{e^{x\ln 2}}< \frac{x^5}{\frac{(x\ln 2)^6}{6!}}= \frac{6!}{\ln^6 2}\cdot \frac 1x$$
Answer: Hint :
\begin{align*}
\frac{x^5}{2^x} &= \exp \left(5 \ln(x)-x \ln(2)\right) \\
&= \exp \left[x\left(5 \frac{\ln(x)}{x}-\ln(2) \right)\right]
\end{align*}
Now, you have the very classical limit (which can be proved with elementary method) $$\lim_{x \rightarrow +\infty} \frac{\ln(x)}{x} = 0$$
so $$\lim_{x \rightarrow +\infty}  \left(5 \frac{\ln(x)}{x}-\ln(2) \right) = -\ln(2)$$
so $$\lim_{x \rightarrow +\infty}  \left[x\left(5 \frac{\ln(x)}{x}-\ln(2) \right)\right] = -\infty$$
and you are done.
Comment: But then how do you show $5 \ln(x) - x \ln(2) \to - \infty$ without converting back to $x^5/2^x$?
Comment: @MarkViola Don't you think it's true that if $f(x) \to \infty$, $g(x) \to L \in \mathbb{R} - \{0 \}$, then $f(x) \cdot g(x) \to \text{sgn}(L) \cdot \infty$?
Comment: @TheSilverDoe Thank you for the update.
Comment: @MarkViola In this answer, $f(x) = x$ and $\displaystyle g(x) = 5 \frac {\ln(x)}{x} - \ln(2)$. $f(x) \to +\infty$ and $g(x) \to - \ln(2) < 0$, so $f(x)g(x) \to - \infty$, so $e^{f(x)g(x)} \to 0$. Is there anything wrong with this?
Comment: @TheSilverDoe Thank you for the answer, but could you explain a bit further? I found intuitive that $\dfrac{x^5}{2^x} \rightarrow 0$ as $x \rightarrow \infty$, but I also would like to show, write down the process to get the solution. I am not sure how the hint would help.
Comment: @user56202 I edited my answer.
Comment: The inner limit is $\lim_{x\to\infty}\left(x\left(5\frac{\log(x)}{x}-\log(2)\right)\right)$.  While $\log(x)/x\to 0$, $x\log(x)/x\to\infty$.  Your argument is therefore flawed.
Comment: @MarkViola No, it is not, see the explanation by user56202.
Comment: @TheSilverDoe That explains nothing about your lack of rigor herein.
Comment: @user56202 Yes.  And what is your point?
Comment: @MarkViola Please don't call a "lack of rigor" anything you don't understand. Just apply user56202's comment with $f(x)=x$ and $g(x)=5\frac{\ln(x)}{x}-\ln(2)$ and you will see that the argument is not flawed.
Comment: @TheSilverDoe Stand down!  It appears you've made some edits.   And now your solution is fine.
Comment: @user56202. No.
Comment: @MarkViola All the edits had been made before your comments... But nevermind, if the solution is fine for everyone, then there is no need to continue the discussion.
Answer: As an alternative way, by ratio test
$$\frac{\dfrac{(n+1)^5}{2^{n+1}}}{\dfrac{n^5}{2^n}}=\frac12\left(1+\frac1n\right)^5 \to \frac12 \implies \dfrac{n^5}{2^n} \to 0$$
and since $\forall x>0\quad \exists n$ such that $n\le x\le n+1$ we have
$$\dfrac{x^5}{2^x}\le \dfrac{(n+1)^5}{2^{n}}=2 \dfrac{(n+1)^5}{2^{n+1}} \to 0$$
Comment: (+1) Nicely done
Comment: @MarkViola Thanks Mark! Nice to see you here around. Bye
Answer: Let $x=5u$. Then
$$\lim_{x\to\infty}{x^5\over2^x}=5^5\left(\lim_{u\to\infty}{u\over2^u}\right)^5$$
so it suffices to compute $\lim_{u\to\infty}u/2^u$.  Let's do this using an inequality starting with the binomial theorem:
$$2^n=(1+1)^n=1+{n\choose1}+{n\choose2}+\cdots+1\gt{n\choose2}={n(n-1)\over2}\ge{n^2\over4}$$
for integers $n\ge2$. It follows that
$$0\le{u\over2^u}\le{\lceil u\rceil\over2^{\lfloor u\rfloor}}\le{\lfloor u\rfloor+1\over\lfloor u\rfloor^2/4}=4\left({1\over\lfloor u\rfloor}+{1\over\lfloor u\rfloor^2}\right)\to0$$
so by the Squeeze Theorem, $\lim_{u\to\infty}u/2^u=0$.
Comment: @Sebastiano, ah yes, you're right. I'll fix it. Thanks!
Comment: Hi, but isn't there a missing $5^5$ out of the limit sign?
Comment: Never mind I had voted with the assurance that you had written a very good answer.  :-)
Answer: All we need is to know that
$$
\lim_{t\to\infty}\frac{e^t}{t}=\infty \tag{1}
$$
Let's prove that, for every $a>1$ and $b>0$ (not necessarily an integer), we have
$$
\lim_{x\to\infty}\frac{x^b}{a^x}=0 \tag{2}
$$
First of all, perform the substitution $x=by$, so $a^x=(a^y)^b$ and our limit becomes
$$
\lim_{x\to\infty}b^b\Bigl(\frac{y}{a^y}\Bigr)^{b} \tag{3}
$$
OK, if we can prove that the limit of the part in parentheses is $0$, we're done. It's quite similar to $(1)$, isn't it? Since $a^y=e^{y\log a}$, we can perform a further substitution $y\log a=z$ and we get
$$
\lim_{y\to\infty}\frac{y}{a^y}=\lim_{z\to\infty}\frac{1}{\log a}\frac{z}{e^z} \tag{4}
$$
which is indeed $0$ because of $(1)$. The assumption that $a>1$ has been used here, because in this case $\log a>0$.
Should we prove $(1)$? You find several proofs that don't use l'Hôpital. Perhaps the simplest is to use the mean value theorem to prove that, for $t>0$, it holds that
$$
e^t>1+t+\frac{t^2}{2}
$$
Comment: Hi very kind. Just for my recent question https://math.stackexchange.com/questions/4259505/easier-way-to-display-of-commutation-lemma-for-limit-operator have you a possibility to give me a simplest answer? Thank you very much.
Answer: $x^5$ and $2^x$ are both increasing monotonically, this is important because it guarantees there's no "weird" behavior at any subset of the real line. At the same time, as you've noticed, $(2^x)'>(x^5)'$. This analysis guarantees the limit. Of course, to be rigorous about it, you'd have to prove both claims made here, so the L'hopital's rule solution might be the easiest method.
Comment: How does this help?
Comment: If, for large enough $x>0, x^5<2^x,$ why is it important that $x^5$ is monotonically increasing? At the very best, this should've been a comment.
Comment: @MarkViola It is a more elegant way to prove the limit of interest.
Comment: It proved nothing of the kind.
Comment: @MarkViola I agree. I just explained *how* it could be proved without l'hôpital.
Answer: In this answer it is shown without using L'Hopital's rule that for every $n>0$,
$$\lim_{x\to\infty}\frac{x^n}{e^x}=0. \tag{1}$$
We can use $(1)$ to show that for any $n>0$ and $a > 1$,
$$\lim_{x\to\infty}\frac{x^n}{a^x}=0. \tag{2}$$
To do this, write $a^x = e^{(\log a)x}$ where $\log a$ is positive since $a>1$. Then, if we set $y=(\log a)x$,
$$\frac{x^n}{a^x}=\frac{x^n}{e^{(\log a)x}}=\frac{1}{(\log a)^n}\frac{y^n}{e^y}.$$
When $x\to\infty$, we know that $y\to\infty$ because $\log a >0$. Therefore the behavior of $x^n/a^x$ follows from that of $y^n/e^y$ which is zero by $(1)$. Hence your limit is zero as it is a special case of $(2)$ where $n=5$ and $a=2$.


How to get at compile time the offset of a thread_local variable

Question: Using gcc under linux, I am searching for a way to get the offset of a thread local variable relative the the thread local storage area.
That offset is what is contained in the object file compiled.
In my opinion there should be a macro or built_in in order to get it.
The code that gives at runtime is as follows in the code bellow. What I need is to get that constant at compile time.
#include <iostream>
#include <thread>

thread_local int x;

template<typename T>
intptr_t getOffset(T& t){
    return (intptr_t)&t-(intptr_t)pthread_self();
}

int main(int argc, char **argv)
{
    std::cout<<"offset:"<<getOffset<int>(x)<<std::endl;
}

Comment: According to [the ELF thread-local storage spec](http://people.redhat.com/drepper/tls.pdf) the offset is not determined until runtime because it is dependent upon the order in which modules load and the size of the architecture-specific TCB (which is not known at compile time since you may run the binary on different versions of the OS each of which has a different TCB).
Comment: @RaymondChen By doing objdump of the file compiled after adding some multiplication instructions, I clearly see from the dump  that the offset is specified in the compiled code ( in that case is -4 ). So in the specific case it is known at compile time. So the binary has only one interpration in that case                                                40153d:       64 8b 14 25 fc ff ff    mov    %fs:0xfffffffffffffffc,%edx
  401544:       ff
  401545:       64 8b 04 25 fc ff ff    mov    %fs:0xfffffffffffffffc,%eax
  40154c:       ff
Comment: @RaymondChen I suspect he _may_ be able to rely on this offset in some cases (see my answer). This would not justify full support in compiler though.
Answer:
In my opinion there should be a macro or built_in in order to get it.

Such macro would not be easy/cheap to implement. First of all you can only determine such offset when compiling the executable because for dynamic library it would depend on library's relative position in dependency list of executable that loads it (or even not be in static TLS block if library is loaded dynamically via dlopen, hence not accessible via constant offset from TCB).
Now, even you try to determine the offset in executable, you can only do it for thread_local variables in executable itself because sizes of thread_local segments for libraries (and their offsets) are determined only at program startup (that's probly because version of loaded library may be newer than one that executable was linked against and thus thread_local segment size may be different as well).
Finally even for executable's variables it'll depend on relative order of object files and static/dynamic libraries during the link so you'd need special support in static linker to compute the offset.
You might suggest Binutils developers to consider adding a link-time relocation to compute thread_local offset in executable or even a runtime relocation to compute thread_local in general case but they will require compelling use-cases to consider such proposal.
As a poor man's workaround you can compile your code two times and extract offsets from symtab:
$ readelf -sW tmp.o | awk '/TLS/{print $8 " " $2}'
yyy 0000000000000000
xxx 0000000000000004


Can I clear all but certain attributes from a model?

Question: I have quite a number of attributes in my model, and under certain circumstances will need to clear all attributes but 2 or 3. Will this require looping through all attributes? Storing those 2–3 attributes temporarily, clearing the model, then adding them back in? Or is there an easier way to pull this off?
Thanks!
Answer: The lazy approach is to use the clear() function and re-add the particular values.
If you have (or may have in the future) events listing on changes, the events are unnecessarily fired.
Take a look at the clear function:
clear: function(options) {
  var attrs = {};
  for (var key in this.attributes) attrs[key] = void 0;
  return this.set(attrs, _.extend({}, options, {unset: true}));
},

It's not hard, to adapt this to a custom clear() function:
var myModel = Backbone.Model.extend({
  // You may also override the Backbone clear function
  partialClear: function(options, keep) {
    var attrs = {};
    for (var key in this.attributes)
      if (!_.contains(keep, key)) attrs[key] = void 0;
    return this.set(attrs, _.extend({}, options, {unset: true}));
  },
});

Then run partialClear with an array of values to keep:
this.partialClear({}, ['id', 'a', 'b']);