text:
Q: Make Facebook plugin responsive So I am using the new Facebook plugin (Page Plugin) and have a hard time to get it responsive on window resize.
I have set the option data-adapt-container-width="true", but that only triggers when there i a page load/reload.
Please se my JSFiddle: http://jsfiddle.net/29zgc790/ (try it in exporer and if that dont work try my plunker: http://plnkr.co/edit/IPnjpJUXxkO4WTLFTTW0?p=preview) where i have set the start width for the plugin to max (500px), but I want to trigger a reload of the plugin when the container (window) gets smaller then the plugin at that particular time.
I am thinking about somthing like:
$(window).resize(function () {
    //Do the reload of plugin
});

Hope you guys have an idea of an solution that can guid me in the right way.

A: Embed the iframe generated:
<iframe id="facebook" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" title="fb:page Facebook Social Plugin" src="http://www.facebook.com/v2.5/plugins/page.php?adapt_container_width=true&app_id=&channel=http%3A%2F%2Fstatic.ak.facebook.com%2Fconnect%2Fxd_arbiter%2FTlA_zCeMkxl.js%3Fversion%3D41%23cb%3Df1ce7bfb%26domain%3Drun.plnkr.co%26origin%3Dhttp%253A%252F%252Frun.plnkr.co%252Ff152208424%26relation%3Dparent.parent&hide_cover=true&href=https%3A%2F%2Fwww.facebook.com%2Fmicrosoft&locale=en_US&sdk=joey&show_facepile=false&show_posts=true&small_header=true&width=500"
  style="border: none; visibility: visible;width: 500px; height: 500px;" class="">
Get parent width and set it into iframe and iframe's src attribute
$(window).resize(function() {
  //Do the reload of plugin
  var new_width = $("#facebook").parent().width();
  $("#facebook").css("width", new_width);
  var url = $('#facebook').attr('src').split("&width=");
  url = url[0] + '&width=' + new_width;
  $('#facebook').attr('src', url);
});

A: After a few days of trying to achieve this, I came up with a working solution!
I actually registered only to share it :)

*

*Copy the iframe code of the page plugin here:
Facebook Page Plugin (go to "Get code" and then click on "iFrame" on the top of the window that just opened.)

*Paste the code to your html inside a div with class fb-column, then remove the width and src attributes (paste the value of the src attribute - the long link - somewhere else, you will need it later)

*Add this code to your main .js file (credit for calculating the box size and calling the function goes to Mugo Web
function resizeFBPlugin() {
  //calculate parent box width
  var container_width = (Number($('.fb-column').width()) - Number($('.fb-column').css('padding-left').replace("px", ""))).toFixed(0);
  // set the src and replace the actual width with the calculated width.
  document.getElementById("fb-column").src = //paster link from iFrame here. Be sure to keep everything as it is, only replace the number after &width= with container_width
  // it should look something like this: 'https://www.facebook.com....&width='+container_width+'&height=......';
  // NOTE: take note of the use of apostrophes and + signs
  //set the width of the iframe
  document.getElementById("fb-column").width = container_width;
};

// call the function on resize and on window load

$(window).on('resize', function() {
setTimeout(function(){resizeFBPlugin()}, 500);
});

$(window).on('load', function() {
setTimeout(function(){resizeFBPlugin()}, 1500);
});

That's it! You now have a fully responsive Facebook page plugin (of course, within the min 180px and max 500px width.
BTW, The Twitter plugin works perfectly. I have no idea why Facebook decided not to fix this... I suppose they don't have the money for the right developers :)

A: So after reading the documentation for the facebook web sdk I found this little function that reloads the iframe.
FB.XFBML.parse();

https://developers.facebook.com/docs/reference/javascript/FB.XFBML.parse
That solved my problem, but @LucaGiardina hade a good solution as well but I think its always a god practice to use the built in functions if thay exist.

A: I have found out some solution but i think the best one is at least for me is that setting the parent tag of fb-comment-wrapper in a certain responsive then use facebook built in css data-width:


text:
Q: HashSet contains() returns false for custom object. hashCode() and equals() seem to be implemented correctly I have the following simple Rectangle class. If two rectangles have the same height and width, they are equal and have the same hashcode. I added a new rectangle to a hashSet.
Set<Rectangle> set = new HashSet<Rectangle>();
set.add(new Rectangle(3,3));

When I try to call contains on a new rectangle with same height and width, it returns false.
set.contains(new Rectangle(3,3)) returns false. I can't figure out why. Any ideas?
   public class Rectangle implements Comparable<Rectangle> {
            final int height, width, area, minimumEdge, maximumEdge;

            public Rectangle(int height, int width) {
                this.height = height;
                this.width = width;
                area = height * width;
                maximumEdge = height > width ? height : width;
                minimumEdge = height < width ? height : width;
            }

            public int compareTo(Rectangle rect2) {
                if (rect2.minimumEdge > this.minimumEdge) {
                    return -1;
                } else if (rect2.minimumEdge < this.minimumEdge) {
                    return 1;
                } else {
                    return 0;
                }
            }

            public int hashCode(){
                return ((width + height)*31);
            }

            public boolean equals(Rectangle rect2){
                return (this.height == rect2.height && this.width == rect2.width);
            }
        }

A: Here:
public boolean equals(Rectangle rect2){
            return (this.height == rect2.height && this.width == rect2.width);
        }

You make your own equals method, not override superclass method.
You must write like:
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Rectangle rect2 = (Rectangle) obj;
    return (this.height == rect2.height && this.width == rect2.width);
}

A: You haven't actually overridden equals().
You created a new equals(Rectangle) method, which has nothing to do with the virtual equals(Object) method.
This is why you should always add @Override when trying to override methods.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Consumer with Generics Trying to understand Generics with Consumer.
class Fruit{}
class Apple extends Fruit{}
class Orange extends Fruit{}

class Util{
    private Collection<Apple> appleList = new ArrayList<>();

    public Util(){
        acceptFruit(ap -> appleList.add(ap);
    }

    public <T extends Fruit> void acceptFruit(Consumer<T> fruitConsumer){
        //FruitService.getAllFruits();
        //some validations and get fruit object
        fruitConsumer.accept(fruit);
    }
}

//Some other class calling Util.acceptFruit(orange -> oranges.add(orange);

I get compilation errors on:
acceptFruit(ap -> appleList.add(ap);
add (Apple) in Collection can not be applied to (Fruit)

and on:
fruit.accept(fruit);
accept (T) in Consumer cannot be applied to (Apple)

Since Apple is extending Fruit, I don't understand why I am getting this error? Any idea on what I am missing in Generics/Consumer concepts?

A: Apple may be a Fruit, but Collection<Apple> is not a Collection<Fruit>.  This is due to the invariance of the generic type.
Ignoring the compilation error inside of acceptFruit (which to me is entirely unclear what you're doing to begin with), your best best is to ensure that your collection contains the superclass that you want to interface with instead of any subclasses.
 private Collection<Fruit> fruitList = new ArrayList<>();

This way, you can consume any fruit you wish in your consumer.
Anything more advanced than this - that is, consuming fruit of a specific kind - is more advanced than the basic generics we have here and is best left as an exercise for the reader.

A: Apple is a subtype of Fruit, but Apple is not known to be a subtype of T, which is an unknown type. T could be Fruit, or Orange, or Banana, and in general Apple cannot be a subtype of all of them.
The way that your acceptFruit method is declared doesn't really make sense, because as a generic method, that means that it must just work no matter what T is. A caller of acceptFruit can call it with T being whatever the caller wants, and acceptFruit must work correctly without knowing what T is. So acceptFruit takes in an argument, a Consumer, but acceptFruit doesn't know at runtime what type that Consumer wants -- it could be a Consumer<Apple> one call, and a Consumer<Orange> the next call -- but acceptFruit has no way of inferring what type is wanted in a particular call, as it doesn't have any other arguments that tell it what it is. In order to invoke fruitConsumer it would need to pass in an instance of an unknown type. So the only ways that acceptFruit can be written safely are: 1) it never invokes fruitConsumer at all; or 2) it always passes null into fruitConsumer.

A: Your acceptFruit() is weird because it calls fruit.accept(fruit). This code calls the consumer with itself as a parameter which causes all the mess in the generic. You have to pass instance of apple to the consumer, so here is your code without errors:
class Util {
    private Collection<Apple> appleList = new ArrayList<>();

    public Util(){
        acceptFruit(ap -> appleList.add(ap), new Apple());
    }

    public <T extends Fruit> void acceptFruit(Consumer<T> fruitConsumer, T fruit){
        //FruitService.getAllFruits();
        //some validations and get fruit object
        fruitConsumer.accept(fruit);
    }
}


text:
Q: KolourPaint, Increase the thickness of the pen tool is there a way to increase the thickness of the pen tool in kolourpaint? mspaint had Ctrl++ make the pen draw thicker lines.
If it's an indirect way, is it possible to assign "Ctrl++" to do the job?

A: The pen tool is set to use the smallest brush square head.
As for increasing the brush size and shape, there is a submenu that appears below the dialogue tool set when clicked.
Essentially the brush small square head is the same as the pen.
While we are at it, Libre Draw is a far superior product and very intuitive friendly.


text:
Q: rails Add email address to cc without actual sending it to this address I have small rails script that can receive emails of our internal employees emails and recent it to real address.
My work flow look likes this:
Admin sent email to Customer real address and Employee internal address, then system parse email change customer real address to system internal, and sent this email to employee real address, which he use, but at this moment I can't cc customer internal address, because it will sent this email to customer again.
So my question is, how I can add email address to cc so that user can see both recipient, but without actual sending that email to customer. Is it even possible?


text:
Q: Текст смещается в зависимости от длины текста, как это исправить Текст в canvas начинается не с начала экрана и смещается, если увеличить длину текста, выходит за пределы текстового поля, если текст длинный. Как это можно исправить?
from tkinter import *
root = tk.Tk()
root.minsize(width=1024, height=768)
canvas1 = tk.Canvas(root, bg='white')
canvas1.create_text(240,40,fill="darkblue",font="Times 20 italic bold",   text="ddddddd")
canvas1.create_text(240,70,fill="darkblue",font="Times 20 italic bold",   text="ddddddddddddddddd")
canvas1.create_text(240,100,fill="darkblue",font="Times 20 italic bold",   text="dddddddddddddddddddddddddddd")
canvas1.create_text(240,130,fill="darkblue",font="Times 20 italic bold",   text="dddddddddddddddddddddddddddddddddddddddddddddddddddddddddd")
canvas1.place(x=0, y=0, height=300, width=970)
root.mainloop()

A: По умолчанию координаты указывают на середину текста, изменить поведение можно с помощью параметра anchor с соответствующим значением.
Максимальная ширина задается с помощью width.
Подробнее тут (на английском).
text = (
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eu "
    "venenatis ex. Donec odio neque, porta sed mattis bibendum, "
    "pellentesque a enim. Donec posuere semper est vitae aliquet. Donec "
    "laoreet nisl eget erat pretium, ac rutrum orci imperdiet. Donec quis "
    "luctus neque. Cras risus arcu, luctus ac sapien a, auctor mollis "
    "lorem. In sit amet purus id neque pharetra vestibulum.")
canvas1.create_text(
    10, 10,
    fill="darkblue",
    font="Times 20 italic bold",
    anchor=tk.NW,
    width=500,
    text=text)


text:
Q: Getting View in some non Activity class I am new to Android, I am working on a project about which I need to customize some views. I need to get some imageview from a layout that was inflated in some BaseAdapter like class (the following UserListAdapter class).
public class UserListAdapter extends SingleTypeAdapter<User> {
    ...
    protected void update(int position, User user) throws IOException {
        ....
        View view = activist.getLayoutInflater().inflate(R.layout.user_list_item,null);
        ImageView imageView = (ImageView) view.findViewById(R.id.iv_avatar);
        ....
    }
}

First, I need to get the current view, that's the reason why I added some activist in the SingleAdapter class which inherits from TypeAdapter (which is the one class that inherits from BaseAdapter)
public abstract class SingleTypeAdapter<V> extends TypeAdapter {

protected Activity activist = null;

public SingleTypeAdapter(final Activity activity, final int layoutResourceId) {
    this(activity.getLayoutInflater(), layoutResourceId);
    activist = activity;
}

But in the update UserListAdapter method, the activist is null. How can I get the current view from the UserListAdapter class ?
Update, here's the TypeAdapter class
/*
 * Copyright 2012 Kevin Sawicki <kevinsawicki@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.kevinsawicki.wishlist;

import android.view.View;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import java.text.NumberFormat;

/**
 * Base adapter
 */
public abstract class TypeAdapter extends BaseAdapter {

  /**
   * Updater for current view
   */
  protected final ViewUpdater updater = new ViewUpdater();

  /**
   * Initialize view by binding indexed child views to tags on the root view
   *

   * Sub-classes may override this method but must call super
   *
   * @param view
   * @param children
   * @return view
   */
  protected View initialize(final View view, final int[] children) {
    return updater.initialize(view, children);
  }

  /**
   * Set current view that is currently being updated
   *
   * @param view
   */
  protected void setCurrentView(final View view) {
    updater.setCurrentView(view);
  }

  /**
   * Get indexed children
   *
   * @param parentView
   * @return children
   */
  protected View[] getChildren(final View parentView) {
    return updater.getChildren(parentView);
  }

  /**
   * Get text view at given index
   *
   * @param childViewIndex
   * @return text view
   */
  protected TextView textView(final int childViewIndex) {
    return updater.textView(childViewIndex);
  }

  /**
   * Get text view at given index
   *
   * @param parentView
   * @param childViewIndex
   * @return text view
   */
  protected TextView textView(final View parentView, final int childViewIndex) {
    return updater.textView(parentView, childViewIndex);
  }

  /**
   * Get image view at given index
   *
   * @param childViewIndex
   * @return image view
   */
  protected ImageView imageView(final int childViewIndex) {
    return updater.imageView(childViewIndex);
  }

  /**
   * Get image view at given index
   *
   * @param parentView
   * @param childViewIndex
   * @return image view
   */
  protected ImageView imageView(final View parentView, final int childViewIndex) {
    return updater.imageView(parentView, childViewIndex);
  }

  /**
   * Get view at given index
   *
   * @param childViewIndex
   * @return view
   */
  protected <V extends View> V view(final int childViewIndex) {
    return updater.view(childViewIndex);
  }

  /**
   * Get view at given index
   *
   * @param parentView
   * @param childViewIndex
   * @return view
   */
  protected <V extends View> V view(final View parentView,
      final int childViewIndex) {
    return updater.view(parentView, childViewIndex);
  }

  /**
   * Set text on text view at given index
   *
   * @param childViewIndex
   * @param text
   * @return text view
   */
  protected TextView setText(final int childViewIndex, final CharSequence text) {
    return updater.setText(childViewIndex, text);
  }

    /**
   * Set text on text view at given index
   *
   * @param parentView
   * @param childViewIndex
   * @param text
   * @return text view
   */
  protected TextView setText(final View parentView, final int childViewIndex,
      final CharSequence text) {
    return updater.setText(parentView, childViewIndex, text);
  }

  /**
   * Set text on text view at index to string resource
   *
   * @param childViewIndex
   * @param resourceId
   * @return text view
   */
  protected TextView setText(final int childViewIndex, final int resourceId) {
    return updater.setText(childViewIndex, resourceId);
  }

  /**
   * Set text on text view at index to string resource
   *
   * @param parentView
   * @param childViewIndex
   * @param resourceId
   * @return text view
   */
  protected TextView setText(final View parentView, final int childViewIndex,
      final int resourceId) {
    return updater.setText(parentView, childViewIndex, resourceId);
  }

  /**
   * Set text on text view to be formatted version of given integer number
   *

   * This method uses the formatter returned from
   * {@link NumberFormat#getIntegerInstance()}
   *
   * @param childViewIndex
   * @param number
   * @return text view
   */
  protected TextView setNumber(final int childViewIndex, final long number) {
    return updater.setNumber(childViewIndex, number);
  }

  /**
   * Set text on text view to be formatted version of given integer number
   *

   * This method uses the formatter returned from
   * {@link NumberFormat#getIntegerInstance()}
   *
   * @param parentView
   * @param childViewIndex
   * @param number
   * @return text view
   */
  protected TextView setNumber(final View parentView, final int childViewIndex,
      final long number) {
    return updater.setNumber(parentView, childViewIndex, number);
  }

  /**
   * Get child view
   *
   * @param childViewIndex
   * @param childViewClass
   * @return child view
   */
  protected <T> T getView(final int childViewIndex,
      final Class<T> childViewClass) {
    return updater.getView(childViewIndex, childViewClass);
  }

  /**
   * Get child view
   *
   * @param parentView
   * @param childViewIndex
   * @param childViewClass
   * @return child view
   */
  protected <T> T getView(final View parentView, final int childViewIndex,
      final Class<T> childViewClass) {
    return updater.getView(parentView, childViewIndex, childViewClass);
  }

  /**
   * Set child view as gone or visible
   *
   * @param childViewIndex
   * @param gone
   * @return child view
   */
  protected View setGone(final int childViewIndex, boolean gone) {
    return updater.setGone(childViewIndex, gone);
  }

  /**
   * Set child view as gone or visible
   *
   * @param parentView
   * @param childViewIndex
   * @param gone
   * @return child view
   */
  protected View setGone(final View parentView, final int childViewIndex,
      boolean gone) {
    return updater.setGone(parentView, childViewIndex, gone);
  }

  /**
   * Set the checked state of the {@link CompoundButton} with at index
   *
   * @param childViewIndex
   * @param checked
   * @return check box
   */
  protected CompoundButton setChecked(final int childViewIndex,
      final boolean checked) {
    return updater.setChecked(childViewIndex, checked);
  }

  /**
   * Set the checked state of the {@link CompoundButton} with at index
   *
   * @param parentView
   * @param childViewIndex
   * @param checked
   * @return check box
   */
  protected CompoundButton setChecked(final View parentView,
      final int childViewIndex, final boolean checked) {
    return updater.setChecked(parentView, childViewIndex, checked);
  }

  /**
   * Set the text on the text view if it is non-empty and make the view gone if
   * it is empty
   *
   * @param childViewIndex
   * @param text
   * @return text view
   */
  public TextView setVisibleText(final int childViewIndex,
      final CharSequence text) {
    return updater.setVisibleText(childViewIndex, text);
  }

  /**
   * Set the text on the text view if it is non-empty and make the view gone if
   * it is empty
   *
   * @param parentView
   *
   * @param childViewIndex
   * @param text
   * @return text view
   */
  public TextView setVisibleText(final View parentView,
      final int childViewIndex, final CharSequence text) {
    return updater.setVisibleText(parentView, childViewIndex, text);
  }

  /**
   * Set relative time span on text view
   *
   * @param childViewIndex
   * @param time
   * @return text view
   */
  public TextView setRelativeTimeSpan(final int childViewIndex, final long time) {
    return updater.setRelativeTimeSpan(childViewIndex, time);
  }

  /**
   * Set relative time span on text view
   *
   * @param parentView
   * @param childViewIndex
   * @param time
   * @return text view
   */
  public TextView setRelativeTimeSpan(final View parentView,
      final int childViewIndex, final long time) {
    return updater.setRelativeTimeSpan(parentView, childViewIndex, time);
  }
}


text:
Q: Jenkins Jacoco Report - unable to exclude packages from the report I am using Jacoco for coverage report generation in Jenkins Pipeline.
Note: This is not a maven based project
While generating the report I want to exclude some of the packages.
For example: paclage1 is to be excluded here

Directory Structure:
+ workspace
  + src
     + com
       - package1
       - package2
  + classes
     + com
       - package1
       - package2
  - jacoco.exec

For this, I have used the following statement in JenkinsFile:
jacoco execPattern: 'jacoco.exec', classPattern: 'classes/', sourcePattern: 'src/', exclusionPattern: '**/package1/**/*.class'

But in the jacoco report the package and it's classes are not getting excluded
This is impacting the coverage badly.
In the exclusion pattern, I have even tried the following other regex, but still not getting excluded:
- exclusionPattern: '**/package1/**/*.class'
- exclusionPattern: '**/package1/**/*'
- exclusionPattern: '**/package1/**.class'
- exclusionPattern: '**/package1/**'
- exclusionPattern: '**/package1/*.class'
- exclusionPattern: '**/package1/*'

- exclusionPattern: 'com/package1/**/*.class'
- exclusionPattern: 'com/package1/**/*'
- exclusionPattern: 'com/package1/**.class'
- exclusionPattern: 'com/package1/**'
- exclusionPattern: 'com/package1/*.class'
- exclusionPattern: 'com/package1/*'

- exclusionPattern: '**/com/package1/**/*.class'
- exclusionPattern: '**/com/package1/**/*'
- exclusionPattern: '**/com/package1/**.class'
- exclusionPattern: '**/com/package1/**'
- exclusionPattern: '**/com/package1/*.class'
- exclusionPattern: '**/com/package1/*'

- exclusionPattern: '/com/package1/**/*.class'
- exclusionPattern: '/com/package1/**/*'
- exclusionPattern: '/com/package1/**.class'
- exclusionPattern: '/com/package1/**'
- exclusionPattern: '/com/package1/*.class'
- exclusionPattern: '/com/package1/*'

And many such more combinations.

I have been even tried sourceExclusionPattern with the similar set of combinations. But still unsuccessful.
Note: package1 is just an example here. In actual case, package1 is something like debashish/core/extra
Need help in finding what I am doing wrong.


text:
Q: Intercepting and rerouting http request sent by javascript scripts to a different server Assuming I have a simple html + javascript application. I have a script from a cdn included in the html via the script:src tag. This script sends a request to a server using jquery's ajax library. Is it possible to intercept and send the request made by the script to a different server instead of the server that it currently sends the request to.
The script sends a request to a server but I would like to send the request first to my personal api, inject some headers using data that is only available in my api, then send the request to their server from my api, thus using my api server as a proxy.


text:
Q: Getting most frequent item in SQLite Database I am using this code to get the most played song in a collection by the number of times it appears in the database:
public Cursor getMostPlayed(){
    String query = "SELECT * " +
            ", COUNT(*) AS 'value'" +
            " FROM " + DatabaseHelper.TABLE_COLLECTIONS_TRACKS +
            " WHERE " + DatabaseHelper.KEY_CATEGORY + " = 'User Activity'" +
            " GROUP BY " + DatabaseHelper.KEY_NAME +
            " ORDER BY 'value' DESC";

    return database.rawQuery(query, null);
}

Problem is, when I query the cursor to get the results, while it does get the most played item, it doesn't order the list by value, but rather by the name.
What's wrong with my query?

A: You have to remove the string delimiters around the value alias.
String query = "SELECT * " +
        ", COUNT(*) AS value" +
        " FROM " + DatabaseHelper.TABLE_COLLECTIONS_TRACKS +
        " WHERE " + DatabaseHelper.KEY_CATEGORY + " = 'User Activity'" +
        " GROUP BY " + DatabaseHelper.KEY_NAME +
        " ORDER BY value DESC";


text: Q: Is there any way possible to extract data after writing to outputstream? I am trying to create several sockets and connecting it with a single client using socket programming. Every time a client tries to communicate with server a new socket gets created and messages can be sent but the problem comes when i try to pass more than one message through server. the first message gets sent and the for the rest, i face stream corrupted exceptions.Following is my code for the class that tries to read object from output stream.


text:
Q: JPA (Hibernate): Error when using @EmbeddedId in generic @MappedSuperclass I am currently defining JPA entities for a legacy database (lots of composite keys, but also single-column keys). I have created the following entity superclass:
@MappedSuperclass
public abstract class AbstractEntity<ID extends Serializable> {
    public abstract ID getId();
    public abstract void setId(ID id);
}

And then a superclass for composite keys (as well as a superclass for long primary key, not listed here):
@MappedSuperclass
public abstract class AbstractEmbeddedIdEntity<ID extends Serializable> extends AbstractEntity<ID> {
    @EmbeddedId
    private ID id;

    public AbstractEmbeddedIdEntity() {
        id = newId();
    }

    @Override
    public ID getId() {
        return id;
    }

    @Override
    public void setId(ID id) {
        this.id = id;
    }

    protected abstract ID newId();
}

And finally concrete entities like this:
@Entity
@Table(name = "firstEntity")
public class FirstEntity extends AbstractEmbeddedIdEntity<FirstEntityId> {

    public FirstEntity() {
    }

    @Embeddable
    public static class FirstEntityId implements Serializable {
        @Column(name = "firstId")
        private String firstId;

        public FirstEntityId() {
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == this) {
                return true;
            }
            if (!(obj instanceof FirstEntityId)) {
                return false;
            }
            FirstEntityId other = (FirstEntityId) obj;
            return
                    Objects.equals(firstId, other.firstId);
        }

        @Override
        public int hashCode() {
            return Objects.hash(firstId);
        }
    }

    @Override
    protected FirstEntityId newId() {
        return new FirstEntityId();
    }
}

Now the issue is that if I have multiple entities like this and try to access an ID property of an entity (currently with Spring Boot, e.g. findByIdFirstId(String firstId)), an exception is thrown:
java.lang.IllegalArgumentException: Unable to locate Attribute  with the the given name [firstId] on this ManagedType [unknown]

I have debugged this and found out that in hibernate, the metamodel maps all of my entities to the same MappedSupperclass instance. During application startup, the @EmbeddedId returned by newId() is set to the MappedSupperclass, overwriting the ID of the previous entity. So in the end, all entities are mapped to the same MappedSupperclass, but the MappedSupperclass only has the @EmbeddedId of the last entity.
In the above example, accessing the ID property fails because the @EmbeddedId of the last entity doesn't have a property called "firstId" (it has been overwritten with the ID properties of the last entity).
Now I am wondering if my approach is wrong, if I am missing something or if this could be an issue with hibernate?
Complete example using spring boot available on github. Run with mvn spring-boot:run.

A: This looks to me like a bug in hibernate, therefore I have created a ticket in the hibernate bug tracker.
As a workaround I am now defining the ID attribute (@EmbeddedId) in the concreate entity classes instead of the abstract superclass.


text:
Q: Properly indent after space in Vim I'm trying to setup a smart indentation with vim. Basically I want the editor to tab after I enter. Here is an example
This is what it's doing currently after enter:
def method
|
end

this is what I want
def method
  |
end

This is strange because I have all of the obvious configurations in vimrc. Here is my .vimrc
set tabstop=2 softtabstop=0 expandtab shiftwidth=2 smarttab
set number
set nowrap
set paste
set smartindent
set autoindent
set cindent

What do I need to do?


text:
Q: run psql query in bash I am new in bash and psql, I want to write a bash code that login a server the connect to psql database do a select query and then return the output. the set up I have as follow.
server named dbs, it has psql install and running. database name = dname, user= tester passwrod = 1234
in the database there is table called node_info it has 3 colons ip, mac, connection_time.
I want to run following query
select  ip, connection_time from node_info where ip=10.10.10.2;
Any tips how to write a shell script to do this remotely?

A: If you have properly set your "pg_hba.conf" configuration file to achieve remote connections, you may try the following:
psql -U tester -h remoteip -p remoteport -d dname -W -c "select ip, connection_time from node_info where ip='10.10.10.2'"


text:
Q: How to limit and flip (exchange) elements of a string in php? I have a string which contains:
A1:B1:C1:D1,E1:F1:G1:H1

I want to remove everything expect:
A1:B1:C1

Afterwards I want to flip elements of the string around, in this case I want to flip the positions of A1 and C1 so A1:B1:C1 becomes C1:B1:A1.
How would I be able to go about doing this?

A: Algorithm:

*

*Obtain the desire string

*Obtain the tokens (A1, B1, C1)

*Save in a temp var A1

*Change the C1 value by A1

*Change the C1 original position by temp

*Make the string.

Code:
<?php

$string = 'A1:B1:C1:D1,E1:F1:G1:H1';

$less = substr($string, 0, 8);

$array = explode(':', $less);
$temp = $array[0];
$array[0] = $array[2];
$array[2] = $temp;

$final = implode(':', $array);

echo $final;
?>


text:
Q: Flask app conflicting routes is it the routes. any ideas? I am trying to make a forum or code sharing like site on pythonanywhere using a flask app, but I have conflicting routes so it fails.
What this is doing is adding a new line to a .csv file (that already exists) when the user completes and html form I have set up. This works fine on the /addpythoncode route, but it fails on the /addflaskcode route.
I will provide the routes and the error log output below. Can someone please help me fix this?
import sqlite3
from flask import Flask, render_template, request, redirect
import random
import csv

app = Flask(__name__)

@app.route('/addpythoncode', methods=['GET', 'POST'])
def addpycode():
  if request.method == 'GET':
      return render_template('addpythoncode.html')
  else:
      dict = {}
      dict["codename"] = request.form['codename']
      dict["name"] = request.form['name']
      dict["code"] = request.form['code']
      f = open("/home/Ethankbdca/mysite/Pythonforum.csv", "a")
      with f:
          fnames = ['codename', 'name', 'code']
          writer = csv.DictWriter(f, fieldnames=fnames)
          writer.writerow(dict)
          return redirect('http://ethankbdca.pythonanywhere.com/pythonforum')

@app.route('/addflaskcode', methods=['GET', 'POST'])
def newflskcode():
  if request.method == 'GET':
      return render_template('addflaskcode.html')
  else:
      dict = {}
      dict["routename"] = request.form['routecode']
      dict["name"] = request.form['name']
      dict["routecode"] = request.form['routecode']
      f = open("/home/Ethankbdca/mysite/Flaskforum.csv", "a")
      with f:
          fnames = ['routename', 'name', 'routecode']
          writer = csv.DictWriter(f, fieldnames=fnames)
          writer.writerow(dict)
          return redirect('http://ethankbdca.pythonanywhere.com/flaskforum')

Here is the message I get on the error log:
2019-03-26 21:21:43,161: OSError: write error

A: I agree with Milad M., but I agree with you that there is no such mistake.
Change the indentation level of return render_template (...). Add a try-except block to the code where the file is written to.
import abort

@app.route('/addpythoncode', methods=['GET', 'POST'])
def addpycode():
  if request.method == 'GET':
      return render_template('addpythoncode.html')
  else:
      dict = {
          'codename': request.form['codename'],
          'name': request.form['name'],
          'code': request.form['code'],
      }
      try:
          fnames = ['codename', 'name', 'code']
          f = open("/home/Ethankbdca/mysite/Pythonforum.csv", "a")
          writer = csv.DictWriter(f, fieldnames=fnames)
          writer.writerow(dict)
          writer.close()
      except Exception as ex:
          abort(500)
      return redirect('http://ethankbdca.pythonanywhere.com/pythonforum')

This should cause an Internal Server Error on read-write problems.


text:
Q: What's the difference between base/uri/path/ etc in haproxy acl? haproxy acl based on
base
uri
path
query
url
capture.req.uri
what's the definition and difference?
for example, a http://www.example.com/aaa/bbb/ccc?x=1&y=2,
which part is base, uri, path, query, url, etc?

A: *

*base - www.example.com/aaa/bbb/ccc

*uri - /aaa/bbb/ccc?x=1&y=2

*path - /aaa/bbb/ccc

*query - x=1&y=2

url - typicaly it's something like full http://www.example.com/aaa/bbb/ccc?x=1&y=2, but afaik haproxy doesn't use it.


text:
Q: Choosing Rails vs. Django based on performance and scalability I'm currently working on a side project (that hopefully will grow into something more), and right now its strictly static front-end stuff; HTML, CSS and jQuery.  So in the meantime, I have time to do heavy research on choosing Ruby on Rails vs. Python/Django.
I've read countless articles comparing the two, which usually come down to "what language do you prefer?" and considerations of the development community.
My question here is strictly of a technical nature, comparing the frameworks (and their respective languages) as such:
Between Ruby/Rails vs. Python/Django:

*

*Which run-time performs better (any statistics or real-world examples would be great)?

*What are the known scalability problems, and which scales better in the long run (again, any technical documentation or data to represent this would be great)?

I understand that scalability comes down to architecture, so the question is what framework and its respective tools, APIs, plug-ins, community, documentation, etc. "guides" you towards the best scalable web architecture from the "get-go"?
Thanks!

A: https://stackoverflow.com/questions/91846/rails-or-django-or-something-else
Does Django scale?
Using Rails as a framework for a large website
https://stackoverflow.com/questions/3042259/django-or-rails
Rails or Django?
...
There are plenty of questions regarding this subject, and none of them answer the question - there's no right answer.
I don't think you should choose a framework on those two metrics. Unless you are building the next Facebook, both will scale to your needs. Similarly both should perform to your needs. Instead have a look at what features of the languages and frameworks appeal to your application etc.

A: That's the wrong approach to thinking about the problem.
Scalability on the web comes from expanding the number of application servers rather than speeding up an individual application server.
Ruby and Python are both slow languages with problematic multithreading and problematic garbage collectors. We use them anyway because they are very good at permitting the developer to write simpler programs that do the job better. It's not worth bothering about the question, which of these two runtimes performs better.
So long as you keep good web architecture, where your application server stateless (where all state is kept in the database or in cookies, but not in server-side sessions), you should not care what the actual performance of an individual request is, so long as it is reasonable. Because if your application server is stateless, you can scale that tier horizontally to cope with any need for scalability.


text:
Q: Garbage collection on Unmanaged COM object references I am working on a project where I am referencing one COM C++ dll. The classes inside this dll are in nested form which creates a hierarchy
Example
 Cats-->
    Cat1-->
      --> Ears
         --> Ear1
         --> Ear2
    Cat2-->
      --> Ears
         --> Ear1
         --> Ear2

Cats and Ears are Collections, So In my case I am Creating object of mammals class :
Mammals objMammals= new Mammals();
objMammals.Cats.Add(); // Adds a cat object with default values

and then you can add Ears and so On and everything works fine.
But Problem occurs when you try the same thing using reflection.

int MammalsId = (int)objMammals.GetType().InvokeMember("FindById", System.Reflection.BindingFlags.InvokeMethod, null,objMammals, new object{0});// returns the Mammals Object Id from hierarchy

object CatsObject = (object)objMammals.GetType().InvokeMember("Cats", System.Reflection.BindingFlags.GetProperty, null,objMammals, new object{1});

The above line works fine but once you call GC.Collect() in between the last two lines the objMammals.GetType() will turn to __ComObject(which does not have Cats) and it will start throwing runtime exceptions.
The Dll reference is Isolated and I can see the generated Manifest file looks correct. I've tried to register the Dll as well as the Interop as well but No luck, If some how I create any reference of Cats object or Ears object before the GC comes in then It works just fine.
I want the objects to always contain their actual type, So I can use the reflection as i need to.


text:
Q: Spelling dictionary corrupted Bug introduced in 9.0 and fixed in 9.0.1

I have a problem with the Check Spelling in Mathematica, that I quite don't understand:
If I try to use the Check Spelling on any notebook, the check just stop before the first word and in the field "Reason for stopping:" is written: "The spelling dictionary file Mathematica.rws could not be loaded. The file may be corrupted."
I found nothing about this on the Internet, but after a research on my computer I found that this file is at "/usr/local/Wolfram/Mathematica/9.0/SystemFiles/SpellingDictionaries/English/Mathematica.rws" (I'm on Linux)
There is also another directory called SpellingDictionaries at ~/.Mathematica/SystemFiles/SpellingDictionaries, but it is empty.
I tried by copying the content of the first directory in the second, but it doesn't work.
I also tried to use another file Mathematica.rws that I found in /WINDOWS/Program Files/Wolfram Research/Mathematica/8.0/SystemFiles/SpellingDictionaries on another computer (under Windows) that had Mathematica V8 (with which the check spelling worked). I doesn't work either.
Can anyone help me ? I would really like to be able to use Mathematica to write my report.

A: I do not recall all the details, but I belive this was a bug on some operating systems (e.g. Linux x86) for$Version 9.0 $ReleaseNumber 0. It should be fixed if you upgrade to 9.0.1. Let me know if that fixes your problem.


text:
Q: WPF - PRISM: How to close CustomPopupWindow with button click This one is playing with me, and I cannot seem to figure it out - I need some external help here bro's!
I want a popup window that does not have the title, minimize, maximize, and close buttons, because we want to style it ourselves and add a custom close button on the popup's screen.
So I followed these links to get where I am now:
https://msdn.microsoft.com/en-us/library/ff921081(v=pandp.40).aspx
https://msdn.microsoft.com/en-us/library/gg405494(v=pandp.40).aspx
https://www.codeproject.com/Articles/269364/MVVM-PRISM-Modal-Windows-by-using-Interaction-Requ
But I still can't figure out how to achieve this. The basic windows have "OK" and "Cancel" buttons, but those are defaults, and I do not want that, that is why I went the "Custom View" way.
Here is my Main Window's xaml:
<Window x:Class="Prototype.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"
        xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
        xmlns:views="clr-namespace:Prototype.Views"
        Height="349.146" Width="727.317"
        WindowState="Maximized">
    <Grid>
        <Button Command="{Binding RaiseCustomPopupViewCommand}">Show Popup Window</Button>

        <i:Interaction.Triggers>
            <prism:InteractionRequestTrigger SourceObject="{Binding CustomPopupViewRequest, Mode=OneWay}">
                <prism:PopupWindowAction IsModal="True" CenterOverAssociatedObject="True">
                    <prism:PopupWindowAction.WindowStyle>
                        <Style TargetType="Window">
                            <Setter Property="ShowInTaskbar" Value="False"/>
                            <Setter Property="WindowStyle" Value="None"/>
                            <Setter Property="ResizeMode" Value="NoResize"/>
                        </Style>
                    </prism:PopupWindowAction.WindowStyle>
                    <prism:PopupWindowAction.WindowContent>
                        <views:CustomPopupView  />
                    </prism:PopupWindowAction.WindowContent>
                </prism:PopupWindowAction>
            </prism:InteractionRequestTrigger>
        </i:Interaction.Triggers>
    </Grid>
</Window>

And here it the Main Window's code:
public class MainWindowViewModel : BindableBase
{
    public InteractionRequest<INotification> CustomPopupViewRequest { get; private set; }

    public MainWindowViewModel()
    {
        CustomPopupViewRequest = new InteractionRequest<INotification>();
    }

    public DelegateCommand RaiseCustomPopupViewCommand => new DelegateCommand(RaiseCustomPopupView, CanRaiseCustomPopupView);

    public string InteractionResultMessage { get; private set; }

    private void RaiseCustomPopupView()
    {
        InteractionResultMessage = "";
        CustomPopupViewRequest.Raise(new Notification { Content = "Message for the CustomPopupView", Title = "Custom Popup" });
    }

    private bool CanRaiseCustomPopupView()
    {
        return true;
    }
}

The InteractionRequestTrigger's SourceObject is a UserControl.
Here is it's xaml:
<UserControl x:Class="Prototype.Views.CustomPopupView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:prism="http://prismlibrary.com/"
             prism:ViewModelLocator.AutoWireViewModel="True"
             xmlns:local="clr-namespace:Prototype.Views"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300"
             MinWidth="300" MinHeight="100">
    <StackPanel Orientation="Vertical" Background="Gray">
        <Button DockPanel.Dock="Right"
                Content="Close"/>
    </StackPanel>
</UserControl>

So as you can see, I have a "Close" button in the UserControl.
I tried using a Command, but even then I cannot acccess the window or execute something to close the window.
Is there some kind of prism command or something I am not aware of?
Is it possible to close the window the way I want with a button?
Any help will be greatly appreciated! :)

A: No matter, I just managed to solve this on my own :).
I was thinking of it differently, but what I actually wanted was the CancelCommand.
This is how we implement it in the UserControl, with NO other changes. Everything is still the same as described above, but the CustomPopup now have the following in it's ViewModel:
public class CustomPopupViewModel : BindableBase, IInteractionRequestAware
{
    public CustomPopupViewModel()
    {
        CancelCommand = new DelegateCommand(CancelInteraction);
    }

    private CustomPopupSelectionNotification notification;

    public INotification Notification
    {
        get
        {
            return this.notification;
        }
        set
        {
            if (value is CustomPopupSelectionNotification)
            {
                this.notification = value as CustomPopupSelectionNotification;
                this.OnPropertyChanged(() => this.Notification);
            }
        }
    }

    public Action FinishInteraction { get; set; }

    public System.Windows.Input.ICommand CancelCommand { get; private set; }

    public void CancelInteraction()
    {
        if (notification != null)
        {
            notification.SelectedItem = null;
            notification.Confirmed = false;
        }

        FinishInteraction();
    }
}

You will also notice that we have a class called CustomPopupSelectionNotification.
Here is it's code:
public class CustomPopupSelectionNotification : Confirmation
{
    public CustomPopupSelectionNotification()
    {
        Items = new List<string>();
        SelectedItem = null;
    }

    public CustomPopupSelectionNotification(IEnumerable<string> items) : this()
    {
        foreach (string item in items)
        {
            Items.Add(item);
        }
    }

    public IList<string> Items { get; private set; }

    public string SelectedItem { get; set; }
}

So in short, I am just cancelling the popup, instead of trying to close it.
I then added the command CancelCommand to the "Close" button on my UserControl.


text:
Q: How can I modify these dplyr code for multiple linear regression by combination of all variables in R lets say I have following data
ind1 <- rnorm(99)
ind2 <- rnorm(99)
ind3 <- rnorm(99)
ind4 <- rnorm(99)
ind5 <- rnorm(99)
dep <- rnorm(99, mean=ind1)
group <- rep(c("A", "B", "C"), each=33)
df <- data.frame(dep,group, ind1, ind2, ind3, ind4, ind5)

the following code is calculating multiple linear regression between dependend variable and 2 independent variables by group which is exactly what I want to do. But I want to regress dep variable against all combination pair of independent variables at once. So how can I combine other models in this code?
df %>%
  nest(-group) %>%
  mutate(fit = map(data, ~ lm(dep ~ ind1 + ind2, data = .)),
         results1 = map(fit, glance),
         results2 = map(fit, tidy)) %>%
  unnest(results1) %>%
  unnest(results2) %>%
  select(group, term, estimate, r.squared, p.value, AIC) %>%
  mutate(estimate = exp(estimate))

Thanks in advance!

A: Not a full tidy answer. Consider building all possible combinations of linear formulas with rapply after initial build with lapply and combn then pass into your tidy method:
indvar_list <- lapply(1:5, function(x)
                 combn(paste0("ind", 1:5), x, , simplify = FALSE))

formulas_list <- rapply(indvar_list, function(x)
                   as.formula(paste("dep ~", paste(x, collapse="+"))))

run_model <- function(f) {
    df %>%
      nest(-group) %>%
      mutate(fit = map(data, ~ lm(f, data = .)),
             results1 = map(fit, glance),
             results2 = map(fit, tidy)) %>%
      unnest(results1) %>%
      unnest(results2) %>%
      select(group, term, estimate, r.squared, p.value, AIC) %>%
      mutate(estimate = exp(estimate))
}

tibble_list <- lapply(formulas_list, run_model)


text:
Q: Pgfplots not plotting bar graph with all symbolic coordinates? I am trying to create a bar graph using pgfplots. Specifically, I have 8 different bins of varying signal length against some computational time. I have set the x axis signal lengths to symbolic coordinates and have those plotted against time. The resultant graph however, does not seem to plot the last "bin" of times (i.e signal length of 32768).
I have the code attached below:
\begin{figure}[htbp]
\centering
\Dshadowbox{
\begin{tikzpicture}[scale=1]
\begin{axis}[
    x tick label style={
        /pgf/number format/1000 sep=},
    ylabel=\textbf{Computation Time} $\mathbf{s}$,
    xlabel=\textbf{Signal Length $\mathbf{N}$},
    xtick=data,
    symbolic x coords = {256,512,1024,2048,4096,8192,16384,32768},
    ybar interval=0.8,
    xtick={256,512,1024,2048,4096,8192,16384,32768},
    bar width = 10pt,
    ymode=log,
    bar shift=0pt,
    log origin=infty,
    width=\textwidth
        ]
\addplot
    coordinates {(256,0.0202) (512,0.0445)
         (1024,0.1578) (2048,0.5877)  (4096,3.5797) (8192,18.8230) (16384,103.7727) (32768,762.0937)};

\addplot
    coordinates {(256,0.0012) (512,0.0034)
        (1024,0.0106) (2048,0.0229) (4096,0.1045) (8192,0.4693) (16384,3.0236) (32768,22.8810)};

\addplot
    coordinates {(256,0.0009) (512,0.0013)
        (1024,0.0027) (2048,0.0059) (4096,0.220) (8192,0.0858) (16384,0.3697) (32768,3.7458)};

\addplot
    coordinates {(256,0.0028) (512,0.0032)
        (1024,0.0052) (2048,0.0168) (4096,0.0638) (8192,0.2927) (16384,1.4904) (32768,9.21)};

\addplot
    coordinates {(256,0.0011) (512,0.0019)
        (1024,0.0085) (2048,0.0486) (4096,0.1973) (8192,0.6917) (16384,3.2107) (32768,17.1235)};

\addplot
    coordinates {(256,0.00006) (512,0.00014)
        (1024,0.00022) (2048,0.00047) (4096,0.0019) (8192,0.0085) (16384,0.3123) (32768,5.9074)};
\end{axis}
\end{tikzpicture}
}
\end{figure}

I'm sure I have made a silly error somewhere but haven't been able to see it as of yet. Any help on the matter would be much appreciated.

A: You need an extra coordinates for each addplot, since ybar interval=0.8 is used;  therefore 8 coordinates only generates 7 ybar because an interval is defined by two coordinates. The last coordinate will only be used to determine the interval width; its y value doesn't change the bar appearance. Here (65536,0.1) is appended as a dummy coordinate to serve as the horizontal end point. Since the OP did not provide \Dshadowbox, it is therefore disable to make a run.
As a side note, if ybar interval=0.8 is removed, (that is no ybar interval plot) then the last coordinate (32768,y) will show.

Code
\documentclass[border=2cm]{standalone}
\usepackage{graphicx}
\usepackage{pgfplots}

\pgfplotsset{compat=1.8}

\begin{document}

%\begin{figure}[htbp]
%\centering
%\Dshadowbox{
\begin{tikzpicture}[scale=1]
\begin{axis}[
    x tick label style={
        /pgf/number format/1000 sep=},
    ylabel=\textbf{Computation Time} $\mathbf{s}$,
    xlabel=\textbf{Signal Length $\mathbf{N}$},
    xtick=data,
    symbolic x coords = {256,512,1024,2048,4096,8192,16384,32768,65536},
    ybar interval=0.8,
    xtick={256,512,1024,2048,4096,8192,16384,32768,65536},
    bar width = 10pt,
    ymode=log,
    bar shift=0pt,
    log origin=infty,
    width=\textwidth
        ]
\addplot
    coordinates {(256,0.0202) (512,0.0445)
         (1024,0.1578) (2048,0.5877)  (4096,3.5797) (8192,18.8230) (16384,103.7727) (32768,762.0937)(65536,0.1)};

\addplot
    coordinates {(256,0.0012) (512,0.0034)
        (1024,0.0106) (2048,0.0229) (4096,0.1045) (8192,0.4693) (16384,3.0236) (32768,22.8810)(65536,0.1)};

\addplot
    coordinates {(256,0.0009) (512,0.0013)
        (1024,0.0027) (2048,0.0059) (4096,0.220) (8192,0.0858) (16384,0.3697) (32768,3.7458)(65536,0.1)};

\addplot
    coordinates {(256,0.0028) (512,0.0032)
        (1024,0.0052) (2048,0.0168) (4096,0.0638) (8192,0.2927) (16384,1.4904) (32768,9.21)(65536,0.1)};

\addplot
    coordinates {(256,0.0011) (512,0.0019)
        (1024,0.0085) (2048,0.0486) (4096,0.1973) (8192,0.6917) (16384,3.2107) (32768,17.1235)(65536,0.1)};

\addplot
    coordinates {(256,0.00006) (512,0.00014)
        (1024,0.00022) (2048,0.00047) (4096,0.0019) (8192,0.0085) (16384,0.3123) (32768,5.9074)(65536,0.1)};
\end{axis}
\end{tikzpicture}
%}
%\end{figure}

\end{document}


text:
Q: Binding ContextMenu defined in a DataTemplate to command Ok, here is my problem: I have a UserControl Template defined in Style.xaml like this
 <Style x:Key="ModulProfTemplate" TargetType="{x:Type UserControl}" >
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type UserControl}">
                <Border BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true" BorderThickness="{TemplateBinding BorderThickness}" DataContext="{Binding DataContext, RelativeSource={RelativeSource TemplatedParent}}">

                    <Border x:Name="border" BorderBrush="#004E6CA9" BorderThickness="1.5">
                        <Grid x:Name="Layout" Background="{Binding Background, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0.5" DataContext="{Binding}">
                            <Grid.ContextMenu>
                                <ContextMenu>
                                    <MenuItem Header="Disponibil" Command="{Binding GridContextMenuCommand}" CommandParameter="disp"/>
                                    <MenuItem Header="Indisponibil" Command="{Binding GridContextMenuCommand}" CommandParameter="indisp"/>
                                </ContextMenu>
                            </Grid.ContextMenu>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="0.497*"/>
                                <RowDefinition Height="0.5*"/>
                            </Grid.RowDefinitions>
                            <StackPanel Orientation="Horizontal" d:LayoutOverrides="Height" HorizontalAlignment="Center" VerticalAlignment="Center">
                                <TextBlock TextWrapping="Wrap" Text="{Binding SalaSaptPara, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                                <TextBlock TextWrapping="Wrap" Text="{Binding MaterieSaptPara, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                            </StackPanel>
                            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
                                <TextBlock TextWrapping="Wrap" Text="{Binding SalaSaptImpara, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                                <TextBlock TextWrapping="Wrap" Text="{Binding MaterieSaptImpara, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="2,0,0,0"/>
                            </StackPanel>
                        </Grid>
                    </Border>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="BorderBrush" TargetName="border" Value="#CA4E6CA9"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

the problem is that i don't know how to bind the command to menuitem. The UserControl's DataContext is set to ViewModel.Luni.M1, and the command is in ViewModel DataContext. So my question is: How do i change the DataContext so i can bind the command?

A: Solved, all i had to do was add a tag to the border that was bound to my viewmodel's datacontext, and after that use PlacementTarget.Tag.MyCommand, as shown like this :)
                        <Border x:Name="border" BorderBrush="#004E6CA9" BorderThickness="1.5" Tag="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=my:CadreDidacticeView, AncestorLevel=1}, Path=DataContext}">
                        <Border.ContextMenu>
                            <ContextMenu>
                                <MenuItem Header="Disponibil" Command="{Binding PlacementTarget.Tag.GridContextMenuCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}">
                                </MenuItem>
                            </ContextMenu>
                        </Border.ContextMenu>


text:
Q: How are calls to static members of another class handled in Java Object Serialization? public class Employee implements java.io.Serializable
{
   public String name = "Tom";

   public void mailCheck()
   {
      String address = SomeClass.ItsStaticField(name);  //call to static

      System.out.println("Mailing a check to " + name
                           + " " + address);
   }
}

public class SomeClass()
{
   // Static Map of <Name, Address>
   private static Map<String, String> NameAddressMap= new HashMap<String, String>();
   string address;

     Static ItsStaticField(name)
       {
          if (NameAddressMap.containsKey(name){
              address = NameAddressMap.get(name);
          }
          else{
            // address =...make a webservice call ... get address for name
            NameAddressMap.put(name, address);
          }
       return address;
       }
}

What happens when an object of the above is serialized? And deserialized on another node in a distributed environment? When is 'SomeClass.ItsStaticField()' invoked? Is the 'address' field's value calculated before serialization and then bundled into bytes as part of the serialization process?
Update: Apologize for taking the liberty to add some more info.
Added sample code for 'SomeClass'.
I have the above code in a distributed environment (specifically Hadoop). I understand this is a bad thing because there are going to be multiple web-service calls, and the intended 'caching mechanism' doesn't really work as expected. What I want to understand is, when and how many times the web-service call would be invoked? And how many instances of the static map 'NameAddressMap' is created on all nodes and when? Thanks much!

A:
What happens when an object of the above is serialized?

The name is serialized

And deserialized on another node in a distributed environment?

The name is deserialized

When is 'SomeClass.ItsStaticField()' invoked?

When you call mailCheck();

Is the 'address' field's value calculated before serialization and then bundled into bytes as part of the serialization process?

No, it is not a member of the object serialized.

A: Serialization serialises the objects fields, not its methods. The contents of the methods remain in the class definition, not in the instance itself.

A: When a class is serialized, the node deserializing it need all the .class files required for the deserialization. In your case, the class SomeClass is part of the dependencies of Employee. So, in order to deserialize an Employee, both Employee.class and SomeClass.class are required on the local node.
Note: due to Java being dynamically compiled, it should work until you actually try to call the mailCheck method.


text:
Q: I keep getting NaN for a value that is produced from all integers I am trying to write a jQuery based math program that will display and average my quiz scores. Everything works perfectly except that in my for loop I have:
specQuizTotalValue += total;

for a var "specQuizTotalValue" that is globally set to 0.
For some reason I keep getting NaN for specQuizTotalValue, even though typeof in each iteration as well as the global definition comes back "number". I also tried pushing to an Array and with two iterations I got [NaN, 16, 36] (16 and 36 are the correct values).
Here is the fiddle - http://jsfiddle.net/mjhd/jf39f/
var specQuizUL = $('#specQuiz ul').length;

var specQuizTotalValue = 0;

for(i = 0; i <= specQuizUL; i++){
var preval = $('#specQuiz ul:nth-child(' + i + ') li:nth-child(2)').html();
var value = parseInt(preval);

var pretot = $('#specQuiz ul:nth-child(' + i + ') li:nth-child(3)').html();
var total = parseInt(pretot);

var avg = (value/total).toFixed(2) * 100;
$('#specQuiz ul:nth-child(' + i + ')').append('
' + avg + ' %
');

    specQuizTotalValue += total;
}

 $('#specQuizTotal').append('
' + specQuizTotalValue + '
');

Please help!!

A: The :nth-child selector is 1-based, not 0-based. In the first iteration,
$('#specQuiz ul:nth-child(0) li:nth-child(2)')

will result in an empty jQuery object, so .html() will return undefined, and parseInt(undefined) returns NaN.
Change your for loop to start from 1:
for(i = 1; i <= specQuizUL; i++) {

A: This line is your problem:
var pretot = $('#specQuiz ul:nth-child(' + i + ') li:nth-child(3)').html();
    console.log(i,pretot,parseInt(pretot));
var total = parseInt(pretot);

when i is 0, pretot is undefined, since that particular selector is not selecting anything. so when pretot is undefined, parseInt(pretot) evaluates to NaN, and one NaN value in a cumulative total will ruin the entire total.


text:
Q: OpenVPN + iptables - define valid routes I have a bastion servers which accept users via OpenVPN. The bastion has two network adapters: one leg on the internet and the other leg on a private network. Each user has different IP address and different places where he can visit inside the private network.
For example: the user John has the static IP 10.8.0.1, on OpenVPN. John can only access this IP address 10.8.1.1, inside the internal network. Any other place that John will try to access should be blocked.
I tried to do something like this:
iptables -A FORWARD -p tcp --source 10.8.0.1 --destination 10.8.1.1 -j ACCEPT

The default policy for INPUT,OUTPUT and FORWARD is block.
I was expected that will allow John access his resource. But actually all his requests are being blocked.
What I'm doing wrong?
Update 1
Adding the full code:
#!/bin/sh
# flush all
iptables -F
iptables -X

# Setting default filter policy
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP

# Allow unlimited traffic on loopback
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

iptables -A FORWARD -p tcp --source 10.8.0.1 --destination 10.8.1.1 -j ACCEPT

# make sure nothing comes or goes out of this box
iptables -A INPUT -j DROP
iptables -A OUTPUT -j DROP


text:
Q: Why DataBinding doesn't work on second time around? The error I got when I change the datasource of BindingSource
"databinding cannot find a row that is suitable for all bindings row that is suitable for all bindings"
        this.RemoveAllBindings(); // My work-around for the meantime

        bdsOrder.DataSource = _ds.Tables["orders"]; // errors here on second time around(first time is blank datatable, second time is when i open existing record, then it errors), dataset comes from Remoting
        bdsOrderDetail.DataSource = _ds.Tables["order_detail"];

        bdsPhoto.DataSource = _ds.Tables["order_photo"];
        bdnPhoto.BindingSource = bdsPhoto;

My Helper extension method work-around on perplexing "databinding cannot find a row..." error.
namespace MycComponentExtension
{
    public static class Helper
    {
        public static void RemoveAllBindings(this Form form)
        {
            RemoveAllBindings((Control)form);
        }

        private static void RemoveAllBindings(this Control root)
        {
            foreach (Control c in root.Controls)
            {
                if (c.Controls.Count > 0) RemoveAllBindings(c);

                root.DataBindings.Clear();
            }
        }

What's the meaning of "DataBinding cannot find a row..." error, if at all possible, can I eliminate my work-around on it?

A: I have seen this error when no DataGridView is involved, but my data source was being updated from another thread (naughty!) and my binding had FormattingEnabled=false. Changing both of these seemed to fix the problem.


text:
Q: Google App Engine Java and Android Getting Started I've been struggling to get the example running from below:
https://developers.google.com/eclipse/docs/getting_started
The first problem I had was didn't have installed 'Google Cloud Messaging for Android Library' in the Android SDK (obvious I know).
But now I have an issue with the auto-generated code in two files in the Android project:
GCMIntentService.java and RegisterActivity.java
The errors are:

*

*The method getDeviceInfo(String) is undefined for the type Deviceinfoendpoint    GCMIntentService.java

*The method listMessages() is undefined for the type MessageEndpoint  RegisterActivity.java

*The method insertDeviceInfo(DeviceInfo) is undefined for the type Deviceinfoendpoint GCMIntentService.java

*The method removeDeviceInfo(String) is undefined for the type Deviceinfoendpoint GCMIntentService.java

I'm using Java SDK v1.7.0_15 on Ubuntu but I also tried on Windows 7 with Java SDK v1.6 and had the same issue. Latest Android Platform 4.2.2 and Google App Engine 1.7.7. Eclipse is Juno Service Release 2.
The problem looks like they are doing some casting wrong, because there is a method getDeviceInfo for inner class DeviceInfoEndpoint inside Deviceinfoendpoint (different capatilisations).
I could try and fix it, but just wondering if I have something wrong in my setup for this to be happening?
Any help would be appreciated.

A: In your GCMIntentService.java class, add .deviceInfoEndpoint() after the endpoint object in the lines with errors as shown below:
DeviceInfo existingInfo = endpoint.getDeviceInfo(registration)
DeviceInfo existingInfo = endpoint.deviceInfoEndpoint().getDeviceInfo(registration)

In RegisterActivity.java change the line
messageEndpoint.listMessages().setLimit(5).execute();

to
messageEndpoint.messageEndpoint().listMessages().setLimit(5).execute();

A: I would make sure you are using the same version of GCM APIs as you have JARs for. There have been quite a few revisions.
I am using the following code with gcm-server.jar, listed at 19718 bytes.
The code I successfully use to send GCM messages to a device is:
public void sendMessage() {
    String notificationToken = mobileDevice.getPushNotificationCode();
    String deviceType = mobileDevice.getDeviceType();

    Sender sender = new Sender(BROWSER_API_KEY);
    Message message = new Message.Builder().addData("message", "blah blah").build();
    String device = "<the key for the device you are sending to goes here>";

    try {
        System.out.println("Sending message...");
        Result result = sender.send(message, device, 5);
        System.out.println("Done sending message");
        if (result.getMessageId() != null) {
            System.out.println("Got message ID: " + result.getMessageId());
            System.out.println("Got error code name: " + result.getErrorCodeName());
            System.out.println("result: " + result);
            String canonicalRegId = result.getCanonicalRegistrationId();
            if (canonicalRegId != null) {
                // Database has more than one record for this device.
                // Replace all of this device's records with this new id
                System.out.println("Got new canonical reg id: " + canonicalRegId);
            }
        } else {
            String error = result.getErrorCodeName();
            if (error.equals(com.google.android.gcm.server.Constants.ERROR_NOT_REGISTERED)) {
                // application has been removed from device - unregister from database
                System.out.println("Got error: " + error);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}


text:
Q: What is this data? Resource Hacker I'm new to using Resource Hacker to alter *.EXE and *.DLL files and I need help understanding all the data it provides when "opening" these files.
More specifically, using Res Hacker, I opened ntoskrnl.exe which is located in C:\Windows\System32\ and I pressed "PREFETCHWLIST : 0" file in the "RCData" folder. This is what Res Hacker displayed:

What does all this data represent? What type of data is displayed in each of the three columns? Thank you!

A: First column is the address in memory.
Second column is the raw dump of the byte data
Third is that same data displayed decoded using defaults.
see here http://www.angusj.com/resourcehacker/


text:
Q: How to sort the predefined colors by color value or by brightness like on the color palette in google drive? I bind the ItemsSource of my ListBox as:
<ObjectDataProvider MethodName="GetType" ObjectType="{x:Type sys:Type}" x:Key="colorsTypeOdp">
    <ObjectDataProvider.MethodParameters>
        <sys:String>System.Windows.Media.Colors, PresentationCore,
                Version=3.0.0.0, Culture=neutral,
                PublicKeyToken=31bf3856ad364e35</sys:String>
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

<ObjectDataProvider ObjectInstance="{StaticResource colorsTypeOdp}"
    MethodName="GetProperties" x:Key="colorPropertiesOdp">
</ObjectDataProvider>

My Xaml for ListBoX :
<ListBox x:Name="coloListBox" Style="{x:Null}"
         ItemsSource="{Binding Source={StaticResource colorPropertiesOdp},
         Converter={StaticResource ColSortConverter}}"
         SelectedItem="{Binding SelectedColor,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent},Converter={StaticResource ColorToStringConverter}}">
     <ListBox.ItemTemplate>
         <DataTemplate>
             <Rectangle Fill="{Binding Name}" Width="15" Height="15" Stroke="#FF211E1E" OpacityMask="Black" StrokeThickness="1"/>
         </DataTemplate>
     </ListBox.ItemTemplate>
     <ListBox.ItemsPanel>
         <ItemsPanelTemplate>
             <WrapPanel Width="250" Orientation="Horizontal"/>
         </ItemsPanelTemplate>
     </ListBox.ItemsPanel>
</ListBox>

Converter
public class ColorSortConverter : IValueConverter
{
    public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
    {
        PropertyInfo[] colorsProperties = null;
        var result = value as PropertyInfo[] ;

        if (result != null)
        {
            colorsProperties = result;
            colorsProperties.OrderBy(i => i.Name).ToArray();
            return colorsProperties;
        }
        return colorsProperties;
    }
}

How to sort the array in the converter in order to get the colors sorted by their HEX value or according to the brightness?

A: Hex-Values
According to this answer you can use System.Windows.Media.ColorConverter to get the hex values of colors
var colorConverter = new ColorConverter();
string hexColorValue = colorConverter.ConvertToString(myColor);

When you have a list of colors, you could simply do
List<Color> SortByHex(List<Color> colors)
{
    var colorConverter = new ColorConverter();
    return color.OrderBy(c => colorConverter.ConvertToString(c)).ToList();
}

Brightness
See here on how to convert a System.Windows.Media.Color to a brightness.
public static float GetBrightness(System.Windows.Media.Color c)
{
    return System.Drawing.Color.FromArgb(c.A, c.R, c.G, c.B).GetBrightness();
}

cf.
List<Color> SortByBrightness(List<Color> colors)
{
    return color.OrderBy(GetBrightness).ToList();
}

Please note: The proposed options won't work in your code out-of-the-box, but you'll have to figure out how to use them in your code. Anyway, they should suffice as a starting point.


text:
Q: Need count value in same tables I have below tables, Here, I want to get the count of the value STAT_NEW = 'Sent to xxxx Project Team'. We need the count values before occuring the values stat_new='Sent to VMO'.
SQL> Select * from sample_test;

ID  CONTRACT_ID                STAT_NEW                                 UPD_DT
-----------------------------  -------------------------------------- ----------
0   CR 01 to MWO 1            Sent to xxxx Project Team               11-AUG-13
1   CR 01 to MWO 1            Sent to xxxx Project Team               11-AUG-13
2   CR 01 to MWO 1            Sent to xxxx Project Team               11-AUG-13
3   CR 01 to MWO 1            Sent to VMO                             12-AUG-13
4   CR 01 to MWO 1            Sent to xxxx Project Team               11-AUG-13
5   CR 01 to MWO 1            Sent to xxxx Project Team               11-AUG-13
6   CR 01 to MWO 1            Sent to VMO                             12-AUG-13

7   CR 01 to MWO 2            Sent to xxxx Project Team               11-AUG-13
8   CR 01 to MWO 2            Sent to xxxx Project Team               11-AUG-13
9   CR 01 to MWO 2            Sent to xxxx Project Team               11-AUG-13
10  CR 01 to MWO 2            Sent to VMO                             12-AUG-13
11  CR 01 to MWO 3            Sent to xxxx Project Team               12-AUG-13
12  CR 01 to MWO 3            Sent to xxxx Project Team               12-AUG-13
13  CR 01 to MWO 3            Sent to VMO                             13-AUG-13

7 rows selected

I have tried below scenario whihc is giving particular contract id and if having only one Sent to VMO then the below scenario is working.
select count(*) from sample_test where upd_dt <= (select UPD_DT from sample_test where stat_new='Sent to VMO' and contract_id='CR 01 to MWO 1') AND stat_new='Sent to xxxx Project Team';

My expected output is like below....
CONTRACT_ID      count of STAT_NEW='Sent to xxxx Project Team'
--------------   ------------
CR 01 to MWO 1    3
CR 01 to MWO 1    2
CR 01 to MWO 2    3
CR 01 to MWO 3    2

A: This is a bit trickier than it seems.  The following should work:
select contract_id, sum(case when stat = 'Sent to xxxx Project Team' then 1 else 0 end)
from (select t.*,
             sum(case when stat = 'Sent to VMO' then 1 else 0 end) over
                 (partition by Contract_Id order by id desc) as SentVMOcount
      from sample_test t
     ) t
where sentVMOcount = 1
group by contract_id;

The key here is sentVMOcount.  This uses the cumulative sum analytic function to enumerate the rows based on the 'Sent to VMO' status that occurs after that row.  So, all the final rows get a count of 1.  The outer query selects these and does the appropriate aggregation.

A: Try this
SELECT CONTRACT_ID,COUNT(STAT_NEW) STAT_NEW_COUNT FROM
(
    SELECT t.*
        ,(SELECT COUNT(id) FROM #MyTable WHERE STAT_NEW='Sent to VMO' AND ID < t.ID) AS cnt
    from #MyTable t
    WHERE STAT_NEW<>'Sent to VMO'
) tt
GROUP BY CONTRACT_ID,cnt

DEMO
OUTPUT
CONTRACT_ID      STAT_NEW_COUNT
CR 01 to MWO 1     3
CR 01 to MWO 1     2
CR 01 to MWO 2     3
CR 01 to MWO 3     2


text:
Q: I am facing issues displaying GUI I created in Gluon Scene Builder using JavaFX on Eclipse, IntelliJ and Netbeans I have included my sample.fxml which I created using Gluon Scene builder.
I am facing issues since whenever I run as Java FX project, I only get a blank screen.
 <?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.effect.Glow?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.text.Font?>

<BorderPane id="login" blendMode="SOFT_LIGHT" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" style="-fx-background-color: gray;" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1">
   <left>
      <Pane prefHeight="299.0" prefWidth="200.0" BorderPane.alignment="CENTER">
         <children>

               <padding>
                  <Insets bottom="5.0" left="15.0" right="8.0" top="5.0" />
               </padding>

               <padding>
                  <Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
               </padding>

         </children>
      </Pane>
   </left>

      <Pane prefHeight="316.0" prefWidth="371.0" BorderPane.alignment="CENTER">
         <children>
            <TextField id="username_tField" alignment="CENTER" layoutX="14.0" layoutY="59.0" prefHeight="30.0" prefWidth="230.0" promptText="Enter username here" style="-fx-background-color: gray;">
               <padding>
                  <Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
               </padding>

               <effect>
                  <Glow />
               </effect>
            </TextField>
            <PasswordField id="password_tField" alignment="CENTER" layoutX="14.0" layoutY="143.0" prefHeight="30.0" prefWidth="230.0" promptText="Enter password here" style="-fx-background-color: gray;">
               <padding>
                  <Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
               </padding>

               <effect>
                  <Glow />
               </effect>
            </PasswordField>
            <Pane layoutX="62.0" layoutY="216.0" prefHeight="57.0" prefWidth="182.0" style="-fx-background-color: gray;">
               <children>
                  <Button id="login_Button" alignment="CENTER" contentDisplay="RIGHT" layoutX="75.0" layoutY="11.0" mnemonicParsing="false" prefHeight="35.0" prefWidth="95.0" style="-fx-background-color: wheat; -fx-border-color: brown;" text="Login" textAlignment="CENTER">

                     <opaqueInsets>
                        <Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
                     </opaqueInsets>
                     <padding>
                        <Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
                     </padding>
                  </Button>
               </children>
            </Pane>
         </children>
      </Pane>

   <top>
      <Pane id="login_title" prefHeight="84.0" prefWidth="600.0" BorderPane.alignment="CENTER">
         <children>

               <padding>
                  <Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
               </padding>

               <opaqueInsets>
                  <Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
               </opaqueInsets>

         </children>
      </Pane>
   </top>
</BorderPane>

When I tried to install e(fx)eclipse, eclipse freezes at loading 19% and none of versions work on my yosemite mac. Also, Netbeans I tried to load GUI from above fxml file, I get a blank screen.
Will really appreciate help on this issue.

A: There is an issue with the BorderPane's blendMode: it is set to "SOFT_LIGHT".
<BorderPane id="login" blendMode="SOFT_LIGHT" maxHeight="-Infinity" ...
                       ^^^^^^^^^^^^^^^^^^^^^

If you remove the attribute, you will see your UI:
<BorderPane id="login" maxHeight="-Infinity" ...

I used the following boilerplate to test it:
package afester.javafx.examples.fxml;

import java.net.URL;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class FxmlViewer extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
       URL location = getClass().getResource("FxmlSample.fxml");
       BorderPane root = FXMLLoader.load(location);
       stage.setScene(new Scene(root));
       stage.show();
    }
}

BTW, a very useful tool to debug such issues is ScenicView - it allows to analyze the JavaFX scene graph at runtime and to even modify the properties of nodes.


text:
Q: Typescript: How to kleisli compose (monadic compose) Promise monad using fp-ts How can I compose two kleisli arrows(functions) f:A -> Promise B and g: B -> Promise C into h:A -> Promise C using fp-ts?
I'm familiar with Haskell so I would ask in this way: What's the equivalent of >=>(fish operator)?

A: Promises are represented by Task or TaskEither monads in fp-ts, which are asynchronous computations. TaskEither additionally models failure and is the same as Task<Either<...>>.
Kleisli Arrows can be composed via chain operation of monads and flow (pipe operator). The result resembles the application of >=> operator in Haskell.
Let's do an example with TaskEither:
const f = (a: A): Promise<B> => Promise.resolve(42);
const g = (b: B): Promise<C> => Promise.resolve(true);

Convert functions returning Promise to ones returning TaskEither using tryCatchK 1:
import * as TE from "fp-ts/lib/TaskEither";
const fK = TE.tryCatchK(f, identity); // (a: A) => TE.TaskEither<unknown, B>
const gK = TE.tryCatchK(g, identity); // (b: B) => TE.TaskEither<unknown, C>

Compose both:
const piped = flow(fK, TE.chain(gK)); // (a: A) => TE.TaskEither<unknown, C>

Here is a copy paste block for Codesandbox:

// you could also write:
// import { taskEither as TE } from "fp-ts";
import * as TE from "fp-ts/lib/TaskEither";
// you could also write:
// import {pipeable as P} from "fp-ts"; P.pipe(...)
import { flow, identity, pipe } from "fp-ts/lib/function";
import * as T from "fp-ts/lib/Task";

type A = "A";
type B = "B";
type C = "C";
const f = (a: A): Promise<B> => Promise.resolve("B");
const g = (b: B): Promise<C> => Promise.resolve("C");

// Alternative to `identity`: use `toError` in fp-ts/lib/Either
const fK = TE.tryCatchK(f, identity);
const gK = TE.tryCatchK(g, identity);

const piped = flow(fK, TE.chain(gK));

const effect = pipe(
  "A",
  piped,
  TE.fold(
    (err) =>
      T.fromIO(() => {
        console.log(err);
      }),
    (c) =>
      T.fromIO(() => {
        console.log(c);
      })
  )
);

effect();

Why no promises?
JavaScript Promises don't adhere to a monadic API, for example they are eagerly computed 2. In functional programming side effects are delayed as long as possible, so we need to use a compatible wrapper in form of Task or TaskEither.

1 identity just forwards the error in failure case. You could also use toError.
2 Incorporate monads and category theory #94 is worth reading, if you are interested in historical reasons.


text:
Q: Help to Prove that $\int_{0}^{\pi\over 4}\arctan{(\cot^2{x})}\mathrm dx={2\pi^2-\ln^2({3+2\sqrt{2})}\over 16}$ I need help on proving $(1)$.
$$I=\int_{0}^{\pi\over 4}\arctan{(\cot^2{x})}\mathrm dx={2\pi^2-\ln^2({3+2\sqrt{2})}\over 16}\tag1$$
This is what I have attempted;
Enforcing a sub: $u=\cot^2{x}$ then $du=-2\cot{x}\csc^2{x}dx$
Recall $1+\cot^2{x}=\csc^2{x}$
$$I={1\over2}\int_{1}^{\infty}\arctan{u}\cdot{\mathrm dx\over u^{1/2}+u^{3/2}}$$
Recall $u^3+1=(u+1)(u^2-u+1)$
$$I={1\over2}\int_{1}^{\infty}\arctan{u}\left({A\over u^{1/2}}+{B\over u+1}+{Cu+D\over u^2-u+1}\right)\mathrm du$$
I am stuck at this point.
Can anyone help to prove $(1)$?

A: For the evaluation of $\displaystyle J=\int_0^{\tfrac{\pi}{2}}\arctan(\sin x)dx$
Perform the change of variable $y=\sin x$,
$\displaystyle J=\int_0^1 \dfrac{\arctan x}{\sqrt{1-x^2}}dx$
Perform the change of variable $y=\sqrt{\dfrac{1-x}{1+x}}$,
$\begin{align}\displaystyle J&=2\int_0^1 \dfrac{\arctan\left(\tfrac{1-x^2}{1+x^2}\right)}{1+x^2}dx\\
&=2\int_0^1 \dfrac{\arctan(1)}{1+x^2}dx-2\int_0^1 \dfrac{\arctan(x^2)}{1+x^2}dx\\
&=\dfrac{\pi^2}{8}-2\int_0^1 \dfrac{\arctan(x^2)}{1+x^2}dx\\
\end{align}$
$\begin{align}
\displaystyle\int_0^1 \dfrac{\arctan(x^2)}{1+x^2}dx&=\Big[\arctan x\arctan(x^2)\Big]_0^1-\int_0^1 \dfrac{2x\arctan x}{1+x^4}dx\\
&=\dfrac{\pi^2}{16}-\int_0^1 \dfrac{2x\arctan x}{1+x^4}dx\\
\end{align}$
Since,
$\displaystyle \arctan x=\int_0^1 \dfrac{x}{1+t^2x^2}dx$
then,
$\begin{align}
\displaystyle K&=\int_0^1 \dfrac{2x\arctan x}{1+x^4}dx\\
\displaystyle &=\int_0^1\int_0^1 \dfrac{2x^2}{(1+t^2x^2)(1+x^4)}dtdx\\
\displaystyle &=\int_0^1\int_0^1 \left(\dfrac{2t^2}{(1+t^4)(1+x^4)}+\dfrac{2x^2}{(1+x^4)(1+t^4)}-\dfrac{2t^2}{(1+t^4)(1+t^2x^2}\right)dtdx\\
&=\displaystyle 4\left(\int_0^1 \dfrac{t^2}{1+t^4}dt\right)\left(\int_0^1 \dfrac{1}{1+x^4}dx\right)-K
\end{align}$
Therefore,
$\displaystyle K=2\left(\int_0^1 \dfrac{x^2}{1+x^4}dx\right)\left(\int_0^1 \dfrac{1}{1+x^4}dx\right)$
Since,
$\begin{align}\displaystyle \int_0^1 \dfrac{x^2}{1+x^4}dx&=\left[\dfrac{1}{4\sqrt{2}}\ln\left(\dfrac{x^2-\sqrt{2}x+1}{x^2+\sqrt{2}x+1}\right)+\dfrac{1}{2\sqrt{2}}\arctan\left(\sqrt{2}x+1\right)+\dfrac{1}{2\sqrt{2}}\arctan\left(\sqrt{2}x-1\right)\right]_0^1\\
&=\dfrac{1}{4\sqrt{2}}\Big(\pi+\ln\left(3-2\sqrt{2}\right)\Big)
\end{align}$
and,
$\begin{align}\displaystyle \int_0^1 \dfrac{1}{1+x^4}dx&=\left[\dfrac{1}{4\sqrt{2}}\ln\left(\dfrac{x^2+\sqrt{2}x+1}{x^2-\sqrt{2}x+1}\right)+\dfrac{1}{2\sqrt{2}}\arctan\left(\sqrt{2}x+1\right)+\dfrac{1}{2\sqrt{2}}\arctan\left(\sqrt{2}x-1\right)\right]_0^1\\
&=\dfrac{1}{4\sqrt{2}}\Big(\pi-\ln\left(3-2\sqrt{2}\right)\Big)
\end{align}$
Therefore,
$\boxed{K=\displaystyle \dfrac{\pi^2}{16}-\dfrac{1}{16}\Big(\ln\left(3-2\sqrt{2}\right)\Big)^2}$
Therefore,
$\boxed{\displaystyle\int_0^1 \dfrac{\arctan(x^2)}{1+x^2}dx=\dfrac{1}{16}\Big(\ln\left(3-2\sqrt{2}\right)\Big)^2}$
Therefore,
$\boxed{\displaystyle J=\dfrac{\pi^2}{8}-\dfrac{1}{8}\Big(\ln\left(3-2\sqrt{2}\right)\Big)^2}$
Addendum:
$\displaystyle I=\int_0^{\tfrac{\pi}{4}} \arctan\left(\cot^2(x)\right)dx$
Perform the change of variable,
$y=\tan x$,
$\begin{align}I&=\displaystyle \int_0^1 \dfrac{\arctan\left(\tfrac{1}{x^2}\right)}{1+x^2}dx\\
&=\displaystyle \int_0^1 \dfrac{\tfrac{\pi}{2}-\arctan\left(x^2\right)}{1+x^2}dx\\
&=\displaystyle \dfrac{\pi^2}{8}-\int_0^1  \dfrac{\arctan\left(x^2\right)}{1+x^2}dx
\end{align}$

A: We first write $I$ as
$$ I= \frac{\pi^2}{16} + \int_{0}^{\frac{\pi}{4}} \left( \arctan(\cot^2 x) - \arctan(1) \right) \, dx. $$
Now using addition formulas for $\arctan$ and $\cos$, we have
$$ \arctan(\cot^2 x) - \arctan(1)
= \arctan\left(\frac{\cot^2 x - 1}{\cot^2 x + 1} \right)
= \arctan(\cos 2x). $$
Consequently we have
\begin{align*}
I
&= \frac{\pi^2}{16} + \int_{0}^{\frac{\pi}{4}} \arctan(\cos 2x) \, dx \\
&= \frac{\pi^2}{16} + \frac{1}{2}\int_{0}^{\frac{\pi}{2}} \arctan(\sin \theta) \, d\theta,
\end{align*}
where the last line follows from the substitution $\theta = \frac{\pi}{2} - 2x$. The last integral can be computed in terms of the Legendre chi function $\chi_2$:
$$ \int_{0}^{\frac{\pi}{2}} \arctan(\sin \theta) \, d\theta = 2\chi_2(\sqrt{2}-1). \tag{1} $$
For a proof of $\text{(1)}$, see my previous answer for instance. There are only a handful of known special values of $\chi_2$, but thankfully
$$\chi_2(\sqrt{2}-1) = \frac{\pi^2}{16} - \frac{1}{4}\log^2(\sqrt{2}+1) \tag{2} $$
is one of them. Summarizing, we have
$$ I = \frac{\pi^2}{8} - \frac{1}{4}\log^2(\sqrt{2}+1), $$
which coincides with the proposed answer.

Addendum. The identity $\text{(2)}$ follows by plugging $x = \sqrt{2}-1$ to the identity
$$ \chi_2\left(\frac{1-x}{1+x}\right) + \chi_2(x) = \frac{\pi^2}{8} - \frac{1}{2}\log x \log\left(\frac{1-x}{1+x}\right), $$
which can be easily checked by differentiating both sides.


text:
Q: How to animate an object along a GeoJSON path using d3.js? I'm using D3.js to generate and render a path from a GeoJSON file. That works fine, but now I'd like to animate an object along that path. I know how to do that using D3 and standard SVG:

*

*Create a transition and set its duration

*For each frame of the transition, use the % complete to find the coordinates along the path

*Move the object to the coordinates found in step 2

That's simple. But the problem I'm having is that d3.geo.path() doesn't seem to return any length or position data like a standard D3 path object (such as the helpful getPointAtLength() method). So I'm unable to find the x,y coordinates of a point at, say, 25% along the path.
Is there a way to obtain this data? (Or is there a better way, such as converting the d3.geo.path() to a regular D3 path?)
Below is a truncated version of my code; a live example is here: http://jsfiddle.net/5m35J/4/
json = {
    ... // snipped for brevity
};

// Draw a GeoJSON line on the map:

map = $('#map');
xy = d3.geo.mercator().scale(480000).translate([630700, 401100]);
path = d3.geo.path().projection(xy);

vis = d3.select("#map")
    .append("svg:svg")
    .attr("width", 960)
    .attr("height", 600);

vis.append("svg:g")
    .attr("class", "route")
    .selectAll("path")
    .data(json.features)
    .enter()
    .append("svg:path")
    .attr("d", path)
    .attr("fill-opacity", 0.5)
    .attr("fill", "#fff")
    .attr("stroke", "#333");

// Draw a red circle on the map:

//len = 100; // how do I find the length of the path?
origin_x = 100;
origin_y = 100;

group = vis.append("svg:g");

circle = group.append("circle")
    .attr({
    r: 10,
    fill: '#f33',
    transform: function () {
        //var p = path.getPointAtLength(0)
        //return "translate(" + [p.x, p.y] + ")";
        return "translate("+ origin_x +","+ origin_y +")";
    }
});

// Animate the circle:

duration = 5000;
circle.transition()
    .duration(duration)
    .ease("linear")
    .attrTween("transform", function (d, i) {
    return function (t) {
        //var p = path.node().getPointAtLength(len*t) // d3.geo.path() doesn't provide a getPointAtLength() method!
        //return "translate("+[p.x,p.y]+")"
        var current_x = origin_x + origin_x * t;
        var current_y = origin_y + origin_y * t;
        return "translate("+ current_x +","+ current_y +")";
    }
});

A: Well, I figured it out, but I'm not completely sure if my solution is the "right" way to do it. Basically, I used D3 to select the raw SVG elements that were created by the d3.geo.path() object.
Note the changes to the targetPath, pathNode, and pathLength variables, and also to the transform() and attrTween() functions:
// Draw a red circle on the map:

group = vis.append("svg:g");

var targetPath = d3.selectAll('.route')[0][0],
    pathNode = d3.select(targetPath).selectAll('path').node(),
    pathLength = pathNode.getTotalLength();

circle = group.append("circle")
    .attr({
    r: 10,
    fill: '#f33',
    transform: function () {
        var p = pathNode.getPointAtLength(0)
        return "translate(" + [p.x, p.y] + ")";
    }
});

// Animate the circle:

duration = 10000;
circle.transition()
    .duration(duration)
    .ease("linear")
    .attrTween("transform", function (d, i) {
    return function (t) {
        var p = pathNode.getPointAtLength(pathLength*t);
        return "translate(" + [p.x, p.y] + ")";
    }
});

Live example is here: http://jsfiddle.net/5m35J/6/


text:
Q: Getting contains to work with multiple words I'm working on search and want to get it error-proof.
let's say we have 3 strings: containsText that contains 2 words I'm looking for in fullTextShort and fullTextLong
My func contains works with fullTextShort as the words that I'm looking for are right after each other, but it doesn't work with fullTextLong where there's a world in between.
How to get the func to return true for both cases?
struct ContainsFuncView: View {
    let fullTextShort = "I like pineapple"
    let fullTextLong = "I like green pineapple"
    let containsText = "like pineapple"

    var body: some View {
        VStack {
            contains(type: "Short")
            contains(type: "Long")
            }
    }

    func contains(type: String) -> Text {
        var containsInFullText: Bool = false

        if type == "Short" {
            containsInFullText = fullTextShort.localizedStandardContains(containsText)
        }

        else if type == "Long" {
            containsInFullText = fullTextLong.localizedStandardContains(containsText)
        }

        return Text("\(containsInFullText ? "Contains" : "Doesn't contain") in fullText\(type)").foregroundColor(containsInFullText ? .green : .red)
    }
}

Thank you!

A: Split containsText at the space. Then test if any or all words are in the text:
containsInFullText = containsText.components(separatedBy: " ").contains { fullTextShort.localizedStandardContains($0) }

containsInFullText = containsText.components(separatedBy: " ").allSatisfy { fullTextShort.localizedStandardContains($0) }

A: You can split the searched text into words and the reduce the search results for each word so the search returns true only when all words are found
let words = containsText.split(separator: " ")

if type == "Short" {
    containsInFullText = words.reduce(true) { contains, word in
        contains && fullTextShort.localizedStandardContains(word)
    }
}

else if type == "Long" {
    containsInFullText = words.reduce(true) { contains, word in
        contains && fullTextLong.localizedStandardContains(word)
    }
}

If you want to return true when at least one word is found, swap the && to || and the initial value to false
if type == "Short" {
    containsInFullText = words.reduce(false) { contains, word in
        contains || fullTextShort.localizedStandardContains(word)
    }
}

else if type == "Long" {
    containsInFullText = words.reduce(false) { contains, word in
        contains || fullTextLong.localizedStandardContains(word)
    }
}