Setting environment variable through SSH git push

Question: I'm reading Scott Chacon's Git book, and just wanted to confirm something. This part:

You also have access to the user doing the pushing if the push is being run over SSH. If you've allowed everyone to connect with a single user (like "git") via public-key authentication, you may have to give that user a shell wrapper that determines which user is connecting based on the public key, and set an environment variable accordingly. Here we'll assume the connecting user is in the $USER environment variable, so your update script begins by gathering all the information you need:
#!/usr/bin/env ruby

$refname = ARGV[0]
$oldrev  = ARGV[1]
$newrev  = ARGV[2]
$user    = ENV['USER']

puts "Enforcing Policies..."
puts "(#{$refname}) (#{$oldrev[0,6]}) (#{$newrev[0,6]})"

I presume that it's required for the pusher to install a script wrapping around the ssh command. For example, the script would perhaps set the GIT_SSH or GIT_SSH_COMMAND environment variable to point to a shell script that may have something like
#!/bin/bash

HOST=$1
shift
ssh -i ~/.ssh/id_rsa $HOST USER=foo $@

Now anytime a git push is done and the remote contains an ssh url, it will invoke that script and update the refs while passing the USER environment variable.
The other way would be to use "SendEnv USER" in ~/.ssh/config on the local machine and "AcceptEnv USER" in /etc/ssh/sshd_config on the remote git server.
Any other ways that come to mind that expand on the part in bold? I'm particularly looking for a way that doesn't require the pusher to do much work in regards to configuring his environment. Assume everyone's running some form of Windows and needs to setup ssh through some Unix emulator like Cygwin.
Answer: This example is not about the shell or the ssh command.
It is taken from the "Server-Side Hook" section, and describe how to tailored the update hook based on the user (authenticated through ssh)

Here we'll assume the connecting user is in the $USER environment variable

There is no indication on how this is done, but gitolite (a perl-based authorization layer, which very much needs the user authenticated id) is using ssh forced command: each public key in the ~git/.ssh/authorized_keys include the call to a wrapper script which takes in parameters the user id.
That script will:

execute the git command
fails if this the command is anything else but a git command

In the ~git/.ssh/authorized_keys, you don't have just the public key, but the call to the wrapper with the user id as a parameter:
command="/wrapper/script userid",no-port-forwarding,no-X11-for        warding,no-agent-forwarding,no-pty ssh-rsa AAAAB3N...
         ^^^^^^^^^^^^^^^
         (forced command)

You can see the environment variable being set by the (gitolite here) wrapper script in src/gitolite-shell#L102-L108.
Comment: Hmm, yes, I've considered Gitolite and I've gotten to the part of an article, regarding installing it on Windows, where all I need to do now is just follow the official Gitolite doc to get it installed. I took another look at the Gitolite docs and researched quite a bit on sshd, authorized_keys, and the ssh forced command option. At the moment, it seems like it's a bit overkill. However, if I take the Gitolite route, ultimately, I'll need to access that userid string in a post-receive to do some conditional behavior based on who's pushing. Thanks for the input. Much appreciated.
Comment: Oh I see, it looks like I can just do what I want with the GL_USER env var, but it also looks like the bare git repos have to exist in the ~/repositories folder which makes things a little bit less transparent in that the devs would have to alter their remote config in their local repos.
Comment: @solstice333 my point was more to illustrate how to set an environment variable with the iser id, based on an ssh forced command calling a script of yours (and not necessarily calling gitolite). Gitolite was just an example on how to do that, but you could write your own script.
Comment: @solstice333 if you write your own script, you only need to figure out how to get the users public key *and* user id, in order to register them in `~/.ssh/authorized_keys` (with a forced command syntax). Then the repos can be anywhere you want since your script will call the git command on them.


Recyclerview withy LinearSnapHelper - snap to next item when release finger from the screen

Question: I have followed this Stack Overflow post to create a recyclerview with viewpager behavior.
Works fine but I need to trigger the scroll to next item when user lift the finger of the screen. Right now only snap to next item when it's 50% visible.
UPDATE WITH SOLUTION
The Crysxd response was the key. To detect the snap direction I added this code at the top of the findTargetSnapPosition function:
if (velocityY < 0)
        snapToPrevious = true
else
        snapToNext = true

Comment: make your own custom `LinearSnapHelper` class, see: https://android.googlesource.com/platform/frameworks/support/+/refs/heads/master/v7/recyclerview/src/main/java/android/support/v7/widget/LinearSnapHelper.java#43
Comment: There aren't a simplest solution? :)
Answer: There's no way around a custom SnapHelper. Here is a class you can copy to your project.
The solution
class ControllableSnapHelper(val onSnapped: ((Int) -> Unit)? = null) : LinearSnapHelper() {
    var snappedPosition = 0
    private var snapToNext = false
    private var snapToPrevious = false
    var recyclerView: RecyclerView? = null

    override fun attachToRecyclerView(recyclerView: RecyclerView?) {
        super.attachToRecyclerView(recyclerView)
        this.recyclerView = recyclerView
    }

    override fun findTargetSnapPosition(layoutManager: RecyclerView.LayoutManager, velocityX: Int, velocityY: Int): Int {
        if (snapToNext) {
            snapToNext = false
            snappedPosition = Math.min(recyclerView?.adapter?.itemCount ?: 0, snappedPosition + 1)
        } else if (snapToPrevious) {
            snapToPrevious = false
            snappedPosition = Math.max(0, snappedPosition - 1)
        } else {
            snappedPosition = super.findTargetSnapPosition(layoutManager, velocityX, velocityY)
        }

        onSnapped?.invoke(snappedPosition)
        return snappedPosition
    }

    fun snapToNext() {
        snapToNext = true
        onFling(Int.MAX_VALUE, Int.MAX_VALUE)
    }

    fun snapToPrevious() {
        snapToPrevious = true
        onFling(Int.MAX_VALUE, Int.MAX_VALUE)
    }
}

You can replace LinearSnapHelper with PagerSnapHelper as well. Simply call snapToNext() or snapToPrevious(). I also implemented a callback which is passed in the constructor.
How it works
We simply overwrite the findTargetSnapPosition(...) method. This method can return any position and the SnapHelper implementation will then compute the scroll animation to get there. The functions snapToNext() and snapToPrevious() simply set a boolean which tells us to snap to the next or previous view the next time findTargetSnapPosition(...) is called. It would also be very simple to add a snapTo(index: Int) function. After setting the boolean, we need to start the snap progress. To do so, we call onFling(...) which would be called when the user moved the RecyclerView. We need to pass in a value which exceeds the minimum velocity set by SnapHelper, so we just use Int.MAX_VALUE. As we never call super.findTargetSnapPosition(...), the actual velocity used by PagerSnapHelper doesn't matter.
Comment: Thank you for your response. I'll check asap and let you know!!
Comment: Please let me know if you have issues, I can then update my repsonse
Comment: Hi Crysxd!! Works very well. Only I added this peace of code to detect the snap direction: if (velocityY < 0)
            snapToPrevious = true
        else
            snapToNext = true
Thanks a lot for your help!!


Given the OSM data for a state, find its area

Question: Apologies if this is a silly question, I'm very new to PostgreSQL/PostGIS.
I have downloaded an .osm file for the entire state of Baden-Württemberg from here - https://download.geofabrik.de/europe/germany/baden-wuerttemberg.html
I have to answer the following questions, by writing queries for the same -

What is the area (expressed in m^2) of Baden-Württemberg?
What is by area the smallest city of Baden-Württemberg?

I have imported the osm file into a PostgreSQL using the osm2pgsql tool.
There seem to be multiple tables that are being created, core and generated by osm2pgsql. In addition to the core tables - planet_osm_nodes, planet_osm_ways and planet_osm_rels there are other tables as well, and I'm not quite sure how to use them to complete my tasks.
It would be really helpful if anybody could provide some insight into how I can go about writing the PostGIS query for the same.
Comment: crossposts: https://gis.stackexchange.com/questions/314541/given-the-osm-data-for-a-state-find-its-area-by-writing-a-postgis-query and https://help.openstreetmap.org/questions/68291/given-the-osm-data-for-a-state-find-its-area-by-writing-a-postgis-query
Answer: I think something like this should give you the cities and their area in square meters in order
SELECT *, ST_Area(way)
FROM planet_osm_polygon
WHERE boundary='administrative'
AND admin_level=7
ORDER BY ST_Area(way)

Same thing should work with the border of Baden-Württemberg only that you would need admin_level=4
https://postgis.net/docs/ST_Area.html
https://wiki.openstreetmap.org/wiki/DE:Grenze


Prove that $S = \{ f\in\textsf{C}([-1,1]) :\, f(-x)=-f(x) \textrm{ for all } x\in [-1,1] \}$ is a subspace of $\textsf{C}([-1,1])$

Question: Let $S = \{ f\in\textsf{C}([-1,1]) :\, f(-x)=-f(x) \textrm{ for all } x\in [-1,1] \}$. Prove that $S$ is a subspace of $\textsf{C}([-1,1])$.
My question: Am I approaching this correctly? My attempt is in the picture below. Thank you guys ahead of time for any help!
Comment: $(f+g)(-1)=-2$ does not show that this is not closed under addition.
Comment: To show that it is not in the set you need to prove that $(f+g)(-1) \neq -(f+g)(1)$. But $$-(f+g)(1)=-f(1)-g(1)=f(-1)+g(-1)=-2$$
Comment: Write down what a certain subset $U$ in vector space $V$ needs to satisfy in order to be a subspace. Then try to apply that to this particular case. I don't wanna give you the answer immediately because exercise is not difficult, but it seems you kinda lost track of what you need to prove.
Comment: really? i thought if the result is not in the set, than it is not closed...?
Comment: ohhhkay. so do i not have to show closure under addition and scalar multiplication? is it safe to say it is in the set because the definition{f(-x)=-f(x)} holds?
Comment: Look, when exercise explicitly tells you to prove something, try to prove it :D. You'll save yourself a lot of time. There are couple of things you've written that are wrong. Why would $f(-1)=-1$ and $g(-1)=-1$? Why do you think that $(f+g)(-1)$ doesn't belong to $[-1,1]$ implies that $f+g$ isn't in $S$?
Comment: Why do you assume that $f(-1)=-1$ and $g(-1)=-1$?  This is not what the definition means.
Comment: yea i now realized that i scuffed that. f(-x)=-f(x) is confusing me for some reason. I dont know how to test (f+g)(−1)≠−(f+g)(1)
Answer: I think that your first error has to do with understanding what $C([-1,1])$ means.  The $[-1,1]$ is the domain of the function.  What your work is showing is that
$$
\{f\in C([-1,1]):f(-1)=-1\}
$$
is not a subspace of $C([-1,1])$ since it is not closed under addition.  The problem is that the assumption that $f(-1)=-1$ is not part of the given information.  In fact, there are many odd continuous functions like $f(x)=\sin(x)$ which do not satisfy these conditions.
The definition
$$
\{f\in C([-1,1]):f(-x)=-f(x)\text{ for all }x\in[-1,1]\}
$$
means that the domain of the functions is $[-1,1]$, the functions are continuous, and they satisfy $f(-x)=-f(x)$, i.e., they are odd functions.  There are many odd functions such that $f(-1)\not=-1$.
What you should prove:

The set is not empty.  Does the $0$ function satisfy the conditions?  Is it continuous on $[-1,1]$?  Does $0(-x)=-0(x)$?
The set is closed under addition.  If you have two functions in the set $f$ and $g$, is $f+g$ in the set?  In other words, is $f+g$ continuous with domain $[-1,1]$?  Is $(f+g)(-x)=-(f+g)(x)$?
The set is closed under scaling.  If you have the function $f$ in the set and $c$ is a scalar, is $cf$ in the set?  In other words, is $cf$ continuous with domain $[-1,1]$?  Is $(cf)(-x)=-(cf)(x)$?

As an example, to show that $(f+g)(-x)=-(f+g)(x)$, we consider the following: Starting with $(f+g)(-x)=f(-x)+g(-x)$, we use the odd property of $f$ and $g$ (since they're in the set) to get $f(-x)+g(-x)=-f(x)-g(x)$.  But this is $-(f(x)+g(x))=-((f+g)(x))=-(f+g)(x)$.
Comment: Well, the question asked you to prove that it was a subspace, so, unless the question is wrong, yes, it's a subspace.
Comment: first off. thank you. secondly,
1. yes
2. yes
3. yes
so S is a subspace of C then?


Is Kinect Star Wars Region Free?

Question: I want to know if Kinect Star Wars PAL is playable on a NTSC-US Xbox 360.
Thanks
Comment: @iMAGEbox because what you are saying is wrong. Whether a game from region X plays on a console in region Y is an arbitrary decision made by the publisher of each individual game.
Comment: @iMAGEbox completely incorrect.
Comment: I know the danish version has danish voice over, it is horrible!
Comment: you cant play PAL games on NTSC.
Comment: @kotekzot why? you cant play PAL games on NTSC region xbox.
Answer: According to Play Asia the PAL Kinect Star Wars is region locked, so a PAL disk should not work on an NTSC-US Xbox 360, sorry!
Comment: What is wrong with this answer?
Answer: It's true, I made the mistake of buying the game before making sure that I can play it...
The only difference is that my console is a NTSC-J console.
But just to emphasize what kotekzot said, I also have many games I bought here in Europe that I could play on my Xbox 360, so it really depends on each game.

Is Kinect Star Wars Region Free?


Git: How to use subfolder of a repository as submodule?

Question: 1. The situtation
Let's say I have a repository with the following folder structure:
repo1\
|
|-Foo\
|-Bar\

2. The Requests
- In a second repo repo2 I want to use repo1 as submodule; but only the contents of the folder Foo\.
- Whenever someone clones repo2 and initializes the submodule, automatically (or only with reasonable effort) there should be only the folder Foo\ present in the submodule folder.
3. What I have tried
- Sparse checkout as indicated here does not work with submodules at all, at least as far as I managed to make it work
- Filter branch as indicated here or here works for me fine; but whenever someone clones repo2 the procedure must be repeated for their clone

4. The Questions
- How can I make that work?
- What else should I try?
Answer:
Convert repo1/foo into separate independent repository
Add this repo as submodule to repo1|repo2

You'll have some headache on intersection of a "split point" for any direction, but... it's fair price for possibility to use now as you want
Comment: If I do a commit in ```repo1```, how will I be able to pull the update into the submodule?


D3.js transitions between charts

Question: I am trying to create a  transition in my bar chart code, that would allow the user to click on a particular and be shown a different set of data related to that bar.
This is a sample dataset:
module_category,component_category,date_repair,actual,predicted
M1,P06,2009/01,39,63
M1,P06,2009/10,3,4
M1,P06,2009/11,4,3
M1,P06,2009/12,4,2
M1,P06,2009/02,29,45
M1,P06,2009/03,29,32
M1,P06,2009/04,10,22
M1,P06,2009/05,13,15
M1,P06,2009/06,9,16
M1,P06,2009/07,7,12

The full dataset can be found here: full dataset
So based on my current code I can create this bar chart:

but now I want to add interactivity that will allow the user after clicking on the bar for e.g "M2", they graph then updates to show the components from the "component_category" related to that module with the respective "actual" and "predicted" values shown as bar charts also.
This is my current code:

var margin = {top: 20, right: 90, bottom: 30, left: 60},
    width = 980 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;
var x0 = d3.scale.ordinal()
        .rangeRoundBands([0, width], .1);

var x1 = d3.scale.ordinal();

var y = d3.scale.linear()
    .range([height, 0]);

var color = d3.scale.category10();

var xAxis = d3.svg.axis()
    .scale(x0)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .tickFormat(d3.format(".2s"));

var svg = d3.select("#maincontent").append("svg")
    .attr('id','chart')
    .attr('viewBox', '0 0 980 500')
    .attr('perserveAspectRatio', 'xMinYMid')
    .attr('width', width + margin.right + margin.left)
    .attr('height', height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var tip=d3.tip()
            .attr("class","d3-tip")
            .offset([-10, 0])
            .html(function(d) { return "No. of repairs: " + d.value; });

d3.csv("data/Consolidated_result.csv", function(error, data) {
  if (error) throw error;

  data = d3.nest()
    .key(function(d) { return d.module_category;}).sortKeys(d3.ascending)
    .rollup(function(values){
        var counts = {}, keys = ['actual', 'predicted']
        keys.forEach(function(key){
            counts[key] = d3.sum(values, function(d){ return d[key]})
        })
        return counts
    })
    .entries(data);

    console.log(data);

  x0.domain(data.map(function(d) { return d.key; }));
  x1.domain(['actual','predicted']).rangeRoundBands([0, x0.rangeBand()]);
  // store all the values in an array
  var yval = [];
    data.forEach(function(d){
        yval.push(d.values.actual);
        yval.push(d.values.predicted);
    });
  y.domain([0, d3.max(yval)]);

  svg.call(tip);

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 0 - margin.left)
      .attr("x", 0 - (height / 2))
      .attr("dy", "1em")
      .style("text-anchor", "middle")
      .text("Number of Repairs");

  var module = svg.selectAll(".module")
      .data(data)
    .enter().append("g")
      .attr("class", "g")
      .attr("transform", function(d) { return "translate(" + x0(d.key) + ",0)"; });

  module.selectAll("rect")
    .data(function(d){
        var ary = [];
        ary.push({name:"actual", value:d.values.actual});
        ary.push({name:'predicted', value: d.values.predicted});
        return ary;
      })
    .enter().append("rect")
        .on('mouseover', tip.show)
        .on('mouseout', tip.hide)
      .on("click", function(d){
        d3.select("svg")
            .style("opacity",0)
            .remove()
            tip.hide()
            setTimeout(componentgroupedchart, 1000);
      })
        /*
      .on("click", function(d){
        d3.select(this)
            setTimeout(updateChart(name), 500);
        })*/
      .attr("width", x1.rangeBand())
      .attr("x", function(d) { return x1(d.name); })
      .attr("y", function(d) { return y(d.value); })
      .attr("height", function(d) { return height - y(d.value); })
      .style("fill", function(d) { return color(d.name); });

  var legend = svg.selectAll(".legend")
      .data(['actual','predicted'])
    .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

  legend.append("rect")
      .attr("x", width - 18)
      .attr("width", 18)
      .attr("height", 18)
      .style("fill", function(d){
        return color(d)
      });

  legend.append("text")
      .attr("x", width - 24)
      .attr("y", 9)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .text(function(d) { return d; });

});

What I want to implement will be to create a function where i update the chart and reload the data and nest it to this:
 data = d3.nest()
    .key(function(d) { return d.module_category;}).sortKeys(d3.ascending)
    .key(function(d) { return d.component_category;}).sortKeys(d3.ascending)
    .rollup(function(values){
    var counts = {}, keys = ['actual', 'predicted']
    keys.forEach(function(key){
       counts[key] = d3.sum(values, function(d){ return d[key]})
          })
       return counts
    })
    .entries(data);

This is so that I can access for each module:

the number of component related to that module &
the actual and predicted repair values

The resulting data then becomes:
var data = [{
   key: "M1"
   values: {
      key: "P06"
      values: {
        actual: 156 ,
        predicted: 228
      },
      key: "P09"
      values: {
        actual: 31,
        predicted: 20
      },
      key: "P12"
      values: {
        actual: 140,
        predicted: 176
      },
      key: "P15"
      values: {
        actual: 38,
        predicted: 40
      },
      key: "P16"
      values: {
        actual: 112,
        predicted:113
      },
      key: "P17"
      values: {
        actual: 20 ,
        predicted: 7
      },
      key: "P20"
      values: {
        actual: 98,
        predicted: 127
      },
      key: "P28"
      values: {
        actual: 143 ,
        predicted: 149
      },
      key: "P30"
      values: {
        actual: 16,
        predicted: 38
      }
  },
  key: "M5"
  values: {
      key: "P06"
      values: {
        actual: 61 ,
        predicted: 65
      },
      key: "P09"
      values: {
        actual: 83,
        predicted: 82
      },
      key: "P12"
      values: {
        actual: 45,
        predicted: 58
      },
      key: "P15"
      values: {
        actual: 26,
        predicted: 31
      },
      key: "P16"
      values: {
        actual: 152,
        predicted:174
      },
      key: "P21"
      values: {
        actual: 74 ,
        predicted: 120
      }
   }
}]

From this new data, the chart then transitions to a new bar chart display that shows the components and their repair values based on the  selected module. I hope the question is much clearer now.
Comment: Your dataset is not clear you have a single record like this M1,P06,2009/01,39,63 so when you click M1 it will be showing P06? there is no M2 in the dataset..
Comment: Hi sorry about that i've put the full dataset here : [link](http://plnkr.co/edit/UVrd1SIzCGWmd2Ky4epl)
Comment: Your data for M1 has multiple values for component_category sometimes its p12 sometimes p16 and all of them have different actual,predicted values  M1,P12,2009/01,35,40
M1,P12,2009/10,3,4
M1,P12,2009/11,2,3
M1,P16,2009/04,9,12
M1,P16,2009/05,10,9 so on drill down which values should be displayed ...can you clarify this on your question so that it can be helpful for people who may answer it.
Comment: okay, editing the question now
Answer: This can be achieved by making one function for making module graph, another for making the drill down category graph. Define the domain with in the functions, since the y axis domain x axis domain will change with with the module/category graph.
I have added comments in the code; in case you have any issues, feel free to ask.
  var margin = {
      top: 20,
      right: 90,
      bottom: 30,
      left: 60
    },
    width = 980 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;
  var x0 = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

  var x1 = d3.scale.ordinal();

  var y = d3.scale.linear()
    .range([height, 0]);

  var color = d3.scale.category10();

  var xAxis = d3.svg.axis()
    .scale(x0)
    .orient("bottom");

  var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .tickFormat(d3.format(".2s"));

  var svg = d3.select("body").append("svg")
    .attr('width', width + margin.right + margin.left)
    .attr('height', height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  var tip = d3.tip()
    .attr("class", "d3-tip")
    .offset([-10, 0])
    .html(function(d) {
      return "No. of repairs: " + d.value;
    });

  d3.csv("my.csv", function(error, data) {
    if (error) throw error;
    fullData = data;
    data = d3.nest()
      .key(function(d) {
        return d.module_category;
      })
      .rollup(function(values) {
        var counts = {},
          keys = ['actual', 'predicted']
        keys.forEach(function(key) {
          counts[key] = d3.sum(values, function(d) {
            return d[key];
          })
        })
        return counts
      })
      .entries(data);
      //make the x axis
    svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);
      //make the y axis
    svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
      .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 0 - margin.left)
      .attr("x", 0 - (height / 2))
      .attr("dy", "1em")
      .style("text-anchor", "middle")
      .text("Number of Repairs");

    makeModuleGraph(data)

    var legend = svg.selectAll(".legend")
      .data(['actual', 'predicted'])
      .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) {
        return "translate(0," + i * 20 + ")";
      });

    legend.append("rect")
      .attr("x", width - 18)
      .attr("width", 18)
      .attr("height", 18)
      .style("fill", function(d) {
        return color(d);
      });

    legend.append("text")
      .attr("x", width - 24)
      .attr("y", 9)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .text(function(d) {
        return d;
      });
  });

  function makeModuleGraph(data) {
    var yval = [];
    data.forEach(function(d) {
      yval.push(d.values.actual);
      yval.push(d.values.predicted);
    });
    x0.domain(data.map(function(d) {
      return d.key;
    }));
    x1.domain(['actual', 'predicted']).rangeRoundBands([0, x0.rangeBand()]);

    y.domain([0, d3.max(yval)]);

    svg.call(tip);

    svg.selectAll("g .x")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

    svg.selectAll("g .y")
      .attr("class", "y axis")
      .call(yAxis);

    var module = svg.selectAll(".module")
      .data(data)
      .enter().append("g")
      .attr("class", "module")
      .attr("transform", function(d) {
        return "translate(" + x0(d.key) + ",0)";
      });

    module.selectAll("rect")
      .data(function(d) {
        var ary = [];
        ary.push({
          name: "actual",
          value: d.values.actual,
          key: d.key
        });
        ary.push({
          name: "predicted",
          value: d.values.predicted,
          key: d.key
        });
        return ary;
      })
      .enter().append("rect")
      .attr("width", x1.rangeBand())
      .attr("x", function(d) {
        return x1(d.name);
      })
      .attr("y", function(d) {
        return y(d.value);
      })
      .attr("height", function(d) {
        return height - y(d.value);
      })
      .style("fill", function(d) {
        return color(d.name);
      }).on("click", function(d) {
        makeComponentCategoryGraph(d);//make the graph for category
      });

  }

  function makeComponentCategoryGraph(d){
    var filtered = fullData.filter(function(k){ if(d.key == k.module_category){return true;}else {return false;}})
    var data = d3.nest()
      .key(function(d) {
        return d.component_category;
      })
      .rollup(function(values) {
        var counts = {},
          keys = ['actual', 'predicted']
        keys.forEach(function(key) {
          counts[key] = d3.sum(values, function(d) {
            return d[key];
          })
        })
        return counts
      })
      .entries(filtered);
          var yval = [];
    data.forEach(function(d) {
      yval.push(d.values.actual);
      yval.push(d.values.predicted);
    });
    x0.domain(data.map(function(d) {
      return d.key;
    }));
    x1.domain(['actual', 'predicted']).rangeRoundBands([0, x0.rangeBand()]);

    y.domain([0, d3.max(yval)]);

    svg.call(tip);

    svg.selectAll("g .x")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

    svg.selectAll("g .y")
      .attr("class", "y axis")
      .call(yAxis);
    svg.selectAll(".module").remove();//remove alll the bar graphs
    var module = svg.selectAll(".module")
      .data(data)
      .enter().append("g")
      .attr("class", "module")
      .attr("transform", function(d) {
        return "translate(" + x0(d.key) + ",0)";
      });

    module.selectAll("rect")
      .data(function(d) {
        var ary = [];
        ary.push({
          name: "actual",
          value: d.values.actual,
          key: d.key
        });
        ary.push({
          name: "predicted",
          value: d.values.predicted,
          key: d.key
        });
        return ary;
      })
      .enter().append("rect")
      .attr("width", x1.rangeBand())
      .attr("x", function(d) {
        return x1(d.name);
      })
      .attr("y", function(d) {
        return y(d.value);
      })
      .attr("height", function(d) {
        return height - y(d.value);
      })
      .style("fill", function(d) {
        return color(d.name);
      })
  }

Working code here.
Comment: Yes this is what I am looking for :). Thanks a lot. Using the filter function to compare the module_category was what I was thinking of but couldn't visualize it. Thanks again

D3.js transitions between charts


Check if date in an array is older than dates in another array

Question: I'm trying to check the date from arrayA against the all the dates in arrayB, if the date from arrayA is older than any in arrayB then return.
Not too sure if I am able to check values in an array against other values in an array.
const dateA = arrayA.map((item) => {
  return item.date;

const dateB = arrayB.map((item) => {
  return item.date;

if (dateA >= dateB) {
return 'date is older'}

Dates in arrayA
[ 2022-02-21T05:00:00.000Z ]

Dates in arrayB
[
  2022-02-18T05:00:00.000Z,
  2022-02-10T05:00:00.000Z,
  2022-02-19T05:00:00.000Z
]

Any help would be appreciated!
Answer: It's a bit confusing what you are asking, and there are contradictions in your question, so I'll make a few assumptions:

I assume that you actually want to know whether all dates in arrayA are later (newer) or the same - and not older - than all dates in arrayB. (I based this on the fact that you showed >= rather than < in your pseudocode and also showed an example in which this is the case.)

I assume that your arrays contain Date objects. (I based this on the array contents that look like they are copied from an inspect-like output - even though your pseudeocode looks as if there would be objects with a date property inside.)

If something isn't quite right about these assumptions, it should be easy to take the concept anyway and adjust it slightly to your actual needs. If for example you do want to make sure all dates in arrayA are actually older, then you'd just have to swap the two arrays in my examples (or invert all operations). Possibly you might want the condition at the end inverted - again I'm not quite sure what you really want because the question is very ambiguous.

So, for possible solutions: You could of course compare every date in arrayA with every date in arrayB (if (arrayA.every(dateA => arrayB.every(dateB => dateA >= dateB)))), but that would be unnecessarily inefficient because there would have to be arrayA.length * arrayB.length comparisons.
A more efficient option would be to calculate the oldest date in arrayA as well as the newest date in arrayB and then just compare those (which will result in approx. arrayA.length + arrayB.length comparisons - note the plus instead of times):
const oldestDateValueA = Math.min(...arrayA.map(Number))
const newestDateValueB = Math.max(...arrayB.map(Number))
if (oldestDateValueA >= newestDateValueB) {
  console.log('Condition fulfilled!')
}

(We could optimize this even further by not using Math.max on the second array but instead .every for comparison with the oldest date of the first array, essentially a mix of the two ways, which would result in fewer comparisons in case a date earlier in the second array would already fail the comparison - however this makes it harder to read and understand in my opinion and the improvement is much less drastic than the previous one we did.)
Comment: Yes both assumptions are correct, I was using dumbie data to test out my logic, so that might have caused the confusion. The logic you provide is a more efficient way to handle this problem.


When should "Log on" or "Log off" be used?

Question:
Possible Duplicate:
Using "Sign in" vs using "Log in"

I'm porting an old application that has a "Log on" screen.  When would I use "Log on" vs the alternatives (Sign In / Log In)?
Comment: See this very similar question: http://ux.stackexchange.com/questions/1080/using-sign-in-vs-using-log-in
Comment: @JonW - Similar? I'd say it's an exact duplicate.
Answer: There is some evidence that Sign In and Sign Out are generally more readily understood than the alternatives, so if you have the opportunity you should change it.
There is some relevant discussion and links to research on this similar question: Using "Sign in" vs using "Log in"


AWS QuickSight Cohort(customers returning rate)

Question: I am using AWS quickSight for anyltics.
I have a data set contains customer, orderDate, order
I want to create a cohort report showing the customer return rate. so assume in the first month I have 100 new customers, I need to show in the next months how many customers from the 100 is returning to use my service.
Example

month 0
month 1
month 2
month 3

Jul, 2022
200
50
20
29

Aug, 2022
250
100
30

Sep, 2022
300
70

Oct, 2022
330

in the example above, in Jul I have 200 new customers, from the 200 customers in the next month 50 customers returned to use our service, then in the second month, 20 customers from the 200 customers return to use our service, and so on.
is this doable using AWS QuickSight, Please share your thoughts
Thank you in advance.
Answer: Please check this How to Perform Cohort Analysis
I think it will answer your question.


Inconsistent Date format

Question: Xcode 9.0.1 · Swift 4 · iPhone 5s
To recreate the problem I'm getting in my app, I've created a single view application and added the following three lines of code to ViewController.viewDidLoad():
    let formatter = DateFormatter()
    formatter.dateFormat = "HH:mm"
    print(formatter.string(from: Date()))

The app is then run on my iPhone and I get the following results:
If the phone is set to 24 hour time (Settings > Date & Time > 24 Hour Time) the code prints "07:45" in the console.
If 24 hour time is switched off at the settings then "7:45 am" is printed in the console.
Question: How do I make the output consistent with the formatter rather than the phone settings?
Answer: DateFormatter uses the system's locale by default, but you can set it yourself to override the default. You can set the locale of the formatter like this:
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
formatter.locale = Locale(identifier: "en_US_POSIX") // This uses am/pm, use a different locale for 24-hour
print(formatter.string(from: Date())) // Prints "12:23"

You can force the time formatting like this:
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
formatter.setLocalizedDateFormatFromTemplate("HH:mm")
print(formatter.string(from: Date())) // Prints "09:47"

formatter.setLocalizedDateFormatFromTemplate("hh:mm")
print(formatter.string(from: Date())) // Prints "9:47 AM"

Comment: That appears to work.  Even though the "en_US" locale favours the 12 hour format, putting it in appears to make the formatter work as expected.  (Consequently, the comment appears to be wrong.)  I assume any locale might make the formatter work.  Some experimentation needed.  Thanks.
Comment: I see that setting the locale to any value, valid, invalid or even to an empty String appears to fix the problem.
Comment: @VinceO'Sullivan you should use the system locale `"en_US_POSIX"` (English (United States, Computer)) when setting a custom dateFormat not `"en_US"` or anything else.
Comment: I added the use of `setLocalizedDateFormatFromTemplate` to my answer, I think thats the way to go.
Answer: Change the dateFormat to HH:mm aa:
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm aa"
print(formatter.string(from: Date()))

Output: (24-hour format is on/off)
11:14 AM
Comment: Thanks, but I don't want that format.  I want "HH:mm" as per my question.
Comment: @VinceO'Sullivan You'll get the same time-format, Except that you'll get the AM/PM in the time. You asked about consistency, this is the one irrespective of the 24-hour format is ON/OFF. Why downvote?

Inconsistent Date format


Turn Internet connection on

Question: It is possible to active WiFi or mobile internet at the backend from one application?
I create an application which needs Internet access. The app should check the Internet connection when it starts. If there is no connection, then turn WiFi or mobile Internet connection on.
Is this possible?
I use the ConnectiveManager to check connectivity state.
Answer: You can use setWifiEnabled() to change the wifi state.
If there are no wifi networks configured, it should automatically use the data network if any.
Use the ConnectivityManager to check if there are any data networks.
Comment: You can not enable Mobile network data without having system privileges granted. This is by design so application can't abuse billable feature. You should show standard Android's settings screen so user can enable that herself.
Comment: Can i make this simular with mobile net?

Turn Internet connection on


How urgent is it to fix cracks in foundation?

Question: I have a house with a floating slab floor built on a cement foundation.  There is a crack in the foundation that is 1/8 inch wide which has existed since before I moved in 4 years ago.  I never thought it was a problem until a guy (who is in concrete repair sales ) told me I should get it fixed.
Unless the crack gets wider or there are observable problems in the house, I'm considering not addressing it at all.  Is this a bad strategy?
If I do wait to fix it, will it likely be much more expensive down the road?
Comment: You're title is asking about cracks in the foundation (which in your case is a slab), but your question body describes settling. Which is it? Also, what is "the floorboard"?
Comment: Depends on the cracks. Photo would help.
Comment: There is a bit of difference between a "floating slab" foundation and a house built on a foundation that also has a floating slab floor. I believe yours is the latter. I would fill that crack with chalk and monitor. If it continues to separate, repairs are in order; if not...
Comment: Oops! I meant caulk, not caked calcium carbonate.
Answer: Small hairline cracks are fairly common in foundations and slabs. They are usually caused by ground subsidence, and typical freeze/thaw cycles. They can also form almost immediately after the slab is poured for various reasons. If the crack continues to open, or there is any shift in the slab, you definitely would want to get it checked out by a professional.
Slabs can be very costly to repair. There are techniques out there such as slab jacking, and underpinning the foundation. These kinds of repairs can be in the tens of thousands of dollars.
Honestly, this sounds like a scare tactic from your contractor to drum up some business. If I were you, I would first fill the crack with a caulk made to fill cracks in concrete, and keep an eye on it. If a full Winter season passes, and there is no change in it, then it should be stable enough to leave it. Just be sure to check it periodically, and inspect for other cracks.
Answer: Best thing to do would be to have a structural engineer inspect it. Some of these types of problems are much easier and cheaper to fix early on. Some settling is expected in any house, but it can get expensive in a hurry if it continues, I just watched a home renovation show where they bought a house out of foreclosure, pulled up the carpet and found HUGE cracks in the slabs in almost every room, ended up being close to $50k to fix! I think it would be worth it to have a professional come out and evaluate it and go from there.
Comment: Expensive drama on a "reality" show? Crazy.


How can I remove this piece from my bathroom sink handle?

Question: I have been trying to remove an old bathroom faucet for two days and I'm stuck.
I can't remove the old faucet handles because I can't seem to remove the part shown in the picture (the big nut and the waterline connector socket pointing toward the camera).

I have tried using a normal wrench, a basic wrench, channel locks, etc. Thinking maybe it was rusted on, I applied a heaping amount of wd-40 to try to break that down but it didn't work. I'm honestly not 100 percent sure this even comes off at this point. But I can't even get around it to remove the other gold looking nut at the top.
I'm just stuck on what to do next. There's barely any room under my sink which has made this a nightmare  any and all help will be much appreciated
Comment: Probably need a basin wrench or crow's foot wrench/spanner as mention in this answer.  https://diy.stackexchange.com/questions/150779/how-can-i-unscrew-this-nut-with-little-clearance?rq=1
Comment: With brass nut, might want a crow's foot flare wrench instead of regular wrench to prevent rounding the corners.
Answer: That type faucet is usually installed on the sink before the sink top is laid into place. Once you set the sink top in place there is not enough room to get a wrench in to loosen a tight fitting that you are experiencing. Lift the sink top off the cabinet, replace the faucet or make necessary repairs and reinstall the top.
Comment: I agree with this suggestion, however, do you have a tip on how to remove a sink that's been set in some form of caulk or, even worse, construction adhesive (as they often are) without destroying the sink and/or cabinet?
Answer: My general rule of thumb is that if the plumbing is 20 years old or more, it usually has to be cut off. And often, even if the plumbing is not 20 years old! Try cutting the upper nut with a Dremel tool outfitted with a metal cutting bit. Also make a similar vertical cut in the lower piece or just hack the whole lower part off.
This suggestion assumes that you can't get a sawzall or hacksaw in there and you don't want to remove the sink.


USB devices not regconized

Question: I am using Ubuntu 12.04. When I mount a USB flash drive, my laptop does not recognise those devices. Can you help me to solve this problem?
lsusb output:
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 007 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 008 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 001 Device 002: ID 0bda:0158 Realtek Semiconductor Corp. USB 2.0 multicard reader
Bus 001 Device 003: ID 04f2:b091 Chicony Electronics Co., Ltd Webcam
Bus 002 Device 004: ID 7614:1236

If you need more details just ask :(
sorry but i really new in ubuntu >"< give me some specific details please... thanks
Comment: Is there any solution to this question?
Answer: There is probably a problem with the drive, or the partition/MBR is messed up.
After you plug it in, enter this in the terminal:
dmesg | tail
what does it say?  Usually from the error message you can tell what the problem is.
Comment: Also: `while true; do sudo dmesg -c; sleep 1; done`, and repeat plug-in/remove the USB device.
Comment: But then you only have 1 second after it clears to type `dmesg` again so you can save it.
Comment: Could you rephrase that? I'm not sure I understand what you mean.
Comment: If you paste that loop in, every 1 second, the kernel ring buffer [dmesg] will be cleared.  Once you type in the sudo password once, it doesn't require it for the rest of the session.  So there, the loop is erasing the log messages every second, you have to type in `dmesg` in another terminal at just the right time or it will be blank.  Do you get it now?

USB devices not regconized


Macro used on multiple workbooks to reset sheets

Question: I am looking to write a macro that will reset sheets within a workbook that has multiple sheets. Essentially here is what it will do:
1. clear cells on Sheet1 B3, B6 and B9 of active workbook where macro is activated (all file names will be different. For example lets call these workbooks "Active")
2. open template file (let's call this file Partner_Checklist.xlsm since this file will be consistent throughout the macro)
3. select all content in Partner_Checklist.xlsm from sheet1
4. Copy all content in Partner_Checklist.xlsm sheet 1
5. Paste content into Active workbook in Sheet2
6. Close Partner_Checklist.xlsm
This will be used for a project where every quarter we need to use these workbooks to perform an audit. Workbooks need to be cleared of the previous review and if the template is updated, make it easier to update across all workbooks.
Any help would be great. Thanks.
Comment: "I am looking to write a macro" - OK so what *precisely* is the problem?  Are you stuck on one particular step?  Have you tried recording a macro and looking at the resulting code?
Answer: The easiest way I can think of is to use the macro recorder, and save a macro of  the operations you want to repeat. If you are unsure of what that is, you have to have the developer tab enabled on your ribbon, then the option to use macro recorder will be on the top left. Here is a link on how to enable the developer tab.
https://msdn.microsoft.com/en-us/library/bb608625.aspx
Record yourself doing it once, then save the macro. Now you can execute that macro anytime, and it will perform the exact operations that you performed while recording.


How to create a struct and its attributes dynamically using go code?

Question: I am new to golang
How to create a struct and attributes dynamically from gocode,
it has to store it as a file in the end.
For example:
Struct name: user
By default, it has to create Name attribute
type User struct {
    Name string
}

it has to store as a file ex: user_struct.go
Could you please someone help to find a way to do it
Comment: Use [text/template](https://golang.org/pkg/text/template/) to write Go code. Use [go/printer](https://golang.org/pkg/go/printer/) to format it.
Comment: Please clear what you actually trying to accomplish.
Comment: @Peter Could you please explain me with details or an example
Answer: Use text/template to write Go code. Since I don't know how you want to do this in detail, I'll use a trivial template in the example. Any kind of real world template is bound produce ill-formated code, but thanks to go fmt you pretty much only have to get the newlines right (leverage semicolons if you ever have trouble with that). go fmt uses go/printer under the hood, and you can too.
See the linked package documentation and examples for details.
package main

import (
    "bytes"
    "go/parser"
    "go/printer"
    "go/token"
    "html/template"
    "io"
    "log"
    "os"
)

var structTpl = `
    package main

    type {{ . }} struct {
            Name string
    }
    `

func main() {
    // Only do this once per template at the start of your program.
    // Then simply call Execute as necessary.
    tpl := template.Must(template.New("foo").Parse(structTpl))

    messy := &bytes.Buffer{}
    tpl.Execute(messy, "User")

    // Parse the code
    fset := &token.FileSet{}
    ast, err := parser.ParseFile(fset, "", messy, parser.ParseComments|parser.DeclarationErrors)
    if err != nil {
        log.Fatal(err)
    }

    // Print the code, neatly formatted.
    neat := &bytes.Buffer{}
    err = printer.Fprint(neat, fset, ast)
    if err != nil {
        log.Fatal(err)
    }

    io.Copy(os.Stdout, neat) // Or write to file as desired.
}

Try it on the playground: https://play.golang.org/p/YhPAeos4-ek
Answer: If you are looking for ast based meta info about struct, receivers, etc  you may consider the following:
package main
import  "github.com/viant/toolbox"

func main() {

    goCodeLocation := ".."
    fileSetInfo, err := toolbox.NewFileSetInfo(goCodeLocation)
    if err != nil {
        panic(err)
    }
    toolbox.Dump(fileSetInfo)
}


python: make websocket connection to elevenlabs with websocket-client

Question: In elevenlabs you can now use the stream feature also with input stream. However, a socket connection must be established for this.
Unfortunately I have to implement the websocket connection myself instead of using the elevenlabs python client, because i have to use the websocket-client library and the elevenlabs client is using a different websocket library.
The problem is, however, that
data = json.loads(ws.recv())
blocks forever and nothing ever seems to arrive. what did I do wrong?
here is my code(BOS and EOS are exactly the same as in the documentations code of elevenlabs python client and rest of it is also nearly the same code):
with closing(create_connection(url, header={"xi-api-key":"mykey")) as ws:

                # Send beginning of stream
                ws.send(BOS)

                # Stream text chunks and receive audio
                for text_chunk in text_chunker(text):
                    data = dict(text=text_chunk, try_trigger_generation=True)
                    ws.send(json.dumps(data))
                    try:
                        data = json.loads(ws.recv()) -> blocking here, never gets over it
                        if data["audio"]:
                            yield base64.b64decode(data["audio"])  # type: ignore
                    except TimeoutError:
                        pass

                # Send end of stream
                ws.send(EOS)

                # Receive remaining audio
                while True:
                    try:
                        data = json.loads(ws.recv())
                        if data["audio"]:
                            yield base64.b64decode(data["audio"])  # type: ignore
                    except ws.exceptions.ConnectionClosed:
                        break

with the original code from the elevenlabs client , which uses the websockets.sync.client library, it works as expected
Answer: found a solution by using WebSocketApp in a thread.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Unable to retrieve data from azure easy table & bind it to a List in Android Studio

Question: I'm developing an Android App and I've created an App services in Azure & I've been trying to understand how to communicate with the DB through the MobileAppServices.
I was successful to Add items into the Tables (Easy tables) but, I couldn't retrieve data from the tables.
I've tried in 2 ways:
Retrieving data with/without AsyncTask.
(1)  I get An error. (Using AsyncTask)
public void onClickVerify(View view)  {

        if (mClient == null)
            return;

        AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    final List<Users> URS = GetItemsFromMobileServiceTable();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Verified = "Account is not Verified";
                            for (Users i : URS) {
                                if (i.getUN() == null)
                                    break;

                                else if( i.getUN() == Username.toString()) {
                                    Verified = "Account Verified";
                                }
                            }
                        }
                    });
                } catch (final Exception e) {}

                return null;
            }
        }.execute();

        runAsyncTask(task);

    }

   private List<Users> GetItemsFromMobileServiceTable() throws ExecutionException, InterruptedException, MobileServiceException {
        return mUser.where().field("UN").eq(Username.toString()).execute().get();
    }

                                              --------- beginning of crash 03-14 12:40:54.623 3500-3500/com.himk.karam.h

E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.himk.karam.h, PID: 3500
                                                                  java.lang.IllegalStateException: Could not execute method for
  android:onClick
                                                                      at android.view.View$DeclaredOnClickListener.onClick(View.java:4725)
                                                                      at android.view.View.performClick(View.java:5637)
                                                                      at android.view.View$PerformClick.run(View.java:22429)
                                                                      at android.os.Handler.handleCallback(Handler.java:751)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:154)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                   Caused by: java.lang.reflect.InvocationTargetException
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at android.view.View$DeclaredOnClickListener.onClick(View.java:4720)
                                                                      at android.view.View.performClick(View.java:5637)
                                                                      at android.view.View$PerformClick.run(View.java:22429)
                                                                      at android.os.Handler.handleCallback(Handler.java:751)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:154)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                   Caused by: java.lang.IllegalStateException: Cannot execute task: the
  task is already running.
                                                                      at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:609)
                                                                      at com.himk.karam.h.Login.runAsyncTask(Login.java:183)
                                                                      at com.himk.karam.h.Login.onClickVerify(Login.java:114)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at android.view.View$DeclaredOnClickListener.onClick(View.java:4720)
                                                                      at android.view.View.performClick(View.java:5637)
                                                                      at android.view.View$PerformClick.run(View.java:22429)
                                                                      at android.os.Handler.handleCallback(Handler.java:751)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:154)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

(2) when launching the Activity that contains that Retrieving action the Activity doesn't load.(without using AsynTask)
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    try {
        mClient = new MobileServiceClient("https://khim.azurewebsites.net",this);

        mClient.setAndroidHttpClientFactory(new OkHttpClientFactory() {
            @Override
            public OkHttpClient createOkHttpClient() {
                OkHttpClient client = new OkHttpClient();
                client.setReadTimeout(20, TimeUnit.SECONDS);
                client.setWriteTimeout(20, TimeUnit.SECONDS);
                return client;
            }
        });

        List<Users> mUsers = mClient.getTable(Users.class).execute().get();//if I remove this line the activity will load normally
        Username = (EditText) findViewById(R.id.etUN);
    } catch (MalformedURLException | InterruptedException | ExecutionException | MobileServiceLocalStoreException e) {
        e.printStackTrace();
    }
}

NOTE: ALL I WANT TO DO IS TO HAVE THE DATA IN A LIST IN ANDROID I DON'T WANT TO VIEW IT TO THE USER.
Comment: `Caused by: java.lang.IllegalStateException: Cannot execute task: the task is already running.` As the exception itself explains, you cannot execute an **AsyncTask** more than once. You can check out [this similar issue](http://stackoverflow.com/questions/6879584/how-to-run-the-same-asynctask-more-than-once) on SO for more info.
Answer: Like Aaron Chen points out, the exception is about executing AsyncTask more than once. In your #1 implementation using AsyncTask, the task is executed twice. First time in AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){@Override protected Void doInBackground(Void... params) { /*...*/ }.execute();, the second time in mUser.where().field("UN").eq(Username.toString()).execute().get();. If you remove the execute() from the first one, it should work just fine.
In your #2 implementation, the activity doesn't load because you're running an async query on UI thread in onCreate() method. If you run it on a background thread, this problem will go away. You can check out this azure documentation on how to query data from your Mobile App backend. There's plenty of examples that should be helpful.


Button does not center inside RelativeLayout that have gravity=center

Question: I have a button inside relative layout that I want to center along with input edit text. I added android:gravity="center"  to relative layout, every was centered correctly other than the button, I even tried to add android:layout_centerInParent="true" to the button but it didn't work. What could be the issue?
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_gravity="bottom">

<ImageView
    android:id="@+id/imageView"
    android:src="@drawable/logo"
    android:layout_weight=".3"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_marginTop="10dp"
    android:layout_gravity="center_horizontal"/>

<RelativeLayout
    android:layout_weight=".1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center">

    <EditText
        android:id="@+id/et_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:hint="Email"/>

    <EditText
        android:id="@+id/et_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_email"
        android:inputType="textPassword"
        android:hint="Password"
        android:ems="10"
        android:layout_marginBottom="20dp"
        android:imeOptions="actionDone"/>

    <Button
        android:id="@+id/b_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_password"
        android:text="Login"/>

</RelativeLayout>

<View
    android:layout_weight=".1"
    android:layout_width="match_parent"
    android:layout_height="0dp"/>

Button is not centered:
Comment: your `LinearLayout` has two child that has weight, if you set gravity to center,you just make view in center of that child not hole screen
Comment: the relative layout has weight and fill parent in width, and I want to center every child inside the relative layout
Answer: android:gravity="center" is a property of LinearLayout so its direct child (the RelativeLayout) inside of it. You still need to center the children inside the RelativeLayout. To center the Button inside of its parent RelativeLayout use android:layout_centerHorizontal="true"
<Button
    android:id="@+id/b_login"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/et_password"
    android:text="Login"
    android:layout_centerHorizontal="true"/>   // here

Docs
Update
Center each View inside of the RelativeLayout
 <RelativeLayout
android:layout_weight=".1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">

<EditText
    android:id="@+id/et_email"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp"
    android:inputType="textEmailAddress"
    android:ems="10"
    android:hint="Email"
    android:layout_centerHorizontal="true"/>

<EditText
    android:id="@+id/et_password"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/et_email"
    android:inputType="textPassword"
    android:hint="Password"
    android:ems="10"
    android:layout_marginBottom="20dp"
    android:imeOptions="actionDone"
    android:layout_centerHorizontal="true"/>

<Button
    android:id="@+id/b_login"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/et_password"
    android:text="Login"
    android:layout_centerHorizontal="true"/>

Comment: So what happened, your `Button` didn't move? That should have worked
Comment: Hmmm...it worked for me by removing `gravity` from the `RelativeLayout` then putting `android:layout_centerHorizontal="true"` in each of the 3 `View`s of the `RelativeLayout`. Then they are all centered. Try that
Comment: Thanks for the answer but the issue with that is I want to center all children combined of relative layout in the middle of its view (horizontally and vertically), and thats why I need to use gravity.
Comment: If you looked at this picture, my relative layout is the gray area and the white area is where the children are centered http://projecteuler.net/project/images/p_173_square_laminas.gif
Comment: I actually did have `gravity` in the `RelativeLayout` when I tried it and it worked for me unless I just don't understand what you want. But that centered all of the children in the `RelativeLayout` and that should be centered in the `LinearLayout`.
Comment: You got it right, for some reason I thought the gravity was not there at first. kudus to you for spending the time to test it and answer.
Comment: I didn't have the `gravity` at first so that was my fault then I edited. Sorry, had several things going on. Glad its working for you. They was that the children needed to be told to be centered in their direct parent (the `RelativeLayout`). The `gravity` in the `RelativeLayout` only applies to its overall position in its direct parent (the `LinearLayout`) not its children.
Answer: Try this..  Use LinearLayout instead of RelativeLayout
<LinearLayout
    android:layout_weight=".1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center">

    <EditText
        android:id="@+id/et_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:hint="Email"/>

    <EditText
        android:id="@+id/et_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_email"
        android:inputType="textPassword"
        android:hint="Password"
        android:ems="10"
        android:layout_marginBottom="20dp"
        android:imeOptions="actionDone"/>

    <Button
        android:id="@+id/b_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_password"
        android:text="Login" />

</LinearLayout>

OR in Your same layout just remove android:gravity="center" add android:layout_centerHorizontal="true" for each EditText and Button
<RelativeLayout
    android:layout_weight=".1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/et_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:inputType="textEmailAddress"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:hint="Email"/>

    <EditText
        android:id="@+id/et_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_email"
        android:inputType="textPassword"
        android:hint="Password"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:layout_marginBottom="20dp"
        android:imeOptions="actionDone"/>

    <Button
        android:id="@+id/b_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_password"
        android:layout_centerHorizontal="true"
        android:text="Login" />

</RelativeLayout>

Comment: The reason I use gravity=center instead of setting each view to center, is that gravity treats all children as one and centered in the relative layout both horizontally and vertically.
Answer: Try this code:
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent" android:layout_gravity="bottom">

<ImageView
    android:id="@+id/imageView"
    android:src="@drawable/logo"
    android:layout_weight=".3"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_marginTop="10dp"
    android:layout_gravity="center_horizontal"/>

<RelativeLayout
    android:layout_weight=".1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center">

    <EditText
        android:id="@+id/et_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:hint="Email"/>

    <EditText
        android:id="@+id/et_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_email"
        android:inputType="textPassword"
        android:hint="Password"
        android:ems="10"
        android:layout_marginBottom="20dp"
        android:imeOptions="actionDone"/>

    <Button
        android:id="@+id/b_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_password"
    android:layout_gravity="center"
        android:text="Login"/>

</RelativeLayout>

<View
    android:layout_weight=".1"
    android:layout_width="match_parent"
    android:layout_height="0dp"/>


Is there an ideal time between paint coats?

Question: I have been repainting my house and wondering about recoat times.
For instance, the gloss I am using states touch dry in 2h, recoat in 6h and fully cured in 24h (depending on temperature, humidity, etc).  Obviously I should wait at least 6h before the next coat.  But is it any better (or worse) to wait longer, e.g. 48h? It seems plausible that the next coat might bond better if the first one is not fully cured, but is this true?
Comment: Follow the instructions on the tin - RTFM. If you leave one coat to cure too long then the second coat can come off easily, and seen this.
Comment: If you wait beyond the cure time of gloss paint then you need to scuff up the entire wall with sandpaper that's 200 grit or finer so that the new coat can adhere properly. Washing down the wall with denatured alcohol would also have the same effect but make sure you have good ventilation.
Comment: It depends on the paint, read instructions. I once used a automotive paint that said " recoat within 24 hours or wait 7 days", so different paints are different.
Comment: @MonkeyZeus are you telling me I don't need to sand if I recoat before full cure? That's hours of my life I'll never get back...
Comment: No specific instructions on this paint, just looking for general guidelines
Comment: Correct. Also, if the existing wall was glossy then you should have sanded it before the first new coat.
Answer: The different dry times listed on paint are really what you need to know in this situation.  The "dry to touch" time means that you can let people back in the area and they won't accidentally get wet paint on them, but that's about all it means.
When you recoat paint too early, the new coat will actually re-wet the previous coat, and your coverage or the paint's hiding ability (hiding stains/colors under the paint) will go down.  Two coats will end up actually being like 1.5 coats or less in some situations.  Not what you want.
So, that's where the recoat time comes in.  At this point, the paint is dry enough that a new layer of paint will not fully re-wet the first layer, but it hasn't been so long that there will be adhesion issues.  This is the optimal time to put on another coat, but its not an exact science.  The time will need to be adjusted based on temperature and air flow, but its a good starting point.
The last time is a "full cure" and after that time has elapsed, the next coat might not stick as well, or at the very least, might not cover very well if you're using a glossier sheen.  Try to recoat before this time has elapsed.  One other note, with a latex/acrylic paint, it might say that "full cure" is 24 hours, but that is rarely true.  It might be something like 75% cured, and 100% can take weeks or longer (to reach its full hardness and durability).


How to speed up Evolution

Question: I have a moderately big Inbox file (around 2.3Gb) and Evolution takes a lot to start (it takes over 2.5 mins until I can perform any action -read or compose mail, for instance-). During that time, the shole system becomes unresponsive, with high HD activity.
It becomes unresponsive when retrieving mail, too: it stalls for about 30 secs. Closing evolution can take yet another 1.5 minutes, also.
Is there any way I can speed things up?

Last Edit: As I have checked that reducing my inbox file size (by means of moving old mail to an 'Archived Mail' folder) does the trick of speeding everything up, while keeping a copy of every mail at hand, my ultimate question is:
Is there any "auto-archive" feature or plug-in or script or anything for Evolution? I could do it "by hand" using saved searches and such, but it would be nice to have it automatically done (as it is in Outlook, for instance)

Previous Edit:
Answering comments:

Evolution retrieves POP mail from gmail and a personal postfix/courier mailserver
I could change to any other mail client provided that A) migration is easy enough  B) Speed problems are likely to vanish with the new client and C) I can sync contacts and calendar with gmail
I'm not experiencing high HDD activity problems with other apps, and swap is not (or at least should not be) a problem, since it's usually at 0% (I'll keep an eye on it, anyway)

Other considerations:

I used to work with Outlook and it managed several 2 Gb files (one was actually the inbox, and three were "archive.pst" files, to which I never added more mails, except when Outlook auto-archived old ones). I even would like to add this pst files to Evolution, so that I can be able to search old mails, but A) I don't know how and B) I'm scared... If evolution can't handle properly a 2.3 Gb file, adding load would be a bad idea, I suppose.
I guess things would speed up if I could "move" some old mail from my Inbox file to another one, but it should be readable and searchable. Anyway, I don't know if this can be done with Evolution, and, as stated, is just a guess.
Comment: Evolution is naturally a little slow. Have you considered another email client, such as Thunderbird?
Comment: Have you got the same problems with other HDD intensive applications? How much of you swap is used when running Evolution?
Comment: A solution that might be overkill is to get an SSD to increase read speed.
Comment: imap or pop? What email service?
Comment: @wojox: pop.... retrieving from gmail and also from personal mail server (postfix+courier)
Comment: @N.N.: No other HDD intensive applications that I can recall. Swap is not used unless I'm using Chorome (tens of tabs open) and a W7 VM.... (I have 8Gb RAM, so swap should not be a problem).... About the SSD... yes, it would be fine, but I'd rather fix it some other way. No budget available :(
Comment: @Warrioring64: I will if I can't fix this one... I'll ask for transition details if necessary....
Comment: @luri Have you tried putting the inbox file on another computer with Evolution to see if it's as slow?
Comment: Not really... actually, this is my "big" machine (8Gb RAM, AMD X6...) Ohers would be an old P5 and my laptop, whose specs are quite lower. Why do you think it could be specifically *this* computer?
Comment: @luri Might be a specific setting on that computer or driver related. Might help to nail the problem down by trying it on another computer.
Comment: I have.. same behaviour... When I open Evolution, the Inbox file is copied (obviously to the same location ~/.local/share/evolution/mail/local). The same happens when I receive mail. It does not seem to "append" anything to the file, but just plainly rewrite it all... The (partial) solution I'm trying right now is: A) Create a filter (search) to select old mails (let's say 2 years old) B) Move these mails to another folder (which means another file) which I imaginatively called OLDMAILS and C) Purge trash (as they're copied there, too when moved)... this way, the Inbox file gets thinner.
Comment: The funny thing is when I import (via pop) mails from Gmail, no matter if they are 'received' or 'sent' by me, it all goes to my Inbox, so it's actually a 'EverythingBox'.... Maybe I should move sent mail, too, to 'Sent mail' folder, reducing the load of work on the -actual- Inbox file
Answer: Beware the .PST files are limited in size by design, i do not recommend using THAT big size into a single file. I use netcat for mail, when no Web avaliable.
Comment: Ok..... The question is... how do I split my Inbox file (it's important to recal that *I haven't added the big .pst files yet*, I'm just talking about my Evolution default Inbox file) in smaller chunks?

How to speed up Evolution


SQL find rows in table based on search results in another table

Question: I'm looking for a way to search a table values from the results of a query on another table :
SELECT entry_id FROM FEEDENTRYSTATUSES WHERE starred > 0 ;
+----------+
| entry_id |
+----------+
|     1036 |
|     1059 |
+----------+
2 rows in set (0.00 sec)

SELECT url from FEEDENTRIES WHERE id = 1036 ;
+---------------------+
| url                 |
+---------------------+
| https://google.com/ |
+---------------------+
1 row in set (0.00 sec)

So I can get a list of IDs from the FEEDENTRYSTATUSES table.
I can retrieve value from second table manually by giving the value 1036.
But I would like to search in table FEEDENTRIES from values returned by first SELECT.
Is here a way to do so ?
Any help very much appreciated.
Thanks a lot
Comment: Go for `INNER JOIN`.
Answer: You can use IN operator and subquery to achieve that:
SELECT url from FEEDENTRIES
WHERE id IN (SELECT entry_id FROM FEEDENTRYSTATUSES WHERE starred > 0);

Or join the tables and filter the data that you need:
SELECT fe.url from FEEDENTRIES fe
    INNER JOIN FEEDENTRYSTATUSES fes ON fe.id = fes.entry_id
WHERE fes.starred > 0;


run an Excel Macro from Python (but an Excel process stays in memory)

Question: with the following python method, I make a call to an Excel macro. I was happy when I got that to work, however I was wondering everytime I was executing this I could see a Windows temporary/lock file of the same name as the .XLA I was using the Macro from.
class XlaMakeUnmake:

    __configFile = 'xla_svn.cfg'
    __vbaTools = 'makeProtected.xla'
    __entries = {}

    def __init__(self):
        self.__readConfig()

    def __newDirs(self, dir):
        try:
            os.makedirs(dir)
        except OSError, e:
            if e.errno != errno.EEXIST:
                raise

    ### WILL ONLY WORK FOR UNPROTECTED
    '''
    filePath: path of XLA to unmake
    outputDir: folder in which the lightweight xla and its components will be pushed to
    '''
    def unmake(self, filePath, outputDir):
        xl = win32com.client.Dispatch("Excel.Application")
        xl.Visible = 0
        self.__newDirs(outputDir)
        xl.Application.Run("'" + os.getcwd() + os.sep + self.__vbaTools +   "'!Unmake", filePath, outputDir)

When I open the task manager, I can see that an Excel process is still running... How to kill it but in a clean fashion when the job is done ? Is xl.Application.Run launching an asynchronous call to the Macro ? In which case it might be tricky...
Thanks guys !! ;)
Comment: You need to release the instance of the Excel application. Not sure how to do that in Python; in VB, you'd set `xl = Nothing`, in Delphi you'd set `xl := nil;`, if that helps.
Comment: I tried to do a "xl = None", but not effect
Answer: I don't know Python, but you need to use:
xl.Quit

Comment: I tried that after "xl.Application.Run", python doesnt complain, but no effect.
Comment: Ahhh, stupid me, I had to do xl.Quit(), otherwise python takes that as a new attribute of the object. It works !


AngularJS, Module object and form name

Question: I having trouble to understand some weird problem, I will explain as sort as i can:
For example i got this form:
<form method="post" action="index.htm" name="chat" novalidate>
        Some error message
        <textarea ng-required="true" type="text" maxlength="200" id="message" name="message" ng-pattern="patterns.chatMessage" ng-model="chat.message"></textarea>
        <input type="submit" value="send" ng-disabled="chat.$invalid">
</form>

Please note(because i didn't included all the code) that ng-pattern="patterns.chatMessage" patterns is a $rootScope property.
So when the page load i was expecting chat.message.$error.pattern to be false, But apparently unless i will set ng-model="some other object like client.message" or set ng-model="some other object property like chat.comment" When the page load chat.message.$error.pattern will be true, So basically if the model object.property is the same as the formName.textareaName i got this wierd problem.
In sort what is happen is that chat.message.$error.pattern is set to true from the moment the page load, If anyone can please explain what is the problem here i will be very thankful, Thank you all and have a nice day.
Answer: You cannot use the same scope variable in form's name tag and in your ng-model.
When you use a form tag in angular, and that tag has a name attribute (e.g. chat), the Angular will create an instance of ngFormController on current scope and will assign that instance to a variable as specified in name attribute (in this case chat).
If you use this very same scope variable chat to host your ng-model than your ngFormController (defined on $scope.chat) will become overwritten by your model and it will produce erratic results.
So, to fix things, you need to rename your form:
<form method="post" action="index.htm" name="chatForm" novalidate>
  Some error message
  <textarea ng-required="true" type="text" maxlength="200" id="message" name="message" ng-pattern="patterns.chatMessage" ng-model="chat.message"></textarea>
  <input type="submit" value="send" ng-disabled="chatForm.$invalid">
</form>

Comment: Thank you Stewie, I understand now, Can you give me a link so i can read more about ngFormController.
Comment: When in doubt look at the docs: **[`form` directive](http://docs.angularjs.org/api/ng.directive:form)** and **[FormController](http://docs.angularjs.org/api/ng.directive:form.FormController)**.

AngularJS, Module object and form name


Add comma at end of each line

Question: I have several html files in a folder, like this:

Hello Guys
Wassap Guys
Bye Guys

In Python I want to open the file and add comma , at end of each line Like this:
,
Hello Guys,
Wassap Guys,
Bye Guys,
,

Then bring them into one line like this:
,Hello Guys,Wassap Guys,Bye Guys,,

Here's what I tried:
import os
for i in os.listdir():
    with open(i, "w+") as f:
        f.write(",".join(f.readlines())+",")

But when i run the module, it deletes all the contents of the html file and leaves only one comma
I also tried this code that a friend sent it to me
import glob
import os
files= glob.glob("C:\\test\\*.html")
for i in files:
    with open(i,'r') as in_file:
        out_file_name = os.path.basename(i)
        with open(f"C:\\test\\{out_file_name}",'w') as out_file:
            out_file.write(','.join(in_file.readlines())+',')
    in_file.close()
    out_file.close()

Answer: You opened the file in write-append mode.  Thus, readlines returns an empty list.
Instead, read the file, close it, and reopen in w mode to overwrite the original contents.
with open("test.txt", "r") as f:
    content = [line.strip() for line in f.readlines()]

with open("test.txt", "w") as f:
    f.write(",\n".join(content)+",")

Comment: gives me err: expected an indented block
Comment: The posted code does not produce that error with Python 3.8.2; you'll have to post what you're doing.
Answer: file_name = "test_file"
string_to_add = "added"

with open(file_name, 'r') as f:
    file_lines = [''.join([x.strip(), string_to_add, '\n']) for x in f.readlines()]

with open(file_name, 'w') as f:
    f.writelines(file_lines)

Answer: You could try this. This gets the file, replaces the new line symbol \n with ,\n to get what you want. Similar to Prune's answer but he adds it to the start of the line as well, my one only adds it to the end.
import os
for i in os.listdir():
    with open(i, "r") as f:
        content = f.readlines()

    with open(i, "w") as f:
        lines = []
        for line in content:
            new_line = line.replace("\n","") + ",\n"
            lines.append(new_line)
        f.write("".join(lines))

Comment: i also added encoding="utf8", worked but i dont want to replace "\n" with ",\n". I want to bring them in one line. Find"[\n\r]+" Replace with "," works on Notepad++ but not working in python
Comment: I don't understand @Michael

Add comma at end of each line


Raw DB querying in Rails

Question: I'm trying to run the following raw query in rails, only to see it fail:
query   = 'SELECT * FROM users WHERE id IN ($1);'
results = ActiveRecord::Base.connection.exec_query(query, "My query", [ [1,2] ]);

What am I doing wrong?
The error I'm getting starts with this:
Could not log "sql.active_record" event. NoMethodError: undefined method `binary?' for 1:Fixnum

Clearly, I'm misusing [1, 2] bind params somehow, but I couldn't find a proper example myself.
P.S. This is minimal failing example, derived of a much more advanced query that can't be turned into ActiveRecord chain of calls. In other words – I can't rely on Arel when building my query.
P.P.S. I'm using rails 4.0.1 and postgresql 9.3
Comment: I am not sure about postgresql since I usually query for MySQL. But anyways, the syntax should be same. Try:

`query   = 'SELECT * FROM users WHERE id IN (?);'`

`results = ActiveRecord::Base.connection.exec_query(query, [1,2])`
Answer: I'm pretty sure your NoMethodError is coming from the logging stuff. If we look exec_query, we see this:
def exec_query(sql, name = 'SQL', binds = [])
  log(sql, name, binds) do
    # call exec_no_cache(sql, binds) or exec_cache(sql, binds)...

Then if we look at exec_cache, we see this:
def exec_cache(sql, binds)
  #..
  @connection.send_query_prepared(stmt_key, binds.map { |col, val|
    type_cast(val, col)
  })

so the binds are supposed to be column/value pairs. The PostgreSQL driver expects col to be a column object so that it can ask it what its name is and how it should format the val, that information is used by the log call in exec_query to produce something pretty and human-readable in the Rails logs. A bit of experimentation suggests that you can use nil as the col and everything is happy.
That means that we've moved on to this:
exec_query(
  'SELECT * FROM users WHERE id IN ($1)',
  'my query',
  [ [nil, [1,2]] ]
)

The underlying driver may or may not know what to do with the [1,2] array, I only have Rails3 with the PostgreSQL extensions available to test and it doesn't like the [1,2]. If Rails4 also doesn't like the array then you can pass the arguments one-by-one:
exec_query(
  'SELECT * FROM users WHERE id IN ($1, $2)',
  'my query',
  [ [nil,1], [nil,2] ]
)

Answer: I ran into a similar issue lately. It turns out that in the where in (?), ActiveRecord is expecting a string, not an array. So you can try passing in a string of comma-separated ids and that should do the trick.
Comment: I ran into this issue too but solved it by doing this:
`sql = "SELECT * FROM table_a WHERE identifier IN (?)"`
`where_equals = ["id_1", "id_2"]`
`ActiveRecord::Base.connection.exec_query(ActiveRecord::Base.send(:sanitize_sql_array, [sql, where_equals]))`
Comment: the `(?)` syntax did not work for me at first.  I switched to using the alternate `'%s'` syntax and then eventually hash syntax.  ```e.g.

sanitize_sql_array(["name=:name and group_id=:group_id", name: "foo'bar", group_id: 4])
# => "name='foo''bar' and group_id=4"

sanitize_sql_array(["name='%s' and group_id='%s'", "foo'bar", 4])
# => "name='foo''bar' and group_id='4'"
``` from https://api.rubyonrails.org/classes/ActiveRecord/Sanitization/ClassMethods.html#method-i-sanitize_sql_array

Raw DB querying in Rails


Can I have a hint on this combinatorics question?

Question: Six faces of identical cubes are painted 6 distinct colors. How many different cubes can be formed?
The answer is surprisingly small but that may be because I don't know how to express the different ways properly. I just incorrectly did $6!$ because if there are 6 ways to color the first face, there are now 5 colors left so 5 ways to color the second face. And so on. Why is this wrong?
Perhaps I need to make use of "identical" and "distinct" from the question. If the cubes are identical, I must divide the answer by something, perhaps $6!$ for the 6 identical faces? And there should be some "choosing" happening but I can see where this fits in but it must be for the "distinct" part. Choose colors as in $6C1, 5C1 ...etc$ but this is the same as $6!$
Please help
Comment: Keep in mind that 2 colorings may be considered the same if you can rotate one to get the other.
Comment: Cube 1: Top = Red, Bottom = Orange, Front = Yellow, Right = Green, Back = Blue, Left = Purple. Cube 2:  Top = Red, Bottom = Orange, Front = Purple, Right = Yellow, Back = Green, Left = Blue. If you rotate Cube 1 by 90 degrees about its vertical axis, you get Cube 2.
Comment: How can this happen if all of the colors are distinct?
Comment: [Burnside's lemma](https://en.m.wikipedia.org/wiki/Burnside%27s_lemma) is often useful in situations like this.
Answer: Two cubes that differ by a rotation are considered the same. There are $24$ ways to orient the cube, all of which are distinct because of the use of distinct colours, so $6!$ must be divided by $24$ to get the correct answer of $30$.
Comment: @user71207 You don't have to repaint the cube to turn it.
Comment: Ok. But why do you consider sides to be the same if the question stipulates that there are 6 distinct colors? The worked solutions say "If all the 6 sides were different it could be arranged in 6! Ways" and then process with your logic. I'm confused - what would a cube with "all 6 sides different mean"?
Comment: Ok thanks, I guess that analogy makes sense
Answer: This is perhaps a more concrete way to arrive at the answer.  Say we will color the faces with the colors, $R,O,Y,G,B,V$.  We have to color some face $R$.  Place the cube on the table, with that face down.  Now we have to color some face $O$.
We can paint the top face, or one of the lateral faces.  Suppose first that we paint the top face.  Now we have to paint one of the lateral faces $Y$.  Whichever face we choose, we can rotate the cube so that that face is facing us.  Now the cube is fixed in place.  $R$ on bottom, $O$ on top, $Y$ facing us.  We can't rotate it without changing the arrangement.   There are $3!$ ways to paint the remaining $3$ faces.
If instead, we paint one of the lateral faces $O$, we can rotate the cube so $O$ is facing us, and again we find it is fixed in place; $R$ on bottom, $O$ facing us.  We have $4!$ ways to paint the remaining $4$ faces.
You may be interpreting the question a bit too literally.  There are indeed $6!$ orders in which we can choose to color the faces of the cube, but in many cases, the results are indistinguishable.  The question is asking for the number of distinct cubes that can be made by coloring each face with one of $6$ given colors.
Answer:
If you label the cube counterclockwise $1$ through $4$ starting from the yellow face, the top face $5$, the bottom $6$, then if we are given the colors: yellow, blue, orange, clear, red and green, pretending the front most face is clear/see-through, a coloring of the cube would be a permutation: $\{1,2,3,4,5,6\}\rightarrow$ {yellow, blue, orange, clear, red, green}.
There are $6\cdot 5\cdot 4\cdot 3\cdot 2\cdot 1\cdot = 6!$ ways to color this cube. But now every coloring can be described the same way $6\cdot 4 =24$ 'different ways'. Looking at our cube, if we rotate it front, back, left, right, enough times we can have $6$ distinct bottom faces, the top face is automatically determined once the bottom face is. Next given a bottom face, we can rotate the cube $90^{\circ}$ counterclockwise 4 times and still have the same coloring.
Answer: Perhaps to record a more advanced answer for those who knows Burnside lemma from group theory:
Denote $X$ to be the set of all possible ways to label each of the 6 faces of the cube with exactly one of six distinct colors. There are $6!$ ways of doing this without considering which ones are the same by rotation.
Now the rotational symmetry group for a cube is the octahedral group $O \simeq S_4$ (https://en.wikipedia.org/wiki/Octahedral_symmetry) with $|O| = 24$.
Now the group $O$ acts on the set $X$, and in each orbit it contains all the colorings that are considered the same when up to rotation. By Burnside lemma, we have the number of orbits $|X/O| = \frac{1}{|O|}\sum_{g\in O} |X^g|$, where $X^g$ is the set of colorings that are unchanged by the action of $g$. Since the cube has six different colors, whenever $g\neq e$ we have $|X^g|=0$, as any nontrivial rotation will not fix the coloring configuration. Unless $g=e$, then we have $|X^e|=|X|= 6!$, as every configuration is fixed by identity.
Hence $|X/O| = \frac{1}{|O|}\sum_{g\in O} |X^g| = \frac{6!}{24}=30$.


disable send button when two conditions aren't met not working in ember.js

Question: I'm trying to create a contact form where the 'Send' button is disabled unless a valid email and a message has been entered. For some reason it's working in the reverse way, when valid email and message entered the button disables. I'm new to ember and cant seem to negate it.
Contact controller
export default Ember.Controller.extend({

email: '',

message: '',

hasValidEmailAddress: Ember.computed.match('email', /^.+@.+\..+$/),
hasEnteredMessage: Ember.computed.notEmpty('message'),

isDisabled: Ember.computed.and('hasValidEmailAddress', 'hasEnteredMessage'),

actions: {

    saveMessage() {
        this.set('responseMessage', `Thank you, your message has been sent. We will get back to you as soon as possible.`);
        this.set('email', '');
        this.set('message', '');
    }
}

});

Contact Template

Contact

        <form>

                Email
                {{input type='email' value=email class='form-control' id='email' placeholder='Email'}}

                Message
                {{textarea value=message class='form-control' id='message' placeholder='Message'}}

            <button class='btn btn-primary btn-default pull-right' disabled={{isDisabled}} {{action 'saveMessage'}}>Send</button>
        </form>

I've tried negating the isDisabled in the template, negating the arguments in the controller both inside and outside of the parenthesis for isDisabled and tried negating the entire line.
Any help would be much appreciated.
Cheers
Answer: In your code, the isDisabled property should actually be called isEnabled, since thats the result you are giving it. Because when hasValidEmailAddress=true AND hasEnteredMessage=true => isDisabled=true which will then disable your button.
You could make another computed property,
do reallyDisabled: Ember.computed.not('isDisabled') and use that in your template.
Or you can install ember-truth-helpers addon (https://github.com/jmurphyau/ember-truth-helpers) and then in you template do disabled={{not isDisabled}}


How can I restart NetHack, or at least replay the introduction?

Question: I feel guilty for what I did: When I first started nethack I skipped the introduction and the instructions.
Now, I don't know how to play that stupid game. I only know how to move. Is there a way to restart the game from the beginning on ubuntu?
Comment: If you don't know what to do, see this http://alt.org/nethack/mirror/www.geocities.com/TimesSquare/Portal/2416/intro.html
Comment: ...but note that the guide linked by @TheIdiotGamer is written for a fairly old version of NetHack (v3.1; current is v3.4.3), and some of the details are no longer true (for example, Elf is no longer a class). The [official guidebook](http://www.nethack.org/v343/Guidebook.html) is more accurate, but not as detailed. There's also a more up-to-date tutorial on [StrategyWiki](http://strategywiki.org/wiki/NetHack). And, of course, there's always the [NetHack Wiki](http://nethackwiki.com/).
Answer: I don't know if this will work, but try deleting or renaming the file <code>.nethackrc</code> in your home directory. This file contains all your settings so if you've made a extensive changes to them you may just want to rename it and then put it back after you've read the introduction.
Comment: thank you, actually it was call nethack.tty I found it in /etc/nethack.