Graphical, free debugger for makefie built C++ programs (Windows XP)

Question: The software I develop uses command line makefiles. My environment uses free tools as much as possible. If you were to ask me which version of make I am using I would struggle to specify that, because I have installed mingw, cygwin and dev-cpp. However, I do know its "the free one", not Microsofts, and the one on my path at the moment is from the dev-cpp directory. Anyway thats not the crux of this question.
My code gets pulled from SCM, built, and finally the exe is placed in a bin directory. I want a free full screen graphical debugger that can debug this exe. I'm not looking for an IDE, but maybe the answer will require installing an IDE. I definitely will not consider moving away from command line makefiles to IDE equivalents.
I have tried this with MSVC and I can do it by attaching to the process after it has started. This is not ideal for two reasons: The tool has to be free and I should be able to debug it from startup. And by the way I will not consider MSVS Express. I already tried it and it kept hanging so it's uninstalled for good now!
In your answer you might want to include instructions as normally these things only work smoothly when you have built the program inside the IDE and I will not be doing that.
The preferred answer will specify a tool that has a small install footprint and works on Linux too. Specify any pre-requisites such as what compiler the code should have been built with. Of course if the instructions are too long then a list of what you have installed yourself is a help.
I will certainly upvote an answer that explains how I can do this with Dev-CPP, as I already have it installed. That doesn't mean it will be the preferred answer. These are the ideal boxes to be ticked in order of priority.

Free (Essential)
Decoupled from the build process (Essential)
Full Screen Graphical (Essential)
Minimalist. Just a debugger would be best. Minimize bloat and learning curve (Ideally)
Powerful debugger i.e. you can be reasonably productive with it (Ideally)
Cross Platform (Ideally)

4 and 5 may be contradictory, but don't worry. That is where trade offs will be made.
EDIT: Some very good answers. Please indicate which of the above boxes you have ticked.
Comment: Why don't you try Cygwin+GDB?
Comment: What? It's THE command line debugger. Its screen size is the size of your command window...
Comment: I have used it like that years ago. Its *not* the solution I'm looking for. Maybe "Full Screen" isn't the expression I should be using.
Comment: Try out [Eclipse CDT](http://eclipse.org/cdt/) or check [Debuggers on Wikipeadia](http://en.wikipedia.org/wiki/Category:Debuggers).
Comment: @dma_k I actually have Eclipse installed but I haven't figued out how to open an exe and debug it.
Answer: Cygwin + http://www.gnu.org/software/ddd/
DDD is graphical front-end to gdb.
You have mentioned you are familiar with gdb itself, so this should come naturally.
Comment: What boxes does it tick and do you know of a pre-built Windows binary anywhere? It has to be built from source.
Answer: With your toolsets installed, you should be able to use gdb already (e.g. included with MinGW). It's minimalistic, but also without any real ui (just command line). To run just call it with your executable as it's parameter: gdb myexe. To pass params: gdb --args myexe first second third
If you prefer an IDE, you could use almost any IDE and add a makefile project instead of a standard project. Most support this.
For (the IMO) best/most productive debugging under Windows you'll still have to switch to MSVC. There's no way around. Other, free IDEs offer similar stuff and features, but so far none managed to get at least almost on par. It shouldn't get stuck or anything on a semi reasonable modern PC. There might have been some other issue.
Comment: It could have been that it's a 7 year old PC.
Comment: Okay, that's not that good. In that case you might be better off using one of the open source solutions or just a command line debugger (e.g. gdb or windbg).
Comment: It's not so bad. It will easily support a graphical debugger. I'm trying to home in on an Open Source version. Does WinDbg only work for code compiled with MSVC?
Comment: GCC supports different formats for debug information, but I think WinDbg won't be able to handle them. Low level debugging will still be available, but you can't expect full functionality when not using MSVC. Although, keep in mind, that you're able to use MSVC from the command line, in case it's just the UI/IDE causing you trouble.
Answer: Most pro Windows developers use WinDBG which is a UI wrapper around several command line debuggers.  It's a more powerful debugger than MSVC because it can operate in both user and kernel mode and has a flexible command line based set of extensions which can perform a large number of automated tasks.  It's free, as in beer, although probably not as in speech.  Using it is much like using gdb although the UI version does have nice dockable window support for watch variables, locals, threads, memory etc.
It's available as part of the debugging tools for windows (which is free) or the Windows SDK...
http://msdn.microsoft.com/en-us/windows/hardware/gg463009
Comment: All except the last.  It's not cross platform, but it is the best debugger on win32 by far.
Answer: I'm not certain why MSVC doesn't work for you for getting the debugger attached before the process actually starts.  Did you try these steps:

Copy all your debugging symbols to be in the same directory as the EXE if not already there.
Start Visual Studio (Visual C++)
From the top menu, select File->Open->Project/Solution. (As if you were about to open a .vcproj file).
From the file selection dialog, navigate to the directory of the EXE you want to debug.
IF necessary, change the file types drop down to be "all files" or "exe files".  Or just type *.* into the file name box to get the dialog to show all files in that folder.
Select the EXE.
From the top menu select Debug->"Step Over".

If all goes well, the IDE debugger will be pointing to the first line of "main" and you can continue to step through your code.  It may prompt you for the location of the source files.  Just tell it where to find it, and it should find everything else.
Now from the tone of your post,  I can kind of tell you would appreciate something more "low level".  I'll suggest "windbg".  It should work for you as well.
http://msdn.microsoft.com/en-us/windows/hardware/gg463009
Comment: Can you elaborate on what you mean by "symbols" in step 1?
Comment: "Symbols" are information/associations telling the debugger which part of the program is refering to which line of source code. When compiling a program with MSVC, there's a pdb file (program debug database) created that's usually placed next to the resulting binary. That's what he's refering to.
Comment: Upvoting this because the VC debugging from startup does work when these steps are followed.


Rotate array return garbage values

Question: class Solution{
    public:

    //Function to rotate an array by d elements in counter-clockwise direction.
    void rotateArr(int arr[], int d, int n){
        int i,j=0,l=0;

        for(l=0;l<=d-1;l++){
            int temp=arr[0];
            for(i=0;i<=n;i++){

                arr[i]=arr[i+1];

            }

            arr[i]=temp;

        }

        // code here
    }
};

For Input:
size:5  rotate :2
1 2 3 4 5
expected output
3,4,5,1,2
your output is:
3 4 5 32766 4196870
the last 2 values is returning as garbage values i dont know why
Comment: Create a [mcve]
Comment: If `n` is the size of the array (number of elements) then the loop condition `i <= n` will go out of bounds of the array. Not to mention that using `i + 1` as index will go out of bounds before even that. And after the inner loop, `i` will be *two* steps out of bounds (with the current loop condition).
Comment: FYI -- Your solution is poor if `n` is a very large number.  Consider using `%` (modulus).
Answer: Okay, you have an off-by-more-than-one error.
for (i = 0; i <= n; i++) {
    arr[i] = arr[i+1];
}
arr[i] = temp;

Let's look at what this does.
n is 5. So your array has 5 items in it. On your first pass, you do:
arr[0] = 2;
arr[1] = 3;
arr[2] = 4;
arr[3] = 5;
arr[4] = garbage;
arr[5] = more garbage;

At this point, i actually is six, so you:
arr[6] = 1;

I think if you change your for-loop to this, it will work better:
for (i = 0; i + 1 < n; i++)

When you end, i will be equal to 4 (the index of the last item in the array), and thus you'll put 0 where you want it.

Rotate array return garbage values


jQuery: Does adding an event listener overwrite the previous listener of the same event?

Question: For example, let's say I have
$(element).on('click', function() {/*Some Stuff*/});

defined somewhere, then later I want to add more features to that same click event. If I do
$(element).on('click', function() {/*Other Stuff*/});

will "Other Stuff" overwrite "Some Stuff"?
Comment: Why the downvotes? The question is clear and concise.
Comment: take a look here http://stackoverflow.com/questions/891989/javascript-adding-an-onclick-handler-without-overwriting-the-existing-one
Comment: Lol, I didn't want to blindly write code without knowing if this was the case. I edited my question to make more sense.
Answer: The second listener won't override the first. jQuery event handlers are added cumulatively and execute in the order they were attached.
The thing that does effect whether one handler prevents the other running is how the function cancels the browser's default click handler (i.e. how you stop the browser following the link's url)
If you use traditional method:
$(element).on('click', function() {

    /* Some Stuff, do your thing */

    return false;
});

The handler above will stop the event itself and propagating to other handlers.
But you can stop the event action without stopping its propagation or the handler:
$(element).on('click', function(e) {

    // prevent the default action at first, just to make it clear :)
    e.preventDefault();

    /* do your thing */

    return /* what you want */;
});

This will ensure that the default click action doesn't occur but that the event continues to other hanlders. jQuery event also has some other useful event propagation methods (e.g. Event.stopPropagation()) which are worth getting to know.
Comment: Oh! That explains it. I always wondered why bother using .preventDefault()... Now I know.
Comment: What if you're adding the exact same callback twice? for example: `jQuery(window).on("scroll, MyClass.scroll")`. Is there a test for that? (I suppose I could look. Sigh.)
Answer: No, the events are not overwritten, they are appended or pushed to the list of event handlers.
This is a typical usage of the observer pattern.
Events can be removed with http://api.jquery.com/off/ or http://api.jquery.com/die/ in case .live was used.
Answer: This has been already been answered but I thought I'd add how I usually address this problem when I am in a situation where I might have a click listener getting duplicated.
I just user query on and off methods...

$(element).off('click'); //Removes a previously added click listener using the on method
$(element).on('click', function() {/Some Stuff/}); //Adds it back and only runs once

http://api.jquery.com/off/

The .off() method removes event handlers that were attached with .on(). See the discussion of delegated and directly bound events on that page for more information. Calling .off() with no arguments removes all handlers attached to the elements. Specific event handlers can be removed on elements by providing combinations of event names, namespaces, selectors, or handler function names. When multiple filtering arguments are given, all of the arguments provided must match for the event handler to be removed.
Comment: good point Josh, I wasn't looking for any ranking. I just stumbled across this as I was researching this issue and thought other people might want to know as well...
Comment: This does not actually answer the question. It just gives a suggested technique. The question was already clearly answered. In this question game you typically either answer the question in a new way or call out that you are providing additional information that was not already provided, if you want the upvotes.
Comment: Understood. I only posted a comment since you seem new to the site.
Comment: This was extremely helpful Matthew. This technique enabled me to solve an issue whereby many vanilla JS event listeners were stacking. Much gratitude to you!
Answer: No it won't. on() is just like bind--it adds the event to $.data("events")
You can explicitly remove stuff via off() though.
Answer: You've misunderstood; adding another handler does not overwrite the first.
See this jsFiddle: http://jsfiddle.net/ymuBs/
Clicking on the link writes "one" to the console. Clicking the button adds another handler to the link. Now clicking the link writes "one" and "two" to the console:


how to make jquery autocomplete simplify

Question: I use jquery autocomplete and it look like my code, to call the plugin, not good. is there any more simple way to call jquery autocomplete
js
$(document).ready(function(){
 $("#m_occupation").autocomplete("search/moccupation.php", {
        selectFirst: true
 });
 $("#foccupation").autocomplete("search/f_occupation.php", {
        selectFirst: true
 });
 $("#g_address").autocomplete("search/g_address.php", {
        selectFirst: true
 });
 $("#relationship").autocomplete("search/relationship.php", {
        selectFirst: true
 });
});

Answer: What you've got isn't really terrible. If you're only ever initializing these autocompletes one time, then it's pretty readable overall, although you do have some repetition.

Cache your jQuery objects for future use. In your snippet above, you only reference each jQuery object (e.g., $("#m_occupation") ) once, but in a real webapp, there's a pretty good chance you'll use it more. Caching helps reduce the number of jQuery finding operations, and is a good practice to adopt even though it's not likely to increase performance for a user noticeably.
Cache your options objects. You're repeating your option declaration multiple times; just declare a single autocompleteOptions object and be done with it.
Refactor initialization into a function. If you're really feeling like the autocomplete initialization is ugly, or complex, or subject to frequent edits, make it a single function. Future global edits to initialization can be made one time rather than multiple times.

A redo of your code taking those into account would look like:
var initAutocomplete = function($el, dataUrl) {
  var autocompleteOptions = { selectFirst: true };
  $el.autocomplete(dataUrl, autocompleteOptions);
};

$(document).ready(function(){
  var $m_occupation, $foccupation, $g_address, $relationship;

  $m_occupation = $('#m_occupation');
  initAutocomplete($m_occupation, "search/moccupation.php");

  $foccupation = $('#foccupation');
  initAutocomplete($foccupation, "search/f_occupation.php");

  $g_address = $('#g_address');
  initAutocomplete($g_address, "search/g_address.php");

  $relationship = $('#relationship');
  initAutocomplete($relationship, "search/relationship.php");
});

You could technically optimize further by using a single string to represent the DOM ID and URL from which you gather the data, but in my experience, that breaks down in maintenance. So I wouldn't couple those too tightly.


Server exiting after upgrading to Rails 5.0.0.rc1 from rails 4.2.6

Question: I am trying to upgrade my app's rails version from 4.2.6 to 5 but I am stuck with the following error.
suramai@rails-tutorial:~/workspace/converse (rails5update) $ rails server -b $IP -p $PORT
=> Booting WEBrick
=> Rails 5.0.0.rc1 application starting in development on http://0.0.0.0:8080
=> Run `rails server -h` for more startup options
Exiting
/usr/local/rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0.rc1/lib/active_support/core_ext/hash/keys.rb:79:in `block in assert_valid_keys': Unknown key: :order. Valid keys are: :class_name, :anonymous_class, :foreign_key, :validate, :autosave, :table_name, :before_add, :after_add, :before_remove, :after_remove, :extend, :primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type, :index_errors (ArgumentError)
        from /usr/local/rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0.rc1/lib/active_support/core_ext/hash/keys.rb:77:in `each_key'
        from /usr/local/rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0.rc1/lib/active_support/core_ext/hash/keys.rb:77:in `assert_valid_keys'
        from /usr/local/rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0.rc1/lib/active_record/associations/builder/association.rb:78:in `validate_options'

Changed the scope
  #default_scope -> { order: 'created_at DESC' }
  scope :created_at, ->  { order('created_at DESC') }

Added gem files
gem "responders"

Created
models/application_record.rb

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
end

Ensured that all models inherit from this new class, for example:
models/user.rb

class User < ApplicationRecord
  [...]
end

Anyone facing the same issue?
Answer: If you are using mailboxes add it as (with the github source) in order to get the master version of mailboxer and this fixed the issue for me
gem 'mailboxer', github: 'mailboxer/mailboxer'
Comment: Thank you @salma-gooma, I have added a [new issue on mailboxer](https://github.com/mailboxer/mailboxer/issues/427) that references this answer, asking to better document the issue...


Error occurs in configuring project:app when I am using any project in android studio

Question: I'm facing weird issue on my android studio.
Whenever I'm running any project on my android studio I'm getting below error.
Error:A problem occurred configuring project ':app'
Could not download hamcrest-core.jar (org.hamcrest:hamcrest-core:1.3): No cached version available for offline mode

If anyone has idea or has faced this issue then please provide me solution so that how can I solve above this problem.
Comment: are you setting gredle settings to work offline ?
Comment: No, how can i see that my gredle setting is offline or online ?
Comment: check File->Settings->Gradle->Global Gradle Settings and give me a feedback if it works
Comment: Was the wrong with the offline gradle option?
Comment: 'Hey, I am done it.error was in Path of gradle not in mode of gradle. And thanks for suggesting the Idea to check gradle setting.' @DasserBasyouni
Comment: 'I don't know but i change my first path and clean the project than again paste same older path and rebuild the project. So it's work.'@DasserBasyouni
Comment: your very wellcome, you may post your answer to you question then, and if anything went wrong again ask me if you want
Answer: It's Not depending on cache files but same project you are running on different devices and for that it will not working some time in your Laptop/PC.
but We need to refresh path of gradle by doing some changes like change path or directory from setting>gradle>gradle_path and also store old path at any location but safe place, because you will need it further.
Now refresh or rebuild your project it will gives error same as first you seen but when you set same path which was first when you change. now rebuild project again it will works properly.


Expected value of an expression

Question: Let $X$ be a discrete random variable such that $\mathbb{E}[X]=1$ and $V a r(X)=2$, then $\mathbb{E}[(X+1)^2]$. Is it true or false?
Solution: $\mathbb{E}[(X+1)^2]=\mathbb{E}[X^2+2X+1]=\mathbb{E}[X^2]+2\mathbb{E}[X] +\mathbb{E}[1]$.
Now, $\mathbb{E}[X^2]=Var(X) + \mathbb{E}[X]^2=2+1=3$.
So $\mathbb{E}[X^2+2X+1]=3+2*1+1=6$.
Hope it's right.
Comment: No, this is not correct. The expectancy of a constant, 1 in this case , is always the constant itself. $\mathbb{E}(1)=1$, because you could regard it as a (discrete) random variable $Y$ with constant value 1, this has nothing to do with $X$.
Comment: Yes, this is correct.
Comment: Thanks, I've another little question: $\mathbb{E}[1]$ is $1$ becaus I have to see it as $\sum_{n=1}1*\mathbb{P}(X=1)$, but $\mathbb{P}(X=1)=1$ ?
Comment: clear, understood :)
Comment: _What_ is true or false? Is there something missing from the first sentence?
Comment: I'm talking about the equality
Answer: Your solution is right, and you can consider the another simple variant to do the same:
$$\mathbb{E}[(X+1)^2]=Var(X+1)+{\mathbb{E}[X+1]}^2 = Var(X)+(\mathbb{E}[X]+\mathbb{E}[1])^2 = 2+(1+1)^2=6.
$$

Expected value of an expression


Show open windows on top panel

Question: Is there a way to show all OPEN apps/windows on the top panel in Ubuntu 18.04 with GNOME DE?
Similar to how it displays ACTIVE windows?
Answer: You may want to use a GNOME shell extension called "Dash to Panel". It's

An icon taskbar for the Gnome Shell. This extension moves the dash into the gnome main panel so that the application launchers and system tray are combined into a single panel, similar to that found in KDE Plasma and Windows 7+. A separate dock is no longer needed for easy access to running and favorited applications.

You can also set the position of the panel to top or bottom from the extension's preferences window as shown in this screenshot:

(screenshot source: this Web Upd8 article)
Comment: that sounds like a great idea, except I like having a separate panel for my favorited apps. The top panel that shows open apps, then becomes less cluttered. I can do this on xfce and KDE. But I may just have to resort to your suggestion for gnome. Thanks.
Comment: In that case you may also want to consider having a separate new taskbar with open windows at the bottom (refer to [this question](https://askubuntu.com/q/961581/480481)). I am not aware of any (relatively simple) solution that puts running application windows at the existing top bar.
Comment: Actually, I tried dash to panel and it allowed me to do exactly what I wanted to do! It lets me disable favorited apps from it, and it allows me to keep my dash to dock panel on the bottom. Here is a screenshot https://imgur.com/HyU9jca  my bottom panel has intelihide enabled so it hides when windows try to occupy it's space.

Show open windows on top panel


Avoiding duplicates in the stored procedures in snowflake

Question: I have written a stored procedure to insert values into the table. But when I called the stored procedure twice, the duplicate values are being inserted into the table. How to avoid duplication of values in stored procedure.
Here is my stored procedure:
CREATE OR REPLACE PROCEDURE get_columns(TABLE_NAME VARCHAR)
RETURNS ARRAY
LANGUAGE JAVASCRIPT
AS
$$
var stmt = snowflake.createStatement({
    sqlText: "SELECT * FROM " + TABLE_NAME + " LIMIT 1;",
});
stmt.execute();

var cols=[];
for (i = 1; i <= stmt.getColumnCount(); i++) {
  INSERT INTO TABLE1 (Col_Name) VALUES ('+"stmt.getColumnName(i)"+');  //DUPLICATE VALUES
}
return cols
$$;

Edit:
I'm retrieving the column names of a Col_table say (Col1, Col2, Col3) and I want these column names into TABLE1.
I called the procedure call get_columns(Col_table) and the column names are inserted into TABLE1.
When I again call the procedure call get_columns(Col_table), TABLE1 will have duplicate values as (Col1, Col2, Col3, Col1, Col2, Col3). I want to avoid duplication either by using merge or update or if any other method.
Comment: Can you give us sample input and end result? What's the goal of the procedure `get_columns`?
Comment: @FelipeHoffa Can you please look at my edit
Comment: Do you know the number of columns in advance ? Is there a valid identifier to check if a record is unique ?
Comment: @Sujitmohanty30 I don't know number of columns in advance. There is no valid identifier to check if a record is unique. I want to avoid duplication while inserting.
Comment: @R0bert I answered based on the desire to have the insert happen only once. But your goal is to call this method multiple times on different tables and have only the different column names?
Comment: FWIW, the code above won't run, as you can't just call `INSERT INTO TABLE1` in the middle of JavaScript code
Comment: @FelipeHoffa I forgot to add the code " var sql_command =INSERT INTO TABLE1 (Col_Name) VALUES ('+"stmt.getColumnName(i)"+')";
                snowflake.execute({sqlText: sql_command});
             }"
Answer: Based on the edited question and comments:

"When I again call the procedure [...], TABLE1 will have duplicate values [...]. I want to avoid duplication either by using merge or update or if any other method"

"The INSERT OVERWRITE is replacing the rows of the table when I called the procedure on two different table columns"

Then, if you don't want to insert repeated values into an existing table, you can do something like this:
INSERT INTO TABLE1(Col_Name)
SELECT *
FROM (SELECT 'i' x)
WHERE x NOT IN (SELECT Col_Name FROM TABLE1);

Replace that SQL code inside your procedure, and you won't see repeated values. Replace 'i' for the value you want to insert.
(as a general comment: I'm not sure the procedure in the question is the most effective solution to the overall stated problem, but this will fix the specific problem of having duplicate rows)
Comment: I don't want to overwrite the contents into the table but before appending to the destination table , I want to check if the row with same values exists .. If that row doesn't exist then I want to insert into table else not.
Comment: The `INSERT OVERWRITE` is replacing the rows of the table when I called the procedure on two different table columns
Comment: Thanks for the answer but I wonder if there is any optimized method to solve this because if a table contains some millions of rows then it would take so long to compute
Comment: Wondering: Why would you expect a table with millions of rows for a case like this - are you somehow going to have millions of different table column names?


Laravel Passport Vue components do not be published in the correct path

Question: According to Frontend Quickstart official documentation of laravel-5.7. I run the command:
php artisan vendor:publish --tag=passport-components

I have no any error messages, it returns:

Copied Directory
[/vendor/laravel/passport/resources/assets/js/components] To
  [/resources/assets/js/components/passport]
Publishing complete.

So, it does not copied to resources/js/components like the documentation stated:

The published components will be placed in your
  resources/js/components directory.

I don't know why does it published in different path other than specified in the documentation? and how could I solve this issue?
Answer: In 5.7 the resources/assets/js directory became resources/js which has been causing issues.
There is an open issue about this on the passport github page: https://github.com/laravel/passport/issues/829


How to get list of user in a particular role?

Question: How to get list of user in a particular role in ASP.net MVC5. I have following code but it returns all the user.
 public ActionResult Index()
  {
        var users = Context.Users.ToList();
        return View(users);
  }

I have role name "Coordinator". I just want all the users with that role.
//View File
@model IEnumerable<Microsoft.AspNet.Identity.EntityFramework.IdentityUser>
@{
    ViewBag.Title = "Index";
}

Roles Listing

Username | Email

    @foreach (var user in Model)
    {

            @user.UserName   |   @user.Email | @Html.ActionLink("Delete", "Delete", new { id = user.Id })

    }

Answer: Assuming each user instance is of type ApplicationUser, and that you implemented Role Based authentication, you can easily filter user with specific roles like so:
public ActionResult Index()
{
        // Assuming that Coordinator has RoleId of 3
        var users = Context.Users.Where(x=>x.Roles.Any(y=>y.RoleId == 3)).ToList();
        return View(users);
}

Comment: Getting Following Error 'Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole' does not contain a definition for 'RoleName' and no extension method 'RoleName' accepting a first argument of type 'Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole' could be found (are you missing a using directive or an assembly reference?)
Comment: see edit. You will need to find out the role id for coordinator.
Comment: Use the Role Manager, see this SO answer:
http://stackoverflow.com/a/22212506/260079
Answer: First create ApplicationRoleManager class to manage roles like below.
    public class ApplicationRoleManager : RoleManager<IdentityRole, string>
    {
        public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
            : base(roleStore)
        {
        }

        public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
        {
            return new ApplicationRoleManager(new RoleStore<IdentityRole, string, IdentityUserRole>(context.Get<ApplicationDbContext>()));
        }
    }

Then add following code to Startup.Auth.cs class in order to create instance of RoleManager during owin start up.
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

Your controller action should be like this.
  public ActionResult Index()
  {
        var roleManager = HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        var users = roleManager.FindByName("Coordinator").Users;

        return View(users);
  }

Hope this helps.


Is it possible to cancel an uplift project?

Question: I started an uplift project but picked the wrong traits for the species. Is it possible to change the traits or cancel the project and choose different ones?
Comment: Is there not a "Cancel" option in the log?
Answer: If you click the "Cancel" button in the situation log, the project will "time out" after 90 days, and the genetic modification points get refunded.
At that point you can start a new project with the traits you want.


Output text only there is no child node with a particular value

Question: I'm receiving XML like the following from a web service call and want to output the text of a message, only if it does not have a PRIVATE label.
<MessageStore>
   <MessageDetails>
      <Text>Message1</Text>
      <Labels>
         PRIVATE
      </Labels>
   </MessageDetails>

   <MessageDetails>
       <Text>Message2</Text>
       <Labels>
         PRIVATE
       </Labels>
    </MessageDetails>

      <MessageDetails>
      <Text>Message3</Text>
      <Labels>
         PRIVATE
         PUBLIC
      </Labels>
   </MessageDetails>

  <MessageDetails>
      <Text>Message4</Text>
      <Labels>
         PUBLIC
         PRIVATE
      </Labels>
   </MessageDetails>

   <MessageDetails>
      <Text>Message5</Text>
      <Labels>
         PUBLIC
      </Labels>
   </MessageDetails>
</MessageStore>

I've tried the following XSLT, but if a message has both private + public labels, its text is still outputted. E.g. "Message3 Message4 Message5". What I want is only "Message 5".
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="MessageDetails">

        <xsl:if test="Labels/Label[not(contains(text(), 'PRIVATE'))]">
            <xsl:value-of select="Text" />
        </xsl:if>

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

Answer: The following XPath (in your xsl:if element) should work:
not(Labels/Label = 'PRIVATE')

Comment: Your test `Labels/Label[not(contains(text(), 'PRIVATE'))]` is true if there is at least one `Label` that does not contain `PRIVATE`. Thus if there is a `MessageDetail` which has several `Label` grandchildren where one does not contain the string `PRIVATE` but another does then your test is true. `not(Labels/Label = 'PRIVATE')` on the other hand tests that there is no `Label` at all which has the contents `PRIVATE`.
Comment: Does exactly what it says on the tin!
Comment: Though I'm not entirely sure why that works and mine doesn't. Could you please explain?


SQL Data Duplication

Question:
sql query
SELECT `user`.`email`,
    `user`.`passwrd`,
    `user`.`status`,
    `useraccounts`.`Balance`,
    `useraccounts`.`AccountID`, `accounts`.`AccountNo`,
    wallet.Server_typ,wallet.DateBought,
    wallet.LastDate,
    wallet.Profit,
    withdraws.walletAdrs,
    withdraws.Amount,
    withdraws.status AS WDStatus,
    withdraws.message,
    withdraws.Date
FROM `user`
LEFT JOIN `useraccounts` ON `user`.`email` = `useraccounts`.`email`
LEFT JOIN `accounts` ON `accounts`.`AccountID` = `useraccounts`.`AccountID`
LEFT JOIN wallet ON user.email = wallet.email
LEFT JOIN withdraws ON user.email = withdraws.email
WHERE user.type = 'user'

This is my query, it works fine but there are many records against an email address. Because of this, my email gets duplicate. whenever i call just email duplicate records come. I just want one email.thanks in advance
Answer: SELECT DISTINCT `user`.`email`, `user`.`passwrd`, `user`.`status`,`useraccounts`.`Balance`, `useraccounts`.`AccountID`, `accounts`.`AccountNo`,wallet.Server_typ,wallet.DateBought,wallet.LastDate,wallet.Profit,withdraws.walletAdrs,withdraws.Amount,withdraws.status AS WDStatus, withdraws.message, withdraws.Date
FROM `user`
LEFT JOIN `useraccounts` ON `user`.`email` = `useraccounts`.`email`
LEFT JOIN `accounts` ON `accounts`.`AccountID` = `useraccounts`.`AccountID`
LEFT JOIN wallet ON user.email = wallet.email
LEFT JOIN withdraws ON user.email = withdraws.email
WHERE user.type = 'user'

Using DISTINCT will provide only distinct records.
Comment: it is still displaying duplicate emails
Comment: You get the distinct of each value in that select.
So if you only want distinct by email, wrap that variable with the distinct.
Read about it here:
http://www.sqlservertutorial.net/sql-server-basics/sql-server-select-distinct/

SQL Data Duplication


write new boundary conditions to a system of ODEs

Question: Suppose we have the following system of equations:
\begin{cases}
\ddot x_1 = f(x_1, x_2) \\
\ddot x_2 = g(x_1, x_2) \\
x_1(0) = \alpha \\
x_2(0) = \beta \\
\dot x_1(0) = \gamma \\
\dot x_2(0) = \delta
\end{cases}
where all the derivatives are made in a time variable $t$.
Since I would like to work with a system of first order equations, I would go like this:
\begin{cases}
\dot x_1 = x_3 \\
\dot x_3 = f(x_1, x_2, x_3, x_4) \\
\dot x_2 = x_4 \\
\dot x_4 = g(x_1, x_2, x_3, x_4)
\end{cases}

How can I apply the starting conditions at time $t=0$ at the new system?

I know this is a silly question but I'm loosing my mind with this problem..
Comment: Yes, that was helpful. Thank you.
Answer: Your approach doesn't make much sense to me. How can the functions $f$ and $g$ depend on 2 variables, but after that, they depend on 4?
I am not used to this kind of ODE notation, but seems to me, after you have introduced the variables $x_3=\dot x_1$ and $x_4=\dot x_2$, you just have to keep it consistent. Don't extend the functions $f$ and $g$ and just do simple symbolic substitution to the initial values and you should be fine.
Comment: Well, since for example $x_3$ is the derivative of $x_1$, if the function $f$ at the beginning had some terms in $\dot x_1$ inside its definition, now it has became $f(x_1, x_2, x_3)$..
I don't know if I made the concept clear..
Comment: I don't think that is possible, however, it might be because I don't understand something about the notation. Even so, a function is a function, once defined for 2 variables, that is it, it cannot change the number of variables like that. Even if the function $f$ were to be a function of functions (which again, I really don't think it is). Usually what $f'=F(f)$ stands for is $$\forall t\in\mathbb{R}:f'(t)=F(f(t))$$ and not that $F$ is a mapping between function spaces.
So in your case $\ddot x_1=f(x_1,x_2)$ means $$\forall t\in\mathbb{R}:\ddot x_1(t)=f(x_1(t),x_2(t))$$
Comment: Okay, now I understand what you mean..


Docker checkpoint can't find crui after crui has been installed in WSL2

Question: I am attempting to use docker checkpoint in my Ubuntu 18 WSL2 environment on a container that was started with docker compose.
The command I am using is docker checkpoint create --checkpoint-dir=./states main-1 statename.
The error I get back is:
Error response from daemon: Cannot checkpoint container main-1: runc did not terminate successfully: exit status 1: CRIU version check failed: exec: "criu": executable file not found in $PATH path= /var/run/desktop-containerd/daemon/io.containerd.runtime.v2.task/moby/fc9b7b3a00b6208753653f31250fb48af8500d22c7889173e7b3276070b7ce30/criu-dump.log: unknown

I installed criu into my WSL using these commands:
 sudo add-apt-repository ppa:criu/ppa
 sudo apt-get update
 sudo apt-get install criu

I know that criu is installed because I can run the executable:
service@laptop1: ~/$ criu

Usage:
  criu dump|pre-dump -t PID [<options>]
  criu restore [<options>]
  criu check [--feature FEAT]
  criu page-server
  criu service [<options>]
  criu dedup
  criu lazy-pages -D DIR [<options>]

Commands:
  dump           checkpoint a process/tree identified by pid
  pre-dump       pre-dump task(s) minimizing their frozen time
  restore        restore a process/tree
  check          checks whether the kernel support is up-to-date
  page-server    launch page server
  service        launch service
  dedup          remove duplicates in memory dump
  cpuinfo dump   writes cpu information into image file
  cpuinfo check  validates cpu information read from image file

Try -h|--help for more info

Output of which criu:
/usr/sbin/criu
I have also made sure that I have enabled experimental features for docker.
Please let me know if theres anymore info I can provide. Thanks!
I also uninstalled and reinstalled criu and got the same result
Answer: This was due to not running criu as root sudo criu


Select Printer Of Web User Using Java Applet

Question: I've been searching a solution for changing the default printer from a java applet (and more) without success.
What I need is to print with javascript's method print(), that prints only in default printer, so, before this, change the default printer to the target printer.
Is this possible? Is there any library to do something like "setDefaultPrinter" or similar?
NOTE: I am trying to print HTML page, rendered as the user sees it in the browser.
Comment: @Andrew
I mean print html page what users see
Comment: *"I've tried to print with Print Service API, but doesn´t work for me because i need to print html code"* Huh?  1) Which 'Print Service API' specifically? Link to the docs. 2) *"print html code"* a) HTML is not code, but mark-up. b) What DYM by *'print **html'***?  Print it rendered as the user might see it in a browser - rendered nicely, or print the raw text (along with the mark-up, styles and JS) that makes the HTML document?
Comment: And the links to the 'print service' you refer to?
Comment: @AndrewThompson Jquery Print Element
Comment: @AndrewThompson you only interested in saying huh ???
Answer: Quoted from In Java how do I change or set a default printer
Try this
<code>PrinterJob pjob = PrinterJob.getPrinterJob();
        PageFormat pf = pjob.defaultPage();
        pjob.setPrintable(null, pf);

        if (pjob.printDialog()) {
          pjob.print();
        }
</code>


Where is this function differentiable?

Question: I'm doing homework and I am not sure how to check where this function is differentiable:
$$ \sum_{n=1}^\infty \frac{1}{x^2+n^2} $$
$$ x \in \mathbb{R}$$
I also don't really know what definitions I need to use. Since my studies is completely online, I lost track of all the material. Could you help me a bit?
Comment: perhaps this will help https://math.stackexchange.com/questions/2312130/proving-an-infinite-series-is-differentiable
Comment: So I need to find the first derivative?
Which leads me to $$ \frac{-2x}{(x^2+n^2)^2} $$

but how do I continue?
Answer: We will use the derivation under sum theorem
Let $$  f_n(x) \triangleq \dfrac{1}{x^2+n^2} $$

You serie converges pointwise at $x=0$.

The derivative of $f_n$ exists and is
$  f_n'(x) \triangleq \dfrac{-2x}{(x^2+n^2)^2} $

Let $K$ a compact of $\mathbb{R}-]0,1[$.
You have $ |f_n'(x)|= \left|\dfrac{-2x}{(x^2+n^2)^2}\right|\leq \left|\dfrac{-2x}{2x^2n^2}\right|\leq_K \dfrac{1}{\min(K)n^2} $
So $\sum f_n'$ converges uniformaly on such  $K$

On $[0,1]$
$$|f_n'(x)| \leq \dfrac{1}{n^2}$$
So it converges absolutely on whole $\mathbb{R}$

Conclusion
$$S\triangleq\sum f_n$$ is differentiable on $\mathbb{R}$
$$ S' \triangleq\sum f_n' $$

Where is this function differentiable?


Can a dishwasher and disposer be on the same 20 ampere circuit?

Question: I am in the process of rewiring kitchen in a 1925 era farmhouse removing knob and tube. Have new 100 amp service and will soon pull 12/2 cu thhn to power .kitchen sink garbage disposer and dishwasher. Am considering placing these two applicances on one/same 20 amp gfci circuit. Would appreciate any thoughts as to propriety of doing so. Do these items need seperate circuits? Is it desireable to have these on own circuit or is that unnecessary. Thank you
Answer: In a kitchen there are a minimum of 2 20 amp circuits required. Where I live a dedicated circuit is required for dishwashers, Most of the houses I have wired have 4 branch circuits or 5. I usually put the fridge on its own circuit, a microwave and the disposal on Thier own circuit, if there is a trash compactor the disposal and compactor. In some cases where a 120 outlet is needed for a gas stove or cooktop I will put that on the same as the microwave. There is not a code requirement for this many circuit but the permits only cost a couple dollars per breaker and a few extra feet of wire. I have had to upgrade quite a few kitchens over the years and only one I installed as the owner was pinching pennies and it cost him almost 3k to do what my proposal was at a 400$ savings up front.


Is there a desktop application for launchpad.net?

Question: I was looking at the Launchpad.net and came to this page (see the screenshot below). I started wondering if there are any desktop applications for using Launchpad.net without the necessity of a web browser.

Are there any?
Answer: This is commonly used for a number of command-line tools, such as those in the ubuntu-dev-tools package,
There is also a desktop client called Ground Control . which mostly focuses on bugs & branches.
Also under development is a Unity Lens which currently can search people, packages & bugs by number. This doesn't use the Launchpad credentials in the screenshot, but the anonymous access.
Comment: It's not overly usable, but is in https://launchpad.net/~ajmitch/+archive/unity-lenses if you feel like trying it out. I haven't spent much time working on it lately though.
Comment: That lens looks interesting, but it has only 9 bzr revisions and no packages for download yet. Do you know how stable/usable it is if you compile it from source at this point?
Answer: There is a list of programs that use the Launchpad API.
It contains desktop applications (eg. Bughugger), but I could not find a mention for a full-blown desktop client.
Comment: Cool, I didn't know there was an actual list maintained. And as it says, any of those programs could serve as examples to help others learn to write more.
Answer: Yes. It's called Ground Control .


Highcharts giving an extra legend when I get data dynamically from Highcharts

Question: I need to create highcharts series dynamically...So I used addSeries,But I am gettng an extra legend. If you have any other methods pls let me know...
I am not including my total chart code....I am jst placing my series in chart...
<code>            $(function () {
                chart = Highcharts.chart('container', {
                    series: [
                        {
                        }
                    ]

                });
            });

json:
    "dataa":
    [
        {
            "name": "Unit Test 1",
            "data":[1,13,15,17,40,50,80]
        },
        {
            "name": "Unit Test 2",
            "data":[2,20,50,40,20,50,15]
        },
        {
            "name": "Unit Test 3",
            "data":[3,50,40,10,30,40,25]
        }
    ]

ajax:
 let dataeDatal=datae.dataa.length;
            for (let i = 0; i < dataeDatal; i++) {
                chart.addSeries({
                    data: datae.dataa[i].data,
                    name: datae.dataa[i].name
                });
            }
        }
</code>

You can check in the image, I am getting an extra series1 legend
Answer: you should initialize your charts as
<code>chart = Highcharts.chart('container', {
  series: []  //should be empty array
});
</code>
fiddle demo


Redstone Producer/Receiver

Question: In Minecraft Pocket Edition, there was recently a new update including basic redstone contraptions. I have experimented around, but I can't find:

What a Tripwire Hook does, and how it produces redstone currents,
What a Note Block is, and where it is in Inventory
What an Activator Rail is used for, and
How Levers work

I know that you touch the lever and it works like a lightswitch, but does it produce its own current like this: =/--() or does it need to process current like this: []---=/---() ([] is producer, - is wire, =/ is lever, () is receiver)

Thank you for the help!
Answer: Assuming they work the same way on pocket as they do on PC:
A pair of Tripwire Hooks need to be used with String in your hand to set it up, then if someone walks over the string it'll produce redstone current.  They can also be used to craft Trapped Chests if those are on Pocket yet, which produce redstone current when opened.
The Note Block can be customized to produce notes of different pitches and plays the note when the incoming current switches from off to on. To place the note block in creative mode, it's on the third tab (the one with the bookshelf), and it's the second item on the 4th row in (I have 18 items in a row). It looks like it's a box with a brown and black checkerboard on it.
Levers produce their own redstone current when on, and don't need an exterior power source.
An Activator Rail modifies the function of minecarts driven over it.
Comment: @OldBunny2800 I edited the item to note where in the creative inventory the note block is located.
Comment: Will accept in 2 mintes. Do you know where in Inventory the note block is?

Redstone Producer/Receiver


Ubuntu not respecting custom keymap

Question: I have modified my keymap for dvorak in the file /usr/share/X11/xkb/symbols/us, but it does not load properly, even after multiple reboots. Suggestions?
EDIT: A partial solution I have found is overwrite a language that I haven't ever used. This leads me to believe that Ubuntu puts a temporary us map file somewhere that it pulls from, as I didn't even have to restart X to get it to work.
Answer: See answer of Zaz at https://askubuntu.com/a/12301/82618
Essentially, you need to append the variant list in /usr/share/X11/xkb/rules/evdev.xml. Doing so worked for me at least on Kubuntu 13.04 but is likely to work on Ubuntu, too.

Ubuntu not respecting custom keymap


Atmel SAM3X dual bank switching not working

Question: I'm currently working with an Atmel SAM3X8 ARM microcontroller that features a dual banked 2 x 256KB flash memory. I'm trying to implement a firmware update feature, that puts the new firmware into the currently unused flash bank, and when done swaps the banks using the flash remapping to run the new firmware.
The datasheet states to do so I need to set the GPNVM2 bit, then the MCU will remap the memory, so Flash 1 is now at 0x80000 and Flash 0 at 0xC0000. This will also lead to the MCU executing code beginning from Flash 1.
To cite the datasheet:

The GPNVM2 is used only to swap the Flash 0 and Flash 1. If GPNVM2 is ENABLE, the Flash 1 is mapped at
  address 0x0008_0000 (Flash 1 and Flash 0 are continuous). If GPNVM2 is DISABLE, the Flash 0 is mapped at
  address 0x0008_0000 (Flash 0 and Flash 1 are continuous).
[...]
GPNVM2 enables to select if Flash 0 or Flash 1 is used for the boot.
  Setting GPNVM bit 2 selects the boot from Flash 1, clearing it selects the boot from Flash 0.

But when I set GPNVM2, either via SAM-BA or my own firmware using flash_set_gpnvm(2) (ASF SAM Flash Service API), it will still boot from the program in Flash 0, and the new program will still reside at Flash 1's offset 0xC0000. The state of GPNVM2 has been verified by flash_is_gpnvm_set(2)
Flashing the firmware itself to Flash1 bank works flawlessly, that has been verified by dumping the whole flash memory with SAM-BA.
There is an errata from Atmel about an issue, that the flash remapping only works for portions smaller than 64KB. My code is less than that (40KB), so this shouldn't be an issue.
I've not found any other people having this issue, nor any example how to use it, so maybe somebody could tell me if I'm doing something wrong here, or what else to check.
Comment: you are not running code from one flash when switching to the other are you?  you are using a trampoline in ram to bounce between them?
Comment: I did reset the controller after setting / clearing the GPNVM2 bit to force it running the new code (both software reset and power off tried). Anyway, I think the remapping is only done during boot, so changing the register will only have effect after restarting
Comment: I agree what what you see in the datasheet, if you  are indeed reading back the GPNVM bits and see bit 2 set but 0x0000 is not mapped to the second bank then maybe its time to contact Atmel/Microchip
Answer: I had the same issue (see here: Atmel SAM3X8E dual bank switching for booting different behaviour).
After some more research I found an Application Note (Link: http://ww1.microchip.com/downloads/en/AppNotes/Atmel-42141-SAM-AT02333-Safe-and-Secure-Bootloader-Implementation-for-SAM3-4_Application-Note.pdf) which explains the boot behaviour of the SAM3X in a more clear way. The problem is that the datasheet is a bit misleading (at least I was confused too). The SAM3X has no ability to remap the the Flash banks. The booting behaviour is a bit different (see the picture in the link, it's a snipped from the Application note, page 33/34):
Booting behaviour SAM3X
Picture 3-9 shows the SAM3X's behaviour at the boot-up. The GPNVM bits 1 and 2 just determine which memory section (ROM/Flash0/Flash1) is mirrored to the boot memory (located at 0x00000000). The mapping of the Flash banks is not changed. Therefore Flash0 still is mapped to 0x00080000 and Flash1 to 0x000C0000).
As the Application Note states some other Atmel microcontrollers are able to really remap the Flash banks (e.g. SAM3SD8 and SAM4SD32/16). These processors change the location of the Flash banks as you can see in picture 3-10.
To be able to update your firmware it is therefore necessary to implement some kind of bootloader. I implemented one by myself and was able to update my firmware even without using the GPNVM bits at all. I also opend a support ticket at Microchip to clarify the booting behaviour. When I receive an answer I hope to tell you more.
EDIT:
Here's the answer from the Microchip support:

Setting the GPNVM2 bit in SAM3X will merely make the CPU 'jump to' or start from flash bank 1 i.e. 0xC0000.
  No actual swap of memory addresses will take place.
To use flash bank 1, you will need to change the linker file (flash.ld) to reflect the flash start address 0xC0000.
For flash bank 0 application, change:
  rom (rx) : ORIGIN = 0x00080000, LENGTH = 0x00080000 /* Flash, 512K /
  to:
  rom (rx) : ORIGIN = 0x00080000, LENGTH = 0x00040000 / Flash, 256K */
For flash bank 1 application, change:
  rom (rx) : ORIGIN = 0x00080000, LENGTH = 0x00080000 /* Flash, 512K /
  to:
  rom (rx) : ORIGIN = 0x000C0000, LENGTH = 0x00040000 / Flash, 256K */
If this is not done, the reset handler in the flash 1 application will point to an address in the flash 0 application.
  So, although code will start execution in flash 1 (if GPNVM2 is set), it will jump back to the flash 0 application.
  The errata stating the 64kb limitation can be ignored.

Therefore the Application Note is right and no actual change of the mmory mapping is performed.
Cheers
Lukas
Comment: Thanks @Lukas for the clarification, and for the info from Microchip. Meanwhile, I have implemented it entirely in software, so don't use the bank switching neither.


How do I chop the first 20 seconds off every video in a folder?

Question: I guess there's an ffmpeg command that would do this.
I have a folder full of a bunch of videos that have an unnecessary 20 second plate at the start.
I don't want to re-encode them or change anything else, just chop off that intro.
Comment: https://superuser.com/a/269960/334516 and loop over the files?
Answer: mkdir output
for f in *.mp4; do ffmpeg -i "$f" -ss 20 -map 0 -c copy "output/$f"; done

This will need to cut on a keyframe for non intra-frame formats (most "consumer" videos these days are non-intra), so it may not cut at exactly 20 seconds.
If your inputs are intra (such as DV), or if you know a keyframe is at or near 20 seconds then move -ss before the -i and it will process somewhat faster.
If you must cut exactly at 20 seconds then you'll need to re-encode: remove the -c copy, but again, it's format dependent if you'll need to do that.
Comment: Thanks! _ffmpeg -ss 20 -i "INPUT" -map 0 -c copy "OUTPUT"_ is the version that worked for me


Generate list of numbers

Question: Hi I want to Generate list of numbers from 1000000 to 2000000 but the problem is that I get an error memory error I was using random everything was good only I get dublcated number and I cant have duplcated number so i switched to xrange
data = []
total = 2000000
def resource_file(info):
    with open(info, "r") as data_file:
        reader = csv_reader(data_file, delimiter=",")
        for row in reader:
            try:
                for i in xrange(1000000,total):
                    new_row = [row[0], row[1], i]
                    data.append(new_row)
            except IndexError as error:
                print(error)
    with open(work_dir + "new_data.csv", "w") as new_data:
        writer = csv_writer(new_data, delimiter=",")
        for new_row in data:
            writer.writerow(new_row)

Comment: You're trying to store the whole thing in memory before writing any of it out.  You could use less memory by only processing one row at a time, rather than trying to store the entire file in memory.
Comment: Are you sure you want to create 1000000 times more elements than there are in the input CSV file? What is the desired outcome? Can you give an small example of the CSV file, and what you expect the resulting CSV file to look like?
Comment: I want to add a number for every line in the csv file in row number 2
Answer: Repeat every line with an extra column ranging 1M..2M
The problem is that you store all these configurations in memory first. First of Python has not a very efficient memory model, and furthermore one million entries per row is quite large anyway.
I propose to not store the data in a list, but simply write these to the file immediately:
total = 2000000
def resource_file(info):
    with open(info, "r") as data_file:
        reader = csv_reader(data_file, delimiter=",")
        with open(work_dir + "new_data.csv", "w") as new_data:
            writer = csv_writer(new_data, delimiter=",")
            for row in reader:
                rowa, rowb = row[0:2]
                for data in xrange(1000000,total):
                    writer.writerow([rowa,rowb,data])

Take rows 1M-2M of the file
In case you want to take lines 1M to 2M of the original file, you can write it as:
from itertools import islice

total = 2000000
def resource_file(info):
    with open(info, "r") as data_file:
        reader = csv_reader(data_file, delimiter=",")
        with open(work_dir + "new_data.csv", "w") as new_data:
            writer = csv_writer(new_data, delimiter=",")
            for row in islice(reader,1000000,total):
                writer.writerow(row)

or you can simplify it, like @JonClemens says, with:
from itertools import islice

total = 2000000
def resource_file(info):
    with open(info, "r") as data_file:
        reader = csv_reader(data_file, delimiter=",")
        with open(work_dir + "new_data.csv", "w") as new_data:
            writer = csv_writer(new_data, delimiter=",")
            writer.writerows(islice(reader,1000000,total))
Comment: but i think in this way rowa, rowb will be outside the loop right
Comment: yes but every line in the info file will be looped =  the amount of the total 2000000
Comment: @Mike: so you only want lines 1M-2M of the original file then? What is `data` doing here? A loop counter?
Comment: data is  what number the range start and where its end  as you can see now  every line is looping 2000000 ['fjc7kr1m92su8eljhb11484kwz.net', 'post dga (malware)', 1032067]
['fjc7kr1m92su8eljhb11484kwz.net', 'post dga (malware)', 1032068]
['fjc7kr1m92su8eljhb11484kwz.net', 'post dga (malware)', 1032069]
['fjc7kr1m92su8eljhb11484kwz.net', 'post dga (malware)', 1032070]
['fjc7kr1m92su8eljhb11484kwz.net', 'post dga (malware)', 1032071]
Comment: @Mike: then there is no reason to write such range function. See edit, second solution.
Comment: If you're not doing much else... `writer.writerows(islice(reader, 1000000, total))` covers it

Generate list of numbers


Door will no longer latch when closed

Question: I have an older home built circa 1977 and one of the bedroom doors now will not stay closed.  Meaning, if I go to close it, the door does not lay flat against the frame, and the door tongue will not go into the grove of the door so it can be latched.  The door is not bowed, nor is the frame broken or cracked.  What is causing the door not to close flushly and how do I remedy?
Comment: The house settled and the latch needs some adjustment.  It's really not too uncommon.  It sounds like you might need to find a friend familiar with household repairs to lend a hand.
Comment: @Tyson - will do.  Was not sure if it was a major issue or something small.  Will look for a "handyman" of sorts in my area to try the repair.
Comment: Sometimes it's simpler than other times, just depends how out of alignment it's become.  It sounds like your door closes correctly but just doesn't quite latch.
Comment: If I push the door all the way, everything aligns as it should.  But it does not "catch" it just springs back open a small amount.
Answer: I experienced this at a previous property of mine.  I found the easiest thing ended up being adjusting the latch.  Unscrew the metal plate and use a small sharp chisel to carve out the required area (and maybe a large drill bit if the actual recess needs expanding more than a millimetre or two).  Any gaps can be filled with wood filler after the fact.
If the case is that the door fails to easily sit flush in the frame then you may want to adjust the hinges (usually by digging out the hinge recess in the frame a little more) to see if that stops the "bounce"
Answer: Depending on the situation you may be able to move the hinges in or out (toward or away from the jamb stop), as well as the strike plate on thee jamb. Far easier than moving the entire jamb for a small adjustment.

Door will no longer latch when closed


Alphabetical word sorting in a sentence (C language)

Question: I am a newbie and this question might sound dumb but, can anyone please explain how does the code(below) actually works? I've tried doing dry runs but I can't seem to understand the algorithm. Thanks alot.
INPUT:

welcome to sanfoundry's c programming class, welcome to c class again

OUTPUT:

again c c class class programming sanfoundry's to to welcome welcome

<code>#include<stdio.h>
#include<string.h>

void main()
{

    int count = 0, c = 0, i, j = 0, k, l, space = 0;
    char str[100], p[50][100], str1[20], ptr1[50][100], cmp[50];

    printf("Enter the string\n");
    scanf(" %[^\n]s", str);
    for (i = 0;i < strlen(str);i++)
    {
        if ((str[i] == ' ')||(str[i] == ', ')||(str[i] == '.'))
        {
            space++;
        }
    }
    for (i = 0, j = 0, k = 0;j < strlen(str);j++)
    {
        if ((str[j] == ' ')||(str[j] == 44)||(str[j] == 46))
        {
            p[i][k] = '\0';
            i++;
            k = 0;
        }
        else
             p[i][k++] = str[j];
    }
    for (i = 0;i < space;i++)    //loop for sorting
    {
        for (j = i + 1;j <= space;j++)
        {
            if ((strcmp(p[i], p[j]) > 0))
            {
                strcpy(cmp, p[i]);
                strcpy(p[i], p[j]);
                strcpy(p[j], cmp);
            }
        }
    }
    printf("After sorting string is \n");
    for (i = 0;i <= space;i++)
    {
        printf("%s ", p[i]);
    }
}
</code>
Comment: yeah I just noticed that , I copied the code from a website so didn't really proofcheck.
Answer: The code is indeed a bit ugly.
There are unused variables; integer values used instead of chars for no reason; the first for cycle can be merged with the second; does it really come from a textbook?
Anyway...
What it does is splitting the string into substrings separated by spaces or comma or point.
After the substrings are copied into the p vector the vector is sorted using bubble-sort.
(If you are studying the sorting algorithms just start with sorting numbers instead of string)
Comment: Its actually from a website , not a textbook. And thank you.


Excel: Dropdown list dependant on other dropdown list

Question: I want the following in Excel:
Two dropdown lists in adjacent cells:
Dropdown list #1 | Dropdown list #1
Dropdown list 1:
One
Two
Three

If I select One in the first cell, the list in the second cell should contain these choices:
One:
1.1
1.2
1.3

If I select Two in the first cell, the list in the second cell should contain these choices:
Two:
2.1
2.2
2.3

And so on. There are a lot of tutorials around, but I'm having some hassle figuring out which of them addresses this exact question.
Update: An example. When selecting f.ex. Group 1 under the Group heading (col A), the entries listed under Group 1 to the right (col D) should appear under the Item heading (col B). And the same for the other Groups.
Answer: Update as promised:
When you're using a List for validation, you have to input a range as shown below.

The OFFSET function allows to to dynamically set a range based on its input criteria.
If you consider this:
=OFFSET(C1,0,0,1,1)

Argument 1 = Anchor cell
Argument 2 = Number of rows to move, you can use minus number here to move rows up and positive numbers to move down
Argument 3 = Number of columns to move. Negative is left, positive to the right.
Argument 4 = Height of the range (can't be negative and is optional, default is 1)
Argument 5 = Width of the range  (can't be negative and is optional, default is 1)

In this instance, the range returned would be C1 as we have no row or column offset and height and width is set to 1
The MATCH function will return an index of where a value appears in a range of cells (range must be either 1 cell wide or 1 cell high)

Based on the above screen print =MATCH("Group2",D1:F1,0) will return 2, as "Group2" appears in the second cell in the D1:F1 range. ("Group1" would return 1, "Group3" would return 3, and "Group4" would return #N/A as it doesn't exist).
So based on that we can put the MATCH function in as our 2nd argument in the OFFSET function, and pick the column that matches the first argument in the MATCH function.
=OFFSET(C1,0,MATCH("Group2",D1:F1,0),1,1) will return back range E1 as we've shifted the columns by 2 from C1 because of the MATCH
=OFFSET(C1,1,MATCH("Group2",D1:F1,0),3,1) will now return back E2:E4 as we've increased the height of the range to 3 and the row offset to 1.
And finally we can change the "Group2" value in the MATCH function to a cell value that will mean the range will dynamically change.
Here I've used Cell A2 =OFFSET(C1,1,MATCH(A2,D1:F1,0),3,1) so whatever value is in cell A2 will be used to offset the range.
And the last thing to do is to put the dynamic range into the validation (I used B2)

This will dynamically set the validation range.

When I'm using OFFSET function with multiple arguments and I'm not sure that it's returning back the right range, I wrote a small helper User Defined Function that I just put in a VBA module.
Public Function GetAddress(rng As Range) As String
GetAddress = rng.Address
End Function

This allows me to put the offset formula in and it will return back the range address. So I can make sure it's right.

There may be a built in function for this, but I've never found it.
Comment: +1. For even more details Contextures has a bunch of pages like [this one](http://www.contextures.com/xlDataVal02.html).
Comment: I'm unable to use this line: " =OFFSET(HD2,MATCH(HA2,HD2:HD5,0)-1,0,1,4)" without getting the usual "Your formula contains an error" message. And that's after removing the H's, since my columns are named "A", "B" etc. and not "HA", "HB" etc.
Comment: @kakemonsteret if you update your original post with cell addresses your lists are in, i'll amend my screenprints to match..
Comment: I've updated the post with an exmaple. I don't mean to be difficult here, but I feel I'm missing something all the way when I try to follow the tutorials. The one at contextures, for example, looks fine but it doesn't work for me, and looking at it I really don't understand how it COULD work.
Comment: @kakemonsteret It's ok.. I'll try to add some more information about how it works..  Give me 30 minutes and I'll update my post.
Comment: Relax - I'm not in that much of a hurry :-) I appreciate your help. though :-)
Comment: @kakemonsteret I've updated my answer with some steps on how it works. Please let me know if anything isn't clear.
Comment: Great - I'll have a look at it :-)
Comment: Sorry, I just don't get it. All the lines you're posting, =MATCH and =OFFSET, give "Formula error" wherever I try to insert them. I might just be thick, of course.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/41134/discussion-between-sam-and-kakemonsteret)
Answer: This solution avoids the use of the volatile OFFSET function.
For the first Data Validation located at A2 use this formula:
=$D$1:$F$1

For the second Data Validation located at B2 use this formula:
= INDEX( $D$2:$F$4, 0, MATCH( $A$2, $D$1:$F$1, 0 ) )

The second formula uses the value selected from the data Validation in A2 to MATCH the corresponding column in D1:F1 and applies the column number to the INDEX function to return the whole column in range D2:F4.

The function INDEX( reference, row number, column number ) returns the entire column or row of the referenceby entering 0 as the row number or column number respectively.


How to get mshtml.IHTMLDocument6 or mshtml.IHTMLDocument7?

Question: I am using IE11 in Windows 7.
Then I added a reference in C# project c:\Windows\System32\mshtml.tld and try to get mshtml.IHTMLDocument6 or mshtml.IHTMLDocument7, but VS2013 doesn't see it.
I can only get mshtml.IHTMLDocument, mshtml.IHTMLDocument2 .. mshtml.IHTMLDocument5.
IHTMLDocument7 interface  https://msdn.microsoft.com/ru-ru/library/windows/hardware/ff975572
Answer: Select the MSHTML assembly reference, look at its Path property and you'll see the problem:

C:\WINDOWS\assembly\GAC\Microsoft.mshtml\7.0.3300.0__b03f5f7f11d50a3a\Microsoft.mshtml.dll

This is the PIA for the mshtml type library, installed on any programmer's machine that has VS installed.  Version 7.0.3300 is a version number from the .NET 1.0 era, it is 14 years old.  Predates IE11 of course, that's why it doesn't have the later interface types.  Using the PIA is never the wrong thing to do, it ensures that your program will run with any version of IE, all the way back to IE6.
But that's not what you want, you'll have to generate your own interop library from the IE11 type library.  Run the Visual Studio Command Prompt, navigate to your project directory and type this command:
  Tlbimp c:\windows\system32\mshtml.tlb /out:Interop.mshtml.dll

It will trundle for quite a while, it is a big one, and spit out several warnings about the PIA being present and several obscure methods and types that cannot be directly used from a .NET program.  You can ignore them, they didn't work in the PIA either.
You now have the Interop.mshtml.dll file in your project directory.  Back to VS, delete the old MSHTML reference and use Project > Add Reference > Browse to select the new one you just created.  Its "Embed Interop Types" property is True by default, no longer a need for a PIA at all and you don't have to deploy the file with your program.  Check the file into source control so you only have to do it once.
And be careful, your program can die with an E_NOINTERFACE exception when it runs on machine that doesn't have the required version of IE installed.  You can use the as operator to cast the document reference to IHtmlDocument7, it will be null if IE is old.


Grabbing output from exec

Question: I'm trying to write a C program that grabs command output and then i'll be passing that to another program.
I'm having an issue, I cant work out how to get the command output and store it.  Below is a sample of what I have
if(fork() == 0){
   execl("/bin/ls", "ls", "-1", (char *)0);
   /* do something with the output here */
}
else{
    //*other stuff goes here*
}

so basically im wondering if there is any way i can get the output from the "execl" and pass it to some thing else (e.g. via storing it in some kind of buffer).
Suggestions would be great.
Answer: You have to create a pipe from the parent process to the child, using pipe().
Then you must redirect standard ouput (STDOUT_FILENO) and error output (STDERR_FILENO) using dup or dup2 to the pipe, and in the parent process, read from the pipe.
It should work.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define die(e) do { fprintf(stderr, "%s\n", e); exit(EXIT_FAILURE); } while (0);

int main() {
  int link[2];
  pid_t pid;
  char foo[4096];

  if (pipe(link)==-1)
    die("pipe");

  if ((pid = fork()) == -1)
    die("fork");

  if(pid == 0) {

    dup2 (link[1], STDOUT_FILENO);
    close(link[0]);
    close(link[1]);
    execl("/bin/ls", "ls", "-1", (char *)0);
    die("execl");

  } else {

    close(link[1]);
    int nbytes = read(link[0], foo, sizeof(foo));
    printf("Output: (%.*s)\n", nbytes, foo);
    wait(NULL);

  }
  return 0;
}

Comment: Indeed fork might not be needed. But if you want to perform operations at the end of the chile task, you have to fork a new process. Wait ensures that parent's process don't quit bedore child.
Comment: Thanks heaps! the great example that shows how to read from it won it for you.
Comment: I found this explanation in my copy of [APUE](http://www.apuebook.com/), section 1.6: "In the child, we call `exec` to execute the command [...]. This replaces the child process with the new program file. The combination of `fork` followed by `exec` is called spawning a new process on some operating systems. In the UNIX System, the two parts are separated into individual functions."
Comment: Okay, all starting to make sense now. From the man page: "The `exec()` family of functions replaces the current process image with a new process image."
Comment: I can read the man pages on dup2, execl, etc, which explains the function calls, but I don't understand the overall picture. Can somebody elaborate why we need to fork? Why do we close the links when we do, and why the wait(NULL) at the end?
Answer: Open a pipe, and change stdout to match that pipe.
 #include <sys/types.h>
 #include <unistd.h>
 #include <stdio.h>
 #include <stdlib.h>

 int pipes[2];

 pipe(pipes); // Create the pipes

 dup2(pipes[1],1); // Set the pipe up to standard output

After that, anything which goes to stdout,(such as through printf), comes out pipe[0].
FILE *input = fdopen(pipes[0],"r");

Now you can read the output like a normal file descriptor. For more details, look at this
Comment: this is much clearer answer in my opinion, would deserve to be the top
Comment: Thanks great awnser, sorry you didnt get the win.
Answer: Thanks Jonathan Leffler, and i optimize the above code for it can't read all response for one time.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>

#define die(e) do { fprintf(stderr, "%s\n", e); exit(EXIT_FAILURE); } while (0);

int main() {
  int link[2];
  pid_t pid;
  char foo[4096 + 1];
  memset(foo, 0, 4096);

  if (pipe(link)==-1)
    die("pipe");

   if ((pid = fork()) == -1)
    die("fork");

  if(pid == 0) {

    dup2 (link[1], STDOUT_FILENO);
    close(link[0]);
    close(link[1]);
    execl("/bin/ls", "ls", "-1", (char *)0);
    die("execl");
  } else {
    close(link[1]);
    int nbytes = 0;
    std::string totalStr;
    while(0 != (nbytes = read(link[0], foo, sizeof(foo)))) {
        totalStr = totalStr + foo;
        printf("Output: (%.*s)\n", nbytes, foo);
        memset(foo, 0, 4096);
    }
    wait(NULL);
  }
  return 0;
}

Answer: If you want the output in a string (char *), here's an option (for Linux at least):
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <unistd.h>

char* qx(char** cmd, int inc_stderr) {
  int stdout_fds[2];
  pipe(stdout_fds);

  int stderr_fds[2];
  if (!inc_stderr) {
    pipe(stderr_fds);
  }

  const pid_t pid = fork();
  if (!pid) {
    close(stdout_fds[0]);
    dup2(stdout_fds[1], 1);
    if (inc_stderr) {
      dup2(stdout_fds[1], 2);
    }

    close(stdout_fds[1]);

    if (!inc_stderr) {
      close(stderr_fds[0]);
      dup2(stderr_fds[1], 2);
      close(stderr_fds[1]);
    }

    execvp(*cmd, cmd);
    exit(0);
  }

  close(stdout_fds[1]);

  const int buf_size = 4096;
  char* out = malloc(buf_size);
  int out_size = buf_size;
  int i = 0;
  do {
    const ssize_t r = read(stdout_fds[0], &out[i], buf_size);
    if (r > 0) {
      i += r;
    }

    if (out_size - i <= 4096) {
      out_size *= 2;
      out = realloc(out, out_size);
    }
  } while (errno == EAGAIN || errno == EINTR);

  close(stdout_fds[0]);

  if (!inc_stderr) {
    close(stderr_fds[1]);
    do {
      const ssize_t r = read(stderr_fds[0], &out[i], buf_size);

      if (r > 0) {
        i += r;
      }

      if (out_size - i <= 4096) {
        out_size *= 2;
        out = realloc(out, out_size);
      }

    } while (errno == EAGAIN || errno == EINTR);

    close(stderr_fds[0]);
  }

  int r, status;
  do {
    r = waitpid(pid, &status, 0);
  } while (r == -1 && errno == EINTR);

  out[i] = 0;

  return out;
}

int main() {
  char* argv[3];
  argv[0] = "ls";
  argv[1] = "-la";
  argv[2] = NULL;
  char* out = qx(argv, 0);
  printf("%s", out);
  free(out);
}

Grabbing output from exec


Optimization of Python comprehension expression

Question: I was trying to get the frequency of max value in an integer list (intlist)
intlist.count(max(intlist))

this works and is good in speed as well.
I wanted to implement the max method with comprehension,-
[x if x>y else y for x in intlist for y in intlist if x!=y][-1]

the later turns out to be very slow.
Can any one point out what is the issue here.
testing with
intlist=np.array([1, 2, 3,3,-1])

in this case the value expected is 2 as 3 is the max value and it occurs 2 times.
Comment: You way to calculate a `max`imum will not work, since the last item in the list comprehension will just be the maximum of the latest two numbers in the arrays that are different, but not per se the largest value globally.
Comment: Think you can use `np.count_nonzero(intlist==intlist.max())` for generic case.
Comment: Are those all integers in that array for your actual use-case?
Answer: The list comprehension will not calculate the maximum value in the first place. Indeed, it will here calculate the maximum of two values from intlist of the latest values. So unless the last two items in the list are the same, it will calculate the maximum of the last two values.
Furthermore it is not very efficient, since it runs in O(n2) time, and O(n2) memory. For huge lists, this would thus require gigantic amounts of memory.
Usually it is not a good idea to use list comprehension if you do not need a list in the first place. You can calculate a maximum with a for loop, where you each time compare an item with the thus far obtained maximum:
def other_max(listlike):
    mmax = listlike[0]
    for x in listlike:
        if x > mmax:
            mmax = x
    return mmax
or with numpy we can sum up the array of booleans:
>>> (intlist == intlist.max()).sum()
2

Comment: thanks.more of an experiment trying to understand comprehension . then i hit up on the slowness. Wanted to understand why it is slow more than whether it is working or not. But i appreciate all the points here.


Looping over list of list division

Question: If I have a list of lists, for example,
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [0,0,0]]

How do I output a list of lists, such that each element is assigned as a fraction of the sum of the sub-list.
In this example, the output should be:
[[1/6, 2/6, 3/6], [4/15, 5/15, 6/15], [7/24, 8/24, 9/24], [0,0,0]]

and should also check for division by zero, in which case, the entries are just zero.
Comment: Where did the denominators come from? Why are they specifically 6, 15, and 24?
Comment: @Rawing i think it is sum of the current list.
Comment: Sum of the sublist eg. 6=1+2+3, 15=4+5+6 ...
Comment: so you want output as 1/6 or 0.1666 ?
Comment: @Jay Parikh As decimal.
Answer: you can use sum of the sublist:
l =  [[1,2,3],[4,5,6],[7,8,9]]
res = [map(lambda x: float(x)/sum(sl), sl) for sl in l]

Results with

[[0.16666666666666666, 0.3333333333333333, 0.5],
 [0.26666666666666666, 0.3333333333333333, 0.4],
 [0.2916666666666667, 0.3333333333333333, 0.375]]

PS,
For python-3.x [map(...) does not return a list, but a map object]1. To get a list:
res = [list(map(lambda x: float(x)/sum(sl), sl)) for sl in l]

PPS,
To avoid division by zero, you can replace the denominator with a conditional expression:  sum(sl) if sum(sl) else 1:
[list(map(lambda x: float(x)/(sum(sl) if sum(sl) else 1), sl)) for sl in l]

Comment: I am getting [, , ]. Can you have a direct ouput without the map?
Comment: @Mat.S apparently you are using python3. if you `list(map(...))` python will convert the map objects to lists.
Comment: Thanks, one last thing, how do you add a case that checks for division by zero and in those cases, the entries are just zero.
Answer: Using a couple of comprehensions as:
Code:
[[float(z)/sum(x) for z in x] for x in y]

Test Code:
y = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

print([[float(z)/sum(x) for z in x] for x in y])

Results:
[   [0.16666666666666666, 0.3333333333333333, 0.5],
    [0.26666666666666666, 0.3333333333333333, 0.4],
    [0.2916666666666667, 0.3333333333333333, 0.375]
]

Answer: It could be done as follows, using list comprehension:
vals = [[1,2,3],[4,5,6],[7,8,9]]
denoms = [sum(entries) for entries in vals]
fracs = [[Fraction(entry, denom) for entry in entries] for entries, denom in zip(vals, denoms)]
floats = [[entry/denom for entry in entries] for entries, denom in zip(vals, denoms)]

Here I first calculate the denominators as the sum of the individual sublists, then I divide each element in the sublists with their respective denominators.
Also, I give you the output both in fractional (fracs) and decimal (floats) form. Pick whichever suits your needs.
Answer: Here we go:
list=[[1,2,3],[4,5,6],[7,8,9]]
newList=[]
subList=[]
for el in list:
    for subEl in el:
        subList.append(subEl/sum(el))
    newList.append(subList)
    subList=[]
print(newList)

Output is:

[[0.16666666666666666, 0.3333333333333333, 0.5], [0.26666666666666666, 0.3333333333333333, 0.4], [0.2916666666666667, 0.3333333333333333, 0.375]]

Looping over list of list division


Lubuntu 15.04 & Windows 10: expanding partition

Question: Lubuntu view:

Windows view:

I want to expand my current Lubuntu partition to use up all the free space left. However, Lubuntu doesn't differ between the real Windows partition and free space. Any safe solution?
I tried gparted as suggested in an answer, but have the same issue:

UPDATE: finally shut down Windows. Now, instead of exclamation mark symbol, there is a symbol of lock near the Windows partition:
UPDATE 2:
Unable to read the contents of this file system!
Because of this some operations may be unavailable.
The cause might be a missing software package.
The following list of software packages is required for ntfs file system support:  ntfsprogs / ntfs-3g
I can mount and unmount the partition as you instructed me without problems, though.

Final solution: reinstalled lubuntu with different settings. I could have tried to move the partition and then resize it, but that would have taken much more time than just reinstalling the whole OS.
Answer: It looks like your Windows system was hibernated and not actually shut down. That causes issues for Linux's ntfs3g driver. So, you need to boot back into Windows and shut it down cleanly.
In their infinite wisdom, the Microsoft developers decided to make it hard for users to shut down their machines. According to this site, you need to:

Mouse over the little gadget in the lower right corner of the screen. (You can also move your mouse cursor to the upper left corner;
  same result. Or, you can press Windows-C on your keyboard.)
In the slide-out menu (known as the Charms Bar) that appears, click Settings.
Click the Power button, and then click your desired action: Sleep, Shut down, or Update and restart.

That's for Windows 8 though. This site seems to suggest it is "easier"  on Windows 10:

Click on start button to pen the Start Menu
On top of it, click on 'Power Options' button next to your name (check the screenshot below) and click on 'Shut down' or 'Restart',
  (Sleep option is also available, which you can use it, if you want).

Anyway, assuming Windows actually allows you to shut down your machine, you can now reboot into Linux where gparted should be able to correctly read and resize your drive. It should look something like this:

While I have actually used gparted to resize NTFS partitions several times and have never had a problem, as always, you should backup your data first.
Comment: Installed gparted, no change.
Comment: @AlexWolf what do you mean "no change"? Did you run `sudo gparted`? Did that open a window like the one I show above with your disk drive? Was the empty space not listed? If so, please take a screenshot and add it to your question.
Comment: I added the screenshot.
Comment: Need more reputation to post more than two links.
Comment: Thanks for the update! I did what you said and things changed a little bit, but not enough to solve the issue. Could you take a look at my updated `GParted` view?
Comment: @AlexWolf that's because you've mounted it. Run `sudo umount /tmp/foo` and try again.
Comment: Did it. New error...


Is it OK to use 1/4" OSB over a standard subfloor before installing 3/4" hardwood on top?

Question: I'm planning to install a hardwood floor to butt up against ceramic tile.  The tile looks like it will be 1/4" proud to the wood.  Can I install 1/4" OSB over the subfloor, then the paper, then the Oak Flooring?
Any problems long term?
Comment: Just keep in mind any areas this might cause issues in, such as steps designed for current height of the subfloor, or toilet flanges. Although 1/4" shouldn't be too big of a deal.
Comment: The flooring will be installed by someone else.  So I do not know about restrictions concerning a leveling compound.  I've had no experience using leveling compound.  However, not sure it is pertinent here as the entire sub floor probably needs to be raised.  If it was just one area that was the question mark, I can see how leveling compound might be optimal.  (I'll know more when I get motivated to tear up the entire 700 sq ft of carpeting)
Comment: I wouldn't use leveling compound to bring an entire room up, nor is it well-suited under a nail-down hardwood floor in my experience. All those nails are going to beat it up pretty badly.
Comment: Are there instructions in the wood product you are using that discourages leveling compound?
Comment: No issues with toilet flanges as this is for living room and dining room adjacent to kitchen and hall way to bedrooms.- but thank you for reminding me of this.
Answer: That will work.  That's probably one of the better things to use to bring your floor level.
Answer: You don't nail/staple 3/4" hardwood into OSB.   It won't stick.   In a couple years you will have a floating floor and issues.   OSB is great but it doesn't hold nails.
Comment: @Phaelaxz - I get it.  I don't believe in creating a weak point especially in the beginning of the nail.   You are giving it wiggle room.   No way I install the wrong subfloor for an expensive flooring.   OSB is for floating floors and carpet.
Comment: OSB holds nails just fine (see also virtually any roof build in the last 30 years and most subfloors), but it's not the primary substrate anyway, being just 1/4" thick.
Comment: I would agree if the flooring is engineered the expansion and contraction due to temp and moisture variations will not be much different but true T&G is not saturated with resin and has much more movement, OSB or underpayment is fine for many flooring systems but I would be careful with real oak it is different.
Comment: @FreshCodemonger - I wouldn't.   Like I said before OSB is great.   The absolute preferred for floating hardwood/vinyl or carpet.   I don't nail things into OSB.   I have had this rule for 20 years.
Comment: ok, thanks.  The OSB will be sandwiched between plywood subfloor and Oak hardwood.  The OSB is only 1/4".  Do you still think that could be an issue?
Comment: As long as the nails are long enough to reach into the plywood you should be fine.  You should also consider some glue/adhesive to eliminate potential squeak.
Comment: I agree any temp change and that OSB will be ripped apart as the oak expands or shrinks. +
Comment: osb is fine for nails - why do you think it has problems with flooring nails?  we aren't talking about particle board.  @ed
Comment: @FreshCodemonger - OSB will microfracture due to bounce and humidity levels/movement over time.   The more humidity variance and the more people walk on the floors the less the OSB nails will hold.   Yea I get that it's only 1/4" and using it isn't the end of the world.   I just don't understand using something that has a greater chance at failure.
Comment: @dmoore Thanks for the explanation.  The manufacturer recommendations and the NWFA allow installation of nail down engineered hardwood flooring on top of 3/4" exterior stamped OSB (thickness is for deflection).  Do you disagree with them?
Comment: @FreshCodemonger - I get that.   I wonder what his hardwood manufacturer suggests - he didn't mention it being engineered.   With 80% of the engineered hardwood being some sort of MDF/crap backing I am not seeing how they can be super stringent on the subfloor.
Comment: @dmoore Preverco (pretty high end) flooring which uses baltic plywood core in their engineered product (pretty much the best grade of plywood) allows nail down install on OSB.  Just curious on your stance, would you never install it on OSB?


Shortening file paths using Python

Question: I have an application which should display to the user the path to a file. Let's say the user inputs /home/me/foo/, the application should shorten that to ~/foo.
Is there any way to do this in Python such that it works cross-platform with Linux and Windows?
Answer: now sure what you are trying to do but changing it to the other format is as simple as:
newpath = "~"+filepath[9:]

if you want this to work with other usernames,
newpath = "~/"+filepath[findfirstindex('foo'):]

Comment: changed my original answer. you can use findfirstindex to start wherever the first index occurs if there are other usernames
Comment: Will this work if the user has a much longer or shorter name?

Shortening file paths using Python


Repair Teleporter in Fallout 4

Question: I built the teleporter in Sanctuary Hills and used it to get into the Institute. The settlement was later attacked and the teleporter was damaged. Unfortunately, because it's a unique building, it cannot be repaired.
I understand that the teleporter is necessary in the future if I want to choose the path of destroying the institute with the Minutemen, so it needs to be operational.
Is there some way to repair it? Especially convenient would be a simple console command (PC version) to repair settlement objects, which I wasn't able to find.
Comment: I don't remember needing it again for anything, even on the minuteman ending
Answer: I've finished the game with each faction at least once, and I've done very nearly every side quest in the game with one character or another.
You don't need the molecular relay again for anything ever, it is always damaged after you use it, and I don't believe it can be repaired.
In the final Minutemen quest, you'll use the relay inside the institute, not the one you built in your settlement.
Furthermore, if you ask the tech person about testing the relay before the first time you use it, they will tell you that it is only going to work once.
Answer: Short answer: No, you can't repair it
Bit longer answer: The teleporter gets Auto-damaged when you use it, but since you got the chip from the institute, you can travel there at any time.
I don't know if you need the teleporter, if you want to destroy the institute with whatever faction, but since it gets auto-damaged, I guess there will be a way to repair it, if you need it again.
EDIT: I read other posts here that indicate that you don't need the teleporter anymore, not even for the destroy the institute missions.
Answer: Yes, it can be done.
Console command "CallFuntion Repair" then choose the part to repair while inside the console command. This has to be done to all 4 parts separately. Then you might have to turn the power source OFF then ON again.
But it works, I do it every playthrough because I like the light show.

Repair Teleporter in Fallout 4


extend app.user in Symfony 2

Question: I use Twig for my project and I wanna extend global object app.user without adding property in my UserClass. I mean this:
I have UserClass:
<?php
namespace Test\CoreBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 * @ORM\Entity(repositoryClass="Test\CoreBundle\Repositories\UserRepository")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

}

And I have Repository:
<?php
namespace Test\CoreBundle\Repositories;

use Doctrine\ORM\EntityRepository;

class UserRepository extends EntityRepository
{

    public function getCountPosts () {
        //some code

        return 10;
    }
}

How can i get access to UserRepository's method getCountPosts inside Twig templates?
Comment: I assume you have a `OneToMany` relation with `Post` entity. What about `{{ app.user.posts|length }}` ?
Comment: Did you consider creating a twig extension and exposing the repository's function via that?
Answer: You can't because business logic has to be in the controllers. You can create extra methods in the entities and call them in a Twig template.
<?php
namespace Test\CoreBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 * @ORM\Entity(repositoryClass="Test\CoreBundle\Repositories\UserRepository")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    public function getCountPosts () {
        //some code
        return 10;
    }

}

And in your Twig file
{{ app.user.getCountPosts() }}

Comment: `app.user.countPosts` would do

extend app.user in Symfony 2


Creating a dylib file on MacOS for use with Python wrapper of Steamworks API

Question: I am a hobbyist programmer trying to integrate the SteamworksForPython API into a Python-based game. This API is a Python wrapper of the Steamworks API, which only officially supports C++. I am working on MacOS Sierra 10.12.6.
Blindly following the documentation, I have done the following:

I have downloaded the SteamworksForPython repo.
I have added the steam header directory from the Steamworks SDK (/sdk/public/steam) to that repo.
I have added to that repo the Steam API file appropriate to my operating system (in my case, libsteam_api.dylib from /sdk/redistributable_bin/osx32).

The next step listed in the documentation is to create a new dylib file. Unfortunately, the steps to do this haven't been described for MacOS yet.
Looking at the process for Linux and Windows, it seems like I need to create this dynamic library file using the repo's SteamworksPy.cpp file and the steam_api.h header file from the Steamworks SDK.
I have researched how to create a dylib file using Xcode and am currently trying to do it. The process seems similar to the one described by the documentation for Windows using Visual Studio.
I have done the following:

I have created a new Xcode project of type plain C++ dynamic library.
I have added SteamworksPy.cpp into the Compile Sources list.
I have added steam_api.h to the Headers list (under public, not private or project).
I have added libsteam_api.dylib to the Link Binary With Libraries section.

I am getting an error when I try to build, however. Here is a screenshot:

And here is a more explicit screenshot of the linker error:

After reading this, this, and this, I think the problem is that Xcode doesn't know where to look for the library I'm trying to link to, so I need to tell it where to look. This should be simple, but I can't manage to do it.
Can anyone give me advice on how to proceed?

Similar questions that were helpful, but didn't lead me to a solution:

How do I create a dynamic library (dylib) with Xcode?
Building and Using a DYLIB in Xcode
ld: library not found
ld: library not found for -lgsl
xcode library not found
Answer: I managed to solve this problem.
Xcode couldn't find the location of the library I was trying to link to.
I noticed that under Build Settings I could specify Path to Link Map File. I tried to hardcode the path to where my library (libsteam_api.dylib) resided, but I got the same error described above.
Then I did something that worked.
I deleted the reference to the library in the Link Binary With Libraries section.
Then I moved the library from its original location into my Xcode project directory.
Then I used the file selection pane in the Link Binary With Libraries section to reselect the library from the Xcode directory.
When I built, everything worked fine.