I want to add the date in MM/DD/YYY after getting the date in YYY-MM-DD

Question: Below are the steps that i have done:
I have read the table and have taken the date in the last row - the date being in YYY-MM-DD
The date gets incremented by 10 and shows the result in YYY-MM-DD format.
But my problem is i need to enter the Date in MM/DD/YYYY format and iam not sure how to do that
Below is my code:
List lastdate = driver.findElements(By.xpath("(//table[contains(@class,'mat-table')]//tr/td[5])[last()]"));
int rowcount = lastdate.size();
System.out.println("Get the rowcount:"+rowcount);
<code>            for(int i=0;i<rowcount;i++)
            {
                String datetext = lastdate.get(i).getText();
             //Specifying date format that matches the given date
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            Calendar c = Calendar.getInstance();

            try{

               //Setting the date to the given date

                c.setTime(sdf.parse(datetext));- datetext - will take the date from the last row of the table which is 2000-04-15.

            }catch(ParseException e){
                e.printStackTrace();
             }

            //Number of Days to add
            int daysToIncrement = 10;
            c.add(Calendar.DATE, daysToIncrement);
            //Date after adding the days to the given date

            String newDate = sdf.format(c.getTime());
            System.out.println("Get the New Date:"+newDate);
</code>
}
When i print the result - it shows the date as 2000-04-25
But i need to add the date in the create screen in MM/DD/YYYY.
Any leads on how to do this ... i.e convert the new date to  MM/DD/YYYY ....
Comment: Instead of using `sdf` to format the date again at the end, create a new `SimpleDateFormat` with the required format string `MM/dd/yyyy`.
Comment: SimpleDateFormat sdfs = new SimpleDateFormat("MM/DD/YYYY");
    String newDate = sdfs.format(c.getTime());
    you mean need to do like this ? can you please confirm
Comment: See the answer by Alex below. Note: Upper/lowercase letters are important in the format string. You need to use `MM/dd/yyyy`, not `MM/DD/YYYY`.
Answer: <code>for(int i=0;i<rowcount;i++)
{
    String datetext = lastdate.get(i).getText();
    //Specifying date format that matches the given date
    SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat outputDateFormat = new SimpleDateFormat("MM/dd/yyyy");
    Calendar c = Calendar.getInstance();

    try {
        //Setting the date to the given date
        c.setTime(inputDateFormat.parse(datetext));- datetext - will take the date from the last row of the table which is 2000-04-15.
    } catch(ParseException e) {
        e.printStackTrace();
    }

    //Number of Days to add
    int daysToIncrement = 10;
    c.add(Calendar.DATE, daysToIncrement);
    //Date after adding the days to the given date

    String newDate = outputDateFormat.format(c.getTime());
    System.out.println("Get the New Date:"+newDate);
</code>


How can I run ajax call from within error function from another ajax call?

Question: I am trying to run an ajax call. If there is an error returned, I would like to capture the responseText and send that to another ajax call which has a php script that will mail the error to me.
      $.ajax ({
            type: "POST",
            url: "includes/add_remove_favorite.php",
            dataType: "json",
            data: {
                "listingType" : listingType,
                "listingId" : listingId
            },
            success: function(data) {
                alert('The first ajax call worked');
            }, //end first ajax success
            error: function(data){ //If the listing doesn't update, display an error message
                var currentURL = window.location;

                $.ajax ({
                    type: "POST",
                    url: "includes/error_email.php",
                    dataType: "json",
                    data: {
                        "url" : currentURL,
                        "errorMessage" : data.responseText
                    },
                    success: function(data) {
                        alert('The email sent successfully');
                    },

                    error: function(data){ //If the listing doesn't update, display an error message
                        alert('The email did not send');
                    }
                }); //end second ajax call

            } //end first ajax error
        }); //end first ajax call

I am able to get the error from the first ajax call, so I know that one works good. But for some reason, the mail script on the second ajax call won't send, and it won't return the success or error message, which tells me the ajax call is not working.
How can I run ajax call from within error function from another ajax call?
Answer: You need to use window.location.href. window.location is an object.
Comment: Yeah! That fixed the problem. I dont' understand why I didn't get a error response if it was the wrong type, but im glad it works now. Thanks for your help!


How do you know if your team can jungle invade?

Question: In many games, especially in pro games, the team(s) may jungle invade. How do you know if your team comp will win a jungle invade, or if your team is suited for one. I know there is always the concern that if the team sees you invading their jungle, they go to counter jungle you. So, how can I team prepare themselves/know if they can jungle invade successfully?
In addition, how do you know if you should leave a creep or not to delay jungle respawn time, especially on a buff? Even though this makes the creep spawn later and hurts the enemy team, it also means you won't know the respawn time either, so when is this a good idea?
Answer: If you have Blitzcrank, Nautilus, Ryze, Maoki, Ahri, Morgana, Janna, or Taric you should try to invade because all of these champions can learn long range CC at level 1.  Meaning your entire team can hide in a bush and wait for someone to poke out and instantly stun them.  Which usually leads to a dead champion unless they are able to instantly flash behind a turret.  Most of the time in low-medium ELO people are so surprised that someone is invading that they flash into a wall and waste it.  Leading to first blood and even additional kills if their team comes to help because it turns immediately into a 4v5 and you know you have a hard cc at level 1.
You should always leave at least one minor camp creep up, especially since the change in jungle not having those big neutral creeps re spawn really slows down a jungler.  If you are able to steal a buff you should kill the entire camp and write down the time that it died so that your team knows exactly when it re spawns so that you can steal it again.
**Summoners Rift Neutral Creep Spawn and Re-Spawn Timers **
Spawn time/Spawn period

Anc Golem 1:55 5:00 -20% CD, +25 flat mp5, +0.5% Max mana
Lizard   ....... 1:55 5:00 8/16/24% Slow, 10-50 True Dmg Twice over 3 seconds
Dragon    ......2:30 6:00 +400XP, +130G*, +130XP*
Baron    ....... 15:00....... +900XP, +250G*, +50 DMG/AP*
Comment: Alternately, if you have Blitzcrank, you could ignore getting first blood and just grab a buff minion over the wall, take it, and gimp the enemy jungler. Oftentimes, no blue buff can spell almost certain doom for certain junglers (Amumu comes to mind).
Answer: If you have a good lvl 1 CC (like a thresh, or blitz) you should consider invading. If you have multiple (like a midlane lux or top lane nautilus), you should definitely invade.
Unless you're a high enough elo (and if you're asking this question, you're probably not), then you can probably assume the opposing team has no clue how to effectively counter an invade. So long as your team remains grouped, doing a fast, early invade will likely have one of the following outcomes.

Best Case: You get a pick and kill them. (Even better, they burn at least one summoner and you still get them).
Commonly: You get a pick and they burn a summoner to survive.
Worst Case: You get engaged on and have to burn a summoner.

It's not likely the enemy is grouped enough to burst someone down on your side. Even if you get caught, it'll most likely be by a group of 3 at most, which most level 1's can survive so long as long as you don't Leroy Jenkins it. If you invade early enough, you can hopefully blow some of their summoners, recall, and will likely have enough time to get back and leash with full hp without missing any creeps.
Additionally, you may end up starting a level 1 fight, in which case it's best to remember to not get too greedy, else you overstay and lose the advantage due to a long recall and lost creeps.
Just remember to be mindful of timers, to get the advantage while you can, and to take advantage of whatever you get out of the invade. It doesn't matter if you burn the ADC's flash in an invade if you don't take that 5 minute window to harass, zone, and hopefully kill them.


irreducible in the ring of integers

Question: There is  a primitive 12-th root of unity and 5 is not a prime since the minimal polynomial mod 5 is reducible. The problem is I don't know how to show 5 is irreducible or not.
What I thought was if this ring of integer is UFD then 5 is not irreducible. so I've found a source that the ring of integer is actually norm-euclidean which means that is PID so UFD.. But then the proof of the theorem seems quite beyond my course.
How to show 5 is irreducible or not?
Thanks.
Answer: Let $\zeta$ be a primitive 12th root of unity. Then $\zeta^3$ is a primitive 4th root of unity, hence $\mathbb{Z}[\zeta]$ contains $i$.
Therefore we can write $5=(2+i)(2-i)$ in $\mathbb{Z}[\zeta]$, and by looking at their norms you can show that neither $2+i$ nor $2-i$ is a unit. Hence $5$ is not irreducible in $\mathbb{Z}[\zeta]$.

irreducible in the ring of integers


Two python2 in the cmd and cannot use pip2 for any of the version

Question: I am using OS X 10.12 and I have some troubles with my python installation. Currently I have two python2 installed. One is Python 2.7.10 at /Library/Python/2.7 and the other is Python 2.7.13 at /usr/local/Cellar/python/2.7.13_1. At the moment, all the pips (pip2, pip2.7, pip) direct to Python 2.7.10, and I cannot use pip for Python 2.7.13 in the cmd. Even Python 2.7.10 has pips, they do not work, for example, when I tried to upgrade numpy, I got error messages like this:
Collecting numpy
  Downloading numpy-1.13.1-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (4.6MB)
    100% |████████████████████████████████| 4.6MB 162kB/s
Installing collected packages: numpy
  Found existing installation: numpy 1.8.0rc1
    DEPRECATION: Uninstalling a distutils installed project (numpy) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
    Uninstalling numpy-1.8.0rc1:
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 342, in run
    prefix=options.prefix_path,
  File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 778, in install
    requirement.uninstall(auto_confirm=True)
  File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 754, in uninstall
    paths_to_remove.remove(auto_confirm)
  File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove
    renames(path, new_path)
  File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 267, in renames
    shutil.move(old, new)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
    copy2(src, real_dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
    copystat(src, dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
    os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/tmp/pip-N61eSI-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy-1.8.0rc1-py2.7.egg-info'

What I want to do is to make pip in the cmd for Python 2.7.13 and make pip2 for Python 2.7.10. And I want them both work.
Answer: An easy method to do this would be to just use -m pip.
<path to python 2.7.10> -m pip
<path to python 2.7.13> -m pip

Or you could add the python 2.7.10 and 2.7.13 to environment variables and just use
<python 2.7.10> -m pip
<python 2.7.13> -m pip

While there are methods to just rename their respective pip to a different name, since I've never really used OSX, I'll leave that for more experienced people to answer.


Resharper takes error on Collection expressions feature of C# 12

Question: A good C# 12 feature is collection expressions.
Resharper take error on this syntax
public List<Model> ListModels { get; set; } = []; // ERROR

I used the following option into Visual Studio 2022 to enable C# 12 on project:

I also added the following line to project file:
<Project Sdk="Microsoft.NET.Sdk.Web">
    <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <LangVersion>latest</LangVersion>
    </PropertyGroup>
.
.
.
</Project>

Is there an options to enable this feature in Resharper 2023.2.*
Comment: Does this answer your question? [How to get rid of the Visual Studio error because it doesn't recognise the new C# 12 syntax for collection expressions?](https://stackoverflow.com/questions/77542631/how-to-get-rid-of-the-visual-studio-error-because-it-doesnt-recognise-the-new-c)
Answer: It's a pity but JetBrains has been late with new .NET/C# versions support for at least several last releases and this one is not exception in this trend. Currently Rider/ReSharper does not fully support .NET 8 SDK - check out the .NET SDK support in JetBrains Rider doc.
You can try installing current EAP version (Which is EAP 8 ATM) of the tool which seems to have this issue fixed.
Note that either way it should not prevent the application from actually building (at least in Rider, tough false negative intellisense is not fun, yes).
See also - Primary Constructors – Using C# 12 in Rider and ReSharper which seems to use EAP versions of the tools.
P.S.
Make sure that you have latest version of VS for ReSharper case.


Sending device unique token to the push notifications provider

Question: My push notifications provider wants me to send a device-unique token to the server, which is not possible, as I figured out after hours of searching (neither with keychain nor identifierForVendor etc).
So atm server stores tons of inactive tokens (after app is reinstalled, token is being refreshed). What is the workaround in this situation?
Answer: If you are talking about the notification APN token to the server, the server can cull them when they attempt to use them.
The Apple Push Notification server will let them know the token is invalid.


include Javascript file in JS file without HTML or DOM in command line script

Question: I'm trying to write some simple tests on JS code that can be run from the command line to test code that has nothing to do with HTML, documents or user interface.  To do this I need to include one file within another to pull the code being tested into the test script.
    What I've found involved HTML or DOM to do the job; for example, something like
document.write( ) or some such.
   Is there a simple way to do this? I'm imaging something like
        include( "code2test.js" );
I'd appreciate any help in solving this.  Can JQuery help or does it have to be used in a HTML/browser context?
Thanks in advance.j
Comment: What are you using to run the tests?
Answer: It sounds like you just need two script tags:

If that doesn't work, try reversing the order.
Comment: I think he's asking how to include a javascript on the webpage AFTER its loaded, via command line, not how to include it in the html.
Comment: No, he's talking about running javascript from the command line, not in a web page at all.
Comment: In that case, you need to append the script to the document: `document.getElementByTagName("head")[0].appendChild(document.createElement("script")).src = "code2test.js";`
Comment: no, according to JacobM, OP is asking for a way to test javascript without going through a browser.
Answer: Sounds like what you need is Require.js. It's designed to allow inclusion of javascript in the web page using javascript rather than script tags. For example, instead of:

using Require.js you can write:
require(["foo.js"],function(foo){
    use_foo_here();
})

The cool thing about Require.js is that it can even be used on Node.js. So for command line invocation you can use Node to run your scripts and the require() statements would work just like it does on the web page.
Answer: If you just want access to a javascript engine (eg Webkit) without using a browser, you can use something like nodeJS or PhantomJS
Answer: We are using Chutzpah as our test runner, and are very satisfied with it. We write the tests using Jasmine. Jasmine does not require a DOM.
At the start of the test file, the references to the JavaScript files under test are added, like this:
/// <reference path="dependantModule.js" />
/// <reference path="code2test.js" />

and then the test code follows:
describe("code2test test suite", function () {

    it("should do something"", function () {
        var result;

        // Assuming code2test.js exposes a global called 'code2test'
        result = code2test.doSomething();
        expect(result).toEqual("the expected result");
    });
});

Chutzpah uses the PhantomJS headless browser. So you can write tests that interact with the DOM if required.
We run the tests through Chutzpah from the command line for continuous integration, but  also run them inside Visual Studio 2010 using the Chutzpah Visual Studio Extension. I believe integration of Chutzpah in VS2012 is even easier, but haven't tried it myself.
The tests can also be ran inside a 'real' browser, which is great for debugging. My browser of choice for debugging the test code is Chrome - the developer tools are great.


How do I get an inclusive result set without using PHP?

Question: Ok, so I've got this table called exp_category_posts that's in charge of storing the relationships between an entry_id and all it's associated cat_ids, as rows in the table (one column for entry_id, one column for cat_id)
For a search plugin I'm writing, a user can search by categories and I want to return all matching entries.
If I try to SELECT entry_id FROM exp_category_posts WHERE cat_id = 1 AND cat_id = 2 I expect to get a set of entries that are assigned to both cats but instead I get an empty results set everytime.  Using OR does not give the results set I want.
The only way I've found to get the results I want is to break it into steps:
Step 1: Do a query for each cat_id.
Step 2: Save the result set as an array.
Step 3: Use a few in_array() calls to filter out the entries that aren't in all of the result sets.
While this method works, it's pretty inefficient.  Is there any way I can get the results I want with a single query instead of doing it this way?
Comment: Suppose `WHERE cat_id = 1` returns 1,2,3,4,5 and `WHERE cat_id = 2` returns 3,4,5,6,7.  The result I want to get is 3,4,5.  Using OR instead of AND would return 1,2,3,4,5,6,7 which is not what I want.
Answer: SELECT
    entry_id
FROM
    exp_category_posts
WHERE
    cat_id = 1 OR
    cat_id = 2
GROUP BY
    entry_id
HAVING
    COUNT(*) = 2

Comment: Elegant solution.  Works slightly faster than JOINs when theres more than 2 cat_ids.
Answer: What you want is the intersection between two sets:

entry_id's that have cat_id = 1
entry_id's that have cat_id = 2

You can get that with INNER JOIN like so:
SELECT c1.entry_id
FROM
    exp_category_posts AS c1
    INNER JOIN (
        SELECT entry_id
        FROM exp_category_posts
        WHERE cat_id = 2
    ) AS c2
        ON c1.entry_id = c2.entry_id
WHERE c1.cat_id = 1

Comment: This approach isn't very easily generalised to intersections of more than 2 sets. If I want to find the intersection of `k` different sets, then using your method I need to join `k - 1` times, which is fairly awkward.


How to get obscure unicode scripts to display

Question: Not sure if this is the best place to post, but I thought I'd try since it relates to linguistics corpora and being able to read texts.
I can see some unicode characters such a Chinese characters (讀 or ), but I can't see others such as the Bhaiksuki characters, which look like this in Wikipedia: , and look like this in Sublime: . Wondering how I get these to show up, if there is some universal font that allows it to work or something. It's not just the Bhaiksuki script, there are many unicode characters that don't show up for me, though most of the standard ones do.
Wondering if I need to install each of these fonts individually or if I can install one font to get everything. This is what the Bhaiksuki and other more obscure unicode blocks look like for me on Wikipedia:

I was able to get all of the major scripts to show up with Google Noto font, but not the more obscure ones.
Comment: I just learnt that it's [actually impossible for a single OTF/TTF font to have every character](https://stackoverflow.com/a/34734338/2854284).
Comment: You should try [GNU Unifont](http://unifoundry.com/unifont/index.html). It has Bhaiksuki at least.
Comment: I think this might be a good post for this site (Linguistics.Meta), but it would be even better to ask it on, e.g., [superuser.se] first (adding specifics for platform/OS/browser/etc.), wait for answers, and repost it here.
Comment: Thank you, I actually tried posting on superuser first (focusing on Mac) lol, but got no responses after a few days so now trying here.
Comment: I mean, this could be a good FAQ for those who have problems browsing linguistics-related Web sites, but I doubt that *asking* it here would attract someone who's ready to answer.
Comment: I see that your rendering of Wikipedia is using comic sans for some reason. Like most people, I have a strong bias against that font, but even putting that aside it could be part of the problem because it probably doesn't support Bhaiksuki.
Answer: According to the repo, Noto has added Bhaiksuki support in November 2018. So updating your Noto fonts should fix that particular issue.
If you're on Debian, using this package should keep your Noto fonts up to date automatically, including any new ones they add (like Bhaiksuki). This package is even more complete, though it takes more disk space (because it includes the CJK planes).
Other than waiting for Google to improve Noto coverage, though, there's not much you can do I'm afraid. In pre-Noto times the only solution was to seek out a specialized font for each script you wanted to use.
Answer: When the obscure script is already included in Unicode, using Unicode codepoints and downloading appropriate fonts is the way to go. Any recent operating system comes with a plethora of fonts preinstalled, just keep your system up-to-date and you will rarely have troubles with missing fonts.
For scripts and characters not yet encoded in Unicode things are much more difficult. They may be encoded in the private use area of Unicode and come with a font using that specific private encoding, ut be aware: another font may have completely different characters on the same points of the private use area! The whole point of Unicode is to decouple characters and fonts as much as possible.
Comment: @abarnert This is a different question and I want to encourage you to ask it here on meta. Don't know whether it is a [:tag:feature-request] or a [:tag:bug] for tagging purpose, but it is certainly worth the attention of SE developers.


What Condition Can Concrete Be In And Be Recycled?

Question: I have a basement slab that I'm going to be breaking up and sending to a recycler. Here's what I would like to avoid:

The concrete being rejected at the site of recycling
The concrete causing some problems with the recycler's facilities

Both are admittedly unlikely, but I'm a worrier. In my basement I have carpet pads that I will be removing to access the slab, and those pads were attached to the concrete with what I assume was construction adhesive several decades ago. I'm wondering how clean I need to get the concrete to be able to get it accepted for recycling.
I asked the recycling facility this question, but didn't get an answer. Anyone know?
Comment: it doesn't have to be pure, they mainly don't want mud and debris...
Comment: @dandavis Great, so as long as I don't have big chunks of carpet pad on it, I should be OK? There's a portion of my slab that's coated with a really tough type of material that is putting up a big fight against my scraper.
Answer: You're fine, as long as the amount of debris is low.  A bit of carpet glue, no problem.  Huge chunks of carpet, or mud, no good.  Of course you can ask the recycling company for a contamination rate, but pretty much if it looks clean, it's good to go.
https://en.wikipedia.org/wiki/Concrete_recycling
Comment: Never would have thought of wikipedia for this. That page actually answered another question I was wondering about as well - is there a problem in recycling concrete with lead-based paint? It looks like there isn't.


How to (re)bind to submit button/form on .load(ed) form

Question: During early in learning how to implement unobtrusive js (using Rails & jQuery) I've run into an issue of how to (re)bind a submit button/form after .load(ing) new content that includes a form.
I've set up a 'create new item' form to show at the top of a lising of items (when the user clicks on a create button)
sale_case/show/_requirments_new.html.haml:
- form_for ([@sale_case, @sale_case_requirement]), :html => { :id => 'requirement_form', :class => "submit-with-ajax"} do |f|
...
%button{ :type => "submit" } Save Requirement

application.js:
jQuery(document).ready(function() {
  jQuery(".submit-with-ajax").submitWithAjax();
}
...
jQuery.ajaxSetup({
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})

jQuery.fn.submitWithAjax = function() {
  this.submit(function() {
    jQuery.post(this.action, jQuery(this).serialize(), null, "script");
    return false;
  })
  return this;
};

requirements_controller.rb:
def create
  @sale_case_requirement = @sale_case.requirements.new(params[:requirement])
      if @sale_case_requirement.save
      @message = "Success..."
      @success = true
  #...
  respond_to do |format|
    format.js
  end
end

requirements/create.js.erb:
mesg("<%= @message %>");
<%- if @success %>
  jQuery("#requirement_form")[0].reset();
  jQuery('#requirements').load('<%= requirements_view_sale_case_requirements_path(@sale_case.id) %>' );
<% end %>

It's all working well the first time around unobtrusively. The problem comes when the user creates the second item (on the form loaded via ajax).
The button is not getting bound to the submitWithAjax function. How do you do that when .load(ing) content?
I ended up having to do this in the partial (obtrusive) in order to get it to work, but it bugs me not to be able to figure this out. :
%button{ :type => "submit", :onclick => "jQuery.post('#{sale_case_requirements_path(@sale_case.id, @sale_case_requirement.id)}', jQuery('#requirement_form').serialize(), null, 'script'); return false;"} Save Requirement

Answer: Change this original code:
jQuery(document).ready(function() {
  jQuery(".submit-with-ajax").submitWithAjax();
}

to this:
jQuery(document).ready(function() {
  jQuery(".submit-with-ajax").live('submit', submitWithAjax);
}

and this original code:
jQuery.fn.submitWithAjax = function() {
  this.submit(function() {
    jQuery.post(this.action, jQuery(this).serialize(), null, "script");
    return false;
  })
  return this;
};

to this:
jQuery.fn.submitWithAjax = function() {
    jQuery.post(this.action, jQuery(this).serialize(), null, "script");
    return false;
};

The jQuery .live() call binds the named handler to the named event on all current and future elements that match the given selector, including elements that are loaded in via ajax.  Hopefully that does what you're looking for.
See the following for documentation on the .live() function: http://api.jquery.com/live/
Comment: Awesome. Thanks so much for your time. (I've benefitted so much from Stack Overflow recently I'm trying to engage and help give back.) See my answer for an issue I had and what I finally did.
Answer: Here's what I ended up changing in the code based on Ender's input. I got an error with finding 'submitWithAjax' with his version of the code, but he pointed me in the right direction and after reading the .live documentation I came up with this which works:
application.js
jQuery(document).ready(function() {

  # Just put it all in one place
  jQuery(".submit-with-ajax").live('submit', function() {
        jQuery.post(this.action, jQuery(this).serialize(), null, "script");
        return false;
      });
...
}

sale_case/show/_requirments_new.html.haml:
# Change the button back to unobtrusive
%button{ :type => "submit"} Save Requirement

Thanks!
Comment: Yeah, upon review, I'm pretty sure that having the parens after the function name in the .live() call was causing the error you came up with.


The limit of consecutive positive integers which are the product of n primes.

Question: The maximum length of a string of consecutive primes is 2: that is, the primes 2, 3. This is easily proven, as no even number other than 2 is prime.
In contrast, consider the set of numbers which are a product of exactly two primes (they don't need to be distinct). This set begins 4, 6, 9, 10, 12 ...
It goes on to include the numbers 33, 34, 35 - a run of three consecutive integers. Is this the longest consecutive run of such numbers?
My conjecture: that each set of numbers which are the product of exactly n primes contains one and only one run of consecutive numbers which is n+1 long.
No idea whether this is true! Thoughts, anyone?
Comment: Out of four consecutive numbers, one is divisible by $4$. It follows that we cannot have four consecutive numbers that are products of $2$ primes.
Comment: They don't need to be distinct right?  Like 25 counts as a semiprime
Comment: Have you tried to find a run of four consecutive numbers that are the product of three primes? Are you requiring the primes to be distinct?
Comment: Good clarification.  The primes don't need to be distinct.
Comment: you should consider $\omega(n) = \sum_{p | n} 1$ instead, the number of distinct primes factors of $n$, without caring of the multiplicity
Comment: That's a good point. How would the situation be different if we were just considering the number of distinct prime factors? I'm guessing you then could have a run of 4 numbers which have exactly 2 distinct primes (at least, the restriction described above wouldn't apply).
Comment: The OEIS entry https://oeis.org/A045984 is "The smallest number $m$ such that factorizations of $n$ consecutive integers starting at $m$ have [the] same number of primes (counted with multiplicity)".   For example $a(3) = 33$ in this sequence.  Searching for 211763 in OEIS gives a lot of sequences related to prime factorizations of consecutive integers.
Answer: The limits each time are defined by the powers of $2$. So a consecutive set of numbers which each have exactly two prime factors (not necessarily distinct) will be bounded by the need to avoid multiples of $2^4=4$ (given that including $4$ itself is not an option).
And a consecutive set of numbers which have exactly three prime factors (not necessarily distinct) will be bounded by the need to avoid multiples of $2^3=8$. So we can possibly expect a run of $7$ such numbers, and the smallest such run starts at $211763$:
$$\begin{array}{c|c}
n &f_1 & f_2 & f_3 \\ \hline
211673 & 7 & 11 & 2749 \\
211674 & 2 & 3 & 35279 \\
211675 & 5 & 5 & 8467 \\
211676 & 2 & 2 & 52919 \\
211677 & 3 & 37 & 1907 \\
211678 & 2 & 109 & 971 \\
211679 & 13 & 19 & 857 \\
\end{array}$$
Comment: A decent long run of numbers with four prime factors would require inclusion of a number $8$ times a prime. The best run under $10$ million is a set of nine consecutive numbers starting at $3405122$.
Comment: Great job finding such a run - how did you do it? Are there more such runs of 7? Will a run of 15 also exists for 4-prime numbers?
Comment: @ThomasDelaney pretty much a straight search for the 7-run of 3-factor numbers. There are 61 such sequences under 10 million. I 'm guessing there will be a 15-run of 4-factor numbers, but also that it will require a very large number space to allow such a coincidence to occur. The 9-run at 3405122 is the only one below 10 million.


Can I change story mode choices made in KOTFE / KOTET by replaying?

Question: As the question states.
Can I go back and replay chapters in Story Mode and alter the outcome of later ones?
Spoilers below

 Let's say I made the decision to save Torian instead of Vette but I later regret that choice.

Or

 Or if I decided to release Valkorion's father's spirit but I decided he would be quite handy to have around for the final stand-off against Vailyn

I've noticed that the choices I make by playing through the chapters again on Veteran Mode has no effect on anything - these chapters just play "one by one".
Answer: No, replays do not affect the decisions you made the first time around.  Ostensibly, this is because even a small change could invalidate the whole tree of later decisions, and they have not spent the time to add an option that would completely wipe out everything you did later.  I'd suspect this is something of a user experience decision too since there are undoubtedly people who would ignore any warnings and reset, and then regret it.
So if you want to make different decisions "for real", you have to create a new character.
Comment: I pretty much thought as much. I had a small hope based on the fact that nothing would really get destroyed by resetting the campaign, as you can't really make any choices that affects anything beyond just the companions you have available in the end; and certain activities would be out of bounds for a short while (Star Fortresses and so on). But thanks :-)


scraping website using python or wget - awaiting response problem

Question: I am trying to download more than 300k HTML files from the same server. I have the URLs in a list/text file. My first attempt was to use python urllib/requests but it was incredibly slow and would get stuck after a few links (10-20). Code example:
for i, url in enumerate(url_list):
    urllib.request.urlretrieve(url, "./pages/"+str(i))

Then I tried simply using wget like this:
wget -i links_file.txt -U netscape
wget works great and it downloads between 1-5 k files without problems and seems very fast but then gets stuck at random (?) files:
Connecting to <website>... connected. HTTP request sent, awaiting response...
Now I can see at which URL it got stuck and just stop the run and start it again from the same point and it works perfectly fine again for another 1-5k downloads. Since I can't do this manually every time it gets stuck until I finally have all 300k files, I was wondering if there is a way how I can stop wget automatically if it awaits a response for too long and then just tries again? Or is there any other/better way to download this many HTML files automatically?
Answer:
how I can stop wget automatically if it awaits a response for too long
and then just tries again?

What you are looking for is called timeout and number of retries. In wget you might use --timeout to set all timeouts at once or use specific timeouts that is
--dns-timeout
--connect-timeout
--read-timeout

In either case you should provide value as number of seconds after = for example --timeout=60
Use --tries to set number of retries (default: 20), for example --tries=10 but keep in mind that in case of fatal error no retry is done.
You might also find useful --no-clobber which effect is that file is not downloaded if already exist such named file (which would be overwritten)
Comment: Thank you I tied these options before, but I think I see were my problem was. That was helpful. I also found another solution of just running wget in a python loop and that ignores the errors and just jumps to the next URL.


how do I put the statement result in a list?

Question: I am trying to save the 'yes' or 'no' results into a list that is named as outlier here.
This is my code
d = {'col1': [1, 2, 3, 4, 5], 'Spread': [10, 10.8, 5.0, 4.9,12.3]}
df = pd.DataFrame(d)
upper_limit = 9

rows = df.index.tolist()
outlier = []
for i in rows:
    if df.Spread[i]>upper_limit:
        result = print('yes') in outlier
    else:
        result = print('no') in outlier

and my output is like this
yes
yes
no
no
yes

after this loop, if I print outlier, it will only return to an empty list.
What did I go wrong at this stage?
How do I save 'yes' or 'no' results in the list?
Thanks in advance!
updated!

Comment: You need to return to your tutorial materials to see what the `print` command does.  You seem to think that it returns a value useful to the program; this is at odds with the documented purpose of displaying values to the console.
Comment: Please supply the expected [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) (MRE).
We should be able to copy and paste a contiguous block of your code, execute that file, and reproduce your problem along with tracing output for the problem points.  This lets us test our suggestions against your test data and desired output.
Your posted code fails due to an undefined data frame.
Comment: Please [include a minimal data frame](https://stackoverflow.com/questions/52413246/how-to-provide-a-reproducible-copy-of-your-dataframe-with-to-clipboard) as part of your MRE.
Comment: @Prune sure just updated
Comment: I'll wait until the MRE is complete.
Comment: `print()` is used to display on screen - not to return value to variable. But often `displaying on screen` is called `returning data` which can be misleading. You need only `result = "yes"` and `result = "no"` - and you need smaller indentation in line `outlier.append(result)`
Answer: print() is used to display text on screen - not to return value to variable.
But often displaying on screen is called "returning data" which can be misleading.
You need only result = "yes" and result = "no".
And you need smaller indentation in line outlier.append(result)
outlier = []

for i in rows:

    # if/else
    if df.Spread[i] > upper_limit:
        result = 'yes'
    else:
        result = 'no'

    # after if/else
    outlier.append(result)

or you can add directly
outlier = []

for i in rows:

    # if/else
    if df.Spread[i] > upper_limit:
        outlier.append('yes')
    else:
        outlier.append('no')

    # after if/else
    # ... nothing ...


Service Broker Activation SP and TempDB Object Permissions

Question: I have an activation SP that calls another SP that calls other SPs to insert and update a table that exists in TempDB. I've created the queue with a user with SA permissions and the activation SP has SA permissions (to try and get around the issue).
I am continuing to get this error:
The SELECT permission was denied on the object 'xxxxxxxx', database 'tempdb', schema 'dbo'.
I have the ability to execute the process without Service Broker (calls the SPs Service Broker is calling, just directly) and it works fine.
Anyone have any ideas?
Thank you
Answer: I don't remember off the top of my head exactly how it goes, but the execution context of activated procedures is odd. Set up a trace (or extended events) and see who's calling your procedure. My guess is that you'll be surprised. You can either throw an "execute as" clause on the procedure, get into some module signing, or grant permissions to the procedure executor.
Comment: Thanks. I ran a trace and still can't see what the issue is. In the activation SP, I can create a temp table as in 'select 1 as c1 into #a', but I can't do anything with objects that exist in the DB (tempdb.dbo.Table1).
Comment: Yes, I understand. In the trace, what login is the execution context for your activation sproc? That login will need permissions (by whatever mechanism) to your objects in tempdb.
Comment: What might be the reason to have service broker enabled in tempdb? I am a new sql server administrator and I am wondering if I can safely disabled it. And is it possible to find out when was it enabled?
Comment: @BartoszSiemasz - that's really a topic for a new question. I'd suggest posting it on dba.stackexchange. If you create it and link to it here, I'll be happy to weigh in.


Highlight Text in Userform TextBox

Question: I want to select/highlight all text in a TextBox on my Userform. I already found >20 forums with the .SelStart and .SelLength solution but it is not working for me...
Are there settings or properties that I need to change to be able to use this?
This is my code:
Private Sub MaterialDescriptionTextBox_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If Len(MaterialDescriptionTextBox.Value) > 40 Then
    MsgBox "The material description can not exceed 40 characters", vbInformation, "Too many characters"
    With Me.MaterialDescriptionTextBox
        .SetFocus
        .SelStart = 0
        .SelLength = Len(.Text)
    End With
End If

Sadly it does not do anything asside from displaying the MsgBox.
Thanks
Answer: You are missing a Cancel = True. The Cancel cancels the Exit event itself but any other code after that will still run.
Private Sub MaterialDescriptionTextBox_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    If Len(MaterialDescriptionTextBox.Value) > 40 Then
        MsgBox "The material description can not exceed 40 characters", vbInformation, "Too many characters"
        Cancel = True
        With MaterialDescriptionTextBox
            .SetFocus
            .SelStart = 0
            .SelLength = Len(.Text)
        End With

    End If
End Sub

Comment: One follow-up: if I add a text of more than 40 characters and then decide to click Cancel (code: Unload Me), this will not work because it will go to the Exit event. Is there a workaround for this?
Comment: @Nicolas I don't understand this parth `click Cancel (code: Unload Me),` How would you click a cancel and how does it relate to Unload Me?
Comment: Sorry for the confusion! I have another sub: CancelButton_Click() which runs "Unload Me" to close the userform. However I cannot click this when I am in the MaterialDescriptionTextBox and there are over 40 characters because exitting this textbox wil trigger my initial sub and will cancel the CancelButton_Click sub.
Comment: @Nicolas that's a wrong approach. The Cancel button should use `Me.Hide` and unloading should be taking place in a standard module like `UserForm1.Show` and when you finally clicked the `Cancel` button an a userform the control returns to the code and then you call `Unload UserForm1`. Technically you are still in the Userform when you try to Unload it and this is discouraged. See [**THIS**](http://vba4all.wordpress.com/category/vba-macros/two-column-listbox-userform-and-saving-results-to-spreadsheet/) to get an idea
Comment: This does not solve my issue though. Is there a way to ignore the Exit event only if I click the Cancel button?
Comment: @Nicolas not sure what you mean. Can you ask a new question instead?
Answer: form userform properties make the show modal = false

Highlight Text in Userform TextBox


Enabling two finger scrolling in Ubuntu gnome 14.04

Question: How to enable two finger scrolling in Ubuntu gnome 14.04 . The feature is seen enabled in dconf Editor, but it is not working. Also there is no option for scrolling in the mouse and touchpad settings.
When the command  xinput; dmesg | grep pnp is typed in the terminal the following output is obtained.(I am copying the terminal output as I cant upload the screenshot image)
karthik@LenovoU41:~$ xinput; dmesg | grep pnp
<code>⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ PS/2 Generic Mouse                        id=13   [slave  pointer  (2)]
⎜   ↳  USB OPTICAL MOUSE                        id=14   [slave  pointer  (2)]
⎜   ↳ Lite-On Technology Corp. USB Keyboard     id=16   [slave  pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]

    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Video Bus                                 id=7    [slave  keyboard (3)]
    ↳ Video Bus                                 id=8    [slave  keyboard (3)]
    ↳ Sleep Button                              id=9    [slave  keyboard (3)]
    ↳ Lenovo EasyCamera                         id=10   [slave  keyboard (3)]
    ↳ Ideapad extra buttons                     id=11   [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=12   [slave  keyboard (3)]
    ↳ Lite-On Technology Corp. USB Keyboard     id=15   [slave  keyboard (3)]

[    0.895283] pnp: PnP ACPI: found 7 devices
</code>
Comment: Please [edit] your question and add output of `xinput; dmesg | grep pnp` terminal command.
Comment: I cant show the screenshot because i dont have enough reputation to post an image.
Comment: I do not need screenshots. Please try again `dmesg | grep pnp` and give FULL output.
Comment: karthik@LenovoU41:~$ dmesg | grep pnp
[    0.895283] pnp: PnP ACPI: found 7 devices
karthik@LenovoU41:~$
Comment: It looks like your touchpad is not supported by kernel yet. You can upgrade your kernel to get new drivers by `sudo apt-get install linux-generic-lts-vivid` and reboot.
Answer: Your touchpad is not supported by the current kernel.
You can upgrade linux kernel to get new drivers by running in terminal
<code>sudo apt-get install linux-generic-lts-vivid
</code>
and reboot.


access to pk in a template form

Question: I want to display all elements of a form including the pk and I have not found a satisfying method to do so:
class SomeForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["number"] = forms.IntegerField(required = True)
        self.fields["id"] = forms.IntegerField(disabled = True)
        self.fields["data"] = forms.CharField(required = False)

    class Meta:
        model = SomeModel
        fields = ["id", "number", "data"]

So now I just call the form in the view with:
class SomeView(TemplateView):
    template_name = "app/sometemplate.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        obj = MODEL.objects.get(pk = context["pk"])
        MODEL_data = {}
        MODEL_data["number"] = obj.number
        MODEL_data["id"] = obj.pk
        MODEL_data["data"] = obj.data

        context["form"] = SomeForm(initial = MODEL_data)
        return context

and now in the templatetags I have a filter get_pk:
@register.filter(name='get_pk')
def get_pk(obj):
    return obj.initial["id"]

and I get the pk in the template with {{ form|get_pk }} and I feel like this is not smart. I tried stuff like {{ form.instance.id }} like suggested here. I still feel there must be an easy way to achieve this?
Comment: `pk` already exists in the context, you use it to get the object via `context["pk"]`, use that `{{ pk }}`?
Comment: Ones should not code tired. This is exactly right.
Answer: I don't know why you need form in template view? You just need to get the context no more..
There are many comments in shared code like:
1-Disabled id field in initial form
2-Using different model name in form and get context data
3-Filtering context by using context["pk"] before assessing obj
Find the revised code,
def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context["obj"] = SomeModel.objects.get(pk = the desired value)
    return context

Note: if you want user to insert pk then you can use input field inside form with get method and get its value inside get context data in this way:
context["pk"] = self.request.GET.get("name of input field ")
In template html you can display fields directly:
{{obj.id}},{{obj.name}}, {{obj.data}}
Comment: I actually did what @Iain Shelvington proposed but your's is also correct and he did not post an answer.

access to pk in a template form


Retrieve minSdkVersion programmatically

Question: I have set the minSdkVersion in the manifest. Now I want to retrieve it in the code. It should be easy but I'm not getting it. How can I do that?
Comment: What is your intent? AFAIK there is no way to retrieve the value, and it doesn't make sense really to do so.
Comment: OMG you know that is easy? But I know 'there is no way'. What are you trying to do.
Answer: minSDKVersion is one of the settings in the Android manifest for which there is no API to read the value.
It's not impossible to get hold of - you just end up having to read the AndroidManifest.xml file yourself via XmlResourceParser parser = getResources().getAssets().openXmlResourceParser("AndroidManifest.xml")
and then parsing the appropriate information out of it.
Answer: I think what you probably actually want to be doing is retrieving the SDK version of the device running the app. It does not make sense to get the minSdkVersion in any scenario I can think of, which as far as I know is impossible anyways, because how is it relevant at all to the application being run on the device? What you want is the device's SDK version so you can check whether or not it's above a certain version, upon which you can perform some action.
If you indeed want the SDK version of the device you can use android.os.Build.VERSION.SDK_INT.
Or if you want to support all android versions then android.os.Build.VERSION.SDK, but the latter will return a String, which you should convert to an int by Integer.parseInt(Build.VERSION.SDK).
Comment: I think minSdkVersion could be useful in build verification tests.

Retrieve minSdkVersion programmatically


MFC displaying png with transparent background

Question: I need a way to display a PNG image with transparent background on a background with gradient color.
I have tried this:
CImage img;
CBitmap bmp;
img.Load(_T(".\\res\\foo.png"));
bmp.Attach(img.Detach());
CDC dcStatus;
dcStatus.CreateCompatibleDC(&dc);
dcStatus.SelectObject(&bmp);
dcStatus.SetBkColor(TRANSPARENT);
dc.BitBlt(rectText.left + 250, rectText.top, 14, 14, &dcStatus, 0, 0, SRCCOPY);
bmp.DeleteObject();

but foo.png gets black background wherever it is transparent in original image.
I did try to do a new bitmap that was painted with transparent color and did all possible operations on it, but that didn't help. Sample of one permutation:
CImage img;
CBitmap bmp;
img.Load(_T(".\\res\\foo.png"));
bmp.Attach(img.Detach());
CBitmap bmpMaska;
bmpMaska.CreateBitmap(14, 14, 1, 1, NULL);
CDC dcStatus;
dcStatus.CreateCompatibleDC(&dc);
dcStatus.SelectObject(&bmp);
CDC dcMaska;
dcMaska.CreateCompatibleDC(&dc);
dcMaska.SelectObject(&bmpMaska);
dcMaska.SetBkColor(dcStatus.GetPixel(0, 0));
//TODO: Bitmap ni transparent
dc.BitBlt(rectText.left + 250, rectText.top, 14, 14, &dcMaska, 0, 0, SRCCOPY);
dc.BitBlt(rectText.left + 250, rectText.top, 14, 14, &dcStatus, 0, 0, SRCAND);
bmp.DeleteObject();
bmpMaska.DeleteObject();

This did not do the trick. Either, there was all black square on the screen, or the result was the same as original.
I have also checked AlphaBlend API, but my code must be pure MFC + C++ witthout any additional APIs.
[Edit]: Company policy is as little APIs as possible. The code is supposed to run on embedded windows systems in real time.
[Edit 2]: I am not bound to PNG image format, meaning, anything that will display as transparent, goes.
Please, tell me what am I doing wrong?
Comment: The old bitmap calls that MFC exposes can't handle alpha. AlphaBlend is the way to go, it's part of the same Windows API that's used internally by MFC. What's the reason for not using it?
Comment: Stupid company policy of using as little APIs as possible. Specially, since application runs on embedded windows systems.
Comment: Good luck to you then.
Comment: Oi @MarkRansom... Assuming I use AlphaBlend... what would I need to do to achieve desired result. As far as I can see from samples AlphaBlend is used to set opacity.
Comment: I forgot to ask, is the .png file 8 or 24 bits?
Comment: I didn't do any reduction, so basically it is either 24 or 32 bit.
Answer:
Convert the png to a 32 bit bmp file. Google 'AlphaConv' and use that. PNG's are a PITA to work with - several API's claim to support them but actually don't, or only partially, or only on some platforms etc.
Load your 32-bit bmp using CBitmap::LoadBitmap (from resources - this is by far the easiest)
Then use CDC::AlphaBlend() to draw your bitmap. TransparentBlt() doesn't work with an alpha channel - it's just either draw the pixel or not. AlphaBlend is part of the win32 API, and you could still investigate CImage::AlphaBlend if you'd like, but that has a bug somewhere (I forgot what exactly) so I always use the raw ::AlphaBlend.
But beware - you need to premultipy the alpha channel for correct display. See my answer on How to draw 32-bit alpha channel bitmaps? .

No variation of what you described will work. You need another API to get this to work. Or, you could use GetDIBits and do your own version of ::AlphaBlend() :)
Answer: Based on what you're asking for (simply some set of pixels being transparent) it's probably easiest to use a 24- or 32-bit BMP, and simply pick a color to treat as transparent. Pre-process your picture to take any pixel that precisely matches your transparent color and increase change the least significant bit of one of the channels.
Given 8 bits per channel, this won't normally cause a visible change. Then draw the pixels you want transparent in one exact color. This is easy to do in something like a paint program.
You can then draw that to your DC using TransparentBlt. That lets you specify the color you want to treat as transparent.
Comment: Would that work with anti-aliasing as well? Basically, my image is a painted circle on transparent background. If I change transparent to let's say pink, some pixels will not be pink, but will not have the color of either app background or circle itself.


Should I increment the value of Room database version when migration strategy is fallback to destructive?

Question: Should I increment the value of the Room database version if I change the content of the database when its migration strategy is set to "fallback to destructive migration"?
Following changes made to database:

Some columns are removed.
Content of some rows is updated in the database file that is stored in assets.
Answer: Yes. You should update the version of the database even with fallback to destructive migration strategy. Room uniquely identifies every database version with an "identity hash string", which is kept in a configuration table.
Keeping the database version unchanged will cause the app to crash with an IllegalStateException. Internally Room checks the identity of the database comparing the identity hash of the current version vs the the one stored in the table called "room_master_table".
You can learn more about this in the below article which also explains in detail how to handle version change and testing.
Reference: https://medium.com/androiddevelopers/understanding-migrations-with-room-f01e04b07929
Answer: UPDATE: It is interesting that the app crashed in some users, but for some users including me, it didn't crash. So it's better to update the version of the database even though its migration strategy is fallback to destructive.
From my experience, it seems we don't have to increment the value of Room database version when its migration strategy is set to "fallback to destructive migration".
I changed the content of the database and removed some columns from the database file.
Then I installed the previous version of the app (unchanged database). Then I used the application and made sure a database instance is created.
Then I installed the new version of the app (changed database). And it didn't crash and everything worked fine. Changes applied to the database.


Do you lose the respective trading cards when uninstalling a steam game?

Question: These days I want to uninstall some games to get more space for the new ones.
I have earned some trading cards playing those games I want to uninstall, but I don't know if uninstalling will make me lose my trading cards of these games. Will this happen? Or I can uninstall without any problem?
Answer: No, trading cards are items stored in your inventory
If you uninstall a game, the cards you've already collected will remain in your inventory.
Additionally, any progress you've made towards collecting cards and the total you've earned out of the available gifted free cards from playing will be preserved. For example, if you have collected 3 out of 4 available "free" cards that can be earned by playing a game when you uninstalled it, reinstalling the game in the future will allow you to collect the one remaining "free" card.
Comment: Additionally, you won't lose your achievements or hours played.  In fact, for steam-cloud enabled games, you shouldn't even lose your save games!  In theory, at least; it's been hit-or-miss for me...
Comment: You can also own Cards for games you dont own. You wont lose any Card on deinstalling a game.
Comment: And sometimes if you have many saves, it only picks one, which is usually some wrong test save..
Answer: No, if you uninstall a game, or Steam, you will not lose your cards. This information is stored in the cloud.


Why does iPod's audio not fade back in after my app caused it to fade out?

Question: My app needs to play some audio files and I want to fade-out the iPod sound, play my file, and then as soon as my audio stops playing fade-in iPod again (just like iPhone handles iPod music when an incoming call comes in)
I'm setting up my app's Audio Session to be kAudioSessionCategory_MediaPlayback and then just before I play my file I call AudioSessionSetActive (true)
then when my file ends playing I call AudioSessionSetActive (false)
What happens is that the iPod audio fades-out with the AudioSessionSetActive (true) call, but it never fades-in again after I call AudioSessionSetActive (false)
I'm using AVFoundation class to play my audio, I audioPlayerDidFinishPlaying in my delegate method and that's where I call AudioSessionSetActive (false).
What am I missing here? Why doesn't the iPod fade-in when I deactive my audio session? Do I have the wrong Audio Session Category for this?
Answer: Ok, this is lovely.
In iPhone OS3, see AddMusic example.
In essence, you do this:
<code>#import <MediaPlayer/MediaPlayer.h>
...
[[MPMusicPlayerController iPodMusicPlayer] pause]
...(play your audio, with AmbientSound category)
[[MPMusicPlayerController iPodMusicPlayer] play]
</code>
This is basic. You can also add fadeout by looping volume change etc.
Answer: I got an answer from Apple about this. Unfortunately, it is not possible with SDK 2.2. I submitted a feature request, so who knows maybe the add this functionality in the future.


Curl get request in Ruby

Question: Would be very grateful if someone could help me convert this curl request into ruby?I have Been trying for a while and can't get the syntax correct.
curl -v -H "Content-Type: application/json" -H "X-Knack-Application-Id:000000" -H "X-Knack-REST-API-Key:000000" https://api.knackhq.com/v1/objects/object_6/records

tried:
uri = URI('https://api.knackhq.com/v1/objects/object_1/records')

Net::HTTP.start(uri.host, uri.port,
              :use_ssl => uri.scheme == 'https') do |http|
                      request = Net::HTTP::Post.new uri

                      # API details of Knack
                      request["X-Knack-Application-Id"] = '56e72cd003219158'
                      request["X-Knack-REST-API-Key"] = 'd9c343d2-2a4b-291e0712a63a'

            end

Comment: A little code formatting wouldn't hurt...
Answer: There are at least two issues.
First, in the cURL command you don't specify a method, hence by default it is a GET, but you use POST in Ruby.
Secondly, you are missing the part where you execute the HTTP request
http.request(request)

Here's the code:
uri = URI('https://api.knackhq.com/v1/objects/object_1/records')
req = Net::HTTP::Get.new(uri)
req["X-Knack-Application-Id"] = '56e72cd003219158'
req["X-Knack-REST-API-Key"] = 'd9c343d2-2a4b-291e0712a63a'

res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
  http.request(req)
end

More examples are available in the Net::HTTP documentation.
Comment: This is what I was trying to achieve but I'm now getting the following error:
     /usr/lib/ruby/1.9.1/net/http.rb:1861:in `initialize': undefined method `empty?' for # (NoMethodError)
Answer: Did you try some gems? I often use RestClient for api reqests, here is my example:
RestClient.post("https://api.knackhq.com/v1/objects/object_6/records", {}, {"X-Knack-REST-API-Key" => "000000", "X-Knack-Application-Id"=>"000000"})
More information about: https://github.com/rest-client/rest-client

Curl get request in Ruby


probability misnoma

Question: There are 3 men let them be $Myself ,X,Y$ out of these $3$ it is given that $2$ will be executed. They are in a custody . I ask the guard whose is going to be executed . so he says he cant tell whole truth so he says X is going to be executed. Now heres where  the doubt is. As X is sure to die my probability of surviving increases from $0.33 $ to $0.50$ but now the book says it isnt so the probability of Y is two times of you to survive. Can someone explain it to me how so?
Comment: This isn't clear, I mean the rules aren't clear.  It sounds like a Monty Hall problem...in that the guard had the ability to chose which of $X,Y$ to name.  But the motives of the guard are unarticulated (unlike the game show host...who will always open a worthless door).
Comment: On what thing do you want the clarification
Comment: What rules govern the guard's response?  I gather he can't lie, but what else?  Again, if this were a Monty Hall problem the guard's response would be restricted to "name a prisoner, not the one asking, who is going to die." That gives the $\frac 23$ answer so reverse engineering suggests this is what is intended.  But, really, it needs to be specified.
Comment: Not mentioned anything about that in the book but if one thinks logically would anyone tell you are going to die ?? That doesnt make sense and yes guard is telling 100% truth
Comment: Well, it seems like a lot to assume.  But if you do assume all that then this is exactly like the Monty Hall problem.  the guard's response carries no information (with respect to the questioner) as it will always be the case that at least one of $X,Y$ is doomed.  Thus the original survival probability of $\frac 13$ is unchanged.
Answer: As stated in the comments, you can think of it like a Monty Hall  problem with a restriction that you cannot switch doors. I.e., what increases your probability to get the prize is the fact that you can (and you will) switch doors. As the probability that you wrong at the first attempt is $2/3$ and by switching doors,  your probability to err decreases to $1/3$. More formally, the conditioned probability that you first failed and then switched to the "prize" door is $\frac{2}{3}\times 1$.
Now, think of it, as you must stick to the first chosen door. In that case you are indifferent to which of the other $2$ doors is "empty". Because you can do nothing with this new information. It is analogues to the prisoners problem, as you cannot change nothing (i.e., the outcome of the game does not depend on your strategy - whether to switch doors or not), so the guard answer bears no information for you. A little bit more formally, without too many arithmetic:
One possible path is that either $A,B$ or $A,C$ will be executed, this happens with probability $2/3$, then the answer of the guard is $C$ or $B$ with probability $1$, and then chances of $A$ to be executed becomes $1/2$. Another path is if $B$ and $C$ are doomed - this happens with probability $1/3$, then the answer of the guard is uniformly random between $B$ and $C$, in either answer the probability of $A$ to be executed becomes $1/2$, so summing up
$$
\frac{2}{3}\times 1 \times \frac{1}{2} + \frac{1}{3}\left(\frac{1}{2}\times \frac{1}{2} + \frac{1}{2}\times \frac{1}{2} \right) = \frac{2}{3} .
$$
For more detailed explanation see here.

probability misnoma


Something about boundedness in $\mathbb{R}^{n}$ and also in general..

Question: Is it true that $A\subset \mathbb{R}^{n}$ is bounded iff every sequence in $A$ has a Cauchy sub-sequence? Also in a more general setting, does such a property have a name attached to it or does it have any significance at all? What happens if we drop $\mathbb{R}^{n}$ out and replace it with any metric space $X$?
Here's my thoughts about the first question. I left out the smallest details since it turned out pretty long.
Assume $A\subset \mathbb{R}^{n}$ is bounded and choose a sequence $(x_{n})_{n\in \mathbb{N}}$ of arbitrary elements from $A$. Since $A$ is bounded we can find a large enough closed cube $K\subset \mathbb{R}^{n}$ which covers it (e.g. $K=\{x\in \mathbb{R}^{n}: x_{i}\leq k \forall i\in \{1,...,n\}\}$ with a large enough $k>0$). Splitting $K$ to $2^{n}$ (closed) sub-cubes there must exist a sub-cube $S_{1}\subset K$ which contains members of the sequence with infinitely many indices (since there are only finite amount of sub-cubes in total). Splitting $S_{1}$again to $2^{n}$ sub-cubes, with the same logic we can find $S_{2}\subset S_{1}$. And eventually, for every $k\in \mathbb{N}$ we find $S_{k+1}\subset S_{k}$, and they are all compact subsets of $\mathbb{R}^{n}$ by Heine-Borel. The diameter of the cubes $S_{k}$ goes to zero as $k \rightarrow \infty$, so the intersection $S:=\cap_{k=1}^{\infty}S_{k}$ (which is non-empty and compact) must be a singleton. For every neighborhood $U$ of $S$ there exists $i\in \mathbb{N}$ so that $S_{k}\subset U$ for all $k\geq i$. On the other hand, every $S_{k}$ contained infinitely many members of $(x_{n})_{n\in \mathbb{N}}$ so $S$ is its cluster point, or more precisely the point in $\mathbb{R}^{n}$ which belongs to $S$, and thus there exists a sub-sequence which converges to it. However, there is no guarantee that it would be a member of $A$, so what is left in our hands is that $(x_{n})_{n\in \mathbb{N}}$ has a Cauchy sub-sequence, and that's it?
Now as a second thought, I guess I could have used the compactness of the closure of $A$, find the sub-sequence that way and get the same results with less hassle.
But the other way seems more clear, if $A$ would not bounded we could find a sequence $(x_{n})_{n\in \mathbb{N}}$ in $A$ such that $d(x_{1},x_{k})=k$ for all $k\in \mathbb{N}$, which again could not have a Cauchy sub-sequence and we get a contradiction.
Any improvements to this and answers to my other questions? What happens in a more general setting?
Comment: You can choose a subsequence $x_{n_k}$ such that $x_{n_k}\in S_k$. This subsequence will be Cauchy since the diameter of $S_k$ goes to $0$ and the $S_k$ are decreasing. Indeed, it's possible that the limit is not in $A$ if $A$ is not closed (for example the sequence $x_k=\frac 1k$ for $A=(0,1)$, but it doesn't matter. For the second question, look for example at the unit ball of an infinite dimension Hilbert space.
Comment: Look up the notion of [total boundedness](http://en.wikipedia.org/wiki/Totally_bounded_space). In $\mathbb{R}^n$ boundedness is equivalent to total boundedness.
Comment: @:Davide: Alright, thanks alot.
@t.b.: Is this due to the fact that the closure of every bounded set is compact?
Comment: Yes. I think Chris's answer addresses this nicely.
Answer: A set $A$ in a metric space is called totally bounded if every sequence has a Cauchy subsequence (note: this is not the usual definition of total boundedness, but is equivalent to it).
In $\mathbb{R}^n$, as you observe, any bounded set is totally bounded, but this is not true in general. A standard counterexample is $\mathbb{R}$ with the metric $d(x,y)=\min(|x-y|,1)$. Clearly $\mathbb{R}$ is bounded with this metric, but $1, 2, 3, \ldots$ has no Cauchy subsequence. A less artificial example is the unit ball of any infinite-dimensional normed space.
I don't know if there's a standard name for spaces where your result is true; that is, where every bounded set is totally bounded.
Comment: Thanks. Very cool counter-example. Your metric $d$ also seems to generate the same topology as the Euclidean metric. edit: nvm my second question.
Comment: Last sentence: spaces in which every bounded set is totally bounded are quite commonly called [proper metric spaces](http://en.wikipedia.org/wiki/Metric_space#Locally_compact_and_proper_spaces) (because this is equivalent to the metric function $d(x,\cdot): X \to \mathbb{R}$ being proper). Some people call them metric spaces with the Heine-Borel property.
Comment: Alright, thanks for the info t.b.
Comment: @t.b.: The article you link to gives a different definition of "proper". Are both in common use?
Comment: Sorry I was having complete metric spaces in mind for which the two definitions are equivalent, so my comment is somewhat irrelevant. The definition of Wikipedia is the commonly used one. The property "bounded iff totally bounded" is equivalent to the completion being proper and my comment is only correct for complete spaces.


Why Jenkins failed with Cordova multi configuration project with build as failure?

Question: I installed Jenkins and started and configured my sample Cordova project with it. I created a multi - configuration project, where my Configure page contains following details.

Multi-configuration project name : Phonegap
Github Project URL :
Source Code Management :
Git Repositories :
Repository URL :
Build Triggers
Poll SCM where Schedule time is :H/5 ****
Configuration Matrix
Name : Platforms
Values: windows android
Build
Command :
cd ProjectName
cordova platform add $PLATFORM
cordova build

and I appiled Save
Now, when I create a build it failed with two platforms
Configurations
Windows and Android
when to clicked on each platform Failed build says:
 C:\Program Files (x86)\Jenkins\workspace\Phonegap\PLATFORM\windows>cd HelloWorldCordova

 C:\Program Files (x86)\Jenkins\workspace\Phonegap\PLATFORM\windows\XXXCordova>cordova platform add $PLATFORM
'cordova' is not recognized as an internal or external command,
operable program or batch file.

 C:\Program Files
 (x86)\Jenkins\workspace\Phonegap\PLATFORM\windows\HelloWorldCordova>cordova build
 'cordova' is not recognized as an internal or external command,
 operable program or batch file.

  C:\Program Files
  (x86)\Jenkins\workspace\Phonegap\PLATFORM\windows\XXXCordova>exit 9009
   Build step 'Execute Windows batch command' marked build as failure
   Finished: FAILURE

so what did I miss and what is the problem here?
Default Jenkins installed in C:.
Can anyone help me how to proceed with such problem? And what are things needs to configure yet?
Answer: It seems that npm is not added to your system's environment variables/PATH as you are getting the error message 'cordova' is not recognized as an internal or external command. NPM manages the 'cordova' command linking as far as I remember
In Windows
Start -> Control Panel -> System and Security -> System -> Environment variables
ADD the following to the end of your PATH
;C:\Users\user1\AppData\Roaming\npm

Replace user1 with the username on which the command is being executed
Semi-colon is important as it splits this entry from the last existing entry in your path, and adding to the end it is important as you don't want to break any existing tools and such that are configured in your path.
Comment: **@Peter Reid** for mac machine facing this issue - /var/folders/sj/01rfz4rx1ws_smjvggb_klzw0000gq/T/jenkins5523192147979463708.sh: line 2: platform: command not found
Build step 'Execute shell' marked build as failure
Finished: FAILURE
Comment: @Swift for MacOS check out this answer https://stackoverflow.com/questions/14803978/npm-global-path-prefix
Comment: no it's not related to it, i have added under Jenkins->Manage Jenkins->nodes->mac-slave->/usr/local/bin/cordova added this path for which cordova now it should pick it platform command from there. as my script is running fine in windows machine say android and windows facing an issue for ios only. hopeless for such error couldn't find anything related to it what configurations shall i add for it ?
Comment: Hmmm...strange, reading now it seems that it is having a problem invoking the platform command rather than the cordova command. I'd suggest opening a separate question - as this seems to be a separate issue.
Comment: **@Peter Reid**: here is the url for http://stackoverflow.com/questions/43464066/platform-command-not-found-for-jenkins-for-ios-build - can you please have a look at it once ?


Unable to Reinstall Ubuntu

Question: I am running 15.10 on a custom build.  I recently upgraded from 15.04, which, for reasons I do not understand, broke MySql.  I ran a fix to Upstart, which fixed MySql temporarily, but left me completely unable to log in at all upon reboot.  After some research and mild panic I decided to just reinstall over the previous installation, because that allegedly saves all data etc.  Pop in install disk, it found the previous installation, but I backed out of the install before letting it get started because I had to run an errand.  I never got past the time zone bit.  Upon returning I boot to the USB again, and now it's no longer finding the previous install.  It is saying that there are no OS installed.  However, when I boot without the install stick I still go back to my normal Ubuntu login.  When I boot to GRUB I still have all of my GRUB options.  However, when I try to boot into recovery mode for GRUB I'm now getting an error after a time that says
No init found.  Try passing init= bootarg
I then get a BusyBox shell.  I have no shell skills whatsoever so this is where I panic.  I really, really, desperately need to fix this.  I can't lose everything I have on this machine.  It would probably cost me my job.  Any help would be greatly appreciated.  But please, I may need you to explain it like I'm five at this point as the panic mode is fully engaged.
Edit: When booting from a live CD my drives and partitions all show in GParted and all are healthy
Comment: Have you tried to boot in the Ubuntu Live CD/USB and used GParted to see if it detects your current Ubuntu partition?
Comment: Stop trying to install/reinstall and backup your files first.
Comment: I've backed up what I can. There are permission issues with accessing them later but that's another problem for another day
Answer: You should try to run boot repair, that's for the booting part. As far as for the login concerns, you should try to login as root if you know the root password. Else, if you cannot login at all, you should remove your hard drive and use it in another computer as an external hard drive (there're tools to do that). As for the future, I recommend you use docker or vagrant holding a stable version of mysql, php or whatever you use.
Comment: Grub repair has been run successfully to no avail.
Answer: Please Check Your boot Option  from BIOS menu.
If it is UEFI change it to LEGACY
And try to reinstall operating system

Unable to Reinstall Ubuntu


moving series from one chart to another

Question: I have Single dashboard with multiple charts.And each chart have multiple series.
Let us say chart1 and chart2
Now is there anyway to move all series and data from one chart to another ? I want to move  all the series (lines and scatters) from chart1 to chart2 , And I want to clear the series in chart1 , which I can do with .dispose method.
  lightningChart().Dashboard({
    container: container,
    numberOfRows: 2,
    numberOfColumns: 1,
    theme: theme,
  });

Answer: there is no utility for this kind of application, so you'll have to go with the simple solution of removing the moved series and recreating them from scratch in the other chart.
The dispose approach for removing the moved series is correct.
For implementation, I'd advise to maintain some data structure for every series and the data it contains. Then you can recreate it and show the same data relatively simply.

moving series from one chart to another


ubuntu dose not run (even loading page)

Question: I have Asus N552VW and non of the versions doesn't run that means it stay on a black page or loading page and doesn't do anything  more.
but when I add this code to grub ubuntu will run but when I restart laptop this code will removed from grub and i have to add this again :
nouveau.modeset=0 pci=noaer

Answer: You can add it to grub permanently by editing the configuration files.
sudo vim /etc/default/grub
Edit this line:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

Change it to:
GRUB_CMDLINE_LINUX_DEFAULT="nouveau.modeset=0 pci=noaer quiet splash"

Save then run sudo update-grub
Comment: when i do it and restart my laptop i get this eror: (a start job is running for detect the avileble GPUs and deal whit any system changes )
Comment: change the above mentioned line to read exactly like the way you edit the grub entry to make it boot. Or is this a new problem?

ubuntu dose not run (even loading page)


SAP ERP integration with C++

Question: Is there a SDK for C++ or .NET available for SAP ERP 4.0 as I need to read and write data into it?
Comment: Could you be more precise about what software and version you really mean? SAP R/3 Release 4.0 was published more than ten years ago, so I doubt you really mean this...
Answer: I am not sure what version SAP ERP 4.0 refers to, but there is certainly the RFC SDK that you can use (can be made to work with C++ and .Net):
Very old version:
http://help.sap.com/saphelp_40b/helpdata/pt/8c/20e2bf493311d1894a0000e829fbbd/frameset.htm
Recent version:
http://help.sap.com/erp2005_ehp_04/helpdata/EN/22/04287a488911d189490000e829fbbd/frameset.htm
Answer: Building on the previous answer: with the C++ RFC SDK you can call ABAP functions and objects on the SAP side. So the actual reading or writing of the SAP data will be done by ABAP code on the other side.
Looking at this from the very high level you have two options with RFC:

find a factory SAP function that does what you want. i.e. write or read the SAP data
or write your own custom ABAP script that does exactly you wanted

In both cases you need to nail down what parameters you need to pass and receive to the ABAP you call, and make sure your RFC calls does that.

SAP ERP integration with C++


Will making a Restoration Loop-Fortify Enchant. . . insane Fortify Sneak percentage make me undetectable?

Question: So if I created a Restoration Loop-Fortify Enchant potion and enchant a piece of equipment with a crazy Fortify Sneak percentage; Will I be undetectable at all times, or only sneaking? My character's already godly enchanted; I'm just trying to go around practically invisible, without having to cast invisible and muffle/placing muffle enchant. Or is there a way to make the spell last "infinitely"(aside from recasting after interacting with objects. I prefer the prior.)
Comment: @Ids i know a better comparison. Will a insane high one handed skill help me hit things harder without hitting things? Since he is  not sneaking it really does not make sense to count the sneak skill to it.
Comment: To answer your 'will it make me invisible without sneaking question. Answer this. Will a crazy fortify one handed skill help you do two handed damage? (the answer is of course, no).
Comment: @Draedalus That running while sneaking skill just means while you're already in sneak mode, you can still "run" and it won't affect your detection.
Comment: Only way to find out: steal something in front of someone ;)
Comment: @MennoGouw Well to be fair, isn't there a skill in the sneak tree that allows you to sneak while running, so isn't it possible that this will help at all times?
Comment: Excessive stealth enchantments make you easier to detect.
Comment: I have a set of 4x57% sneak gear(+228% total) and shrouded hood plus all ranks of stealth and 100 sneak(sometimes blessing of Nocturnal). I can sneak right up to an enemy facing me in a decently lit dungeon and sneak attack them in the face. A super high sneak enchant via resto loop should make you undetectable while sneaking. Similar with lockpicking. A super high lockpick enchant makes the whole interface the sweet spot. Maybe you are thinking of pickpocket, where any enchant actually makes your chances go down(not sure about potions, maybe same with them).
Answer: Your sneak skill only affects yours chances of detection while sneaking.


Is UX better marketing than marketing?

Question: In our field we continue to sell our product in terms of better user experience, easier to complete tasks, less pressure on user and so on. We do that being convinced that it benefits our customers and employers. This is great, because we make the digital world better and easier and more joyful.
Marketers also sell products and solutions to companies to solve problems and issues. They too have a vision and a concept of a better digital world, but from a different facet. I'm often stunned by how they accomplish tasks and gain rightful trust by the customers.
Sometimes marketers and user experience experts are colliding; sometimes they work side by side in collaboration. But from a general notice – which marketing activity gets the best conversion rate marketing or UX? Does a dollar spent on UX make more ROI than a dollar spent on marketing?
Comment: That'd be a really tough one to call. I'm sure there's a sort of see-saw effect where beyond a certain point your product's UX is SO BAD any UX work out performs marketing, and a point where your product is so good improving it won't increase usage more than marketing would.
Comment: +1 This was surely an interesting subject to discuss, and I like the look of the answers so far.
Comment: @BenBrocka I know - that's why this question exists. Hopefully someone on this Q&A have an answer to this question – because I think it's an important one. At least that's where our shareholder is driving us.
Answer: Marketing = UX…
There is a remarkable amount of overlap between modern marketing and UX. Marketing is more than advertising and sales. It also includes market research, which identifies what would be useful, valuable, and desirable to consumers. Modern marketing also participates in developing the products themselves, ensuring they meet their target "value propositions." Marketers may test prototype products on consumers and provide feedback to development. All very much like user-centered design.
"Emotional design" and desirability have been parts of marketing long before UX got into it. Advertising, placement, and promotion are equivalent to UXers designing for findability, persuasion, and trust. The very word "conversion" comes from marketing.
Back in the 1980s, well before the web, there was a revolution in marketing, characterized by a shift away from "pushing" existing products onto consumers, to fulfilling consumers' real needs through research and innovation. In this approach, the marketer is the "customer advocate" in the business. Sounds familiar, doesn't it?
…Except for the Scale
The difference between marketing and UX is the scale of operations and units of analysis, with marketing concerned with more broad and abstract product features and consumer characteristics, while UX covers details down to each click and pixel. Thus, the two are neither redundant nor in competition with each other, but compliment each other. I don't think you can say which is better for getting conversions or promoting user satisfaction any more than you can say whether finance or accounting are more important for handling money for the business. Both have a role.
Beware, Young Skywalker
I don't think there's a conflict between marketing and UX, but there is a conflict between the light and dark side in both UX and marketing. When seduced by the dark side, both marketers and UXers pursue conversions at the cost of a truly positive consumer/user experience. What you may see as a conflict between marketing and UX may really be a conflict between Dark Marketing and Light UX. However, there's conflict between Dark UX and Light UX too. Some have used the Force of UX to persuade users of something they shouldn't believe or earn their trust in something untrustworthy.
Better ROI?
Whether you're talking marketing or UX, I believe the light side is usually better for most businesses in the long run. Usually. Most businesses. But not always for everyone. In certain situations the dark side will get you more money. That doesn't make it right, however.
I've more on marketing, UX, and ethics at A Man of Wealth and Taste. For a non-technical intro to modern marketing, I recommend Kotler on Marketing.
Comment: Speaking of dark UX, I find http://wiki.darkpatterns.org/Home both enlightening and fun to read.
Comment: +1 Excellent points as always on your answers. I like the distinction and reasoning between light and dark UX|Marketing!
Comment: +1 A very insightful answer, and very clever put together... I'll have a look at your article when I get the time, it does look intriguing!
Comment: I think once you broaden the the definition of marketing as you have in your first paragraph, you start to home in on the field of Customer Experience (CX), and Service Design - and oh yes, that is *very* relevant and topical to the field of User Experience at the moment. UX and CX are [different things](http://johnnyholland.org/2012/03/why-user-experience-is-different-from-consumer-experience/) but [natrual allies](http://informaat.com/blog/customer-experience-the-natural-ally-for-ux-in-business.php), with the middle ground perhaps being [Strategic UX](http://www.disambiguity.com/cxvux/)
Answer: Quote from Richard Reed, co-founder of Innocent Smoothies:

"90% of our marketing strategy goes into the bottle."

Innocent is not a digital company but the point is that they invest a lot into the quality of their actual product. They are very successful.
Marketing is much more efficient (aka delivering better conversion rates = higher ROI) if the promise made in the marketing messages (usually: "Our product is great") is kept by the product itself. And many successful digital products distinguish themselves by great UX.
Products fail due to bad UX, despite big marketing budgets. And products with great UX fail because of a missing product-market-fit. And some products fail because the world never got to know about them, due to the absence of good marketing.
That said, I think a valuable product with a good user experience is the precondition for efficient marketing and makes the job of marketing much easier. The ROI of marketing activities for a good  product is certainly higher than for bad products.
Back to the Innocent example:
Customers loved these smoothies and since they loved them so much, they would tell their friends, and they would buy them too. This is word-of-mouth marketing and the same holds true for great digital products, which we usually call "going viral". So a dollar spend in marketing for a product that creates loyal customers has the potential for continuously growing ROI.
My summary:
Spend your budget on building a valuable product with great UX and safe a little bit of the budget to do marketing. As a result the ROI on the marketing budget spent will be much higher.
Comment: The Gizmondo fiasco is a great example of a product that received tons attention from marketing efforts and PR trick shows but failed horribly due to terrible UX.
Comment: @BennySkogberg I didn't mean to say this is an usual question but rather unusual to use this Inncocent smoothi example. Your question is excellent and a good fit!
Comment: @BennySkogberg Hm, talking about profile image and the UX of Gravatar is worth another thread. But yes, first step on the way to a better username :P
Comment: +1 That's a wise answer. And I agree, this is an unusual question for this site. But that's what I try to do here – expand the Q&A on UX because I feel it deserves greater attention. Questions regarding button placement and strict design issues are valuable too, but the abstract and meta-like questions possibly make us think different and we might reflect of what we do every day.
Comment: And I see you have gotten yourself a profile image! Nice! :-)
Answer:
"Marketing is to create a customer" (Peter Drucker)
"UX is to create a happy customer" (Me)
Answer: It's a struggle monetizing UX to begin with. I think finding a dollar-for-dollar comparison with Marketing is going to be tough.
That said, I think you still need both. And, sadly, when you can't have both, often marketing is the better investment.
I base that statement on the simple fact that there is a LOT of bad products out there with atrocious UX that seem to thrive in spite of that--and that's typically via marketing.
Some companies thrive by focusing on UX. Apple is perhaps one of the flag bearers of that model. But they still seem to be the exception rather than the rule.
Comment: +1 There is always a struggle between different disciplines of who's getting the bigger share of the invested capital. I know this one is a tough call. In my opinion, based on pure assumptions, I think marketing dollar is considered more valuable in the short run and UX dollar in the long run. But I don't know.
Answer: This takes into account the marketing / UX cross over. I see UX crossing over into many functions that already exist within a business. This is the reason that many business feel that they are doing UX because the concepts that make up UX artefacts and deliverables have been produced by already established departments.
Like already noted in the answers each department within a business is subtly different and reports appropriately to answer their own remit. UX is the sum of all of this knowledge unless its used together to answer the wider questions and demands UX as a practice is unable to deliver the expected results.
I get to talk to many departments and functions within the companies I work with, when I succeed and the conversions start providing answers my agency rapidly gains respect as we are linking people and data together with the organisation that otherwise would remain in unconnected silos and databases.
Comment: +1 for the argument on cross over disciplines. I also see this in my daily work. But there is a difference. Just because you know the software Balsamiq, doesn't men you make great Wireframes and prototypes. And that I think is the difference between real UX work and want-to-be UX work.
Answer: How many of us know a product with a terrible UX but became successful in their market? That is when the product functionality overcame the UX. It's the dancing bear, as Cooper (2004, p.26) calls it as when a great idea triumphs over poor design.  The notion of dancing bear overlooks the fact that the bear is actually a terrible dancer. A successful poor UX product is not necessarily a marketing victory. Sometimes the product just offers functionality that is so important (value) to the user that UX fades into the background.
UX and marketing should not mix, except for when you are briefing to the marketing people the benefits your UX has to the users. In the end, it will be the marketing department that will decide if the UX information is valid or not for them. We can say that all depends on the company's strategies and how they want to present that product to the users. Unfortunately, not every company has UX in the centre of their goals.
And about ROI, your answer is already here in a previous question on this site: What is the ROI of UI or UX design?
Comment: +1 A really great answer to this question! I agree to a lot of your arguments, and you are close to @DA01 answer. However I'm not asking for the ROI on UX. I'm asking if the ROI of UX is better than the ROI of marketing. Related? Yes, but not the same.
Comment: Fair enough. Now that the ROI part is clear to me, I'll say that you shouldn't try to compare UX ROI with marketing ROI. Because you will always need marketing to promote your product. Imagine you have the best UX in the world, but it is hidden in a jungle. No one will know about your fantastic product, right? See Apple for example. They have fantastic UX products, but they have a good marketing too. Having said that, I think great UX products need less 'effort' from the marketing team to promote. But this is just my guess.
Answer: The objectives of UX design and marketing overlap but are not exactly the same. UX design, like marketing, is a multi-disciplinary field that requires many different skills combined to create an outcome.
Where the two areas start to diverge is in the focus of their respective activities, with UX continuing to hone in on the user's mental model to help deliver a product or service (as measured by the experience), whereas marketing goes into the consumer's perception about the brand and message of the organization providing the products or services, which doesn't actually have to be the same as the experience from using the products or service (although it definitely helps).
The most successfully companies try to align these two activities as much as possible, but not every company dedicate resources and personnel into these two areas, while some companies don't differentiate between the two. Some companies do without marketing or UX design, with the products or services directly driven by specific product or service improvement processes (e.g. PRINCE 2 or Kaizen).
There is no question that every company has their own approach or philosophy for making money, but the fact that the design discipline has its roots in engineering and industrial design (combined with information technology) makes it more grounded towards the social and physical sciences, while marketing much more focused on the social sciences (like psychology) but does use some techniques and analysis from statistics.
Sadly, both fields are lacking in the level of ethical design practices as business continue to borrow and misuse principles and techniques that help them sell more of their products and services...
Answer: Prior to about 2007 when it was plain old Usability there wasn't much overlap.
The broadening of the definition to UX bought more of an overlap with Marketing.
There is no one answer to the "which is better value" question: every product case will be different.

Is UX better marketing than marketing?


Adding 2 Piece Powder Room + Laundry

Question: I'm looking to add a powder room and laundry to the ground floor of our home. Most of the plumbing runs through the central wall on our side split and the W/C & lav will be on this wall too, making the draining/venting a bit simpler. However the laundry will not be on this wall so I'm hoping to use a cheater vent here so I don't need to drill half the joists in this room or open upper-floor walls to get a vent out the roof.
I've attached some diagrams of my plans and was hoping someone could give me some feedback / review things in general. Additionally, I have a couple more specific questions:

Is it better to connect the powder room and laundry both directly to the stack or am I okay joining them. I'm trying to avoid cutting too much of the copper out.
Is it possible to install back-to-back sinks that share a wall like the laundry/garage sinks in my diagram? If so what kind of fitting would work?

*NOTE: Stuff in blue is being added
Answer: All and all it looks good!
Regarding the Powder Room:
It is totally fine to join the powder room and laundry room on the same branch (as in your last picture). In addition, if the height is limited, instead of using a 3x2 sanitary tee on the vertical pipe to the toilet, you can use a 3x2 wye on the horizontal pipe before the toilet 90° to connect the sink and still vent the toilet.
Back to Back Sinks:
Yes, you can install sinks back to back. The fitting used here is a double sanitary tee or sometimes referred to as a sanitary cross.
Additional Comments
Note that some locations require that there is a fire-rated separation between the garage and the rest of the house. You can still penetrate the wall but you may be required to provide an approved fire stopping around the penetration. What you use will depend on how the wall is constructed and the drainage materials used. The same would apply to the water pipe penetrations.
Where I live we cannot use 90° elbows when transitioning from vertical to horizontal. We are required to use two 45° elbows. It's a bit silly, as we can use a hub x hub 45° and a fitting x hub 45° together and get close to the same radius as a short sweep 90°, but code is code. I know that many other jurisdictions/codes allow the use of long sweep 90° elbows for vertical to horizontal transitions.

Adding 2 Piece Powder Room + Laundry


Converting EVSE with 6-50 to 14-50

Question: Is it safe to replace a 6/3 soow on a 6-50 adapter with a 14-50 adapter? I have an additional 6/3 soow to use. The adapter says it must be used with a 4 wire, but the charger only uses a 3 wire cord currently. Do I leave the ground disconnected and just use the hot wires + neutral?
Answer: If your EV charger has worked so far with a 6-50, or is shipped with a 6-50 adapter, then it probably doesn't need neutral to function.  That's no surprise, honestly.
There is nothing wrong with changing the plug to 14-50.  In that case, you simply do not connect neutral in the plug.
You certainly do connect safety ground!  In all cases!
In cordage such as SOOW type, the /3 designator means it has 3 wires: black white and ground.  (/2 is groundless, /4 includes a red wire).
Use the white wire as one of the "hot" wires.  The usage will be obvious in this case, but bonus points if you color the wire with a sharpie to indicate it is not neutral.

Converting EVSE with 6-50 to 14-50