Dropdown - Search - Autocomplete

Question: I am working on a payment solution.
One of the main actions is adding a Beneficiary (payment receiver). To add beneficiary you need to specify the currency and the country of that beneficiary.
At the moment I am using something similar to these two examples:
http://ivaynberg.github.io/select2/
http://harvesthq.github.io/chosen/#selected-and-disabled-support to select the currency or the country
I decided to use this widget because it incorporates 3 actions:
1) The user can use dropdown to view all the currencies that we support (not all currencies  are supported)
2) The user can search the currency - GBP, Pound Sterling, Great British...
3) Autocomplete - so the user doesn't have to type the whole thing out.
Is there a better way to do this? What is it?
Or am I overthinking this and should stick with a input box and autocomplete only?
Answer: It is easier for users to select a country than a currency:
Try to detect the country of the user (e.g. by browser localization) or select a default if it couldn't be detected. Let the user choose the country if it isn't correct.
Than set the currency for that country and when that isn't what the user wants, let him/her choose one him/herself. If the user chooses a currency before a country, than don't change the currency automatically after the country is chosen.
I wouldn't let the user type in a input field by the way. Drop downs allow users to see what options they have and allow typing as well to quickly jump to their choice. For the last to work use the HTML select element or use a css/javascript equivalent that supports this.  (Your both examples have such feature).
By the way I like the second example. It immediately has focus on the search box like it is "advising" you to type instead of scroll all the way down.
Answer: The user should be in control of a widget, get feedback, and know the affordances.
So, there are two things to consider:

I understand you have a web service; what will happen when the user is using a mobile device?
What will happen if the user isn't sure what currency a country is using? There might have been a change of name, or a change of currency altogether.

For these reasons, the answer depends on how many currencies you support. If it's five or seven currencies, then a simple dropdown will be fine. The user will feel in control of the widget, know where to click, and if their currency is available at all. The cognitive workload will be small.
If it's thirty five, problem! That's where you would need an autocomplete field to eliminate choices, and thus also the cognitive workload. The component will have to make it obvious where to type and if the user has successfully selected their currency. But: in this case do not forget to test on mobile too!
Comment: Completely agree about the user being in control! We support at least 25 different currencies, so a normal dropdown would be too much. We have considered mobile, and I think we will have to do similar thing to "Amount": search + eliminate choices. Thank you!

Dropdown - Search - Autocomplete


Replacing a electric receptacle in the middle of a series

Question: I have an electric receptacle that looks like this.

It's half-hot and in the middle of a series to one other socket.
UPDATE: The photo above is the one I had goofed up putting back together. Here's what it actually looks like (the red and black are on the same side as expected)

And this is of course a plain receptacle.

I haven't been able to figure out (even with similar results) if it's possible to replace the top one with a bottom one. Another problem is determining which wire in each pair is from upstream or downstream.
Am I supposed to pigtail the pairs, along with a third wire that goes to this outlet? Mentally that doesn't seem like the right thing, but I couldn't really tell you why.
What would be the "correct" replacement receptacle for this usage? I'm having a hard time picking the right search terms.
Comment: There's a definite crack in the plastic, so it seems like replacing this is a good idea. Also, it's hard to tell for sure, but it _looks_ like the tab is missing on the "black wire" side, so it looks like it's a split outlet, except that the bottom half would have never worked. Can you confirm if both outlets work/ever worked? Can you provide a square on shot of _both_ sides of the outlet?
Comment: A bit late here. @isherwood I'm replacing it simply because the contacts are loose, stuff doesn't stay stuck in.
Comment: Why are you replacing the outlet? Did it work as it's shown there?
Comment: Your replacement outlet is fine, but I'd really like to know why it was wired that way. That looks like original work from construction. Don't you think?
Comment: My only guess is that (if both tabs are removed) the installer just used the outlet as a wire nut to connect the reds for downstream use.
Comment: @FreeMan It seems I attached the wrong photo of a mistake I had made when putting the outlet back together. Black and red are definitely on the same side, pull tab broken, with white and a pull tab in place. My bad!
Answer: This example should trip the breaker the second it is turned on.
Someone screwed up and stabbed the reds on the wrong side. They probably broke the tab to get half the receptacle to work and not trip the breaker, or pulled the red feeder at the switch.
When the new receptacle is installed don't use the backstabs--they are the leading cause of failure. Pigtail is the correct method, or use more expensive outlets which have a plate at the screw and allow 2 wires per screw.
The tab should be broken on the black/red or "hot" side. The tab should not be broken on the white side.
Normally the red is a switched hot and the black is a always hot. Since this was mis-wired it would never work with both receptacles.
Comment: Or, the red carries on elsewhere as isherwood mentioned in a comment on the OP and a wire nut on the reds, bypassing the outlet completely, will give the OP 2 working receptacles here now.
Comment: @freeman Even if used to carry on it would be a code violation as it is a hot  conductor on a neutral lug. The only color wires allowed on that lug are white and gray.  My belief is who ever wired it made a mistake notice the broken tab on the hot side? This is why I stated it probably tripped the breaker and the tab was then removed or the red from the switch. I can't believe any electrician would do this or leave it. I have seen DIY like this and it was not caught on inspection, but probably no inspection/ no permit.
Comment: @EdBeal I goofed! The original photo was of when I made mistakes months ago. I added new ones, which have the black and red on the correct side. Thanks for the rest. So, it looks like the answer is either 1) pigtail the two and shove it under the same screw, or 2) buy a plate and clamp outlet.
Comment: Thanks, @EdBeal. I stand corrected.
Answer:
One weird thing to my eyes is that white and red are on the same side.

Yeah, that's broke-a-doodle.  Either someone wildly miswired other points in the circuit, or this tripped the breaker instantly when someone threw the switch, or it "burned out" one of the backstab connections which happens all the time.

Another problem is determining which wire in each pair is from upstream or downstream.

Doesn't matter. Work it out; regardless of what the answer is, the wiring will be identical.   So it is not a thing you need to know.

Am I supposed to pigtail the pairs, along with a third wire that goes to this outlet? Mentally that doesn't seem like the right thing, but I couldn't really tell you why.

It literally does not matter.  You can pigtail, or you can use a receptacle which allows an onboard splice.   Your call, you can do it any way which suits you.
For instance, I usually pigtail because I'm attaching quad outlets on metal boxes in stress positions like on ceilings or under desks. Much easier to assemble the domed covers and pigtails on an ergonomic bench!
The only exception is certain applications where pigtailing is required. Safety ground, obviously.  Or neutral in certain types of circuits.

What would be the "correct" replacement receptacle for this usage?

Not the 50 cent cheapie in your photo. If you graduate to the $2.50 spec-grade outlets, most of them have a feature called "screw-and-clamp" where each screw also functions as a plate clamp, that can grab up to 2 wires.  Easy peasy.
Comment: I goofed, the photo I had attached is when I had made a mistake, new photos attached with correct wiring. Thank you for the rest, I appreciate breaking down the answer. It sounds like the answer is either pigtail each pair under the same screw, or buy a plate-and-clamp outlet. Having a hard time searching for it on Home Depot, but I'll take a look in store, hopefully they're actually $2.50


Can XMM registers be used to do any 128 bit integer math?

Question: My impression is definitely not but perhaps there is a clever trick?
Thanks.
Comment: I think SSE4 has support for 128 bit integers.
Comment: @leppie: no, that's not correct - there are a few 64 bit integer operations (e.g. `PADDQ` and `PSUBQ`) but that's as far as it goes.
Comment: [Is __int128_t arithmetic emulated by GCC, even with SSE?](http://stackoverflow.com/q/16566437/995714) [practical BigNum AVX/SSE possible?](http://stackoverflow.com/q/27923192/995714)
Answer: Not directly, but there are 64 bit arithmetic operations which can be easily combined to perform 128 bit (or greater) precision.
Comment: It's possible, but just keep in mind that there are no add-with-carry operations so the actual implementation might be slower than the scalar version.
Comment: @Jasper: good point - it's reltively easy to implement (although non-trivial) but performance may not be much better than just using the two 64 bit scalar ALUs which most modern x86 CPUs have.
Answer: The xmm registers can do arithmetics on 8, 16, 32 and 64 bit integers. It doesn't produce a carry flag so you can't extend the precision beyond 64 bits. The extended precision math libraries use the general purpose registers which are 32 bit or 64 bit, depending on the OS.


Minecraft - How to select flying arrows by NBT data given to them in item form

Question: On my private (vanilla 1.9) Minecraft server, me and my friends are trying to make custom arrows, such as TNT, ender, high explosive etc. These arrows have NBT data such as a tag "tntarrow" for a TNT arrow. However, when an arrow gets shot, it seems to 'lose' it's NBT data for some reason, so we have no way of telling normal, TNT and ender arrows apart in the air.
Is there any way of working out what kind of arrow (normal, TNT, ender etc) an arrow is while flying, so that when arrows land I can apply my own commands to activate the custom arrow's effects? I'm happy to re-purpose tipped arrows that give buffs (strength, speed, healing etc) if that is possible.
Just to clarify, if I give a player an arrow with a tag "tntarrow", like so:
/give player arrow 1 0 {Tags:["tntarrow"]}

Then, when it's shot, this selector doesn't work:
@e[type=Arrow,tag=tntarrow]

So, I would like to have some way of having only certain arrows being selected.
If it is possible to re-purpose tipped arrows, then I would also like to know how to do that. (For me to re-purpose them, I need to remove potion effects and have a way of selecting them.)
Answer: Adding Tags to the item will not be set as the entity's Tags data. All the item data itself will be lost except for Potion and CustomPotionEffects, which are copied to the arrow entity if existent.
Tipped arrows will be necessary, but you can apply custom effects to reduce any issues should it strike a player or mob, such as setting the duration to 0. Currently the Instant Healing effect does not function on tipped arrows, but you may need to switch to something else should it work in the future.
The amplifier would be how you'd differentiate arrows from one another.
Example arrows to provide:
/give @p minecraft:tipped_arrow 64 0 {CustomPotionEffects:[{Id:6b,Duration:0,Amplifier:0b}]}

/give @p minecraft:tipped_arrow 64 0 {CustomPotionEffects:[{Id:6b,Duration:0,Amplifier:1b}]}

Then you'd label those arrows based on the effects it has, with the amplifier making each one unique:
/scoreboard players tag @e[type=Arrow,tag=!tntarrow] add tntarrow {CustomPotionEffects:[{Id:6b,Duration:0,Amplifier:0b}]}

/scoreboard players tag @e[type=Arrow,tag=!custom2] add custom2 {CustomPotionEffects:[{Id:6b,Duration:0,Amplifier:1b}]}

And finally, target based on that label:
/say @e[type=Arrow,tag=tntarrow] is a "tntarrow".


Change input css/animation via jQuery using ASP.NET Field Validator

Question: I currently have a form with about 10 controls like this:
<code><asp:TextBox ID="fullname" Width="200" MaxLength="50" runat="server"/>
<asp:RequiredFieldValidator Display="Dynamic" ValidationGroup="contact" ControlToValidate="fullname" ID="RequiredFieldValidator1" runat="server" ErrorMessage="*"/>
</code>
I love the way ASP.NET fieldvalidators work, with one exception: it's hard for me to override the fact that when the validation fails not an asterisk should be displayed as it is now, but instead the input field that failed should be highlighted in red.
I want to do the highlighting of the input field via jQuery so that I have full control over css/animation. I don't want to use the ASP.NET animation as it is overly complex in my opinion.
I also checked this post: Change Text Box Color using Required Field Validator. No Extender Controls Please
but it does not provide a clear answer.
So: is there a way to keep my current ASP.NET validator controls, but override the displaying (and hiding) of their ErrorMessage property and instead use jQuery to add (or remove) an animation/css to the validated input field?
Requirements:
- code must work for requiredfieldvalidator/regularexpressionvalidator etc.
- capture enter key
- remove error css if user corrects the input field and validation is succesful
Thanks!
Answer: You need to use Custom Validator
aspx:
<code>  <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
                <asp:CustomValidator ID="cvFirstName" runat="server" SetFocusOnError="true" Display="Dynamic"
                    ValidateEmptyText="true" ControlToValidate="txtFirstName" ClientValidationFunction="validateValue"></asp:CustomValidator>
</code>
JS:
<code>   <script type="text/javascript">
        function validateValue(source, args) {
            if (args.Value == "") {
                args.IsValid = false;
                document.getElementById(source.id.replace('cv', 'txt')).className = 'Invalid';
            }
            else {
                args.IsValid = true;
                document.getElementById(source.id.replace('cv', 'txt')).className = 'Valid';
            }
        }
    </script>
</code>
CSS:
<code> <style type="text/css">
        .Invalid
        {
            border: 1px solid red;
        }
        .Valid
        {
            border: 1px solid White;
        }

    </style>
</code>
Comment: I read something about that too, but how would I then implement this for regularexpressionvalidator and in cases where I need to match two fields? (e.g. password match or email match)
It seems that with your suggestion for those cases I would have to write all validation logic myself?


Jquery String remove everything - before - first - "\n" & first "\n"

Question: I need to remove everything before first first "\n" incl. the "\n"
is there any possibility?
Thanks!
Comment: Yes it is possible
Comment: post a sample string
Comment: @JJJ uhm yeah but i need to remove the "first" and before first.
Comment: @GAX Yes, the duplicate does exactly that.
Answer: Yes, use String#replace method with negated character class regex(for matching anything other than newline).
 str.replace(/^[^\n]+\n/,'')

var str = `abc
def
ghi`;

console.log(str.replace(/^[^\n]+\n/, ''))

Or split string by the newline character, get elements except first and rejoin it using newline character.
 str.split('\n').slice(1).join('\n')

var str=`abc
def
ghi`;

console.log(str.split('\n').slice(1).join('\n'))

Or you can use String#slice method by getting the index of first newline character using String#indexOf method.
 str.slice(str.indexOf('\n'))

var str = `abc
def
ghi`;

console.log(str.slice(str.indexOf('\n') + 1))
Comment: Thank you!
str.split('\n').slice(1).join('\n')
worked fine for me.
Comment: @GAX : glad to help you :)


Why am I not able to pass to a perl script a variable string for sprintf?

Question: I come with the following perl problem. Take this piece of code and put it into test.pl
my $str=shift;

printf "$str", @ARGV;

Then run it like this:
perl test.pl "x\tx%s\n%s" one two three

The expected output for me should be:
x    xone
two

Instead I got
x\sxone\ntwo

Where am I wrong?
Answer: Perl converts escape sequences within strings at compile time, so once your program is running you are too late to have "\t" and "\n" converted to tab and newline.
Using eval would fix this, but it's very insecure. I recommend you use the String::Interpolate module to process strings after compilation. It uses Perl's native interpolation engine so has the exact same effect as if you had coded the string into your program.
Your test.pl becomes
use strict;
use warnings;

use String::Interpolate qw/ interpolate /;

my $str = shift;

printf interpolate($str), @ARGV;

output
E:\Perl\source>perl test.pl "x\tx%s\n%s" one two three
x       xone
two
E:\Perl\source>

Update
If you just want to allow for a small subset of the possibilities that String::Interpolate supports then you could write something explicit like, say
use strict;
use warnings;

my $str = shift;

$str =~ s/\\t/\t/g;
$str =~ s/\\n/\n/g;

printf $str, @ARGV;

but a module or eval are the only real ways to support a general Perl string on the command line.
Comment: @thebrxinthewalls: Yes, although you could code a few special cases. See my update. What is the problem with using a non-core module? Installing modules is really very easy.
Comment: So the only way of doing this using standard perl modules is `eval`, right?


Will unpainted plaster become water damaged?

Question: We have had our bathroom done recently and the builders plastered one of the walls, then fitted the sink and toilet.
I am now going to paint the walls myself, but I'm concerned about the plaster behind the sink and cistern.
Should I remove the sink and cistern to paint behind?
If I leave those hidden bits of plaster unpainted would they suffer from water damange over time?

(It feels wrong to pay someone to fit a bathroom, then immediately take out the units yourself)
Answer: They will not suffer from water damage unless water gets back there. Normally, that shouldn't happen and there are millions of installations with no paint behind toilet tanks and sinks with no deterioration. But it's still up top you if you want to make absolutely sure.


If using LINQ For Queries, Do We Need to Unit-Test Sorting?

Question: I have the following two methods on an interface for my service layer:
ICollection<T> FindAll<T>(Expression<Func<T, bool>> predicate) where T : Post;
ICollection<T> FindAll<T,TKey>(Expression<Func<T, bool>> predicate, OrderingOptions<T,TKey> orderingOptions) where T : Post;

They are extremely similar.
The first one (basically) does this:
return repository
   .Find()
   .OfType<T>()
   .Where(predicate)
   .Take(maxRows)
   .ToList();

The second one (basically) does this:
return repository
   .Find()
   .OfType<T>()
   .Where(predicate)
   .WithOrdering(orderingOptions)
   .Take(maxRows)
   .ToList();

WithOrdering is a pipe extension method i created:
public static IOrderedQueryable<T> WithOrdering<T,TKey>(this IQueryable<T> source, OrderingOptions<T,TKey> postOrderingOptions)
        {
            return postOrderingOptions.SortAscending
                       ? source.OrderBy(postOrderingOptions.OrderingKey)
                       : source.OrderByDescending(postOrderingOptions.OrderingKey);

        }

OrderingOptions<T,TKey> is a generic class i implemented to provide fluent ordering.
So, that being said - i have numerous unit tests for the first method (ensure collection is returned, ensure null is returned for an empty collection, ensure filtered correctly, ensure max rows is returned, etc).
But my question is - how do i test the second method? Do i need two? Given that the only thing that is different is that im using the .OrderBy (or .OrderByDescending) methods.
If im testing that, am i simply testing the LINQ framework?
If not, how can i even test this?
Couple of (possibly important) points:

This are methods on a service layer, which retrieve IQueryable's on a repository, that is implemented with Entity Framework 4.0
For my unit-tests, the service layer is injected (via StructureMap) a mock repository, but i also toggle this to the real repository manually when i want to do integration testing

Guidance/best practices would be highly appreciated.
Thanks!
Answer: You need to unit-test the second method just to make sure it works. If you refactor something that changes how it works and fix the first one, how will you know if you forgot to fix the second one? If you refactor WithOrdering, how will you know that things still work? I would have a unit test to test ascending and one to test descending.
Comment: Agreed. But `how` can i unit test that? Will i have to (for example) grab say 3 items that i know the date for (using a method to get a single item), then grab 3 items ordered by date (using the second method), and compare the values manually? (ie ordered list items[0].date == firstItem.date?)
Comment: RPM1984: You could grab 3 items and `Assert(items[0].date <= items[1].date && items[1].date <= items[2].date)` for ascending and `Assert(items[0].date >= items[1].date && items[1].date >= items[2].date)` for descending.
Comment: Yep, that's what i thought. Okay, cheers. +1, but i'll leave the question open for a bit (just so i can see other's thoughts). Thanks.


finding the value of $a$ for minimal solid

Question: Given that $y=x^2+ax-0.25$ is bounded by $x=0$ and $y=1$ and spinning around the x-axis.
What is the value of $a$ for min volume of that solid?
My attempt: $x^2+ax-0.25=1$ so $x=\frac{-a\pm \sqrt{a^2+5}}{2}$.
Then, $f(a)=\pi \int_{0}^{\frac{-a+\sqrt{a^2+5}}{2}}(1-(x^2+ax-0.25)^2)dx$
But that will lead to: $f(a)=1/480 (-225a+20a^3+8a^5+200 \sqrt{5+a^2}-8a^4 \sqrt{5+a^2})π$
And then $f'(a)=0$ will be very hard to solve.
Any ideas?
Update: wolfram gave me an answer but i wonder if it can be done without that.
Thanks.
Answer: I think you overcomplicated the problem.
You only need to find out what is the minimum of :
$f(a)=\int_{0}^{\frac{-a+\sqrt{a^2+5}}{2}}|x^2+ax-0.25|dx$
Since the volume is going to be the rotation of this area around the axis $x$. If you minimize the area, you minimize the volume.
The function $y=x^2+ax-0.25$ has a positive zero in $x=\dfrac{-a+\sqrt{a^2+1}}{2}$, which is smaller than $\dfrac{-a+\sqrt{a^2+5}}{2}$, so that divide the integral in two domains.
Comment: so i can use that reasoning: "if the area is minimize so is the volume"? and i didn't understand about why i need to divide the integral.
Comment: I'd appreciate if you can elaborate in the answer.
Comment: @aron I am wrong in fact. I thought that using the fact that it was with a max $y$ of 1 was allowing this, but there is no reason why $|y|$ would be limited in fact...
Comment: so what can we do?


Is it possible to read arbitrary data at arbitrary array offset in glsl?

Question: TL;DR
In a Vulkan / GLSL ray tracing program, I have several shader files, all accessing the same material buffer of arbitrary data. All materials have an arbitrary layout, e.g. one might be a float, one might contain two vec3s and a float.
Can I access a buffer (i.e. an array of uint type) with just an offset within the shader (i.e. the same buffer binding is shared, I cannot use dynamic offsets set on the CPU side) and read out a struct without having to read every member of the struct individually? I am aware of not being able to read a vec3 from a buffer as just 3 values, but that is not my problem. Just assume I only read good data types that don't waste space.
See in the image, I want to access at the given green position with just knowing the size of the struct that will follow at that position.

In C++ it would be something like this:
uint32_t* buffer; //assume this has all the data in it
struct mat2
{
    glm::vec3 data1;
    float data2;
}

//the following line is what I try to achieve
mat2 matData = *((mat2)(buffer+offset);

Long explanation
I am trying to setup a buffer that contains material parameters.
The problem is that I have to support a large number of materials, that may differ drastically in number of parameters, e.g. there might be an entry with two uints and then an entry with five floats.
Since I assume using one buffer per material is bad (due to the number of layouts bindings I'd have to use) I wanted to tightly pack the material parameters into a single byte buffer and readout from the shader with a known offset to the material for the hit geometry.
I have a shader file per material, so no material is aware of other material structs - it just knows the offset into the array for its own data.
While I have basically set up the buffer (though apperantly the smallest chunks I am allowed to use are 4 bytes), I have trouble actually reading out of this buffer in GLSL. Given a simple struct for one material:
struct BlinnPhongParams
{
    vec3 diffuse;
    vec3 specular;
    float specIntensity;
};

And the material buffer:
layout(binding = 123, set = 0) readonly buffer MaterialParamsBuffer
{
    uint[] data;
}uMaterialParamsBuffer;

Currently I am reading every member from the buffer individually:
BlinnPhongParams getMaterialParams(uint offset)
{
    BlinnPhongParams bpParams = BlinnPhongParams(
        //DiffuseCol
        vec3(
            uintBitsToFloat(uMaterialParamsUintBuffer.data[offset]),
            uintBitsToFloat(uMaterialParamsUintBuffer.data[offset+1]),
            uintBitsToFloat(uMaterialParamsUintBuffer.data[offset+2])),
        //SpecularCol
        vec3(
            uintBitsToFloat(uMaterialParamsUintBuffer.data[offset+3]),
            uintBitsToFloat(uMaterialParamsUintBuffer.data[offset+4]),
            uintBitsToFloat(uMaterialParamsUintBuffer.data[offset+5])),
        //SpecIntensity
        uintBitsToFloat(uMaterialParamsUintBuffer.data[offset+6])
    );
    return bpParams;
}

I would like to make reading from this buffer as easy as possible, ideally just say "at this offset, I have a struct that looks like this", e.g. I would like to have something like this:
BlinnPhongParams getMaterialParams(uint offset)
{
    // here is the problem
    BlinnPhongParams params = BlinnPhongParams(&uMaterialParamsBuffer.data[offset]);
}

Is this possible?
Comment: What API is this code using to access the data? OpenGL, Vulkan, etc...
Comment: I'm using Vulkan / GLSL
Answer: The shaders themselves have the structure memory layout in them and indexing into the array is essentially (sizeof(material)+alignment) * offset So what the listed pseudocode is already doing is pretty close to what is needed to index directly. The sizeof(material) would also need to be carefully computed since data alignment inside a struct follows the buffer type layout rules. For example the two vec3's actually align to vec4 boundaries. So internally at least 8 bytes are lost for alignment. This complicates writing the data since it is up to the program to place the data at the correct offset for both the structure alignment and the internal alignment, which is basically identical to what the shader is going to do to access it. For a vec3 25% of the memory is being lost to alignment.
As an example the listed struct layout would look something like the following in C++: (note that I am doing this from memory so please don't write these numbers in stone)
struct phong {
   vec3 diffuse; float alignment;
   vec3 specular; float alignment2;
   int intensity;
};

Where the actual size of the struct would add another 12 bytes to the end of the int so that sizeof(phong) == 48 instead of the expected 28.
The unusable memory issue can be overcome with careful design of materials, like folding the specular intensity into the specular color to align it on a vec4 boundary, etc.
So this is all doable but automating it so that the programmer doesn't have to hand tune every shader is more challenging.
Comment: But this solves only the C++ part. I have that down however, the access in GLSL is the part I'm struggling with, seeing as the buffer contains various materials with arbitrary members, all of them tightly packed.
Comment: The entire point here is that you can't just pack the memory any old way you feel like it.  Doing it the way I described packs the memory about as tightly as it can be packed. The data has to be put in the buffers where it meets the requirements of GLSL. Then in the shader access is simply "params_buffer[passed_in_index]".
Comment: I can live with accessing it as a vec4 rather than a vec3 and a float, but this is not the problem I'm trying to solve. The problem might be that my data starts at position 2 in the buffer. I will add an image to hopefully clarify my issue.
Comment: You should consider switching to an array of vec4's for the SBO or using dynamic offsets.  Dynamic offsets set the start of the array where you want it (but there are still alignment rules). GPU's rely heavily on streaming data, to do that they depend on alignment, you can't just force your own rules on the system and expect performant shaders. The problem you are trying to solve and the solution I described are one and the same, with alignment rules applied. Good luck.


If I drill holes in a door, would I then at a later time be able to conceal them reasonably well?

Question: I have an over-the-door organizer in my pantry. It's about 5 feet tall and composed of three joined sections.
Problem is—since it has breaks on the vertical supports—it is wobbly.  When I open the door it moves just a little bit more slowly; when I close the door it wants to keep going after latching the door. Whenever it moves, half of its contents fall off, which is undesirable.
I want to put moly bolts in the door (hollow core) and affix the rack to the door to tighten it up a bit. I've been given the go ahead only if I can be sure that I can semi-convincingly patch the holes if we remove the rack. So is this something that it's possible to do? My first instinct if it were drywall would be to just use spackle and paint it, but obviously that won't work on a woodgrain door.
Edit: Based on the implied difficulty of doing what I wanted to do I opted for command strips. Originally that wouldn't have worked as the door rack is composed of modular shelf rails like the one pictured below, ergo a very small surface area for the command straps to stick to. I wound up JB-welding a metal plate to the back of the rails to increase the applicable surface area while still allowing for the locking mechanism of the shelving space.

Comment: Maybe try some 3M removable [command strips](http://www.command.com/3M/en_US/command/hooks-strips/) instead.  It's unlikely you will be able to conceal holes in your door.
Comment: Can you post a picture of the door?
Comment: @mmathis Unfortunately I asked on my lunchbreak at work, but will post a picture this evening.
Answer: There are better options to attach temporarily fixtures.  I would first try using 3M Command Strips to secure the organizer to the door.  In this way you can easily take it down without drilling holes in your door.  They also make velcro so you can remove the organizer and put it back later if you wish.
Answer: No. Or maybe yes.
Replicating wood grain even in painted wood or synthetic wood is very difficult. If you create holes large enough for togglers (3/8" minimum), you'll almost certainly need to sculpt the grain channels into the wood filler. If you're a crafty person, it can be done.
Of course you'll likely need to paint the entire door face to achieve a good blend.


Pandas iterrows change the type of columns to float. How to cast it back to original type?

Question: Pandas iterrows change the type of columns. According to this github issue, it is an intended behavior.
Any idea of a pythonic and elegant way of casting it back to the original type?
Note that I have multiple column types.
minimal example
df = pd.DataFrame([range(5), range(5)])
df.iloc[:,1] = df.iloc[:,1].astype('float')
for row in df.iterrows():
    print row

Results with
(0, 0    0.0
1    1.0
2    2.0
3    3.0
4    4.0
Name: 0, dtype: float64)
(1, 0    0.0
1    1.0
2    2.0
3    3.0
4    4.0
Name: 1, dtype: float64)

Note that df.dtypes returns the types of columns, however, I couldn't think of an elegant way of using it to cast the row back to that type.
Answer: Try using df.itertuples instead:
df = pd.DataFrame([range(5), range(5)], columns=list('abcde'))
df.iloc[:,1] = df.iloc[:,1].astype('float')

for row in df.itertuples():
    print(row)

Pandas(Index=0, a=0, b=1.0, c=2, d=3, e=4)
Pandas(Index=1, a=0, b=1.0, c=2, d=3, e=4)

Answer: You can do this iteration keeping the data type in the following way:
import pandas

df = pandas.DataFrame({'ints': list(range(5)), 'floats': [float(i) for i in range(5)]})
print(df)
for idx in df.index:
    print(f'Integer number: {df.loc[idx,"ints"]}')
    print(f'Float number: {df.loc[idx,"floats"]}')

The output (in Python 3.8.5) is
   ints  floats
0     0     0.0
1     1     1.0
2     2     2.0
3     3     3.0
4     4     4.0
Integer number: 0
Float number: 0.0
Integer number: 1
Float number: 1.0
Integer number: 2
Float number: 2.0
Integer number: 3
Float number: 3.0
Integer number: 4
Float number: 4.0

Comment: confirmed behavior also in Python 3.6, and 3.7. thanks!


Can't apply 3d properties to autoshape

Question: The workbook I am working on in Excel uses graphics with 3d properties which are set in VBA.  I just changed an image in the workbook, and now Excel complains that it can't execute any of the following lines of code:
Selection.ShapeRange.ThreeD.Depth = fsdoord
Selection.ShapeRange.ThreeD.ExtrusionColor.RGB = carcol
Selection.ShapeRange.ThreeD.PresetLightingDirection = msoLightingBottom

The error produced is
Run-time error '70':

Permission denied

I can still apply all the other properties to this shape; it only errors when I try to execute the lines relating to the 3d properties.
Does anyone have any insight into why this might be happening?
Thanks in advance...
Answer: ShapeRange is actually a collection of Shapes. You need to drill down one more level to get the shape object. (As the properties you are trying to use apply to Excel.Shape.)
    Sub Example()
    Dim ws As Excel.Worksheet
    Dim shp As Excel.Shape
    Set ws = Sheet1
    Set shp = ws.Shapes(1)
    shp.ThreeD.Depth = 10.5!
    shp.ThreeD.ExtrusionColor.RGB = &HF08300
    shp.ThreeD.PresetLightingDirection = msoLightingBottom
End Sub
Sub Example2()
    Dim shpRng As Excel.ShapeRange
    Dim shp As Excel.Shape
    Set shpRng = Selection.ShapeRange
    Set shp = shpRng.Item(1)
    shp.ThreeD.Depth = 25.5!
    shp.ThreeD.ExtrusionColor.RGB = &HFF0083
    shp.ThreeD.PresetLightingDirection = msoLightingBottom
End Sub

Comment: Are you using the exact code I pasted above, or are you trying to get the shape by name? Because trying to create a shape with a name that already exists will throw that specific error as well.
Comment: I used my code but tried referencing the object as ...ShapeRange.Item(1)... - it still had the same error
Comment: Then I'd have to say the problem lies outside of the code block you posted. Can you go ahead and post the whole procedure?
Answer: There's a remark on the Help page for the ThreeDFormat object and it's repeated on the MSDN page here

You cannot apply three-dimensional
  formatting to some kinds of shapes,
  such as beveled shapes or
  multiple-disjoint paths. Most of the
  properties and methods of the
  ThreeDFormat object for such a shape
  will fail.

So if your new shape falls into one of those rather sketchily-defined categories then that might be your problem
Comment: No, neither of these categories - its an image, and before I changed the image it worked fine (I only replaced the image with a different picture)
Answer: Okay, I sort of found the problem.  When I replaced the image, I deleted the original image and inserted a new one using Insert>Image>From File... It turns out that the original image must have had some sort of 3d properties applied already, because when I replaced the image by just changing the fill colour of the auto-shape, it worked (in other words, I kept all the properties and only changed the fill).

Can't apply 3d properties to autoshape


How to alter width of movieclip in slider from parent

Question: I have a slider component setup in my flash app. This slider has a few extra movieclips that I have created.
From the parent timeline, I would like to change the width of one of those movieclips in my slider.
I can't just access the child movieclip like I usually would (slider_mc.other_mc.width) because it sits in a slider so it gives me this error:

ReferenceError: Error #1069: Property other_mc not found on
  fl.controls.Slider and there is no default value.     at
  play_fla::MainTimeline/frame1()

Does anyone know how I could do this?
Thanks
EDIT:
Just to explain further:
the slider component is a movieclip with the instance name slider_mc and other_mc sits inside the slider movieclip. I need to alter other_mc's width from the parent movieclip.
Hope that helps.
Answer: You need to listen to events from the Slider. Something like this should work if both the slider and other mc are in the same timeline
import fl.events.SliderEvent;

slider_mc.addEventListener(SliderEvent.THUMB_DRAG, thumbDragHandler);

function thumbDragHandler(event:SliderEvent):void {
    other_mc.width = event.value;
}

Comment: I think you've slightly misunderstood. The `other_mc` is in the `slider_mc`. I want to alter `other_mc` from the parent. The code you supplied wont work as `other_mc` is not in the parent. Originally, I should just be able to do `slider_mc.other_mc.width` but because `slider_mc` is a slider component, it's not working.
Comment: Ahh ok I'm not sure how or why you would put an mc inside the slider component, but I guess the issue is that other_mc is not part of the Slider component's Class definition. Using MovieClip(slider_mc).other_mc or slider_mc["other_mc"] might give you the access you want


For every positive integer $k$ not divisible by $101$ there exists $n$ such that the sum $1+k+k^2+...+k^n$ is divisible by 101

Question: I can write the sum using geometric series as $\frac{k^{n+1} - 1}{k-1}$ but I'm not sure how to continue from here. I've tried using induction but I got stuck.
Comment: @Peter If $k\equiv1$ $\mod 101$ then $k^n\equiv1$ $\mod 101$ and so $n=100$ is a solution.
Comment: This is not true, if $k$ is divisible by $101$
Comment: It is not true for $k=101$.  You need parentheses in your expression of the geometric series sum.  As written you have $k^{n+1}-\frac 1k-1$
Comment: In the case that $k\ne 0\mod 101$ and $k\ne 1\mod 101$, Fermat's little theorem guarantees that $n=99$ is a solution. So we can concentrate on the case $k\equiv 1\mod 101$
Comment: @Fishbane This completes the proof.
Answer: You mention in your tags the pigenhole-principle.
This is a way to solve this. In the comments Peter pointed out, that the statement fails when $k$ is divisible by $101$.
Observe for every $n$ the remainder modulo $101$. If you get the remainder $0$ then you are done. If you do not get it, then you can just calculate arbitrary many $n$ values. At most 101.
After that you have to get a remainder which we already had.
Then you have for some $m$ and $n$ that
$\sum_{i=0}^n k^i\mod 101\equiv\sum_{i=0}^m k^i\mod 101$.
Without loss of generality $m>n$, and we have after subtraction
$\sum_{i=n+1}^{m} k^{i}\equiv 0\mod 101$. Hence divisibility by 101.
So you have $k^{n+1}+\dotso +k^m=k^{n+1}(1+k+\dotso +k^{m-(n-1)})$.
As $101$ is prime, and $101\nmid k$, we have $101\nmid k^{n+1}$. Hence
$101\mid 1+k+\dotso +k^{m-n+1}$


Unable to access my desktop computer hard disk

Question: I was working normally on my desktop computer with Windows 8.1, then my power supply stopped working, the PC shut down and it won't turn on again until I replace the power supply (which I can because it's December 31)
I used my converter to connect my FILES (D:) Hard disk via USB to my Ubuntu laptop (It has nothing to do with windows, windows is in another physical hard disk) and I get this error:

I've read this question, but it requires you to start Windows (I can't do it) I need some solution I directly on Linux.
Thank you beforehand!
Comment: The link provides a number of options without having to boot into windows.
Comment: @JacobVlijm I tried them but it doesn't work if I follow those instructions, I'm new to Ubuntu relatively and I haven't made this before. I've tried them but I think I'm doing nothing
Comment: you can not restart your computer and access to Windows ?
Comment: If you're talking about my Desktop computer, no, the power supply is not working, so I have the disk where I store my files (not the OS) connected via USB to my laptop, like an external drive.
Comment: It probably not a hibernation issue since it crashed due to power supply. Sometimes I am unable to mount my windows partitions because windows has them flagged to run a disk check next time Windows boots. I think this is what is happening here. Added an answer.
Answer: You may be able to get it working still from Ubuntu
Install ntfs-3g with
<code> sudo apt-get install ntfs-3g.
</code>
Then run the ntfsfix command on your NTFS partition.
For example:
ntfsfix /dev/hda6
Make sure to change /dev/hda6 to whatever it actually is.
Once that finishes, try to mount again.
Comment: IT WORKED IT WORKED LOL I'm so happy you saved me!
Comment: What I needed to know was in the error dialog! :P
Comment: Glad I was able to help... P.S - the info you need is often found in the error log, but I didn't see it at first either


How to keep internet connection alive until a given time?

Question: I want to keep my internet alive until a given time (say for example until midnight). This is so because the connection I have is based on a 3G HSPA+ connection and I want to wait until midnight to get better offpeak rates. However I want to keep the connection active until such time without disconnecting due to inactivity.
The only option I saw was to ping a random website such as www.google.com, periodically (say every 5 mins).
Are there any other methods ? Can you also provide the script/implementation details of the methods suggested by you ?
thanks
Answer: If you except no output, simply put ping www.google.som into your cron with frequency set to 5 minutes.
Open cron file with crontab -e (in terminal)
and add new entry
*/5 17-23 * * * ping -c1 www.google.com
Where:
*/5 means every minute divisible by 5
17-23 hours
* every day of month
* every month
* every day of week
Save and you are done.
Comment: `ping www.abc.com` would be sending pings in the background without stop. You can do just **one ping** likes this `ping -c1 www.abc.com`


Connecting condensate pump to sewer

Question: My AC condensate pump currently pumps through a vinyl tube directly outside my house. However, I just replaced my broken home humidifier and realized that the previous one never had its drain properly installed and it just dripped into a plastic bucket or into the crawlspace (bad). I connected the drain of the new one to the condensate pump so it can pump out the excess water from the humidifier. As it often drops below freezing here and I'm worried the tube will freeze now that the humidifier drains into the pump during the winter.
Here is the tube outlet on the side of the foundation:

I was wondering if I can tie the condensate pump line into my sewer drain in the crawlspace. I've got a shower drain with the trap in the crawlspace so I could install a PVC wye above the trap and drop the vinyl tube into there.
Here are some photos of the drain.

I assume there is a vent that goes up the wall, behind the shower and out the roof.
Is this reasonable? I was worried if I added a separate trap for the condensate pump that it might dry out during shoulder seasons when the AC/humidifier are not running. I'm not sure if this is relevant but this would become my lowest open drain and I guess would be a problem if the sewer backed up, although it seems best that this happens in the crawlspace.
I'm in Franklin County, WA if that matters, I'm not sure how to look up codes for condensate draining into the sanitary sewer.
Thanks!
Comment: If you connect a condensate drain to the sanitary sewer, it has to be through an air gap (a trapped connection might be allowed, I'd have to check the codes again).  You wouldn't want the HVAC system sucking up sewer gas.
Comment: The pump acts as an an air gap
Answer: Yes, you can plumb the outlet of the condensate pump into the tailpiece of the shower. Assuming the condensate line is properly trapped, then there should be no problem.
You'll notice in the code snippet below, that it says "If discharged into the drainage system, equipment shall drain by means of an indirect waste pipe.". Which means you cannot, plumb the condensate drain directly into an untrapped waste line or vent.

Uniform Plumbing Code
Chapter 8 Indirect Wastes
814.0 Condensate Wastes and Control.
814.1 Condensate Disposal. Condensate from air
  washers, air-cooling coils, fuel-burning condensing
  appliances, the overflow from evaporative coolers,
  and similar water-supplied equipment or similar air-conditioning
  equipment shall be collected and
  discharged to an approved plumbing fixture or
  disposal area. If discharged into the drainage system,
  equipment shall drain by means of an indirect waste
  pipe. The waste pipe shall have a slope of not less
  than one-eighth (1/8) inch per foot (10.4 mm / m) or 1
  percent slope and shall be of approved
  corrosion-resistant material not smaller than the
  outlet size as required in Table 8-2 for air-cooling
  coils or condensing fuel-burning appliances, respectively.
  Condensate or wastewater shall not drain
  over a public way.
814.3 Point of Discharge. Air-conditioning condensate
  waste pipes shall connect indirectly to the
  drainage system through an airgap or airbreak to a
  properly trapped and vented receptors dry wells,
  leach pits, or the tailpiece of plumbing fixtures.
  Condensate waste shall not drain over a public
  way.
Chapter 2 Definitions
211.0  -I-
Indirect Waste Pipe - A pipe that does not connect
  directly with the drainage system but conveys liquid
  wastes by discharging into a plumbing fixture, interceptor,
  or receptacle that is directly connected to the
  drainage system.
222.0 -T-
Tailpiece - The pipe or tubing that connects the
  outlet of a plumbing fixture to a trap.

So you could have something like this, with the condensate pump.

If you can maintain the proper slope, you could remove the condensate pump.

In this situation the condensate pump is not required, since the tailpiece of the shower serves as the air gap. And you won't have problems with sewer gas, since the drain is protected by the trap on the shower drain.
You'll want to use proper fittings to connect to the tailpiece, rather than hacking together some leaking contraption.  Without knowing the size and material of the condensate drain, I can't tell you exactly what fittings to use. In the end, you should end up with something like this.

You'll cut the tailpiece, and fit in a new 45° wye. Then you'll use whatever adapters and reducers are required, to go from the condensate drain into the PVC wye. The condensate drain has to maintain the minimum slope, so you'll have to work with that as a constraint.
Comment: Thanks so much! Do I need an additional air gap like in an indirect waste receptor or something like this http://www.ecotech-dla.com/dla-g15.htm to prevent sewer backup going into the condensate tube?
Comment: Wouldn't directly connecting the wye to the condensate drain tube without an air gap result in any sewer back-up travelling up the drain tube instead of out. I was thinking I could do it like a washing machine drain where the tube simply hangs into the open stand pipe. Thanks!
Comment: @s0rce A standpipe is probably a better solution, if you're worried about a backup.  It sounded like you had a specific plan in mind, so I was simply pointing out how it could be done.  Without being there, it's difficult to suggest every possibility, or to evaluate which solution is best.
Comment: Technically, the shower tailpiece is an air gap.
Comment: It would not be code required.
Answer: As long as the A/C & Dehumidifier are above the crawlspace it's a perfectly good plan. Staple or clip the shared hose to the joist in a positive slope to the new PVC wye drain & cap the new PVC drain, then drill a snug sized hole in the cap to receive the hose to prevent slip-out.
Being a drain, without sags, freezing shouldn't be an issue. You can likely get rid of the condensate pump, now or when it dies...certainly try it. And, I commonly suggest replacing those accessible traps with a trap that has a screw-in clean-out at the bottom, it's your call.
Comment: The AC and humidifier are in the crawlspace. There is a pump that currently sends the water outside but I was thinking it could send it into the sewer through a trap and air gap instead.
Comment: Oh, I thought that was just the tube down there. Well, you have your freezing issue licked then...since the pump, usually, stays half-full. Yay, the old plan is still perfectly good to go!!! And, NOPE on the Air Gap & Separate Trap. The A/C & Dehumidifier hoses or pipes should be in very loose holes at the pump. If not, then you can just drill an intake hole or 2 in a safe spot(s), it'll act as an overflow too for when the pump dies. Stick to the plan of doing a Wye above the shower's trap, 2" up or more to avoid any impossible slosh back.
Comment: I've also been told that I shouldn't do this in the crawlspace and instead have the tubing from the pump go up to the laundry room and just put the tube into the same drain as the washing machine...
Comment: Sure, it's your place. But: Did they give you any reason? Do they think some 1/2" hose below any air flow's natural convection is going to "magically" spew methane? Did they explain an Air Gap is nothing but an empty section of the hose? Why not go super simple & just drill a nice tight hole in the cap or in the top of your ABS's inner shoulder clean-out there. You won't be violating anything & you'll be doing better than almost any pro, as you well know with the old bucket & tube through the wall highest level of professionalism hack jobs
Comment: The only reason I could find is the additional humidity from having the open drain pipe in the crawlspace.
Comment: I'd still vote for your original plan, which is not only perfectly fine but now also fully confirmed by Tester101 as proper & legal. Sorry if you misunderstood. There wasn't going to be any open drain pipe, just the pump was going to be left as is with it's loose holes...which are really no concern like that bucket was. But definitely not, the hose would go into the new Wye above the shower trap & your Wye arm for the hose would be fully capped. You'd drill a hole in the cap to receive the hose...much less or zero of a humidity possibility than the laundry drain pipe upstairs idea.

Connecting condensate pump to sewer


How does xTerm communicate with the XWindows session that contains it?

Question: I want to script opening chromium in kiosk mode under Linux (openSUSE 12.3) and XWindows, while controlling which monitor chromium appear in. I also need to have this script be run outside of a standard xterm, e.g. via ssh into the machine where chromium AND the display will run (i.e. I want the application to appear on one of the displays of the machine I'm connecting to, not the machine I'm connecting from).
I can do everything I want by hand in xterm on the target machine, but I won't be running these scripts in xterm. Somehow, the xterm environment is special: it knows how to talk to the containing XWindows session, and in fact knows which actual monitor it is hosted on. For example:

When I ssh into the machine and try to run an XWindows GUI on the target machine's display, it (reasonably) complains "Can't open display". However, even when I set the DISPLAY environment variable to the same value I see in xterm, I still get the error (although it now includes the current DISPLAY value). I've also tried setting DISPLAY to a variety of permutations on ":X.Y", where X and Y are small integers, but again to no avail.
If I run chromium in --kiosk mode from xterm, it takes over the monitor that currently contains the xterm window. If I drag xterm to my other monitor then chromium will launch in that monitor. I want that control when I launch chromium from my script, but can't figure out the background magic.

For window manipulation, I've seen suggestions to use wmctrl or devilspie, but I'm a bit nervous about depending on tools that haven't been updated in years. I'd also prefer to have chromium launch in the right place right off the bat, rather than having it appear in the wrong place and then be moved. And neither app can help me launch the app remotely.
So, here are the questions. First, how does xterm tell chromium how to connect to the right XWindows session and monitor? Second, how do I simulate that from a completely separate ssh connection? (Again: it's more than just the DISPLAY variable.)
Thanks,
Dan
Comment: After some more research I've found that `xauth` is the key to launching an application on a remote display's screen. And, as @n.m. noted (sorry; can't get the darn user link to work), Chromium launches on the monitor containing the cursor, not the launching terminal window.
Answer: You can't open X client on the target machine's display because of permissions: not anyone that can ssh into a machine may "take ownership" of it's screen. These are things controlled by xset -- read up on it.
As for the display: I assume that the specific monitor is controlled by the second part of the DISPLAY environment. At least that's what I remember from reading about X. I've never actually worked in a multi-monitor X environment.
Comment: (1) No, `xset` has nothing to do with permissions. (2) You remember incorrectly. Screens and monitors are very different things under X11. The second part of the `DISPLAY` variable is responsible for the screen number. You cannot drag windows between screens, only between monitors.
Answer: Xterm is not special. Your mouse pointer is. Chromium will appear on the monitor your mouse pointer happens to be in. This is probably the default behaviour of your window manager.
Chromium does not respect the usual window position requests. You cannot tell Chromium where to appear, you must tell your window manager where to place the Chromium window. Methods of doing that, if they exist, totally depend on what window manager you have.
If you ssh to your machine as the user that has started the X session, you should have no problem connecting to that session.


merge 3 arrays and display the data inside horizontale HTML table

Question: I have 3 arrays after merge these array I get this results
Here is the function I used for merge arrays
function mergeArrays(...$arrays)
 {

     $length = count($arrays[0]);
     $result = [];
     for ($i=0;$i<$length;$i++)
     {
         $temp = [];
         foreach ($arrays as $array)
             $temp[] = $array[$i];

         $result[] = $temp;
     }

     return $result;

 }

 $mg = mergeArrays($serviceName, $quantite, $prix);

Here is php inside mpdf

  SERVICE
  UNITE
  PRIX

';
for ($i = 0; $i < count($mg); $i++)
  for($j = 0; $j < count($mg); $j++):
  $html .='
  '.$mg[$i][$j].'	';
endfor;
$html.=
'

Output
enter image description here
I want to make a new line after each 3 column of data.
Thank you for helping me
Answer: It looks like you're just missing the opening and closing
s, in the outer for loop. You could add the tags like this:
for ($i = 0; $i < count($mg); $i++) {
    $html .= '
'; //open row
    for($j = 0; $j < count($mg); $j++) {
        $html .=''.$mg[$i][$j].'	';
    }
    $html .= '
'; //close row
}


Passing string_view when returning string

Question: I've been reading up on the benefits of using std::string_view, and why it should be used in parameter lists. And I understand that returning a string_view is generally not recommended.
However, say I have a simple function that accepts a string adds a suffix. I can think of two methods:
std::string AddSuffix(std::string_view inputString)
{
    return std::string(inputString) + "!";
}

Or
std::string AddSuffix(std::string inputString)
{
    return inputString + "!";
}

If I have to make a copy of the inputString either way, is there any reason to use one over the other?
Comment: One advantage of the 1st method: it doesn't require to construct a `std::string` for `inputString`. A `string_view` can be constructed without copy e.g. from a zero-terminated string literal.
Comment: If we're counting copies/moves, passing `std::string` by value is probably better, especially if you then do `std::move(inputString) + "!"`. But in reality I wouldn't bother, and would use a `std::string_view` parameter for consistency with everything else, then `std::format` (or equivalent) to add `"!"`.
Comment: The second option is a bit more readable and is preferable, but it's oversimplified. Usually functions have more return points independent on parameter values like `return {};` and the first option is preferable. Voting to close as "opinion-based" question.
Comment: @wohlstad ...except the function body then constructs `std::string` from it anyway. :(
Comment: @HolyBlackCat you are right of course. I was just refering to the interface design.
Answer: The problem of both your variants is that they create 2 std::string objects, both of which need to allocate memory (in case that those strings are long enough not to fit into the SSO buffer). The cause here is that operator+ returns (by value) a new string object.
If you want to save one allocation, you can modify the std::string_view case as follows:
std::string AddSuffix(std::string_view inputString)
{
  std::string temp;
  temp.reserve(inputString.size() + 1);
  temp = inputString;
  temp += "!";
  return temp;
}

In this case, only a single allocation is required when RVO is applied (all major implementations will apply it).
Live demo showing allocations: https://godbolt.org/z/44P37qhP3.
Comment: `temp += "!";` is worse than `temp.push_back('!');`
Comment: @phuclv Could you explain why?
Comment: because it requires `std::string::operator+=(char*)` or `std::string::append(char*)` to scan for the null-terminator in the string to append, then copy all characters until that point, and some bad implementations may even create a new std::string from that and append. OTOH `std::string::push_back(char)`, `operator+=(char)`  or `std::string::append(char)` simply increase the size if required then write a single char at the end


Need mfgr of double hung casements w/"PG" engraved on lock

Question: I purchased a mobile home that has had its windows redone since DOM. I would like to have additional windows put in, and would prefer them to match existing. Only problem, I can't find any identifying numbers, letters or anything on the windows except an outline of PG is engraved on the metal bracket/rise of the lock (pic attached). I've googled endlessly and can not figure out who manufactures these windows?
They are double-glazed, double-hung casements, non-tilt, 44.5"x51" @ 4 "panels" across (panels created by vinyl dividers between panes).
Thanks in advance!
Comment: Unfortunately, there's no guarantee the maker of the lock hardware is the maker of the windows.
Comment: Look for a faint etched stamp at one corner of the glass.
Answer: That logo looks like Portland Glass, located in lovely Portland Maine.
Answer: What is your location? There are literally hundreds (maybe thousands?) of aluminum window manufacturers. The one that is most likely is PG Aluminum; a South African manufacturer.
Comment: haha, wow! I'm in Maine, on the coast. Probably NOT the SA mfg. but i will check into it anyway! thank you!
Comment: Yeah, probably not African. Maybe the wonders of technology would allow you to search with that picture of the maker's mark, to find similar images?


Count how many rows have a nested value in the arrays of a json column in MariaDB 10.4

Question: I have the following values inside a cell of a json column in MariaDB 10.4:
{
    "0": [
        21,
        "Pallet da 1250kg (50 * Sacco da 25kg)",
        "1250",
        "kg"
    ],
    "1": [
        21,
        "Sfuso",
        "12",
        "kg"
    ],
    "2": [
        12,
        "Sacco da 5kg",
        "10",
        "kg"
    ],
    "3": [
        12,
        "Pallet da 2500kg (2 * Pallet da 1250kg (50 * Sacco da 25kg))",
        "5000",
        "kg"
    ]
}

The keys ("0", "1", "2", "3") are automatically generated.
I would like to count the number of rows that have the second element of each array identical to the one I pass in the condition.
For now I'm capable of doing such a thing:
query = '''SELECT COUNT(*) AS rowcount FROM ordine_al_fornitore WHERE JSON_CONTAINS(fca_ordinati, '"''' + myVar + '''"', '$.[*]')'''

Which print is:
SELECT COUNT(*) AS rowcount FROM ordine_al_fornitore WHERE JSON_CONTAINS(fca_ordinati, '"Sacco da 5kg"', '$.[*]')

I just know how to pass the key in a fixed way ($.[*]), while actually I would like to iter through the keys to check if that value exists in cell 1 of the array (and consequently count).
I would like to know how I can improve my query.
Thanks in advance!
Comment: What version of MySQL are you using?
Comment: I edited the question above to make it more clear to readers that this is MariaDB, not MySQL. MariaDB has been slowly diverging from MySQL since 2010, so it should be considered a different software product with different features.
Comment: @wchiquito The one that is inside XAMPP. I don't know exactly, how can I retrieve this information? However the version of XAMPP is v3.2.4
Comment: @Memmo https://serverguy.com/servers/check-mysql-version/
Comment: @BillKarwin Thanks for your support! I thought XAMPP had MySql by default. Then investigating I found out that it had mariaDB. I have to get a culture on these technologies.
Answer: In order to do this, you need to serve JSON_CONTAINS a flat array of strings to search in.
a) JSON_EXTRACT(fca_ordinati, '$.*') to get an array of object's values
b) JSON_EXTRACT(fca_ordinati, '$.*[1]') to get an array of each entry's 2nd value (index 1)
c) JSON_CONTAINS(..., '"Sacco da 5kg"') search for string appearance in that array
SELECT COUNT(*)
FROM ordine_al_fornitore
WHERE JSON_CONTAINS(
  JSON_EXTRACT(fca_ordinati, '$.*[1]'),
  '"Sacco da 5kg"' -- note the string needs to have quotes
);

This works on MySQL 5.7.22 or newer: https://www.db-fiddle.com/f/bNyV8wMbNhF1qTWBCBt7un/0
And MariaDB 10.3 or newer: https://dbfiddle.uk/?rdbms=mariadb_10.3&fiddle=d1c3d750ee2ef58a60d234a58f0fc5d2
Comment: Also, you may try `WHERE JSON_CONTAINS(JSON_EXTRACT(fca_ordinati, '$.*[1]'), '"Sacco da 5kg"')`.
Comment: Glad it works :-) My edited answer should now be correct even for MariaDB. The `->` operator is just MySQL's alias on `JSON_EXTRACT`, which is not supported by MariaDB. PS: Always start with platform and version, please :-) You've asked about MySQL, but you test answers against MariaDB.
Comment: I have an error `com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '> '$.*[1]', '"Sacco da kg (Colli)"' )' at line 1`. This is my printed query:
`SELECT COUNT(*) AS rowcount FROM ordine_al_fornitore WHERE JSON_CONTAINS(fca_ordinati -> '$.*[1]', '"Sacco da 5kg"' );`
Comment: That strange, since it works on DB Fiddle. What version (`select @@version;`) are you running?
Comment: DB server: 10.4.11-MariaDB - mariadb.org
Comment: However I point out that `JSON_CONTAINS` in other contexts has always worked for me, like [that](https://stackoverflow.com/questions/64535158/check-if-an-element-is-contained-in-the-values-array-of-a-json-column-in-mysq)


Restore Install GUI with Xfce

Question: I've installed Xubuntu on my laptop last night, and then again on my computer at work, and I came to notice that the Xfce desktop looks so much better on the latter. On my laptop, I get all the panels ordered the same way, but the colours are plain and the icons are very different.
I suspect it has to do with the fact that my laptop's had an xubuntu on itself once, until about 4 months ago, before I went to look at Ubuntu's Netbook Edition.
How can I get the same shiny desktop settings as I have on this fresh, virgin install?
Comment: Two screenshots to compare them would be awesome.
Answer: Check that you are using the new Greybird theme:

From the menu choose Settings - Settings Manager.
Double click the Appearances Icon
Choose the 'greybird' style
icons should be "elementary xubuntu dark"
Fonts should be "droid sans"

Restore Install GUI with Xfce


Javascript Recursion?

Question: I am practicing recursion. Conceptually I understand how this should work, (see below) but my code isn't working.
Please tell me what I am doing wrong. And please explain each step of your code and how it works. Clear Explanation is ten times better than just giving me code that works.
  /*
  buildList(0, 5) ==  buildList(0, 5 - 1) // [0]
  buildList(0, 4) ==  buildList(0, 4 - 1) // [0,0]
  buildList(0, 3) ==  buildList(0, 3 - 1) // [0,0,0]
  buildList(0, 2) ==  buildList(0, 2 - 1) // [0,0,0,0]
  buildList(0, 1) ==  buildList(0, 1 - 1) // [0,0,0,0,0]
  */

var buildList = function(value, length) {
    var result = [];
   if (length === 0) {
    return result;
   }

   result.push(value);

   return  buildList(result.push(value), length - 1);

};

buildList(0, 5);

I understand how recursion works on a conceptual level.
Answer: Your approach can't work, because the base case returns a new empty array, and other cases return the result of the recursion.
Instead, you should first recurse and then push
var buildList = function(value, length) {
  if (length <= 0) return [];
  var recur = buildList(value, length-1);
  recur.push(value);
  return recur;
};

Alternatively, in the base case you can avoid creating a new array
var buildList = function(value, length, array=[]) {
  if (length <= 0) return array;
  array.push(value);
  return buildList(value, length-1, array);
};

Comment: @spaceDog: The recursive call inside the alternative version is also in tail position that is, ES2015 compliant engines can optimize this call (tail call optimization). As a result the alternative version is as fast as an imperative loop.
Comment: @Iven I wasn't thinking about performance (because then a loop or `[].fill` would be better), but good point. [②ality](http://www.2ality.com/2015/06/tail-call-optimization.html) has a nice article about tail call optimizations.
Answer: The problem is that with every call to your function, the result variable gets reinitialized to []. If you declare that variable outside your function, the code works:
var result = [];
var buildList = function(value, length) {

   if(length === 0){
    return result;
   }

   result.push(value);

   return  buildList(result.push(value), length - 1);

};

buildList(0, 5);
console.log(result);

Comment: Not a very good solution. Imagine you want to build two lists, then both results would end up being a concatenation of the two lists you originally wanted.
Answer:   /*
  buildList(0, 5) ==  buildList(0, 5 - 1) // [0]
  buildList(0, 4) ==  buildList(0, 4 - 1) // [0,0]
  buildList(0, 3) ==  buildList(0, 3 - 1) // [0,0,0]
  buildList(0, 2) ==  buildList(0, 2 - 1) // [0,0,0,0]
  buildList(0, 1) ==  buildList(0, 1 - 1) // [0,0,0,0,0]
  */

var result = []; //(1)

var buildList = function(value, length) {
   if (length === 0) {
    return result;
   }

   result.push(value);

   return  buildList(value, length - 1);  //(2)

};

buildList(0, 5);

You're doing two things wrong:

You're initializing result inside the method.  This means every time the recursive method call is made, you're resetting result to an empty array.
You're passing the array into the recursive call of buildlist().  You want to be passing the value in there.
Comment: So the second time around making a list you'll end up with a concatenation. Not only that the first list you made have had a mutation since they are the same array...

Javascript Recursion?


Dynamic Variable inside Oozie EL Function

Question: I am writing a frequency-based coordinator workflow.
The configs are stored in some oozie.wf.properties file as:
-- java properties config
myFrequencyDays=1

The coordinator definition looks like:
<coordinator-app xmlns="uri:oozie:coordinator:0.4" name="MyCoord"  frequency="${coord:days($myFrequencyDays)}" start="${coordStartTime}" end="${coordEndTime}" timezone="${timezone}">
   <action>
      <workflow>
         <app-path>${appLocation}/application.workflow.xml</app-path>
      </workflow>
   </action>
</coordinator-app>

This however fails with EL Parsing error because of ${coord:days($myFrequencyDays)}
Any idea to achieve this ?
Answer: You won't be able to use a parameter from properties inside of an Oozie EL function. The solution would be to use the chron syntax described in the Coordinator Functional Spec.
So, in your properties file you would have something like frequency="0 12 * * *" and the coordinator definition would include frequency=${frequency}


Trouble Installing MySQL workbench

Question: I am new to Ubuntu Linux. My Professor asked us to download Ubuntu 10.10. I have made several attempts to download MySQL as 32 and 64 bit in Debian packages and it keeps failing. See below for what i wrote in the terminal. As you can see I get an error. I also get an error in the Ubuntu Software Center stating " Dependency is not satisfiable: libatkmm-1.6-1 (>= 2.22.1) ". Could you please give me some guidance so I know what I am doing wrong. Thank you in advance.
root@ubuntu:~# dpkg -i '/home/user/mysql-workbench-gpl-5.2.47-1ubu1204-i386.deb'Selecting previously deselected package mysql-workbench-gpl.
(Reading database ... 118286 files and directories currently installed.)
Unpacking mysql-workbench-gpl (from .../mysql-workbench-gpl-5.2.47-1ubu1204-i386.deb) ...
dpkg: dependency problems prevent configuration of mysql-workbench-gpl:
 mysql-workbench-gpl depends on libatkmm-1.6-1 (>= 2.22.1); however:
  Package libatkmm-1.6-1 is not installed.
 mysql-workbench-gpl depends on libc6 (>= 2.15); however:
  Version of libc6 on system is 2.12.1-0ubuntu6.
 mysql-workbench-gpl depends on libctemplate0; however:
  Package libctemplate0 is not installed.
 mysql-workbench-gpl depends on libglib2.0-0 (>= 2.31.8); however:
  Version of libglib2.0-0 on system is 2.26.0-0ubuntu1.
 mysql-workbench-gpl depends on libglibmm-2.4-1c2a (>= 2.32.0); however:
  Version of libglibmm-2.4-1c2a on system is 2.25.5-0ubuntu1.
 mysql-workbench-gpl depends on libgtk2.0-0 (>= 2.24.0); however:
  Version of libgtk2.0-0 on system is 2.22.0-0ubuntu1.
 mysql-workbench-gpl depends on libgtkmm-2.4-1c2a (>= 1:2.24.0); however:
  Version of libgtkmm-2.4-1c2a on system is 1:2.20.3-1.
 mysql-workbench-gpl depends on libmysqlclient18 (>= 5.5.13-1); however:
  Package libmysqlclient18 is not installed.
 mysql-workbench-gpl depends on libpangomm-1.4-1 (>= 2.27.1); however:
  Version of libpangomm-1.4-1 on system is 2.26.2-1.
 mysql-workbench-gpl depends on libpcre3 (>= 8.10); however:
  Version of libpcre3 on system is 8.02-1.
 mysql-workbench-gpl depends on libpython2.7 (>= 2.7); however:
  Package libpython2.7 is not installed.
 mysql-workbench-gpl depends on libstdc++6 (>= 4.6); however:
  Version of libstdc++6 on system is 4.5.1-7ubuntu2.
 mysql-workbench-gpl depends on libzip2 (>= 0.10); however:
  Package libzip2 is not installed.
 mysql-workbench-gpl depends on python-paramiko; however:
  Package python-paramiko is not installed.
 mysql-workbench-gpl depends on mysql-client; however:
  Package mysql-client is not installed.
 mysql-workbench-gpl depends on python-pysqlite2; however:
  Package python-pysqlite2 is not installed.
dpkg: error processing mysql-workbench-gpl (--install):
 dependency problems - leaving unconfigured
Processing triggers for desktop-file-utils ...
Processing triggers for python-gmenu ...
Rebuilding /usr/share/applications/desktop.en_US.utf8.cache...
Processing triggers for hicolor-icon-theme ...
Processing triggers for shared-mime-info ...
Processing triggers for python-support ...
Errors were encountered while processing:
 mysql-workbench-gpl

Comment: 10.10? NO he did not... he should know 10.10 is end of life. Use 12.04 and mysql+workbench will install :+ Beside that for future installing: when using DPKG you must manually install all the dependencies.
Answer: Open your terminal. Write the following:
sudo apt-get update
sudo apt-get install libctemplate0 libzip1 python-pysqlite2 mysql-client python-crypto python-paramiko
sudo apt-get install mysql-workbench

Press Enter and write down your password then another Enter. Done
Comment: @kamil That's not what I meant.  I meant the dependencies don't exist on the mirrors anymore.  10.10 is EOL which means it is no longer supported.  The user needs to use a non-End of Life release.
Comment: @Rinzwind I edited the answer
Comment: When i Open the terminal and type in the command i get this...
Comment: user@ubuntu:~$ sudo apt-get install mysql-workbench
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package mysql-workbench
user@ubuntu:~$
Comment: @user247553 what do you get?
Comment: @kamil he's on 10.10.  That will error with getting dependencies.
Comment: @user247553 I advise you to install ubuntu 12.04 at least because it's a long term stable release and still supported by mysql workbench. any way try my answer edited above
Comment: @ThomasW. actually there is no mysql official release right now to 10.10. Although 10.04 have a download in their site. I am trying to help
Comment: W: Failed to fetch http://extras.ubuntu.com/ubuntu/dists/maverick/main/source/Sources.gz  404  Not Found

W: Failed to fetch http://extras.ubuntu.com/ubuntu/dists/maverick/main/binary-i386/Packages.gz  404  Not Found

E: Some index files failed to download, they have been ignored, or old ones used instead.
user@ubuntu:~$
Comment: @user247553 that's not a problem. continue
Comment: For the second command line you suggested I get this...
Comment: user@ubuntu:~$ sudo apt-get install libctemplate0 libzip1 python-pysqlite2 mysql-client python-crypto python-paramiko
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package libctemplate0 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

Package libzip1 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source...
etc
Comment: user@ubuntu:~$ sudo apt-get install mysql-workbench
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package mysql-workbench
user@ubuntu:~$
Comment: I advise you as moderators are saying to upgrade at least to version 12.04 because you cannot solve this problem easily.
Answer: You want to install MySQL Workbench.
The version you try to install is made for Ubuntu 12.04 and has some versions requirements for some of the deps.
You need to try with MySQL Workbench for 10.04/10.10 if you are forced to use 10.10, but still it would be recommended to use 12.04.
Also, after you will install MySQL Workbench compatible with 10.10, you will need to do
sudo apt-get install -f

to fix dependencies.
If you downloaded from MySQL.com, then choose older versions (on the right side of Select Platform) and download 10.04 version. Choose 32 if your installation is on 32 or 64 in case of 64.
Comment: I downloaded Ubuntu Linux 10.04 (x86, 32-bit), DEB and the I get the same error. Is there something else that could be preventing me from installing MySQL? This is what I got when i entered the command you suggested above...is this what is suppose to happen?
Comment: user@ubuntu:~$ sudo apt-get install -f
Reading package lists... Done
Building dependency tree
Reading state information... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
user@ubuntu:~$
Comment: try to clean any changes previous done.

`sudo dpkg --purge mysql-workbench-gpl`

no retry with the recent download and run

`sudo apt-get install -f`

to get all those deps.

Trouble Installing MySQL workbench


Best fit vs segregated fit vs buddy system for least fragmentation

Question: I am working on a dynamic memory allocation simulation(malloc() and free()) using a fixed sized array in C and i would like to know which of these will give the least amount of fragmentation(internal and external)? I do not care about speed, being able to reduce fragmentation is the issue i want to solve.
For the buddy system i've read that it has high internal fragmentation because most requested size are not to the power of 2.
For the best fit, the only negative i've heard of is that it is sequential so it takes a long time to search(not a problem in my case). In any case i can use a binary tree from my understanding to search instead. I could also split the fixed sized array into two where the left size is for smaller blocks and the right size is for bigger blocks. I don't know of any other negatives.
For segregated fit it is similar to the buddy system but i'm not sure if it has the same problems for fragmentation since it does not split by a power of 2.
Does anyone have some statistics or know the answer to my question from having used these before?
Answer: Controlling fragmentation is use-case dependent. The only scenario where fragmentation will never occur is when your malloc() function returns a fixed size memory chunk whenever you call it. This is more in to memory pooling. Some high-end servers often do this in an attempt to boost performance when they know what they are going to allocate and for how long they will keep that allocation.
The moment you start thinking of reducing fragmentation in a general purpose memory manager, these simple algorithms you mentioned will do no good. There are complex memory management algorithms like jemalloc, tcmalloc and Poul-Henning Kamp malloc that deal with this kind of problem. There are many whitepapers published around this. ACM and IEEE have plethora of literature around this.


Should I take the side of the poor oppressed Duergar, or the racist Genies in the Civil Rights Negotiation?

Question: I've been asked to mediate a civil rights dispute between a striking band of Duergar who are being deprived of their Dunkaroos and Rubies, and a conspiracy of racist Genies working on behalf of the Square-Enix-Goya Corporation who wish to deprive the dwarves of their Civil Rights at all costs and get maximum yields from the Chupa Mines.
Now I already know that there's no benefit to trying to reach a compromise - there are only rewards for choosing a side. What I'm not sure of is just how the rewards: Armor and a +50 VP potion from the dwarves or (less useful) armor and a Wish from Kazaam; stack up against each other.
Which is the better choice?
Comment: I don't even... wat...
Comment: @LessPop_MoreFizz That settles it! I am playing this game.
Comment: Two things: first, does this Kazaam have a Shaq-esque appearance? Secondly, this made me miss dunkaroos.
Comment: @Fluttershy Not just Shaq-esque. It *is* Shaq.
Answer: The ideal choice is almost certainly to side with the Genies in all matters except for the ban on elixirs - those should be completely legalized.
Relaxing the ban on the elixirs does not forfeit your reward for negotiating in the Genies favor if you conduct the rest of the negotiations in the most one-sided manner possible (the last option to every other question), but does allow you to get the Mysterious Potion from the dwarf who asks at what range you can smell his brews. This yields +50 VP to any one character.
The armor reward for siding with the Genies, the Falcon Jodhpurs is the best armor in the game for Balthios - by an equally large margin to the armor the Dwarves award to Barkley - and he needs the extra guard to compensate for his low HP and otherwise weak Guard stat.
Additionally, siding with the Genies grants you a magic lamp and a wish from Kazaam -  if you wish for Power, all of your characters will gain +5 to all stats.
By contrast, siding with the Dwarves yields the Shrekimono, the best armor in the game for the Barkleys -  however, while Hoopz could certainly use the +10 Guard vs the Mithril Jersey, the +5 from Kazaam combined with the benefit of the Jodhpurs for Balthios and the bonuses to all other stats are clearly the superior choice. Unless, y'know, you've got one of those conscience things. Which you shouldn't. It's every man for himself in the post-cyberpocalypse after all.
Comment: For some reason the only words I can see in this answer are "you should play this game"
Comment: @Tacroy Good news! It's available [as a free download for both Windows and OS X](http://www.talesofgames.com/related_game/barkley-shut-up-jam-gaiden/)!


Is there a difference in difficulty between hardcore and softcore?

Question:
Possible Duplicate:
Differences between Hardcore and Normal heroes

Other than the obvious death restrictions, is there a difference in difficulty level between hardcore and softcore mode? In particular, I've heard that there are higher quality items available to hardcore players. Does this make encounters any easier, keeping in mind that you really, really don't want to die?
Comment: Duplicate of: http://gaming.stackexchange.com/questions/66173/differences-between-hardcore-and-normal-heroes, and http://gaming.stackexchange.com/questions/68088/what-are-the-advantages-of-hardcore-mode
Answer: As per current wiki:
A player may create a Hardcore character - the true test of the player's skills.
A Hardcore character is the same as a normal character except for the following:

When a Hardcore character dies, the game ends and you cannot simply
reload your last save point because the character is gone forever.
When a Hardcore character dies, they are not removed from the
Character Selection Screen, instead remaining there as a robed figure
(as pictured) to remind players of their loss until the character is
deleted by the player.
Only the Items the Character has worn can be looted by other players
(if the player has allowed this before the character died). In
effect, the game treats you like a mortal human being rather than the
semi-immortal non-Hardcore characters, accordingly called Softcore by
Hardcore players.
Hardcore characters are displayed in a more aggressive pose in the
Character Selection Screen, depicting their tense state of play.
Hardcore characters get different Titles for beating the game.

Other than these, there are no other differences in gameplay terms. Dead hardcore characters will even retain whatever position on the Hardcore Ladder they may have achieved (albeit with their names in gray) until they have been surpassed by enough other players to knock them off of the Ladder. Hardcore mode is regarded by many as a more realistic playing experience.
Comment: I believe that wiki you have linked is for Diablo II. In particular, there are no titles in D3(?). Also, I'm pretty sure that you can't loot other players at all in D3.
Comment: interesting, i'll wait and confirm, but I am pretty sure that there are no other benefits.
Comment: [This wiki entry](http://www.diablowiki.net/Hardcore) is much more recent.  Of note, the body of your character doesn't appear to be lootable, meaning your items on you are all gone.
Comment: ill edit my comment, but atm i get 504 on the link


A property of the fourier series

Question: Show that any periodic function $f(x)$ with period $2\pi$ which is both odd and satisfies $f(\pi-x)=f(x)$ has $b_{n}=0$ for $n$ even and so has a fourier series of the form $$f(x) = \sum^{\infty}_{m=0} c_{m}\sin{(2m+1)x}.$$

So we know $f$ is odd and periodic with period $2\pi$ thus it has a fourier series of the form $$f(x) = \sum_{n=1}^{\infty}b_{n}\sin{(nx)}\quad \text{where}\quad b_{n}=\frac{2}{\pi}\int^{\pi}_{0}f(x)\sin{(nx)} \ {\rm d}x.$$
Integrating $b_{n}$ by parts yields
\begin{align}b_{n} &= \frac{2}{\pi}\left[-\frac{1}{n}\Big[f(x)\cos{(nx)}\Big]^{\pi}_{0}+\frac{1}{n}\int^{\pi}_{0}f'(x)\cos{(nx)} \ {\rm d}x\right]\\ &= -\frac{2}{n\pi}\Big[f(\pi)\cos{(n\pi)}-f(0)\Big]+\frac{2}{n\pi}\int^{\pi}_{0}f'(x)\cos{(nx)} \ {\rm d}x\end{align}
Notice however $f(x) = f(\pi-x)$ thus $f(\pi) = f(0)$ so $$b_{n} = -\frac{2f(0)}{n\pi}\Big[(-1)^{n}-1\Big] + \frac{2}{n\pi}\int^{\pi}_{0}f'(x)\cos{(nx)} \ {\rm d}x$$
Now from this point onwards I'm not sure what to do with the second integral since we don't know $f(x)$ it will never cancel. Is what I have done going on the right track and what would be the next steps?
Answer: $$f(\pi-x) = \sum_{n=1}^{\infty} b_n \sin{n(\pi-x)} = \sum_{n=1}^{\infty} (-1)^{n+1} b_n \sin{n x}$$
The only way $f(\pi-x)=f(x)$ is when $b_n=0$ when $n$ is even.
Answer: Use the fact that $f(\pi-x)=f(x)$ to show that for $n$ even,
$$\int_0^\pi f'(x)\cos nx\,dx=-\int_0^\pi f'(x)\cos nx\,dx.$$

A property of the fourier series


How to enter SWTOR's Flashpoint "The Esseles" in Veteran mode?

Question: My friend and I are starting a playthrough of SWTOR. We've done the Flashpoint "The Esseles" on Story Mode a few times now, and wanted to try it on Veteran Mode. However, whatever we try, we always end up in a Story Mode version.
The steps we take:

Group up freshly
Start conversation to pick up the quest
Both choose "Veteran Mode" when the options in the chat wheel pop up
Both make sure the "Mission Difficulty Preference" is set to "Veteran"
Make sure the instance phase has been reset, to prevent old instances from troubling us
Run into the instance

However:

The result: we get thrown into a Story Mode flashpoint, and a related Story Mode quest pops up
Expected: starting the Veteran Mode flashpoint

Here's a screenshot of most of the above points visible:

Is there some trick or setting we need to use to enter "The Esseles" on Veteran Mode?
Comment: I believe Veteran mode is split into level 10-15 and 16+ sections.  Are you both in the same level range?  You might also need to use Group Finder for the first range, not sure.
Answer: The missions you currently have in your log are both for Veteran Esseles. Or rather, the mission "[FLASHPOINT] The Esseles" is difficulty-agnostic - it is the same on all difficulty levels. When entering a flashpoint on Story mode, you should have a "[STORY] Flashpoint:..." mission and (in most cases) will receive server messages about the GSI Combat Support Droid. (I've actually not done Story mode flashpoints in a group before, so I don't know if the droid is only for true solo runs.)
Note that the "two players recommended" in the Veteran Esseles description is not an error; unlike every other flashpoint, The Esseles (and its Imperial counterpart, The Black Talon) was originally designed for two players.
Comment: Gosh, you were right! How confusing :) - Thx a bunch!


Add SUM of values of two LISTS into new LIST

Question: I have the following two lists:
first = [1,2,3,4,5]
second = [6,7,8,9,10]

Now I want to add the items from both of these lists into a new list.
output should be
third = [7,9,11,13,15]

Comment: Does this answer your question? [Element-wise addition of 2 lists?](https://stackoverflow.com/questions/18713321/element-wise-addition-of-2-lists)
Answer: The zip function is useful here, used with a list comprehension.
[x + y for x, y in zip(first, second)]

If you have a list of lists (instead of just two lists):
lists_of_lists = [[1, 2, 3], [4, 5, 6]]
[sum(x) for x in zip(*lists_of_lists)]
# -> [5, 7, 9]

Comment: @ealeon: The "zipping" stops when the shortest iterable is exhausted. So if `first` is length 10 and `second` is length 6, the result of zipping the iterables will be length 6.
Comment: just curious how would zip() handles if array lengths for different? i.e what does zip returns for different array lengths and how would that affect the operation for x + y
Comment: Is there a way to do this when you don't know the number of lists?
Comment: @traggatmot:

`>>> lists_of_lists = [[1, 2, 3], [4, 5, 6]]`
`>>> [sum(x) for x in zip(*lists_of_lists)]`
`[5, 7, 9]`
Answer: From docs
import operator
list(map(operator.add, first,second))

Answer: Default behavior in numpy.add (numpy.subtract, etc) is element-wise:
import numpy as np
np.add(first, second)

which outputs
array([7,9,11,13,15])

Comment: use np.add(first, second).tolist() to get the result in a list
Comment: If `first` and `second` are np arrays you can just do `first + second`. And if you want to save the result in first, you can also do: `first += second`.
Answer: Assuming both lists a and b have same length, you do not need zip, numpy or anything else.
Python 2.x and 3.x:
[a[i]+b[i] for i in range(len(a))]

Answer: Try the following code:
first = [1, 2, 3, 4]
second = [2, 3, 4, 5]
third = map(sum, zip(first, second))

Comment: +1 for this compact and self explanatory solution. It's worth noting that this works for more than 2 lists as well: `map(sum, zip(first, second, third, fourth, ...))`
Answer: This extends itself to any number of lists:
[sum(sublist) for sublist in itertools.izip(*myListOfLists)]

In your case, myListOfLists would be [first, second]
Answer: The easy way and fast way to do this is:
three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]

Alternatively, you can use numpy sum:
from numpy import sum
three = sum([first,second], axis=0) # array([7,9,11,13,15])

Answer: first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
three = list(map(sum, first, second))
print(three)

# Output
[7, 9, 11, 13, 15]

Answer: one-liner solution
list(map(lambda x,y: x+y, a,b))

Answer: If you have an unknown number of lists of the same length, you can use the below function.
Here the *args accepts a variable number of list arguments (but only sums the same number of elements in each).
The * is used again to unpack the elements in each of the lists.
def sum_lists(*args):
    return list(map(sum, zip(*args)))

a = [1,2,3]
b = [1,2,3]

sum_lists(a,b)

Output:
[2, 4, 6]

Or with 3 lists
sum_lists([5,5,5,5,5], [10,10,10,10,10], [4,4,4,4,4])

Output:
[19, 19, 19, 19, 19]

Answer: My answer is repeated with Thiru's that answered it in Mar 17 at 9:25.
It was simpler and quicker, here are his solutions:

The easy way and fast way to do this is:
 three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]

Alternatively, you can use numpy sum:
 from numpy import sum
 three = sum([first,second], axis=0) # array([7,9,11,13,15])

You need numpy!
numpy array could do some operation like vectors
import numpy as np
a = [1,2,3,4,5]
b = [6,7,8,9,10]
c = list(np.array(a) + np.array(b))
print c
# [7, 9, 11, 13, 15]

Comment: You don't _need_ numpy to sum pairwise elements in two lists.
Answer: What if you have list with different length,
then you can try something like this (using zip_longest)
from itertools import zip_longest  # izip_longest for python2.x

l1 = [1, 2, 3]
l2 = [4, 5, 6, 7]

>>> list(map(sum, zip_longest(l1, l2, fillvalue=0)))
[5, 7, 9, 7]

Answer: You can use zip(), which will "interleave" the two arrays together, and then map(), which will apply a function to each element in an iterable:
>>> a = [1,2,3,4,5]
>>> b = [6,7,8,9,10]
>>> zip(a, b)
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
>>> map(lambda x: x[0] + x[1], zip(a, b))
[7, 9, 11, 13, 15]

Answer: Here is another way to do it. We make use of the internal __add__ function of python:
class SumList(object):
    def __init__(self, this_list):
        self.mylist = this_list

    def __add__(self, other):
        new_list = []
        zipped_list = zip(self.mylist, other.mylist)
        for item in zipped_list:
            new_list.append(item[0] + item[1])
        return SumList(new_list)

    def __repr__(self):
        return str(self.mylist)

list1 = SumList([1,2,3,4,5])
list2 = SumList([10,20,30,40,50])
sum_list1_list2 = list1 + list2
print(sum_list1_list2)

Output
[11, 22, 33, 44, 55]

Answer: If you want to add also the rest of the values in the lists you can use this (this is working in Python3.5)
def addVectors(v1, v2):
    sum = [x + y for x, y in zip(v1, v2)]
    if not len(v1) >= len(v2):
        sum += v2[len(v1):]
    else:
        sum += v1[len(v2):]

    return sum

#for testing
if __name__=='__main__':
    a = [1, 2]
    b = [1, 2, 3, 4]
    print(a)
    print(b)
    print(addVectors(a,b))

Answer:     first = [1,2,3,4,5]
    second = [6,7,8,9,10]
    #one way
    third = [x + y for x, y in zip(first, second)]
    print("third" , third)
    #otherway
    fourth = []
    for i,j in zip(first,second):
        global fourth
        fourth.append(i + j)
    print("fourth" , fourth )
#third [7, 9, 11, 13, 15]
#fourth [7, 9, 11, 13, 15]

Answer: Here is another way to do it.It is working fine for me .
N=int(input())
num1 = list(map(int, input().split()))
num2 = list(map(int, input().split()))
sum=[]

for i in range(0,N):
  sum.append(num1[i]+num2[i])

for element in sum:
  print(element, end=" ")

print("")

Answer: j = min(len(l1), len(l2))
l3 = [l1[i]+l2[i] for i in range(j)]

Comment: While this code snippet may be the solution, [including an explanation](https://meta.stackexchange.com/questions/114762/explaining-entirely-%E2%80%8C%E2%80%8Bcode-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
Answer: If you consider your lists as numpy array, then you need to easily sum them:
import numpy as np

third = np.array(first) + np.array(second)

print third

[7, 9, 11, 13, 15]

Answer: Perhaps the simplest approach:
first = [1,2,3,4,5]
second = [6,7,8,9,10]
three=[]

for i in range(0,5):
    three.append(first[i]+second[i])

print(three)

Answer: first = [1,2,3,4,5]
second = [6,7,8,9,10]
third=[]
for i,j in zip(first,second):
    t=i+j
    third.append(t)
print("Third List=",third)

output -- Third List= [7, 9, 11, 13, 15]

Comment: Please describe this code and why you think it solves the problem
Comment: Please don't post code-only answers. The main audience, future readers, will be grateful to see explained *why* this answers the question instead of having to infer it from the code. Also, since this is an old question, please explain how it complements all other answers.
Answer: In this question your code gets two lists of molecular weights.
Print:
The second lowest molecular weight for each list (2 numbers)
The average molecular weight for the two lists together (single number)
Make a new list that includes all the elements from both lists, except for the maximum and minimum values (all values from the two list except 2 values). Then sort this list and print it.
Note: the number of elements in each list is not fixed.
Variables names: mws1, mws2
You may define additional variables in your code if needed.
See example of the output.
An example for the output (mws1 = [71, 88, 90], mws2 = [77, 5, 24, 65]):
Second lowest of first list: 88
Second lowest of second list: 24
Average of merged lists: 60.0
Sorted values from both lists, excluding extreme values: [24, 65, 71, 77, 88]
Another example for the output (num = mws1 = [26, 34, 14, 66, 78], mws2 = [98, 15, 88]):
Second lowest of first list: 26
Second lowest of second list: 88
Average of merged lists: 52.375
Sorted values from both lists, excluding extreme values: [15, 26, 34, 66, 78, 88]
Another example for the output (mws1 = [10, 53, 70, 1], mws2 = [22, 27]):
Second lowest of first list: 10
Second lowest of second list: 27
Average of merged lists: 30.5
Sorted values from both lists, excluding extreme values: [10, 22, 27, 53]
Answer: You can use this method but it will work only if both the list are of the same size:
first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
third = []

a = len(first)
b = int(0)
while True:
    x = first[b]
    y = second[b]
    ans = x + y
    third.append(ans)
    b = b + 1
    if b == a:
        break

print third


What happens if I use the travel system to access DLC content before I unlock the travel system in the plot?

Question: I'm at the second playthrough for my level 43 Soldier and my mission log says I'm at the "Getting Lucky" mission. I could do that, or I could access my DLC by using the fast travel system.
...except I haven't unlocked the fast travel system yet in the plot!

This looks eerily like a one-way trip... or is it? What happens if I take the plunge?
Answer: It's not a one way trip - the fast travel nodes in the DLC content are always enabled, regardless of your progress in the main story line, as the DLC is treated as completely separate from the story line with only a few minor restrictions (like level) in order to access them.
For example, I created a new character and went off to Mad Moxxie's Underdome, not only was I allowed to travel to the Underdome (even though I hadn't unlocked the fast travel system and my fast travel list looked like your screenshot but with all of the DLC travel points in it) and travel back using the fast travel system at the Underdome.
Comment: FWIW this is true in Borderlands 2 as well
Comment: One minor side-note - I took a trip to Jakobs Cove in the middle of playthrough 1. It worked fine, but unfortunately, it locked the Jakobs Cove location into the middle of my list of locations. Any new locations I visited were placed after Jakobs Cove, but before the rest of the DLC (which stayed at the bottom of the list). So you may want to hold off on taking the trip until after you've reached every area in the main game, just to keep your list a bit tidier.