text:
Q: Rails 4 nested form - nested models not saving I am getting ready to give up on this... I 've searched every question on this, done multiple tests and I can't figure it out.
I am trying to create new records of a model (absences) through nested attributes (classroom -> students).
Here is a hash that I manually created and gets saved when I call
# hash: {"classroom"=>{"rank"=>"aaa", "grade_id"=>"", "students_attributes"=>{"0"=>{"last_name"=>"aaa", "first_name"=>"aaa", "absences_attributes"=>{"0"=>{"class_time"=>"1", "status"=>"valid"}}}}}, "id"=>"26"}

@classroom = Classroom.find(params["id"])
@classroom.update(params["classroom"])

This gives me:
(0.5ms)  begin transaction
SQL (1.3ms)  UPDATE "classrooms" SET "rank" = ?, "updated_at" = ? WHERE "classrooms"."id" = ?  [["rank", "aaa"], ["updated_at", "2016-08-10 21:09:17.883875"], ["id", 26]]
SQL (0.2ms)  INSERT INTO "students" ("last_name", "first_name", "classroom_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)  [["last_name", "aaa"], ["first_name", "aaa"], ["classroom_id", 26], ["created_at", "2016-08-10 21:09:17.897997"], ["updated_at", "2016-08-10 21:09:17.897997"]]
SQL (0.2ms)  INSERT INTO "absences" ("class_time", "status", "student_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)  [["class_time", 1], ["status", "Αδικαιολόγητη"], ["student_id", 51], ["created_at", "2016-08-10 21:09:17.902018"], ["updated_at", "2016-08-10 21:09:17.902018"]]
(11.4ms)  commit transaction
=> true

HOWEVER
when I get this hash through the form submission the update doesn't happen and no "absences" are getting created. Here is what the console looks like:
Processing by ClassroomsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"blabla",
"classroom"=>{"students_attributes"=>{"0"=>{"absences_attributes"=>{
"0"=>{"student_id"=>"50", "date"=>"2016/08/17", "class_time"=>"1", "status"=>"valid"},
"1"=>{"student_id"=>"50", "date"=>"2016/08/17", "class_time"=>"2", "status"=>"valid"},
"2"=>{"student_id"=>"50", "date"=>"2016/08/17", "class_time"=>"3", "status"=>"valid"},
"3"=>{"student_id"=>"50", "date"=>"2016/08/17", "class_time"=>"4", "status"=>"valid"},
"4"=>{"student_id"=>"50", "date"=>"2016/08/17", "class_time"=>"5", "status"=>"valid"},
"5"=>{"student_id"=>"50", "date"=>"2016/08/17", "class_time"=>"6", "status"=>"valid"},
"6"=>{"student_id"=>"50", "date"=>"2016/08/17", "class_time"=>"7", "status"=>"valid"}},
"id"=>"50"}}}, "id"=>"27"}
Classroom Load (0.2ms) SELECT "classrooms".* FROM "classrooms" WHERE "classrooms"."id" = ? LIMIT 1 [["id", 27]]
(0.1ms) begin transaction Student Load
(0.3ms) SELECT "students".* FROM "students" WHERE "students"."classroom_id" = ? AND "students"."id" = 50 [["classroom_id", 27]]
(0.1ms) commit transaction

Here is my Classrooms Controller
class ClassroomsController < ApplicationController

  def new
    @classroom = Classroom.new
    @students = 30.times {@classroom.students.build}
  end

  def create
    @classroom = Classroom.new(classroom_params)
    if @classroom.save
      redirect_to @classroom
    else
      flash.now[:danger] = "Try again."
      render "new"
    end
  end

  def show
    @classroom = Classroom.find(params[:id])
  end

  def data
    @classroom = Classroom.find(params[:id])
    @classroom.students.each { |student| 7.times { student.absences.build } }
  end

  def update
    @classroom = Classroom.find(params[:id])
    @classroom.update_attributes(classroom_params)
    redirect_to @classroom
  end

  private
    def classroom_params
      params.require(:classroom).permit(:id, :grade_id, :rank, students_attributes:
        [:id, :classroom_id, :first_name, :last_name, absences_attributes:
        [:id, :student_id, :date, :status, :class_time]])
    end
end

Classroom Model
class Classroom < ActiveRecord::Base
  # belongs_to :grade
  has_many :students, inverse_of: :classroom, dependent: :destroy
  accepts_nested_attributes_for :students, allow_destroy: true,
  reject_if: proc { |a| [a[:first_name], a[:last_name]].any? {|b| b.blank?}}

  has_many :absences, through: :students
  accepts_nested_attributes_for :absences, allow_destroy: true,
  reject_if: proc { |a| a[:status].blank? }

  validates :rank, presence: true
end

Student Model
class Student < ActiveRecord::Base
  belongs_to :classroom, inverse_of: :students
  has_many :absences, inverse_of: :student

  accepts_nested_attributes_for :absences, allow_destroy: true,
  reject_if: proc { |a| a[:status].blank? }

  # validates :first_name, presence: true
  # validates :last_name, presence: true

  def full_name
    return last_name + " " + first_name
  end
end

Absence Model
class Absence < ActiveRecord::Base
  belongs_to :student, inverse_of: :absences

  # validates :date, presence: true
  # validates :class_time, presence: true
  # validates :status, presence: true, inclusion: { in: ["valid",
  #   "invalid", "erased"] }
end

I have turned off all validations as to be sure this is not the reason they are not being saved.
Nested form view

Absences

    <input type="text" class="form-control">

  <%= form_for @classroom do |class_f| %>
    <% @classroom.students.each do |student| %>
      <div class="student_<%= student.id %>">

<%= student.full_name %>

            <% 7.times do |i| %>
              <%= i + 1 %>
            <% end %>

          <%= class_f.fields_for :students, student do |student_f| %>
            <% student.absences.each_with_index do |absence, i| %>
              <div class="school-hour text-center" data-value="<%= i + 1 %>">
                <%= fa_icon "plus" %>
                <%= fa_stacked_icon "plus", base: "circle-o" %>
                <%= fa_icon "minus" %>
                <%= student_f.fields_for :absences, absence do |ab_f| %>
                  <%= ab_f.hidden_field :student_id, value: absence.student_id %>
                  <%= ab_f.hidden_field :date, class:"input-absence-date" %>
                  <%= ab_f.hidden_field :class_time, value: i + 1 %>
                  <%= ab_f.hidden_field :status, class:"input-absence-status" %>
                <% end %>

            <% end %>
          <% end %>

    <% end %>

      <%= button_to "Submit", "#", class:"btn btn-primary"%>

  <% end %>

The hidden fields without values are getting filled via javascript before form submission. I don't think that relates to the problem though. The params hash comes through, but the absences are not saving.

A: Without having spent a lot of time looking at this, could this be the problem?
reject_if: proc { |a| a[:status].blank? }

It appears the params are passing in status as "" which .blank? evaluates as true.
Whatever your form is passing in, in your first example you have "status"=>"valid" but in your 2nd example from the form "status"=>""

A: I found out that the problem was the reject_if on the classroom model.
I was trying to update the absence through the user, I wasn't actually changing the name of the user, and so not passing it as a param. As a result the record didn't pass the reject_if: proc { |a| [a[:first_name], a[:last_name]].any? {|b| b.blank?}} so it didn't reach the absence record at all. I tried putting a :new_record? validation in the reject if along with the other checks, but that didn't work out.
I found the solution in this answer: https://stackoverflow.com/a/13774269/5909738
Awesome and clean. Look at the comments as well.


text:
Q: Installing Rubymine without sun-java6-jre I'm using Ubuntu 10.04 and am looking to install Rubymine. It seems every tutorial recommends installing sun-java6-jre before downloading rubymine but aptitude and apt-get are returning nothing, claiming that sun-java6-jre no longer exists.
I'm completely unfamiliar with how to handle tar files and am unfamiliar with what to do once I start extracting files from the download.

A: The Sun Java 6 packages are available from the "partner" repositories,
which you can enable by adding the following lines to
/etc/apt/sources.list, and then running sudo apt-get update:
deb http://archive.canonical.com/ubuntu lucid partner
deb-src http://archive.canonical.com/ubuntu lucid partner

After adding the "partner" repositories, you will be able to install
the sun-java6-jre package the usual way (Ubuntu Software Center,
Synaptic, apt-get, whatever).
Alternatively, you can try installing openjdk-6-jre instead, which
is entirely free software and is thus available from the main
repositories:
apt-get install openjdk-6-jre

Information on Java support for Ubuntu is available at:
https://help.ubuntu.com/community/Java

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to divide all element in list at once :: DART _num.sort();
List<int> _answer = [];

for (int i = 1; i <= _num.last; i++) {
  // help me pls
  if (_num % i == 0) {
  }

i'm trying to do Greatest common divisor code but i don't know how to check if int i can divide all items in the list at once and remainder == 0

*

*If there is a better way to do this please tell me, thank you


text:
Q: how to rapidly increment counters in Cassandra w/o staleness I have a Cassandra question. Do you know how Cassandra does updates/increments of counters?
I want to use a storm bolt (CassandraCounterBatchingBolt from storm-contrib repo on github) which writes into cassandra. However, I'm not sure how some of the implementation of the incrementCounterColumn() method works .. and there is also the limitations with cassandra counters (from: http://wiki.apache.org/cassandra/Counters) which makes them useless for my scenario IMHO:

*

*If a write fails unexpectedly (timeout or loss of connection to the coordinator node) the client will not know if the operation has been performed. A retry can result in an over count CASSANDRA-2495.

*Counter removal is intrinsically limited. For instance, if you issue very quickly the sequence "increment, remove, increment" it is possible for the removal to be lost
Anyway, here is my scenario:
I update the same counter faster than the updates propagate to other Cassandra nodes.

Example:
  Say I have 3 cassandra nodes. The counters on each of these nodes are 0.
  Node1:0, node2:0, node3:0
An increment comes: 5 -> Node1:0, node2:0, node3:0
Increment starts at node 2 – still needs to propagate to node1 and node3
  Node1:0, node2:5, node3:0
In the meantime, another increment arrives before previous increment
  is propagated: 3 -> Node1:0, node2:5, node3:0
Assuming 3 starts at a different node than where 5 started we have:
  Node1:3, node2:5, node3:0

Now if 3 gets propagated to the other nodes AS AN INCREMENT and not as a new value
(and the same for 5) then eventually the nodes would all equal 8 and this is what I want.
If 3 overwrites 5 (because it has a later timestamp) this is problematic – not what I want.
Do you know how these updates/increments are handled by Cassandra?
Note, that a read before a write is still susceptible to the same problem depending from which replica node the read executes (Quorum can still fail if propagation is not far along)
I'm also thinking that maybe putting a cache b/w my storm bolt and Cassandra might solve this issue but that's a story for another time.

A: The current version of counters are just not a good fit for a use case that requires guarantees of no over-counting and immediate consistency.
There are increment and decrement operations, and those will not collide with each other, and, barring any lost mutations or replayed mutations, will give you a correct result.
The rewrite of Cassandra counters (https://issues.apache.org/jira/browse/CASSANDRA-6504) might be interesting to you, and it should address all of the current concerns with getting a correct count.
In the meantime, if I had to implement this on top of a current version of Cassandra, and an accurate count was essential, I would probably store each increment or decrement as a column, and do read-time aggregation of the results, while writing back a checkpoint so you don't have to read back to the beginning of time to calculate subsequent results.
That adds a lot of burden to the read side, though it is extremely efficient on the write path, so it may or may not work for your use case.

A: To understand updates/increments i.e write operations, i will suggest you to go through  Gossip, protocol used by Cassandra for  communication. In Gossip every participant(node) maintains their state using the tuple σ(K) = (V*N) where σ(K) is the state of K key with V value and N as version number.
To maintain the single version of truth for a data packet Gossip maintains a Reconciliation mechanism  namely Precise & Scuttlebutt(current). According to Scuttlebutt Reconciliation, before updating any tuple they communicate with each other to check who is holding the highest version (newest value) of the key. Whosoever is holding the highest version is responsible for the write operation.
For further information read this  article.

A: Counters in C* have a complex internal representation that avoids most (but not all) problems of counting things in a leaderless distributed system. I like to think of them as sharded counters. A counter consists of a number of sub-counters identified by host ID and a version number. The host that receives the counter operation increments only its own sub-counter, and also increments the version. It then replicates its whole counter state to the other replicas, which merge it with their states. When the counter is read the node handling the read operation determines the counter value by summing up the total of the counts from each host.
On each node a counter increment is just like everything else in Cassandra, just a write. The increment is written to the memtable, and the local value is determined at read time by merging all of the increments from the memtable and all SSTables.
I hope that explanation helps you believe me when I say that you don't have to worry about incrementing counters faster than Cassandra can handle. Since each node keeps its own counter, and never replicates increment operations, there is no possibility of counts getting lost by race conditions like a read-modify-write scenario would introduce. If Cassandra accepts the write, your're pretty much guaranteed that it will count.
What you're not guaranteed, though, is that the count will appear correct at all times unless. If an increment is written to one node but the counter value read from another just after, there is not guarantee that the increment has been replicated, and you also have to consider what would happen during a network partition. This more or less the same with any write in Cassandra, it's in its eventually consistent nature, and it depends on which consistency levels you used for the operations.
There is also the possibility of a lost acknowledgement. If you do an increment and loose the connection to Cassandra before you can get the response back you can't know whether or not your write got though. And when you get the connection back you can't tell either, since you don't know what the count was before you incremented. This is an inherent problem with systems that choose availability over consistency, and the price you pay for many of the other benefits.
Finally, the issue of rapid remove, increment, removes are real, and something you should avoid. The problem is that the increment operation will essentially resurrect the column, and if these operations come close enough to each other they might get the same timestamp. Cassandra is strictly last-write-wins and determines last based on the timestamp of the operation. If two operations have the same time stamp, the "greater" one wins, which means the one which sorts after in a strict byte order. It's real, but I wouldn't worry too much about it unless you're doing very rapid writes and deletes to the same value (which is probably a fault in your data model).
Here's a good guide to the internals of Cassandra's counters: http://www.datastax.com/wp-content/uploads/2011/07/cassandra_sf_counters.pdf


text:
Q: Oddly drawn GraphicsPath with Graphics.FillPath I have written some code which creates a rounded rectangle GraphicsPath, based on a custom structure, BorderRadius (which allows me to define the top left, top right, bottom left and bottom right radius of the rectangle), and the initial Rectangle itself:
public static GraphicsPath CreateRoundRectanglePath(BorderRadius radius, Rectangle rectangle)
{
    GraphicsPath result = new GraphicsPath();

    if (radius.TopLeft > 0)
    {
        result.AddArc(rectangle.X, rectangle.Y, radius.TopLeft, radius.TopLeft, 180, 90);
    }
    else
    {
        result.AddLine(new System.Drawing.Point(rectangle.X, rectangle.Y), new System.Drawing.Point(rectangle.X, rectangle.Y));
    }
    if (radius.TopRight > 0)
    {
        result.AddArc(rectangle.X + rectangle.Width - radius.TopRight, rectangle.Y, radius.TopRight, radius.TopRight, 270, 90);
    }
    else
    {
        result.AddLine(new System.Drawing.Point(rectangle.X + rectangle.Width, rectangle.Y), new System.Drawing.Point(rectangle.X + rectangle.Width, rectangle.Y));
    }
    if (radius.BottomRight > 0)
    {
        result.AddArc(rectangle.X + rectangle.Width - radius.BottomRight, rectangle.Y + rectangle.Height - radius.BottomRight, radius.BottomRight, radius.BottomRight, 0, 90);
    }
    else
    {
        result.AddLine(new System.Drawing.Point(rectangle.X + rectangle.Width, rectangle.Y + rectangle.Height), new System.Drawing.Point(rectangle.X + rectangle.Width, rectangle.Y + rectangle.Height));
    }
    if (radius.BottomLeft > 0)
    {
        result.AddArc(rectangle.X, rectangle.Y + rectangle.Height - radius.BottomLeft, radius.BottomLeft, radius.BottomLeft, 90, 90);
    }
    else
    {
        result.AddLine(new System.Drawing.Point(rectangle.X, rectangle.Y + rectangle.Height), new System.Drawing.Point(rectangle.X, rectangle.Y + rectangle.Height));
    }

    return result;
}

Now if I use this along with FillPath and DrawPath, I notice some odd results:
GraphicsPath path = CreateRoundRectanglePath(new BorderRadius(8), new Rectangle(10, 10, 100, 100));
e.Graphics.DrawPath(new Pen(Color.Black, 1), path);
e.Graphics.FillPath(new SolidBrush(Color.Black), path);

I've zoomed into each resulting Rectangle (right hand side) so you can see clearly, the problem:

What I would like to know is: Why are all of the arcs on the drawn rectangle equal, and all of the arcs on the filled rectangle, odd?
Better still, can it be fixed, so that the filled rectangle draws correctly?
EDIT: Is it possible to fill the inside of a GraphicsPath without using FillPath?
EDIT: As per comments....here is an example of the BorderRadius struct
public struct BorderRadius
{
    public Int32 TopLeft { get; set; }
    public Int32 TopRight { get; set; }
    public Int32 BottomLeft { get; set; }
    public Int32 BottomRight { get; set; }

    public BorderRadius(int all) : this()
    {
        this.TopLeft = this.TopRight = this.BottomLeft = this.BottomRight = all;
    }
}

A: I experienced the same problem and found a solution. Might be too late for you @seriesOne but it can be useful to other people if they have this problem.
Basically when using the fill methods (and also when setting the rounded rectangle as the clipping path with Graphics.SetClip) we have to move by one pixel the right and bottom lines. So I came up with a method that accepts a parameter to fix the rectangle is using the fill or not. Here it is:
private static GraphicsPath CreateRoundedRectangle(Rectangle b, int r, bool fill = false)
{
    var path = new GraphicsPath();
    var r2 = (int)r / 2;
    var fix = fill ? 1 : 0;

    b.Location = new Point(b.X - 1, b.Y - 1);
    if (!fill)
        b.Size = new Size(b.Width - 1, b.Height - 1);

    path.AddArc(b.Left, b.Top, r, r, 180, 90);
    path.AddLine(b.Left + r2, b.Top, b.Right - r2 - fix, b.Top);

    path.AddArc(b.Right - r - fix, b.Top, r, r, 270, 90);
    path.AddLine(b.Right, b.Top + r2, b.Right, b.Bottom - r2);

    path.AddArc(b.Right - r - fix, b.Bottom - r - fix, r, r, 0, 90);
    path.AddLine(b.Right - r2, b.Bottom, b.Left + r2, b.Bottom);

    path.AddArc(b.Left, b.Bottom - r - fix, r, r, 90, 90);
    path.AddLine(b.Left, b.Bottom - r2, b.Left, b.Top + r2);

    return path;
}

So this is how you use it:
g.DrawPath(new Pen(Color.Red), CreateRoundedRectangle(rect, 24, false));
g.FillPath(new SolidBrush(Color.Red), CreateRoundedRectangle(rect, 24, true));

A: I'd suggest explicitly adding a line from the end of each arc to the beginning of the next one.
You could also try using the Flatten method to approximate all curves in your path with lines. That should remove any ambiguity.
The result you're getting from FillPath looks similar to an issue I had where the points on a Path were interpreted incorrectly, essentially leading to a quadratic instead of a cubic bezier spline.
You can examine the points on your path using the GetPathData function: http://msdn.microsoft.com/en-us/library/ms535534%28v=vs.85%29.aspx
Bezier curves (which GDI+ uses to approximate arcs) are represented by 4 points. The first is an end point and can be any type. The second and third are control points and have type PathPointBezier. The last is the other end point and has type PathPointBezier. In other words, when GDI+ sees PathPointBezier, it uses the path's current position and the 3 Bezier points to draw the curve. Bezier curves can be strung together but the number of bezier points should always be divisible by 3.
What you're doing is a bit strange, in that you are drawing curves in different places without explicit lines to join them. I'd guess it creates a pattern like this:
PathPointStart - end point of first arc
PathPointBezier - control point of first arc
PathPointBezier - control point of first arc
PathPointBezier - end point of first arc
PathPointLine - end point of second arc
PathPointBezier - control point of second arc
PathPointBezier - control point of second arc
PathPointBezier - end point of second arc
PathPointLine - end point of third arc
PathPointBezier - control point of third arc
PathPointBezier - control point of third arc
PathPointBezier - end point of third arc

That looks reasonable. GDI+ should be drawing a line from the last endpoint of each curve to the first endpoint of the next one. DrawPath clearly does this, but I think FillPath is interpreting the points differently. Some end points are being treated as control points and vice versa.

A: The real reason for the behavior is explained at Pixel behaviour of FillRectangle and DrawRectangle.
It has to do with the default pixel rounding and the fact that FillRectangle/FillPath with integer coordinates end up drawing in the middle of a pixel and get rounded (according to Graphics.PixelOffsetMode).
On the other hand, DrawRectangle/DrawPath draw with a 1px pen that gets perfectly rounded on the pixel boundaries.
Depending on your usage the solution could be to inflate/deflate the rectangle for FillRectangle/FillPath by .5px.

A: "Is it possible to fill the inside of a GraphicsPath without using FillPath?"
Yes...but I think this is more of a parlor trick (and it might not work as you expect for more complex shapes).  You can clip the graphics to the path, and then just fill the entire encompassing rectangle:
        Rectangle rc = new Rectangle(10, 10, 100, 100);
        GraphicsPath path = CreateRoundRectanglePath(new BorderRadius(8), rc);
        e.Graphics.SetClip(path);
        e.Graphics.FillRectangle(Brushes.Black, rc);
        e.Graphics.ResetClip();


text:
Q: SQL Server 2012 Running version 9.0.1399 instead of 11.0.**** I have sql server 2008 running on my machine for a  pretty long time now. I recently installed  2012 on the same system without problems. But on starting the software, I got a prompt saying I can import the sql server 2008 settings to sql server 2012, for which I mistakenly selected Yes instead of No. Now sql server 2012 is running 9.0.1339 version (version of 2008) instead of the one that comes with 2012. I uninstalled 2012 and installed again hoping that it will return to the default settings but it didn't work.
Please I need help in resolving this issue.
Many thanks.

A: I think , this will help you.
First close your management studio.
go to your use folder (in win 7/8, C:\Users\username)
From that open "Documents\SQL Server Management Studio\Settings"
In that you will find some files, move it to other folder.
Now, open management studio again.


text:
Q: Android listActivity onListItemClick with CheckBox my question is how to access and change the checkBox mode for any item in a listactivity. I have an XML template file with a checkbox and a textview, and these define a row. Here's what I'm trying so far:
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
        Toast.makeText(this, "You selected: " + Integer.toString(position), Toast.LENGTH_LONG).show();

        CheckBox checkbox = (CheckBox) findViewById(R.id.checkbox);
        if (checkbox.isChecked() == false) {
            checkbox.setChecked(true);
        } else {
            checkbox.setChecked(false);
        }

}

Obviously though using R.id.checkbox only toggles the first checkbox (actually, it does the first checkbox of whatever part of the list I'm looking at on my screen). I'm not sure what function to use to get the checkbox of any row though. The Toast works fine btw, so at least it registers position properly.
Thanks for any help.
EDIT - I'm now trying to subclass the SimpleCursorAdapter to better control the behaviour I want. Here is that subclass:
public class musicPlaylist extends SimpleCursorAdapter {

private Cursor c;
private Context context;
private ArrayList<String> checkList = new ArrayList<String>();
private final static int SELECTED = 1;
private final static int NOT_SELECTED = 0;

public musicPlaylist(Context context, int layout, Cursor c,
        String[] from, int[] to) {
    super(context, layout, c, from, to);
    this.c = c;
    this.context = context;

}

public View getView(int pos, View inView, ViewGroup parent) {
    View v = inView;
    if (v == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.song_item, null);
    }

    this.c.moveToPosition(pos);
    int columnIndex = this.c.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
    String song = this.c.getString(columnIndex);

    TextView sTitle = (TextView) v.findViewById(R.id.text1);
    sTitle.setText(song);
    v.setId(NOT_SELECTED);
    v.setTag(song);
    v.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            if (v.getId() == NOT_SELECTED) {
                v.setId(SELECTED);
                Toast.makeText(context, "Test: " + v.getId(), Toast.LENGTH_SHORT).show();
                v.setBackgroundColor(Color.parseColor("#FFFFFF"));

            } else {
                v.setId(NOT_SELECTED);
                Toast.makeText(context, "Test: " + v.getId(), Toast.LENGTH_SHORT).show();
                v.setBackgroundColor(Color.parseColor("#000000"));
            }

        }
    });

    return v;
}

}
And for reference, here is the XML of the ListActivity I'm making:
<?xml version="1.0" encoding="utf-8"?>

 <ListView android:id="@android:id/list"
           android:layout_width="fill_parent"
           android:layout_height="fill_parent"
           android:layout_weight="1"
           android:drawSelectorOnTop="false"
           android:fastScrollEnabled="true"
           android:cacheColorHint="#00000000"
           />

 <TextView android:id="@android:id/empty"
           android:layout_width="fill_parent"
           android:layout_height="fill_parent"
           android:text="No data"/>

Current behaviour: the list of songs from the SD card is made into a nice scrollable list. I do get somewhat proper responses from getView()'s onClick: The first time I click an item, it Toasts that its tag is "1" and its background goes white, while the second time I toast the same item, I get "0" and the background goes black, which is as expected.
The problem is if I select item1 (making its background white) and then scroll down, I'll notice that item11, item21, item31, ... , etc ALSO have white backgrounds. But when I click on them, their ID attribute goes to "1", meaning they've technically never been clicked before! So basically when the scroll "refreshes" to the next list of 10, it copies the color scheme of the first 10...?
Hope I explained it clearly.

A: I think this is bit deeper question and not direct answer is needed.
What do you want to achieve? Do you really want to make selected ONLY the checkboxes that you see on screen? Mind that this might be pretty random - list view only holds item views for the checkboxes that are visible on screen and they are reused for other items whenever the item is scrolled outside the screen.
I'd say that almost for sure you need to change state of all the checkboxes in your list (even those not visible) or some subset of them (like section). Which really translates into the proper way it should be done:

*

*modify your data model appropriately
marking the appropriate flags selected in corresponding data model elements
(some boolean values you store per item)

*call notifyDataSetChanged() on your adapter.

As a result, list view will recreate all the views which are visible on screen. Assuming that your "getView()" in adapter is written correctly, it will read the right model and update checked state on the item appropriately.
By notifyDataSetChanged - if you have 10 items visible on screen you will have 10 times getView() called for every item visible.

A: I recommend using android:choiceMode="multipleChoice" instead of manually manipulating your rows this way. The row widget will need to implement the Checkable interface, which can either be done by using CheckedTextView as the row itself, or creating a subclass of your desired container and implementing Checkable on it.

A: You use "global" view instead your row view. Try like that:
 @Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
   super.onListItemClick(l, v, position, id);

    CheckBox checkbox = (CheckBox) v.findViewById(R.id.checkbox);
    if (checkbox.isChecked() == false) {
        checkbox.setChecked(true);
    } else {
        checkbox.setChecked(false);
    }
 }


text:
Q: Why does my .NET console app hang when waiting for Ctrl-C I'm building a simple console app that starts up a timer and does some stuff. I want to close down if the user presses Ctrl-C.
When I code this up, the application detects the Ctrl-C but then hangs and never closes. What am I doing wrong?
Here's the code:
using System;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        private static readonly AutoResetEvent _closeEvent = new AutoResetEvent(false);

        static void Main(string[] args)
        {
            Console.WriteLine("Hello World - waiting for Ctrl-C");

            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                Console.WriteLine("Got the Ctrl-C");
                _closeEvent.Set();
            };

            // Start up a timer and do work here...

            Console.WriteLine("Before WaitOne");
            _closeEvent.WaitOne();
            Console.WriteLine("After WaitOne");
        }
    }
}

I'm wondering if this is just a side-effect of the Visual Studio debugger? If I run it without debugging then press Ctrl-C, the console then shows "Press any key to continue..." and pressing a key then terminates the application.

A: It seems that the key to making this work is to set
eventArgs.Cancel = true;

inside the CancelKeyPress handler.
It all works nicely then, and the application terminates correctly.


text:
Q: In Java, class OneDimArrayMethods, method seqSearch, I'm getting a "cannot find symbol" error I know all the potential causes for this error, but I can't see the problem. The error is on line 17. It's probably something simple, but I could use another pair of eyes on this, thanks!!
    import java.util.*;

    public class TestSeqSearch
    {
       static Scanner console = new Scanner(System.in);

       public static void main(String[] args)
       {
          int[] intList = new int[10];
          int number;
          int index;

          System.out.println("Line 10: Enter "
                         + intList.length + " integers.");

          for (index = 0; index < intList.length; index++)
              intList[index] = console.nextInt();

          System.out.println();

          System.out.print("Line 14: Enter the number "
                         + "to be searched: ");
          number = console.nextInt();
          System.out.println();

          index = OneDimArrayMethods.seqSearch(intList,
                                 intList.length, number);   //Line 17

          if (index  != -1)
              System.out.println("Line 19: " + number
                               + " is found at position "
                               + index);
          else
              System.out.println("Line 21: " + number
                             + " is not in the list.");
       }
    }


text:
Q: Diagonal of a 3D array How can one extract the "diagonal" from three-dimensional array in R?  For a matrix (2D array) one can use the diag(...) function.  In a similar way, given an N x N x M array, a natural operation is to convert it into an N x M matrix by taking the diagonal from each N x N slice and returning it as a matrix.
It's easy to do this using a loop, but that is not idiomatic R and is slow.  Another possibility is to use slightly complex indexing (see my own answer to this question) but it is a bit hard to read.  What other alternatives are there?  Is there a standard R way to do this?

A: Create an array and fill it by some values:
> a=array(0,c(10,10,5))
> for (i in 1:10) for (j in 1:10) for (k in 1:5) a[i,j,k]=100*i+10*j+k-111

Run the apply function:
> apply(a,3,diag)
      [,1] [,2] [,3] [,4] [,5]
 [1,]    0    1    2    3    4
 [2,]  110  111  112  113  114
 [3,]  220  221  222  223  224
 [4,]  330  331  332  333  334
 [5,]  440  441  442  443  444
 [6,]  550  551  552  553  554
 [7,]  660  661  662  663  664
 [8,]  770  771  772  773  774
 [9,]  880  881  882  883  884
[10,]  990  991  992  993  994

A: Various diagonals:
A = array(1:12, c(2, 2, 3))

apply(A, 1, diag)
#     [,1] [,2]
#[1,]    1    2
#[2,]    7    8
apply(A, 2, diag)
#     [,1] [,2]
#[1,]    1    3
#[2,]    6    8
apply(A, 3, diag)
#     [,1] [,2] [,3]
#[1,]    1    5    9
#[2,]    4    8   12

A: Although I'm not enamored of the term "3d.diagonal" for this result, it can be achieved with this simple function (up to identity modulo transpose):
arr <- array(1:27,c(3,3,3)  )
apply(arr, 3, function(x) x[row(x)==col(x)] )
# returns same value as diag.3d (arr)
     [,1] [,2] [,3]
[1,]    1   10   19
[2,]    5   14   23
[3,]    9   18   27

I think a "real diagonal" would be arr[ cbind(1:3,1:3,1:3) ]

A: One possible approach is to use indexing, where the indices are a matrix with three columns.  For example:
diag.3d <- function(A) {
  # Expect a N x N x M array

  stopifnot(length(dim(A)) == 3)
  n <- nrow(A)
  stopifnot(n == ncol(A))
  m <- dim(A)[3]

  IXS <- cbind(1:n, 1:n, rep(1:m, each = n))
  cn <- colnames(A)
  rn <- dimnames(A)[[3]]
  matrix(A[IXS], ncol = n, byrow = T, dimnames = list(rn, cn))
}

Although indices (in variable IXS) seem hard to read.

A: Another approach is subseting the 3 dimensions array with a 2 dimensions matrix:
a <- array(1:100,dim = c(5,5,4))
ref <- cbind(1:5,1:5,rep(1:4,each= 5))
a[ref]

Output is a vector instead of a matrix. On my computer it is more efficient than apply() and you can also fill the diagonal values.


text:
Q: jQuery .css() if statement, timeout string isn't working? I'm working on this navbar that when bgColor is true it needs to change the background color to rgba(15,18,65,0.9).
But when bgColor isn't true the background color needs to change. This works but it's to quick so I thought to put a delay on it, but for some reason it won't return the string and change background color.
If I console log the color instead of returning it it works fine. So what am I misunderstanding here? It only needs to delay the false color option.
$(".navbar-dark")
   .css("background-color", bgColor ? "rgba(15,18,65,0.9)" :
         setTimeout(function(){return "rgba(15,18,65,0)";}, 1000)
       );

A: Use if and put setTimeout() in else block
if (bgColor) {
    $(".navbar-dark").css("background-color", "rgba(15,18,65,0.9)")
} else {
    setTimeout(function () {
        $(".navbar-dark").css("background-color", "rgba(15,18,65,0)");
    }, 1000);
}

A: Like an alternative, you can use delay() method of JQuery, like this:
if (bgColor)
    $(".navbar-dark").css("background-color", "rgba(15,18,65,0.9)");
else
    $(".navbar-dark").delay(1000).css("background-color", "rgba(15,18,65,0)");

A: Just set the variable, then return out of the function with a blank value:
$(".navbar-dark").css("background-color", bgColor ? "rgba(15,18,65,0.9)" :
     setTimeout(function(){bgColor = "rgba(15,18,65,0)"; return;}, 1000)
 );


text:
Q: función modal en javascript, error con f5 Utilizando javascript, ejecuto un modal con un mensaje luego de un cierto tiempo de inactividad.
Funciona bien, pero por lógica en este caso si presiono F5 o cualquier tecla, o si hago clic en cualquier parte, luego de haber excedido el tiempo establecido para la inactividad me redirige al login. Eso lo hace. Pero si presiono F5 no redirige al login!
La pregunta es ¿Cómo hago para capturar ese evento también y que rediriga al login así presione F5?
Les comparto el código Javascript
function TiempoActividad() {
    setTimeout("alertamodal()", 3000); // 15 minutos
  }
  function alertamodal(){
        $('#sesionalert').modal('show');
        $('#sesionalert').on('click', function(){
          $('#sesionalert').modal('hide');
          location.href = "<?php echo Router::url(array("controller" => "Users", "action" => "logout")); ?>";
        })
  }

Les agradezco de antemano


text:
Q: How to get the latest posts with a condition within a month in Laravel? I have the following posts:
title           rating    created_at
-----------------------------------
Post title 1    3         2021-06-21 13:00:19
Post title 2    5         2021-06-16 13:00:19
Post title 3    4         2021-03-21 13:00:19
Post title 4    7         2021-03-18 13:00:19
Post title 5    10        2021-02-26 13:00:19

I want to list the latest 3 best rated posts within a month, but there are only 2 posts, so I want to add 1 more.
I want to get this result:
Post title 2 - rating 5
Post title 3 - rating 4
Post title 1 - rating 3

Is it possible in Laravel?
I use the following code, but it only lists two posts:
Post::query()->orderBy('rating', 'desc')
->where('created_at', '>=', Carbon::now()->subDays(30))
->limit(3)
->get();

A: Use whereBetween and using carbon firstOfMonth() and  endOfMonth()
Post::orderByDesc('rating')
      ->whereDate('created_at','<=',Carbon::now()->firstOfMonth())
      ->limit(3)
      ->get();

A: try take() instead of limit()
Post->orderBy('rating', 'desc')
 ->where('created_at', '>=', Carbon::now()->subDays(30))
 ->take(3)
 ->get();


text:
Q: move fragment(?) by swiping and show underlying fragment Small question, but I think it is an interresting one as I haven't found the answer yet:
what is being used in the Youtube app to be able to swipe the fragment(?) to the right and showing the options behind it. You can do it on the main page and then your personal settings are being displayed.
Anyone have an idea how this is done? I saw it in one other (none-google) app too...

A: To get similar effect in app you can use ViewPager.
Some information and code examples: http://android-developers.blogspot.com/2011/08/horizontal-view-swiping-with-viewpager.html


text:
Q: Producing list of contents in CSS looking awkward I am trying to produce the following list in CSS/HTML from scratch:

Unfortunately, I ran into a few issue with absolute positioning, the elements seem to be on top of each other.
How do I use relative or flexboxes positioning to fix this?

.contact-container {
  display: flex;
  position: relative;
  padding: 1em;
}

.contact-container:hover {
  cursor: pointer;
  background-color: #f7f7f7;
}

.contact-avatar-container {
  width: 100%;
  display: block;
}

.contact-avatar {
  width: 40px;
  height: 40px;
  border-radius: 20px;
}

.contact-online-status {
  background-color: #41dc21;
  height: 0.5em;
  position: absolute;
  right: 0;
  top: 15px;
  left: 45px;
  width: 0.5em;
  border-radius: 100%;
}

.contact-name {
  position: absolute;
  top: 32px;
  left: 70px;
  font-size: 1.25em;
  font-weight: 700;
  -webkit-font-smoothing: antialiased;
}

.contact-last-known-interaction {
  position: absolute;
  top: 15px;
  left: 70px;
  font-size: 0.75em;
  font-weight: 300;
  color: rgb(147, 147, 147);
}

.contact-call-button {
  height: 34px;
}

.contact-call-button .phone {
  position: absolute;
  top: 30px;
  right: 30px;
  fill: rgb(57, 220, 12);
  font-size:16px;
  height: 20px;
}

Abul Philip

Last spoke Mar 27

<svg viewBox="0 0 14 14" class="phone">
          <path d="m13.76 12.32-.38.54v.05.06c-1.41 2-5.42 1-9-2.28s-5.3-7.55-3.89-9.56v-.06l.07-.07.38-.52a1.15 1.15 0 0 1 1.77-.12l1.9 1.75a1.59 1.59 0 0 1 .27 2l-1.28 1.89a16.23 16.23 0 0 0 2.27 2.52 15.17 15.17 0 0 0 2.66 2l1.28-1.84a1.15 1.15 0 0 1 1.78-.12l1.89 1.75a1.58 1.58 0 0 1 .28 2.01z"></path>
        </svg>

John Smith

Became friends Mar 27

<svg viewBox="0 0 14 14" class="phone">
          <path d="m13.76 12.32-.38.54v.05.06c-1.41 2-5.42 1-9-2.28s-5.3-7.55-3.89-9.56v-.06l.07-.07.38-.52a1.15 1.15 0 0 1 1.77-.12l1.9 1.75a1.59 1.59 0 0 1 .27 2l-1.28 1.89a16.23 16.23 0 0 0 2.27 2.52 15.17 15.17 0 0 0 2.66 2l1.28-1.84a1.15 1.15 0 0 1 1.78-.12l1.89 1.75a1.58 1.58 0 0 1 .28 2.01z"></path>
        </svg>

A: You were missing styling for your outermost container. Also, you had a contact container, but multiple avatar containers inside it. I have separated out your contacts into their own containers and applied a grid to the list container.
Edit: Also, I realize that the phone icon is not fully in line with the rest of the elements, but I did not attempt to fix it because the CSS seems like a house of cards with all those absolute positions and top, left, right adjustments.
Edit 2: I added some flexboxes and slightly modified the HTML to see how it looks. Hope it helps!

.contact-list-container {
  display: grid;
  font-family: sans-serif;
}

.contact-container {
  display: flex;
  flex-flow: row nowrap;
  align-content: center;
  justify-content: start;
  padding: 1em;
}

.contact-container:hover {
  cursor: pointer;
  background-color: #f7f7f7;
}

.contact-avatar-container {
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  align-items: center;
}

.contact-name-state-container {
  display: flex;
  flex-flow: column nowrap;
  justify-content: start;
}

.contact-controls-container {
  display: flex;
  flex: 1 1 auto;
  flex-flow: row nowrap;
  justify-content: end;
  align-items: center;
}

.contact-avatar {
  width: 40px;
  height: 40px;
  border-radius: 20px;
}

.contact-online-status {
  background-color: #41dc21;
  height: 0.5em;
  position: relative;
  align-self: start;
  right: 10px;
  width: 0.5em;
  border-radius: 100%;
}

.contact-name {
  font-size: 1.25em;
  font-weight: 700;
  -webkit-font-smoothing: antialiased;
}

.contact-last-known-interaction {
  font-size: 0.75em;
  font-weight: 300;
  color: rgb(147, 147, 147);
}

.contact-call-button .phone {
  fill: rgb(57, 220, 12);
  font-size: 16px;
  height: 20px;
}

Last spoke Mar 27

Abul Philip

<svg viewBox="0 0 14 14" class="phone">
          <path d="m13.76 12.32-.38.54v.05.06c-1.41 2-5.42 1-9-2.28s-5.3-7.55-3.89-9.56v-.06l.07-.07.38-.52a1.15 1.15 0 0 1 1.77-.12l1.9 1.75a1.59 1.59 0 0 1 .27 2l-1.28 1.89a16.23 16.23 0 0 0 2.27 2.52 15.17 15.17 0 0 0 2.66 2l1.28-1.84a1.15 1.15 0 0 1 1.78-.12l1.89 1.75a1.58 1.58 0 0 1 .28 2.01z"></path>
        </svg>

Became friends Mar 27

John Smith

<svg viewBox="0 0 14 14" class="phone">
          <path d="m13.76 12.32-.38.54v.05.06c-1.41 2-5.42 1-9-2.28s-5.3-7.55-3.89-9.56v-.06l.07-.07.38-.52a1.15 1.15 0 0 1 1.77-.12l1.9 1.75a1.59 1.59 0 0 1 .27 2l-1.28 1.89a16.23 16.23 0 0 0 2.27 2.52 15.17 15.17 0 0 0 2.66 2l1.28-1.84a1.15 1.15 0 0 1 1.78-.12l1.89 1.75a1.58 1.58 0 0 1 .28 2.01z"></path>
        </svg>

A: Use flexbox, as commented here before, absolute positioning everything is poor practice. It will only destroy rather than make things beautiful if overused. Made an example for you using flexbox. Made a fiddle as example, hope it helps :)
Also wrap information in parent elements, easier to style them then.

Became friends Mar 27

John Smith

/*parent to contact containers, we want flexed children hence -> display: flex;*/
.contact-container {
  display: flex;
  flex-direction: column;
  position: relative;
}

/*parent to contact information, we also want the information to flex to easily handle it -> display: flex;*/
.contact-avatar-container {
  width: 60%;
  flex: 1;
  display: flex;
  flex-direction: row;
  padding: 1em;
  border: 1px solid #d3d3d3;
  border-radius: 5px;
  margin: 5px;
}

/*flex the elements, some bigger than others depending on content*/
.contact-information {
    flex: 3;
    margin-left: 15px;
}

/*for example, this one is flexed less when the content is less*/
.contact-call-button {
  flex: .5;
}

.contact-avatar {
  width: 40px;
  height: 40px;
  border-radius: 20px;
}

.contact-online-status {
  background-color: #41dc21;
  height: 0.5em;
  width: 0.5em;
  border-radius: 100%;
}

.contact-call-button svg {
  width: 20px;
  height: 20px;
  border: 2px solid lightgreen;
  border-radius: 50%;
  padding: 10px;
}

.contact-name {
  font-weight: bold;
  font-size: 20px;
  vertical-align: middle;
}

Last spoke Mar 27

Abul Philip

<svg viewBox="0 0 14 14" class="phone">
          <path d="m13.76 12.32-.38.54v.05.06c-1.41 2-5.42 1-9-2.28s-5.3-7.55-3.89-9.56v-.06l.07-.07.38-.52a1.15 1.15 0 0 1 1.77-.12l1.9 1.75a1.59 1.59 0 0 1 .27 2l-1.28 1.89a16.23 16.23 0 0 0 2.27 2.52 15.17 15.17 0 0 0 2.66 2l1.28-1.84a1.15 1.15 0 0 1 1.78-.12l1.89 1.75a1.58 1.58 0 0 1 .28 2.01z"></path>
        </svg>

Became friends Mar 27

John Smith

<svg viewBox="0 0 14 14" class="phone">
          <path d="m13.76 12.32-.38.54v.05.06c-1.41 2-5.42 1-9-2.28s-5.3-7.55-3.89-9.56v-.06l.07-.07.38-.52a1.15 1.15 0 0 1 1.77-.12l1.9 1.75a1.59 1.59 0 0 1 .27 2l-1.28 1.89a16.23 16.23 0 0 0 2.27 2.52 15.17 15.17 0 0 0 2.66 2l1.28-1.84a1.15 1.15 0 0 1 1.78-.12l1.89 1.75a1.58 1.58 0 0 1 .28 2.01z"></path>
        </svg>


text:
Q: Installing lxml on RHEL for Python 2.7 So the RHEL machine originally had Python 2.4. I installed Python 2.7.
I want to install lxml module and I cannot use pip or setup tools due to proxy concerns. I used
sudo yum install python-lxml
It installed lxml for Python 2.4 which is the default. How can I make the install for the 2.7 version.

A: The short answer is, not easily.  I'm assuming you're using RHEL5 since you mentioned python 2.4 was in the repo.  The problem is that lxml is not a pure python library, it is a rather thin wrapper around two C/C++ libraries, libxml2 and libxslt.  This means that any RPM installer you find for python-lxml or any attempt to build python-lxml from source is going to require you to have those two libraries installed.
To make matters worse, python-lxml requires 2.7 or greater of libxml and 1.1.23 of libxslt.  RHEL5 supports libxml 2.6 and libxslt 1.1.17.  This means you won't be able to find any standard RHEL5 RPMs for installing the proper versions of those two libraries as any RPM for greater versions will probably depend on greater versions of other things.  For example, the libxml2 2.7 RPM that ships with RHEL6 requires GLIBC 2.7 and RHEL5 has GLIBC 2.6.
However, it appears you can probably install libxml2 and libxslt from source fairly easily as explained here.  Once you've done that it should be straightforward to build python-lxml from source following the directions on the site.


text:
Q: Delete function in Yii2 So I have made a CRUD in Yii and at first, I autogenerated the code using Gii but had to change the look and feel of the CRUD.
This is inside a table where I want to allow the user to delete an item:
<a class="" title="" data-id="1718" href="index.php?r=crm/proposal/<?php array('url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$data->id),'confirm'=>'Are you sure you want to delete this item?')) ?>">Delete
The auto generation created access rules:
public function accessRules()
{
    return array(
        array('allow',
            'actions'=>array('index','view'),
            'users'=>array('*'),
        ),
        array('allow',
            'actions'=>array('create','update'),
            'users'=>array('@'),
        ),
        array('allow',
            'actions'=>array('delete'),
            'users'=>array('@'),
        )
    );
}

And lastly here is the delete function:
public function actionDelete($id)
{
    $this->loadModel($id)->delete();
    if(!isset($_GET['ajax']))
        $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('@'));
}

For some reason when I click on delete link on the page it doesn't delete. It just reloads and does nothing.


text:
Q: Algorithm to Calculate Symmetry of Points Given a set of 2D points, I want to calculate a measure of how horizontally symmetrical and vertically symmetrical those points are.
Alternatively, for each set of points I will also have a rasterised image of the lines between those points, so is there any way to calculate a measure of symmetry for images?
BTW, this is for use in a feature vector that will be presented to a neural network.
Clarification
The image on the left is 'horizontally' symmetrical. If we imagine a vertical line running down the middle of it, the left and right parts are symmetrical. Likewise, the image on the right is 'vertically' symmetrical, if you imagine a horizontal line running across its center.
What I want is a measure of just how horizontally symmetrical they are, and another of just how vertically symmetrical they are.

A: This is just a guideline / idea, you'll need to work out the details:
To detect symmetry with respect to horizontal reflection:

*

*reflect the image horizontally

*pad the original (unreflected) image horizontally on both sides

*compute the correlation of the padded and the reflected images

The position of the maximum in the result of the correlation will give you the location of the axis of symmetry.  The value of the maximum will give you a measure of the symmetry, provided you do a suitable normalization first.
This will only work if your images are "symmetric enough", and it works for images only, not sets of points. But you can create an image from a set of points too.

A: Leonidas J. Guibas from Stanford University talked about it in ETVC'08.
Detection of Symmetries and Repeated Patterns in 3D Point Cloud Data.


text:
Q: How to advertise on non-developer SE websites? Going to selfserve compaign setup page, I can only see 3 websites: Stack Overflow, Super User and Server Fault.
Are there any plans to expand the selfserve advertising for the other websites as well?

A: We currently do not have any plans to extend the self-serve options beyond Stack Overflow, Super User and Server Fault. As @animuson states above, if you are interested in targeting sites outside of those three, you need to speak to a sales rep directly. Please email adsales@stackoverflow.com for any inquiries. :-)


text:
Q: Get three letter month and day from string date? I have string date such like,
NSString * dateStr = @"2014-12-31";

I want to get month in three letter month such like Des (from dateStr) and day such like 31
I tried about 2 hour but i can't get it properly..
My code is..
First convert string to date ;
NSString *dateStr = [[self.listOfEvents objectAtIndex:indexPath.row] objectForKey:@"EventDate"];
NSDateFormatter *DTFormatter = [[NSDateFormatter alloc] init];
[DTFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *eventDate = [DTFormatter dateFromString:dateStr];
NSLog(@"eventDate - %@", eventDate);

And now convert date to string;
NSDateFormatter *currentDTFormatter = [[NSDateFormatter alloc] init];
[currentDTFormatter setDateFormat:@"dd MMM"];
NSString *eventDateStr = [DTFormatter stringFromDate:eventDate];
NSLog(@"eventDateStr - %@", eventDateStr);

So, please suggest me where i was wrong here.
EDITED :
I got console output is

eventDate - 2014-12-31 18:30:00 +0000
  eventDateStr - 2014-12-31

A: The problem is you are converting using old dateformatter that is DTFormatter you have to use currentDTFormatter in place of it.
Try with currentDTFormatter this formatter.
NSDateFormatter *currentDTFormatter = [[NSDateFormatter alloc] init];
[currentDTFormatter setDateFormat:@"dd MMM"];
NSString *eventDateStr = [currentDTFormatter stringFromDate:eventDate];
NSLog(@"%@", eventDateStr);

A: Try adding this line [currentDTFormatter setDateStyle:NSDateFormatterMediumStyle]; before you are calling setDateFormat
Here is the appropriate passage from apple's documentation:
    NSDateFormatterMediumStyle

    Specifies a medium style, typically with abbreviated text, such as "Nov 23, 1937".

    Equal to kCFDateFormatterMediumStyle.

    Available in OS X v10.4 and later.

    Declared in NSDateFormatter.h.

A: It's also saying here https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1 to use just one "d" for the days so "EdMMM" should work for english locale or I guess "dMMM" even "d MMM"

A: Have you tried:
[formatter setDateFormat:@"dd-MMM-YYYY HH:mm"];

and then
[formatter stringFromDate:someNSDate];

A: Here is the Solution
NSString * dateStr = @"2014-12-31";
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"];
NSDate* date = [df dateFromString:dateStr];
NSLog(@"%@", date);
[df setDateFormat:@"dd MMM"];
NSString *dateString = [df stringFromDate:date];
NSLog(@"%@", dateString);

Try out

A: Please try to use the below code to convert your date string...
- (NSString*) formatDateString:(NSString*)date
{
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:@"yyyy-MM-dd"];

NSDate *formattedDate = [inputFormatter dateFromString: date];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"dd MMM"];

NSString *displayDate = [NSString stringWithFormat:@"%@", [outputFormatter stringFromDate:formattedDate]];

return displayDate;

}
And also you can set format styles to NSDateFormatter for formatting your date string
setTimeStyle:

setDateStyle:
You can check NSDateFormatter for your reference from below link.
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html


text:
Q: Serde/jsonrpc-core: convert between to representations of the same data I utilize the jsonrpc-core library to for communication based on the JSON-RPC 2.0 specifications. When registering rpc methods via add_method, they take one parameter, which is an already parsed jsonrpc_core::Params value that represents the params of the request object.
However, I have an  enum data type that is also a representation of this data:
#[derive(Serialize, Deserialize)]
pub enum Event {
    Warning { level: String, time: String, source: String, log: String },
}

I can now easily convert between those representations through
let params: jsonrpc_core::Params = ...
let string: String = serde_json::to_string(&params).unwrap();

let event: Event = serde_json::from_str(&string).unwrap();

However, serializing and deserializing in this manner seems like a waste, is there any other way to convert from two equivalent types that implement serde_json's Serialize/Deserialize traits?


text:
Q: How to write functional Test with spark I have a spark batch job that talks with cassandra. After the batch job gets completed , I need to verify few entries in cassandra and the cycle continues for 2-3 times. How do I know when the batch job ends ? I don't want to track the status of batch job by adding entry in db.
How to write functional test in spark ?


text:
Q: 2 Homeservers 2 Domains possibel? i have a homeserver with nextcloud which is running fine.
i got a domain (domain.com) registered and my homeserver uses ddclient to update the dns settings of the domain.
now i am working on another project with a raspberry pie which also should have a domain.
i already changed the listening ports of the raspberry apache2 to e.g. 8090 and got the port forwarded correctly.
when i open domain.com:8090 it redirects me to my raspberry instead of my homeserver which is nice.
Now....How can i get domain2.com go to my raspberry? it always leads to my homeserver :(
Did i missed some settings?
Solved
<VirtualHost *:80>
ServerName domain.com
ServerAlias www.domain.com
ProxyPreserveHost On
ProxyPass / http://192.168.2.108:80/
ProxyPassReverse / http://192.168.2.108:80/
<Location />
Order allow,deny
Allow from all
</Location>
RewriteEngine on
RewriteCond %{SERVER_NAME} =domain.com [OR]
RewriteCond %{SERVER_NAME} =www.domain.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>


text:
Q: exc_bad_access when Property added I have a TabBarController in one tab I have a TableViewController inside a NavigationController.
When I add a property like
@property CGFloat rowHeight;

or add something like
if ([self.modelTypeCell isEqualToString:@"TypeOneCell"])

I get an
error: gdb remote returned an error: E08 EXC_BAD_ACCESS (Code=1....

in this line
@autoreleasepool {
    return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}

I cant debug anything and no breakpoint get hit before the error occurs.
EDIT: Zombies didnt give me informations, in Instruments and on a real device no error was thrown...
EDIT2:
I found out the problem should lay here
-(void)setupControllerDictionaries
{
self.masterViewControllerDictionary = [[NSMutableDictionary alloc] init];

TableMasterViewController *master = [[TableMasterViewController alloc] initWithModelType:ModelTypeCustomer];

[self.masterViewControllerDictionary setObject:master forKey:[NSNumber numberWithInt:ModelTypeCustomer]];
[master release];

}
when I comment out the master release the error is gone, maybe its the error maybe its somewhere else

A: Property can be best used when written like this:
@property(nonatomic, assign) CGFloat rowHeight;
nonatomics is for that the property can perform in multiple threads and assign means that property should use assignment property while assigning to property something. The retain can not be used with this as this variable is not a pointer type


text:
Q: ASP.NET AJAX GUI Toolkit Anybody worked with Coolite toolkit?
How to add a Coolite child control in a Coolite window?
In ASP.NET(C#) of course!!!

A: You put the controls in the <Body> element. Here is an example of a window with an accordion panel and in the first panel there is a color picker.
<ext:Window ID="Window1" runat="server" Title="Child Control Test" Height="300px"
    Width="500px" BodyStyle="padding: 6px; background-color: #fff;" Collapsible="True"
    Modal="True" Icon="Application">
    <Body>
        <ext:Accordion ID="Accordion1" runat="server" Animate="true">
            <ext:Panel ID="Panel1" runat="server" Border="false" Title="Item 1">
                <Body>
                Panel 1 Content
                <ext:ColorPalette ID="ColorPalette1" runat="server" Width="400" Height="200"></ext:ColorPalette>
                </Body>
            </ext:Panel>
            <ext:Panel ID="Panel2" runat="server" Border="false" Collapsed="true" Title="Item 2">
                <Body>
                Panel 2 Content
                </Body>
            </ext:Panel>
        </ext:Accordion>
    </Body>
</ext:Window>

Here is a screen shot of the result:
Coolite Window with Child Controls http://ryanscook.com/Files/CoolliteChildControl-screen1.jpg


text:
Q: Can I use Wireshark to see what URLs my computer is invoking? Is it possible to use Wireshark to see what URL and what params are being requested by my computer?
Something like:
www.foobar.com/someendpoint/bazboo

Does Wireshark offer this information in its package capture information?
I downloaded Fiddler2, but it did not show any new request being made while I interacted with this application in question. I'm sure it's doing online requests and not loading data from local cache.
Would Wireshark show me this URL being invoked?

A: Absolutely. Wireshark will show ALL network traffic over a network including URLs, unencrypted passwords, etc.


text:
Q: Fire-base stuck and not connecting with android studio HI i'm beginner android developer.I'm using Fire-base in my project but it's not connecting and stuck on Launching Web Connect flow....Please Help....it works fine with manual connection ...but tool isn't working.

A: This problem arises when you don't have any project on Firebase. You can resolve this issue by following the points below.

*

*Make sure that you are logged in with the same Google account on Android Studio and Firebase. On Firebase home page, click on Go to console (present on the upper right corner). After that a page will appear.

*Click on Create a project.

*Follow the commands coming on the way.

*Check all the boxes to allow different permissions required to setup the project.

*Click on Create project.

*Open Android Studio (already running in mentioned state).

*After 1-5 seconds the issue will be resolved.

Well done. You solved the problem :)

A: This happened to me also, and I resolved it with these steps:

*

*Go to the browser window that opened for Firebase.

*Click button called "Create a project"

*Named the new project in the Firebase site and nothing happened in my Android Studio.

*Closed the browser and clicked cancel in Android Studio.

*Started the process over in Android Studio, then when Firebase website opened, I clicked on the project I'd made in step #3.

*Then the browser redirected and said "Your Android Studio project is connected to your Firebase Android app"

*...and the "Launching Web Connect flow" went away and it now shows as connected!

Hope this helps.

A: At the time of writing this, Firebase Assistant plugin is incompatible with Android Studio 4.1, so you'll have to connect your project with Firebase manually by creating a new Firebase project and copying over the google-services.json

A: Once you click on connect to firebase, then you will be redirected to the firebase page.
If you already have the project created in the firebase website and want to use the same then simply click on the existing project or else create a new project.
Once you are inside that project, you will get a window as
Then simply click on connect and your android studio project will be connected with the firebase project.


text:
Q: Instantly detect client disconnection from server socket How can I detect that a client has disconnected from my server?
I have the following code in my AcceptCallBack method
static Socket handler = null;
public static void AcceptCallback(IAsyncResult ar)
{
  //Accept incoming connection
  Socket listener = (Socket)ar.AsyncState;
  handler = listener.EndAccept(ar);
}

I need to find a way to discover as soon as possible that the client has disconnected from the handler Socket.
I've tried:

*

*handler.Available;

*handler.Send(new byte[1], 0,
SocketFlags.None);

*handler.Receive(new byte[1], 0,
SocketFlags.None);
The above approaches work when you are connecting to a server and want to detect when the server disconnects but they do not work when you are the server and want to detect client disconnection.
Any help will be appreciated.

A: "That's just the way TCP works and you have to live with it."
Yup, you're right. It's a fact of life I've come to realize. You will see the same behavior exhibited even in professional applications utilizing this protocol (and even others). I've even seen it occur in online games; you're buddy says "goodbye", and he appears to be online for another 1-2 minutes until the server "cleans house".
You can use the suggested methods here, or implement a "heartbeat", as also suggested. I choose the former. But if I did choose the latter, I'd simply have the server "ping" each client every so often with a single byte, and see if we have a timeout or no response. You could even use a background thread to achieve this with precise timing. Maybe even a combination could be implemented in some sort of options list (enum flags or something) if you're really worried about it. But it's no so big a deal to have a little delay in updating the server, as long as you DO update. It's the internet, and no one expects it to be magic! :)

A: Implementing heartbeat into your system might be a solution. This is only possible if both client and server are under your control. You can have a DateTime object keeping track of the time when the last bytes were received from the socket. And assume that the socket not responded over a certain interval are lost. This will only work if you have heartbeat/custom keep alive implemented.

A: Someone mentioned keepAlive capability of TCP Socket.
Here it is nicely described:
http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html
I'm using it this way: after the socket is connected, I'm calling this function, which sets keepAlive on. The keepAliveTime parameter specifies the timeout, in milliseconds, with no activity until the first keep-alive packet is sent. The keepAliveInterval parameter specifies the interval, in milliseconds, between when successive keep-alive packets are sent if no acknowledgement is received.
    void SetKeepAlive(bool on, uint keepAliveTime, uint keepAliveInterval)
    {
        int size = Marshal.SizeOf(new uint());

        var inOptionValues = new byte[size * 3];

        BitConverter.GetBytes((uint)(on ? 1 : 0)).CopyTo(inOptionValues, 0);
        BitConverter.GetBytes((uint)keepAliveTime).CopyTo(inOptionValues, size);
        BitConverter.GetBytes((uint)keepAliveInterval).CopyTo(inOptionValues, size * 2);

        socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
    }

I'm also using asynchronous reading:
socket.BeginReceive(packet.dataBuffer, 0, 128,
                    SocketFlags.None, new AsyncCallback(OnDataReceived), packet);

And in callback, here is caught timeout SocketException, which raises when socket doesn't get ACK signal after keep-alive packet.
public void OnDataReceived(IAsyncResult asyn)
{
    try
    {
        SocketPacket theSockId = (SocketPacket)asyn.AsyncState;

        int iRx = socket.EndReceive(asyn);
    }
    catch (SocketException ex)
    {
        SocketExceptionCaught(ex);
    }
}

This way, I'm able to safely detect disconnection between TCP client and server.

A: I've found quite useful, another workaround for that!
If you use asynchronous methods for reading data from the network socket (I mean, use BeginReceive - EndReceive  methods), whenever a connection is terminated; one of these situations appear: Either a message is sent with no data (you can see it with Socket.Available - even though BeginReceive is triggered, its value will be zero) or Socket.Connected value becomes false in this call (don't try to use EndReceive then).
I'm posting the function I used, I think you can see what I meant from it better:

private void OnRecieve(IAsyncResult parameter)
{
    Socket sock = (Socket)parameter.AsyncState;
    if(!sock.Connected || sock.Available == 0)
    {
        // Connection is terminated, either by force or willingly
        return;
    }

    sock.EndReceive(parameter);
    sock.BeginReceive(..., ... , ... , ..., new AsyncCallback(OnRecieve), sock);

    // To handle further commands sent by client.
    // "..." zones might change in your code.
}

A: This worked for me, the key is you need a separate thread to analyze the socket state with polling. doing it in the same thread as the socket fails detection.
//open or receive a server socket - TODO your code here
socket = new Socket(....);

//enable the keep alive so we can detect closure
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

//create a thread that checks every 5 seconds if the socket is still connected. TODO add your thread starting code
void MonitorSocketsForClosureWorker() {
    DateTime nextCheckTime = DateTime.Now.AddSeconds(5);

    while (!exitSystem) {
        if (nextCheckTime < DateTime.Now) {
            try {
                if (socket!=null) {
                    if(socket.Poll(5000, SelectMode.SelectRead) && socket.Available == 0) {
                        //socket not connected, close it if it's still running
                        socket.Close();
                        socket = null;
                    } else {
                        //socket still connected
                    }
               }
           } catch {
               socket.Close();
            } finally {
                nextCheckTime = DateTime.Now.AddSeconds(5);
            }
        }
        Thread.Sleep(1000);
    }
}

A: This is simply not possible.  There is no physical connection between you and the server (except in the extremely rare case where you are connecting between two compuers with a loopback cable).
When the connection is closed gracefully, the other side is notified.  But if the connection is disconnected some other way (say the users connection is dropped) then the server won't know until it times out (or tries to write to the connection and the ack times out).  That's just the way TCP works and you have to live with it.
Therefore, "instantly" is unrealistic.  The best you can do is within the timeout period, which depends on the platform the code is running on.
EDIT:
If you are only looking for graceful connections, then why not just send a "DISCONNECT" command to the server from your client?

A: Since there are no events available to signal when the socket is disconnected, you will have to poll it at a frequency that is acceptable to you.
Using this extension method, you can have a reliable method to detect if a socket is disconnected.
static class SocketExtensions
{
  public static bool IsConnected(this Socket socket)
  {
    try
    {
      return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
    }
    catch (SocketException) { return false; }
  }
}

A: The example code here
http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected.aspx
shows how to determine whether the Socket is still connected without sending any data.
If you called Socket.BeginReceive() on the server program and then the client closed the connection "gracefully", your receive callback will be called and EndReceive() will return 0 bytes. These 0 bytes mean that the client "may" have disconnected. You can then use the technique shown in the MSDN example code to determine for sure whether the connection was closed.

A: Expanding on comments by mbargiel and mycelo on the accepted answer, the following can be used with a non-blocking socket on the server end to inform whether the client has shut down.
This approach does not suffer the race condition that affects the Poll method in the accepted answer.
// Determines whether the remote end has called Shutdown
public bool HasRemoteEndShutDown
{
    get
    {
        try
        {
            int bytesRead = socket.Receive(new byte[1], SocketFlags.Peek);

            if (bytesRead == 0)
                return true;
        }
        catch
        {
            // For a non-blocking socket, a SocketException with
            // code 10035 (WSAEWOULDBLOCK) indicates no data available.
        }

        return false;
    }
}

The approach is based on the fact that the Socket.Receive method returns zero immediately after the remote end shuts down its socket and we've read all of the data from it.  From Socket.Receive documentation:

If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received, the Receive method will complete immediately and return zero bytes.
If you are in non-blocking mode, and there is no data available in the protocol stack buffer, the Receive method will complete immediately and throw a SocketException.

The second point explains the need for the try-catch.
Use of the SocketFlags.Peek flag leaves any received data untouched for a separate receive mechanism to read.
The above will work with a blocking socket as well, but be aware that the code will block on the Receive call (until data is received or the receive timeout elapses, again resulting in a SocketException).

A: Above answers can be summarized as follow :
Socket.Connected properity determine socket state depend on last read or receive state so it can't detect current disconnection state until you manually close the connection or remote end gracefully close of socket (shutdown).
So we can use the function below to check connection state:
   bool IsConnected(Socket socket)
    {
        try
        {
            if (socket == null) return false;
            return !((socket.Poll(5000, SelectMode.SelectRead) && socket.Available == 0) || !socket.Connected);
        }
        catch (SocketException)
        {
            return false;
        }

        //the above code is short exp to :
        /* try
         {
             bool state1 = socket.Poll(5000, SelectMode.SelectRead);
             bool state2 = (socket.Available == 0);
             if ((state1 && state2) || !socket.Connected)
                 return false;
             else
                 return true;
         }
         catch (SocketException)
         {
             return false;
         }
        */
    }

Also the above check need to care about poll respone time(block time)
Also as said by Microsoft Documents : this poll method "can't detect proplems like a broken netwrok cable or that remote host was shut down ungracefuuly".
also as said above there is race condition between socket.poll and socket.avaiable which may give false disconnect.
The best way as said by Microsoft Documents is to attempt to send or recive data to detect these kinds of errors as MS docs said.
The below code is from Microsoft Documents :
 // This is how you can determine whether a socket is still connected.
 bool IsConnected(Socket client)
 {
    bool blockingState = client.Blocking; //save socket blocking state.
    bool isConnected = true;
    try
    {
       byte [] tmp = new byte[1];
       client.Blocking = false;
       client.Send(tmp, 0, 0); //make a nonblocking, zero-byte Send call (dummy)
       //Console.WriteLine("Connected!");
    }
    catch (SocketException e)
    {
       // 10035 == WSAEWOULDBLOCK
       if (e.NativeErrorCode.Equals(10035))
       {
           //Console.WriteLine("Still Connected, but the Send would block");
       }
       else
       {
           //Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
           isConnected  = false;
       }
   }
   finally
   {
       client.Blocking = blockingState;
   }
   //Console.WriteLine("Connected: {0}", client.Connected);
   return isConnected  ;
 }

//and heres comments from microsoft docs*

*

*The socket.Connected property gets the connection state of the Socket as of the last I/O operation. When it returns false, the Socket was either never connected, or is no longer connected.

*Connected is not thread-safe; it may return true after an operation is aborted when the Socket is disconnected from another thread.

*The value of the Connected property reflects the state of the connection as of the most recent operation.

*If you need to determine the current state of the connection, make a nonblocking, zero-byte Send call. If the call returns successfully or throws a WAEWOULDBLOCK error code (10035), then the socket is still connected; //otherwise, the socket is no longer connected .

A: Can't you just use Select?
Use select on a connected socket. If the select returns with your socket as Ready but the subsequent Receive returns 0 bytes that means the client disconnected the connection. AFAIK, that is the fastest way to determine if the client disconnected.
I do not know C# so just ignore if my solution does not fit in C# (C# does provide select though) or if I had misunderstood the context.

A: Using the method SetSocketOption, you will be able to set KeepAlive that will let you know whenever a Socket gets disconnected
Socket _connectedSocket = this._sSocketEscucha.EndAccept(asyn);
                _connectedSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);

http://msdn.microsoft.com/en-us/library/1011kecd(v=VS.90).aspx
Hope it helps!
Ramiro Rinaldi

A: i had same problem , try this :
void client_handler(Socket client) // set 'KeepAlive' true
{
    while (true)
    {
        try
        {
            if (client.Connected)
            {

            }
            else
            { // client disconnected
                break;
            }
        }
        catch (Exception)
        {
            client.Poll(4000, SelectMode.SelectRead);// try to get state
        }
    }
}

A: This is in VB, but it seems to work well for me.  It looks for a 0 byte return like the previous post.
Private Sub RecData(ByVal AR As IAsyncResult)
    Dim Socket As Socket = AR.AsyncState

    If Socket.Connected = False And Socket.Available = False Then
        Debug.Print("Detected Disconnected Socket - " + Socket.RemoteEndPoint.ToString)
        Exit Sub
    End If
    Dim BytesRead As Int32 = Socket.EndReceive(AR)
    If BytesRead = 0 Then
        Debug.Print("Detected Disconnected Socket - Bytes Read = 0 - " + Socket.RemoteEndPoint.ToString)
        UpdateText("Client " + Socket.RemoteEndPoint.ToString + " has disconnected from Server.")
        Socket.Close()
        Exit Sub
    End If
    Dim msg As String = System.Text.ASCIIEncoding.ASCII.GetString(ByteData)
    Erase ByteData
    ReDim ByteData(1024)
    ClientSocket.BeginReceive(ByteData, 0, ByteData.Length, SocketFlags.None, New AsyncCallback(AddressOf RecData), ClientSocket)
    UpdateText(msg)
End Sub

A: You can also check the .IsConnected property of the socket if you were to poll.


text:
Q: unable to create new native thread When I start my server I get thes error, but the server is still working fine !

Exception in thread "main" java.lang.OutOfMemoryError: unable to
  create new native thread  at java.lang.Thread.start0(Native Method)
    at java.lang.Thread.start(Thread.java:658)  at
  Gateway.main(Server.java:21)

public static void main(String args[]) {
    try {
        DatagramSocket serverSocket = new DatagramSocket(Integer.parseInt(args[0]));;
        System.out.println("Waiting for clients");
      while (true) {

          Child cServer = new Child(serverSocket);
        cServer.start();
      }
    } catch (IOException ex) {
      System.out.println(ex);
    }
  }
}

Child class
public Child(DatagramSocket ssocket) {
         this.socket = ssocket;

       }

       public void run() {
           while(true)
            {
               byte[] receiveData = new byte[1024];

EDIT:
I tried to make like in this example, it work fine here
public static void main(String[] args) throws IOException {
        server = new MyServer();
        server.runServer();
    }

    private void runServer() {
        int serverPort = 8071;
        try {
            System.out.println("Starting Server");
            serverSocket = new ServerSocket(serverPort);

            while(true) {
                System.out.println("Waiting for request");
                try {
                    Socket s = serverSocket.accept();
                    System.out.println("Processing request");
                    executorService.submit(new ServiceRequest(s));
                } catch(IOException ioe) {
                    System.out.println("Error accepting connection");
                    ioe.printStackTrace();
                }
            }
        }catch(IOException e)

A: You are creating new Child objects in an infinite while loop until all available memory is consumed.

A: Does new Child() or cServer.start() block?  I'm suspicious that your while (true) is a rapid infinite loop that chews up your heap space.  Once the OutofMemoryError is thrown (milliseconds at most), the app finishes and the server reclaims all that memory, so it looks like your server is still working.


text:
Q: Shoutcast stats using JSON This is probably a really simple answer, but I have been trying every variation to pull the Current Song / Artist from shoutcast data. My code is:
$str = file_get_contents('https://radio.siteurl.com/api/nowplaying/1/');
$json = json_decode($str, true); // decode the JSON into an associative array
$listeners = $json['listeners'];
$streamer = $json['live']['streamer_name'];

Both listeners and streaming name information pulls through but I cannot for the life of me get the current song and artist to pull through...
I've tried the below variations but these don't seem to pull anything through
  Attempt 1. $current =  $json['live']['song']['now_playing']['text'];
Attempt 2. $current =  $json['song']['text'];
Attempt 3. $current =  $json['live']['now_playing']['text'];
Attempt 4. $current =  $json['now_playing']['text'];

JSON
 {"station":{"id":1,"name":"HabboFests","shortcode":"habbofests","description":"The official and public station!","frontend":"shoutcast2","backend":"liquidsoap","listen_url":"https:\/\/144.91.82.172:8000\/radio.mp3?1576958492","is_public":true,"mounts":[{"path":"\/radio.mp3","is_default":true,"id":21,"name":"128kbps MP3","url":"https:\/\/144.91.82.172:8000\/radio.mp3?1576958492","bitrate":128,"format":"mp3","listeners":{"current":4,"unique":4,"total":4}}],"remotes":[]},"listeners":{"current":4,"unique":4,"total":4},"live":{"is_live":false,"streamer_name":""},"now_playing":{"elapsed":25,"remaining":228,"sh_id":23228,"played_at":1576958475,"duration":253,"playlist":"Christmas Songs","is_request":false,"song":{"id":"e1e0cdfc0bc7b603015f37766222e7a5","text":"Kylie Minogue - Every Day's Like Christmas","artist":"Kylie Minogue","title":"Every Day's Like Christmas","album":"Kylie Christmas","lyrics":"","art":"https:\/\/144.91.82.172\/api\/station\/1\/art\/cb9d8e05cc17cc07400260ef-1575815687.jpg","custom_fields":[]}},"playing_next":{"sh_id":23229,"played_at":0,"duration":159,"playlist":"Christmas Songs","is_request":false,"song":{"id":"60fea47da48da3c68087ffba2e60a13a","text":"The Drifters - White Christmas","artist":"The Drifters","title":"White Christmas","album":"White Christmas \/ The Bells Of St. Mary's [Digital 45]","lyrics":"","art":"https:\/\/144.91.82.172\/api\/station\/1\/art\/50ab3d2ef25ca7968b492457-1575815658.jpg","custom_fields":[]}},"song_history":[{"sh_id":23227,"played_at":1576958303,"duration":175,"playlist":"Christmas Songs","is_request":false,"song":{"id":"63a79704646c11cac1b690d589429c0b","text":"Krystl - Wonderful Time","artist":"Krystl","title":"Wonderful Time","album":"A Lady Christmas","lyrics":"","art":"https:\/\/144.91.82.172\/api\/station\/1\/art\/587ac84c31fd7979a62052b3-1575815576.jpg","custom_fields":[]}},{"sh_id":23226,"played_at":1576958092,"duration":214,"playlist":"Christmas Songs","is_request":false,"song":{"id":"bad0adc241f1fca11e9e95a79c1344f1","text":"Andra Day; Stevie Wonder - Someday at Christmas","artist":"Andra Day; Stevie Wonder","title":"Someday at Christmas","album":"Merry Christmas from Andra Day","lyrics":"","art":"https:\/\/144.91.82.172\/api\/station\/1\/art\/33cf40c7a38fc8743e588c63-1575815650.jpg","custom_fields":[]}},{"sh_id":23225,"played_at":1576957921,"duration":174,"playlist":"Christmas Songs","is_request":false,"song":{"id":"a920bd3f836328ae0612d3a6b480e70a","text":"Miss Montreal - Being Alone At Christmas","artist":"Miss Montreal","title":"Being Alone At Christmas","album":"So... Anything Else?","lyrics":"","art":"https:\/\/144.91.82.172\/api\/station\/1\/art\/1781ab2da39580e64ea25386-1575815579.jpg","custom_fields":[]}},{"sh_id":23224,"played_at":1576957704,"duration":220,"playlist":"Christmas Songs","is_request":false,"song":{"id":"42ba18fb92b572796c3c52b641fd865b","text":"The Darkness - Christmas Time (Don't Let the Bells End)","artist":"The Darkness","title":"Christmas Time (Don't Let the Bells End)","album":"Christmas Time (Don't Let The Bells End)","lyrics":"","art":"https:\/\/144.91.82.172\/api\/station\/1\/art\/d96ea24a8f2d5cfe9dd167d0-1575815721.jpg","custom_fields":[]}},{"sh_id":23223,"played_at":1576957492,"duration":215,"playlist":"Christmas Songs","is_request":false,"song":{"id":"e67e7931ed63555472be551fa284a4b6","text":"Jethro Tull - Ring Out, Solstice Bells","artist":"Jethro Tull","title":"Ring Out, Solstice Bells","album":"Complete Christmas Party","lyrics":"","art":"https:\/\/144.91.82.172\/api\/station\/1\/art\/12103cb786e08dec5a6484aa-1575815644.jpg","custom_fields":[]}}],"cache":"station"}

A: All you need to do is follow the path to the elements you need, e.g.:
echo $json['now_playing']['song']['text']; //output: Kylie Minogue - Every Days Like Christmas
echo $json['now_playing']['song']['artist']; //output:Kylie Minogue

You can use print_r() or var_dump() to get better visibility of the path to your data.


text:
Q: Image not showing when using PHP to link to SRC Trying to use php to link to an image in a different folder than the file I am currently in but the image isn't showing.
Here's the path file:
<?php
if (!defined("ROOT_PATH")) define ("ROOT_PATH", realpath(dirname(__FILE__)));
if (!defined("BASE_URL")) define ("BASE_URL", "http://localhost/stnresp");
?>

Here's the code I am using at the moment:

  <a href="<?php echo BASE_URL . '/index.php'; ?>"><img class="header-logo" src="<?php echo ROOT_PATH . '/assets/images/stn-logo-cropped.png'; ?>" alt="">

I can't understand why the root path isn't taking the link to the root directory and then through to the image? What am I missing?
Thanks

A: realpath defines the physical path of the file, instead the src attribute of the image needs url path.
In your case you have to use BASE_URL instead of ROOT_PATH:

    <a href="<?php echo BASE_URL . '/index.php'; ?>"><img class="header-logo" src="<?php echo BASE_URL . '/assets/images/stn-logo-cropped.png'; ?>" alt="">


text:
Q: Get list of open files (descriptors) in OS X I would like to get a list of open files in a process on os x (10.9.1). In Linux I was able to get this from /proc/PID/fd. However I'm not sure how to get the same on OS X. I found that the procfs is not present on the OS X (by default. possible implementations present, but I do not want to go that way).
So how do I get (natively) the list of open files in a process on OS X. One way is lsof. is there any other support available? please let me know where I can get more info on this.
Thanks.

A: I had a hard time getting Activity Monitor to show open files for a process that was running as root (via sudo). The original question mentions lsof, and it does the trick exactly. If you know the process name or PID, it's super quick.
Find processes by name:
lsof -c processname

Find processes by PID:
lsof -p 123

(Prefix with sudo as needed, such as if you are not the owner of the process.)

A: The clean and simple approach to inspect the current process (i.e. the equivalent of /proc/self/fd on Linux) is to use ls /dev/fd/:
e.g.
$ touch "file"
$ exec 3<>file

$ ls /dev/fd/

0 1 2 3

A: List open files on /Volumes/VolumeName:
lsof | grep "/Volumes/VolumeName"

A: At least on OSX 10.10 (Yosemite, didn't check on Mavericks), you can get the list of open files by process via the default activity monitor application. Just double click on the relevant process on the list and select "Open Files and Ports" tab on the popup.
Tip: cmd+f shortcut on that pane allows for searching and highlighting on the content.

A: "You can get the list of open files by process via the default activity monitor application. Just double click on the relevant process on the list and select "Open Files and Ports" tab on the popup."
But "you had a hard time getting Activity Monitor to show open files for a process that was running as root (via sudo) or others user".
So just run Active Monitor by sudo, that`s it
sudo /Applications/Utilities/Activity\ Monitor.app/Contents/MacOS/Activity\ Monitor

A: I use the What's Open application that is very handfull (with filters, disk selection, ...).
You can find it there : http://whatsopen.en.softonic.com/mac.

A: Since you asked "Is there any other support [than lsof] available?", try this:
Create a command line tool using the "proc_pidinfo" C API referenced in the selected answer to this question: How can I programmatically get the list of open file descriptors for a given PID on OS X?

You can use proc_pidinfo with the PROC_PIDLISTFDS option to enumerate the files used by a given process. You can then use proc_pidfdinfo on each file in turn with the PROC_PIDFDVNODEPATHINFO option to get its path.

A: This works for some things:
sudo fs_usage | grep dev

for /dev/ files or similar.

A: lsof -c /^74016$/ -d^txt -FcfadDtns0
The -F instructs lsof to produce output suitable for consumption by another process, such as Perl or awk. In man lsof search for OUTPUT FOR OTHER PROGRAMS for details. The characters that come after -F represent a field you want to select for output. The output then puts each of these characters in front of the respective field. Example output:
p212^@cloginwindow^@
fcwd^@a ^@tDIR^@D0x1000004^@s704^@n/^@
f0^@ar^@tCHR^@D0xf218cacb^@n/dev/null^@
f1^@au^@tCHR^@D0xf218cacb^@n/dev/null^@
f2^@au^@tCHR^@D0xf218cacb^@n/dev/null^@
f3^@ar^@tREG^@D0x1000004^@s216424^@n/Library/Application Support/CrashReporter/SubmitDiagInfo.domains^@
f4^@ar^@tREG^@D0x1000004^@s77^@n/private/etc/security/audit_user^@
f5^@ar^@tREG^@D0x1000004^@s652^@n/private/etc/security/audit_class^@
f6^@ar^@tREG^@D0x1000004^@s358^@n/private/etc/security/audit_control^@
f7^@ar^@tREG^@D0x1000004^@s111033^@n/System/Library/Frameworks/CoreImage.framework/Versions/A/Resources/ci_stdlib.metallib^@
f8^@au^@tIPv4^@d0xc401abd77f1dd1d9^@n*:*^@
f9^@ar^@tREG^@D0x1000004^@s308316^@n/System/Library/Frameworks/CoreImage.framework/Versions/A/Resources/ci_filters.metallib^@
f10^@au^@tREG^@D0x1000004^@s1536^@n/private/var/folders/4g/3lkhwv6n7_76_1s8snscvhxc0000gp/C/com.apple.loginwindow/com.apple.metal/3902/libraries.maps^@
f11^@au^@tREG^@D0x1000004^@s65536^@n/private/var/folders/4g/3lkhwv6n7_76_1s8snscvhxc0000gp/C/com.apple.loginwindow/com.apple.metal/3902/libraries.data^@
f12^@au^@tREG^@D0x1000004^@s1536^@n/private/var/folders/4g/3lkhwv6n7_76_1s8snscvhxc0000gp/C/com.apple.loginwindow/com.apple.metal/Intel(R) HD Graphics 630/functions.maps^@
f13^@au^@tREG^@D0x1000004^@s131072^@n/private/var/folders/4g/3lkhwv6n7_76_1s8snscvhxc0000gp/C/com.apple.loginwindow/com.apple.metal/Intel(R) HD Graphics 630/functions.data^@
p421^@ccoreauthd^@
fcwd^@a ^@tDIR^@D0x1000004^@s704^@n/^@
f0^@ar^@tCHR^@D0xf218cacb^@n/dev/null^@
f1^@au^@tCHR^@D0xf218cacb^@n/dev/null^@
f2^@au^@tCHR^@D0xf218cacb^@n/dev/null^@
p537^@cUserEventAgent^@
fcwd^@a ^@tDIR^@D0x1000004^@s704^@n/^@
f0^@ar^@tCHR^@D0xf218cacb^@n/dev/null^@
f1^@au^@tCHR^@D0xf218cacb^@n/dev/null^@
f2^@au^@tCHR^@D0xf218cacb^@n/dev/null^@
f3^@au^@tunix^@d0xc401abd77b9c8579^@n->0xc401abd77b9c8709^@
f4^@au^@tunix^@d0xc401abd77b9c7129^@n->0xc401abd77b9c8899^@


text:
Q: Is this true: $\ \lim_{n\to\infty} \left( \frac{1}{n} \sum_{i=0}^{n-1} \frac{i}{n-i} \right) = e$? I was doing the old thing where you play with numbers (with help of my calculator) and came across what seems to be an interesting observation:
$$\ \lim_{n\to\infty} \left( \frac{1}{n} \sum_{i=0}^{n-1} \frac{i}{n-i} \right) = e.$$
At least, this seems to be what is happening with low values of $\ n\ $ with my calculator. So I'm not certain it is correct.
Is this correct, and why? How do we change the left hand side into an integral? I totally forgot how to do this. Or can we prove it with one of the definitions of $\ e\ ?$
Thanks in advance

A: This is not true.
Write $S_n = \sum_{i = 0}^{n - 1}\frac i{n - i}$. Adding $1$ to each summand, we get $$n + S_n = \sum_{i = 0}^{n - 1}\frac n{n - i} = n\sum_{i = 1}^n\frac 1 i = nH_n$$where $H_n$ denotes the harmonic number.
From this, it's clear that the limit diverges, as the harmonic numbers do.