text:
Q: How do I add a rating app button in my app in android studio before publishing my app? I have created a navigation menu in my application where users can use and select the option of rating my app. The problem I am currently having is trying to figure out how to add a link to the rate my app button before I have actually published the app? How do developers add this option to their app before publishing it and what would be the best code to use for this problem?
This is the current code I have added in my MainActivity.java to send the user to rate my app. What changes should I make to this code?
 @Override

public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
    case R.id.nav_thumb:
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.mydomain.tapp"));
        startActivity(intent);
        break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;

}

A:  try {
    startActivity(new Intent(Intent.ACTION_VIEW,
                             Uri.parse("market://details?id=" + this.getPackageName())));
} catch (android.content.ActivityNotFoundException e) {
    startActivity(new Intent(Intent.ACTION_VIEW,
                             Uri.parse("http://play.google.com/store/apps/details?id=" + this.getPackageName())));
}

A: /*
* Start with rating the app
* Determine if the Play Store is installed on the device
*
* */
public void rateMyApp()
{
    try
    {
        Intent rateIntent = rateIntentForUrl("market://details");
        startActivity(rateIntent);
    }
    catch (ActivityNotFoundException e)
    {
        Intent rateIntent = rateIntentForUrl("https://play.google.com/store/apps/details");
        startActivity(rateIntent);
    }
}

private Intent rateIntentForUrl(String url)
{
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("%s?id=%s", url, getPackageName())));
    int flags = Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
    if (Build.VERSION.SDK_INT >= 21)
    {
        flags |= Intent.FLAG_ACTIVITY_NEW_DOCUMENT;
    }
    else
    {
        //noinspection deprecation
        flags |= Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET;
    }
    intent.addFlags(flags);
    return intent;
}

Add this code in the Activity or Class from where you would like to call.
Just call rateMyApp() with user click action


text:
Q: Appending iteratively matched patterns from a pdf in a new pandas column I have a dataset containing species names. I would like to retrieve the authorship of each species from a pdf file and add the new names (with authorship) in a new column.
I struggle to append each new names iteratively in my dataset. I tried append and concat without success.
The table looks like this:
>>> pandas.read_csv('data.csv')[0:10]
   id_ref  id_sp                     species
0   20053  60645          Species Subspecies
1   20053  61094  Acantholimon lycopodioides
2   20053  61095        Achillea millefolium
3   20053  61096        Aconitum chasmanthum
4   20053  61097      Aconitum heterophyllum
5   20053  61098              Aconitum laeve
6   20053  61099      Aconitum rotundifolium
7   20053  61100          Aconitum violaceum
8   20053  61101          Aconogonon alpinum
9   20053  61102     Aconogonon rumicifolium

Here is my code so far:
from PyPDF2 import PdfFileReader
import pandas
import regex

table = pandas.read_csv('mydata.csv')
table['full_name'] = ''

tmp = []

pdf = 'myfile.pdf'
pdf_r = PdfFileReader(pdf)
page_rg = range(29, 225)
for p in page_rg:
    page = pdf_r.getPage(p)
    text = page.extractText()
    tmp.append(text)

full_text = ''.join(tmp)

for sp in table.species:
    sp_re = sp + r'\s+[(A-Z][^:(\/]+(?=\s)'
    if regex.search(sp_re, full_text):
        full_name = regex.findall(sp_re, full_text)
    else:
        full_name = ''
    # line of code to add the matched string in the 'full_name' column

Printing full_name in the loop gives the following:

['Acantholimon lycopodioides (Girard) Boiss.']
['Achillea millefolium L.']
['Aconitum chasmanthum Stapf ex Holmes']
['Aconitum heterophyllum Wall. ex Royle']
['Aconitum laeve Royle']
['Aconitum rotundifolium Kar. & Kir.']
['Aconitum violaceum Jacquem. ex Stapf']
['Aconogonon alpinum (All.) Schur']
['Aconogonon rumicifolium (Royle ex Bab.) Hara']

The desired output is:
   id_ref  id_sp                     species                                     full_name
0   20053  60645          Species Subspecies
1   20053  61094  Acantholimon lycopodioides    Acantholimon lycopodioides (Girard) Boiss.
2   20053  61095        Achillea millefolium                       Achillea millefolium L.
3   20053  61096        Aconitum chasmanthum          Aconitum chasmanthum Stapf ex Holmes
4   20053  61097      Aconitum heterophyllum         Aconitum heterophyllum Wall. ex Royle
5   20053  61098              Aconitum laeve                          Aconitum laeve Royle
6   20053  61099      Aconitum rotundifolium            Aconitum rotundifolium Kar. & Kir.
7   20053  61100          Aconitum violaceum          Aconitum violaceum Jacquem. ex Stapf
8   20053  61101          Aconogonon alpinum               Aconogonon alpinum (All.) Schur
9   20053  61102     Aconogonon rumicifolium  Aconogonon rumicifolium (Royle ex Bab.) Hara

A: You could just use enumerate and pandas iloc to modify your loop and populate the full name column as you go. I modified your loop in the code below so that you can do it:
for i, sp in enumerate(table.species):
    sp_re = sp + r'\s+[(A-Z][^:(\/]+(?=\s)'
    if regex.search(sp_re, full_text):
        full_name = regex.findall(sp_re, full_text)
    else:
        full_name = ''
    table.full_name.iloc[i] = full_name

From your question it seems that full_name may be in list format. In that case you could just change full_name for full_name[0] when assigning it to the table dataframe to get just the string inside the list.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Listbox DataSource not working when added to a ToolStripDropDown I have been struggling all day with this problem, although I couldn't find a solution. I apologize for the long post, I tried to be concise  and clear.
This is what works: I create a Form and inside its class I create a ListBox dynamically and set its DataSource to a DataTable as follows:
public partial class FrmAddress : Form
{
    private ListBox listBox1 = new ListBox();

    public FrmAddress()
    {
        this.InitializeComponent();

        [...]

        this.Controls.Add(listBox1);
    }

    [...]

    private void Load_Countries()
    {
        this.listBox1.DataSource = dtCountries;
        this.listBox1.DisplayMember = "Country";
        this.listBox1.ValueMember = "Country_ID";
    }

    [...]
}

This does not work: Create a custom control (inherited from ToolStripDown), create a new instance of ToolStripControlHost(listBox1), add that instance to the ToolStripDown. Set the listBox1.DataSource to a DataTable. When ToolStripDown is show, the listbox is there but empty (not showing the datasource content).
public class CtlDropdownPopup : ToolStripDropDown
{
    ListBox controlToPop;
    ToolStripControlHost controlHost;

    public CtlDropdownPopup(ListBox controlToPop)
    {
        this.controlToPop = controlToPop;
        this.controlToPop.Location = Point.Empty;

        this.controlHost = new ToolStripControlHost(this.controlToPop);

        [...]

        this.Items.Add(this.controlHost);
    }
}

public class CtlCombobox : ComboBox
{
    private readonly CtlDropdownPopup suggestionDropDown;
    private readonly ListBox suggestionList = new ListBox();

    public CtlCombobox()
    {
        this.suggestionDropDown = new CtlDropdownPopup(this.suggestionList);
    }

    public void Source(DataTable dt, string display, string value)
    {
        this.suggestionDT = dt;

        this.suggestionList.DataSource = dt;
        this.suggestionList.DisplayMember = display;
        this.suggestionList.ValueMember = value;
    }
}

The custom CtlDropdownPopup is called like: (simplified)
private CtlCombobox LstCountry;
this.LstCountry.Source(dtCountries, "Country", "Country_ID");

As I said, the ToolStripDropDown is shown with the listBox1 in it, but the list is empty. Curiously if I modify the Source() method to
    public void Source(DataTable dt, string display, string value)
    {
        this.suggestionDT = dt;

        // this.suggestionList.DataSource = dt;
        // this.suggestionList.DisplayMember = display;
        // this.suggestionList.ValueMember = value;

        if (this.suggestionList != null)
        {
            foreach (DataRow row in dt.Rows)
            {
                this.suggestionList.Items.Add(row[display].ToString());
            }
        }
    }

The listbox is shown with the items on it. Although this workaround does the job, it is annoying not finding the answer of why can't I set the DataSource directly (as I did directly in the first example), but manually having to add the items.
Any ideas will really help me to sleep well tonight :)
Thought #1: I believe since the same dtCountries is linked to other ComboBox1.DataSource, that may be the problem, so I set this.controlToPop.DataSource = dt.Copy(); in hopes "it is not somehow linked to the combobox", but the problem presists.
Side note: I am trying to create a custom combobox, that suggest items within the DataTable.
Idea from https://www.codeproject.com/Tips/789705/Create-combobox-with-search-and-suggest-list

A: You need to set the BindingContext property of the ListBox.
When a ListBox (or any control) is added onto the form, it inherits its BindingContext property from the form. Now since you're adding the ListBox onto another TopLevel control with .BindingContext == null, it doesn't inherit that property from the form, hence, it has no BindingContext.
You can simply avoid this problem by creating a new BindingContext for the ListBox:
public void Source(DataTable dt, string display, string value)
{
    this.suggestionDT = dt;

    this.suggestionList.BindingContext = new BindingContext();  // <<<<<<<<<<<<<
    this.suggestionList.DataSource = dt;
    this.suggestionList.DisplayMember = display;
    this.suggestionList.ValueMember = value;
}

You can also copy the BindingContext from the form instead (either through the CtlCombobox control or by passing it as a parameter).
Hope that helps.


text:
Q: How to dynamically set variables in mutation with react-adopt? In my component, I am using react-adopt, to compose graphql queries and mutations, so that my render props don't get too messy. I have the following code:
This is my mutation, it takes one argument - planID.
const CREATE_ORDER_MUTATION = gql`
  mutation CREATE_ORDER_MUTATION($planID: String!) {
    createOrder(planID: $planID) {
      planID
      name
      description
      subscriptionType
      images
      subscriptionType
      pricePerMonth
}
}

This is the adopt function, it takes a couple of mutations, one of which is createOrder. The way Apollo works is that I need to pass variables prop to createOrder component here. The problem is, I don't have the planID at this point. planID is available only inside of the actual component.
const Composed = adopt({
  toggleCart: <Mutation mutation={TOGGLE_CART_MUTATION} />,
  createOrder: <Mutation mutation={CREATE_ORDER_MUTATION} />,
});

My component looks like this. I have the planID available here, but how can I pass it as an argument to mutation?!
render() {
const { plan } = this.props;
return (
  <Composed>
    {({ toggleCart, createOrder }) => {
      const handleAdd = () => {
        toggleCart();
        Router.push('/waschingmachine');
        createOrder();
      };
      return (

      );
    }}
  </Composed>
);
}

If there is no way to solve it this way, how would you approach it differently?

A: Here is how you can pass arguments through react-adopt way into your inner mutations mapper:
// In a nutshell, `react-adopt` allows you to pass props to your `Composed`
// component, so your inner `mapper` can access those props to pass them to
// your <Query> or <Mutation>

// Here's your initial `Composed` component from above
const Composed = adopt({
  // `planId` is passed from below via props (see `<ContainerComponent />)
  toggleCart: ({ planId, render }) => (
    <Mutation mutation={TOGGLE_CART_MUTATION} variables={{ planId }}>{render}</Mutation>,
    ),
  // `planId` is passed from below via props (see `<ContainerComponent />)
  createOrder: ({ planId, render })=> (
    <Mutation mutation={CREATE_ORDER_MUTATION} variables={{ planId }}>{render}</Mutation>
  )
});

// `<ContainerComponent />` will take a plan as its props and passed `planId` to
// the `<Composed />` component
const ContainerComponent = ({ plan }) => (
  <Composed planId={plan.id}>
    {({ toggleCart, createOrder }) => {
      const handleAdd = e => {
        e.preventDefault();
        toggleCart();
        // ...
        createOrder();
        // ...
      };

      // Whatever your UI needs you can pass them here via here
      return <YourPresentationComponent onClick={handleAdd} />;
    }}
  </Composed>
)

// Now all you need to do is to pass `plan` from your render() to the
// <ContainerComponent /> (This is the render() where you return your
render() {
  const { plan } = this.props;
  return <ContainerComponent plan={plan} />
}

Hopefully this can be helpful to solve your issue! Just a side note, you can also get the previous mapper value and pass them onto the next mapper fn as part of the argument, see below:
const Composed = adopt({
  // Here you can retrieve the actual `plan` by using `userId` and pass the result
  // into your next children mapper fn to consume
  plan: ({ userId, render }) => (
   <Query query={GET_PLAN_GRQPHQL} variables={{ userId }}>{render}</Query>
  ),
  // `plan` is actually coming from above <Query /> component
  toggleCart: ({ plan, render }) => { //... },
  createOrder: ({ plan, render }) => { //...}
});

A: The mutate function passed in the rendered children can be called with options.
Options can include variables used in the GraphQL mutation string. [1].
This means that you can call the createOrder mutation function like so.
createOrder({ variables: { planID: 'some plan id' } });

Given the dynamic nature of planID, there are a number of ways to implement this. One of which is to use data attributes as below:
A data attribute can be set on for the plan id on the button .
<button onClick={handleAdd} data-planid={plan.id} type="button">
      Select Plan
</button>

handleAdd can be refactored to get the planid from the target dataset attribute and invoke createOrder with planID variable.
const handleAdd = event => {
    const planID = event.target.dataset.planid;
    toggleCart();
    Router.push('/waschingmachine');
    createOrder({ variables: { planID } });
};

Another is to directly pass planID to handleAdd when calling it in the onClick prop for the button.
<button onClick={() => handleAdd(plan.id)} type="button">
      Select Plan
</button>

Then update the handler
const handleAdd = planID => {
    toggleCart();
    Router.push('/waschingmachine');
    createOrder({ variables: { planID } });
};

There are tradeoffs to both approaches. For the earlier approach, the planid are set in the DOM as attributes and can be read later.
While for the later one, N handlers are created for N plans and are kept in memory.


text:
Q: Function: Getting clicked object from QGraphicsScene I'm novice in programming and need a help.
I have a class Station, which contains X and Y fields:
Class Station {
int x
int y
...
}

All the stations are drawing on a QGraphicsScene as a circles and text:
this->scene.addEllipse(x1, y1, diam, diam, pen, QBrush(...));

I need a function getClickedStation, which is waiting for click on a QGraphicsScene, finding the circle and returns the station appropiate of its coordinates:
Station* getClickedStation(...) { ... }

Is there any ways to do it?
I've tried this just to get coordinates:
QList<QGraphicsItem*> listSelectedItems = scene.selectedItems();
QGraphicsItem* item = listSelectedItems.first();
ui->textBrowserMenu->append(QString::number(item->boundingRect().x()));
ui->textBrowserMenu->append(QString::number(item->boundingRect().y()));

but the program crashes with it...

A: No, you do it wrong. I wrote small example. You should subclass QGraphicsScene and reimplement mousePressEvent and process clicks in it. For example:
*.h
#ifndef GRAPHICSSCENE_H
#define GRAPHICSSCENE_H

#include <QGraphicsScene>
#include <QPoint>
#include <QMouseEvent>
class GraphicsScene : public QGraphicsScene
{
    Q_OBJECT
public:
    explicit GraphicsScene(QObject *parent = 0);

protected:
    void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent);
};

#endif // GRAPHICSSCENE_H

In cpp
void GraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
    //qDebug() << "in";
    if (mouseEvent->button() == Qt::LeftButton)
    {
        QGraphicsItem *item = itemAt(mouseEvent->scenePos(), QTransform());// it is your clicked item, you can do everything what you want. for example send it somewhere
        QGraphicsEllipseItem *ell = qgraphicsitem_cast<QGraphicsEllipseItem *>(item);
        if(ell)
        {
            ell->setBrush(QBrush(Qt::black));
        }
        else
            qDebug() << "not ell" << mouseEvent->scenePos();
        }

}

On the scene there are a few ellipses, when you click somewhere in scene we get item under cursor and check it is it ellipse for example. If is, then we set new background to it.
Main idea are itemAt method and qgraphicsitem_cast


text:
Q: regex and substitution in java I am trying to strip and replace a text string that looks as follows in the most elegant way possible:
element {"item"} {text {
          } {$i/child::itemno}

To look like:
<item> {$i/child::itemno}

Hence removing the element text substituting its braces and removing text and its accompanying braces.
I believe the appropriate regex to do this is:
/element\s*\{"([^"]+)"\}\s*{text\s*{\s*}\s*({[^}]*})/

but I am unsure as to the number of backslashes to use in java and also how to complete the final substitution which makes use of my group(1) and replaces it with < at its start and > at its end:
So far I have this (although perhaps I might be better off with a full rewrite ?)
 Pattern p = Pattern.compile("/element\\s*\\{\"([^\"]+)\"\\}\\s*{text\\s*{\\s*}\\s*({[^}]*})/ ");
             // Split input with the pattern
        Matcher m = p.matcher("element {\"item\"} {text {\n" +
                "          } {$i/child::itemno} text { \n" +
                "            } {$i/child::description} text {\n" +
                "            } element {\"high_bid\"} {{max($b/child::bid)}}  text {\n" +
                "        }}  ");

// Next for each instance of group 1, replace it with < > at the start

I think I've stumbled across a problem. What I am trying to do is somewhat harder than I previously stated. With the solution I have below:

element {"item"} {text { } {$i/child::itemno} text { } {$i/child::description} text { } element {"high_bid"} {{max($b/child::bid)}} text { }}

GIVES:

<item> {$i/child::itemno} text { } {$i/child::description} text { } element {"high_bid"} {{max($b/child::bid)}} text { }}

When I expected:
<item>{$i/child::itemno}{$i/child::description}<high_bid>{fn:max($b/child::bid)}</high_bid></item>

A: *

*Java regex-es are written without delimiters. So lose the forward slashes;

*every single backslash needs one extra, so \s becomes \\s;

*all { need to be escaped: \\{, and } need no escape (although it doesn't hurt if you do escape them).

Try:
String text = "element {\"item\"} {text { } {$i/child::itemno}";
System.out.println(text.replaceAll("element\\s*\\{\"([^\"]+)\"}\\s*\\{text\\s*\\{\\s*}\\s*(\\{[^}]*})", "<$1> $2"));

Output:
<item> {$i/child::itemno}


text:
Q: Cylinder Orientation between two points on a sphere, Scenekit, Quaternions IOS I've been trying to draw a cylinder between two points on the outer edge of a sphere using SceneKit. I have already produced a line between these two points using primitive geometry and openGL with SCNRendering Delegate, but now I need to produce a cylinder between these two (well, not just two, but any two 3D vectors that sit on the surface of the sphere). I've been working on this for about 3 days straight now, and I've gone through everything I could find on implementing Quaternions to make this happen, but as it stands, I can't get it to work. Academic articles, scientific studies, and nothing, nothing is working to realign a cylinder between two fixed points. I need an algorithm to do this.
Anyway, here's my most recent code that doesn't work, but this is just a small snippet of nearly 2k lines of code I've worked through so far without the intended result. I know I can move to something more advanced like building my own SCNProgram and/or SCNRenderer to then access GLSL, OpenGL, and Metal complexity, but this seems like something that should be possible using Scenekit and converting between GLKit vector structs to and from SCNVector structs, but so far it's impossible:
Code:
The following code ingests Longitude and Latitude coordinates and projects them onto the surface of a 3D sphere. These coordinates are returned through a proprietary function I build where I received a SCNVector3 of {x,y,z} coordinates that display accurately on my 3D sphere. I draw a line between two sets of Longitude and Latitude coordinates where the lines that are drawn using primitives shoot through the center of the sphere. So, as I mentioned above, I want this same functionality but with cylinders, not lines (by the way, the longitude and latitude coordinates listed here are bogus, they are randomly generated but both fall on the Earth's surface).
drawLine = [self lat1:37.76830 lon1:-30.40096 height1:tall lat2:3.97620 lon2:63.73095 height2:tall];

float cylHeight = GLKVector3Distance(SCNVector3ToGLKVector3(cooridnateSetOne.position), SCNVector3ToGLKVector3(coordinateSetTwo.position));

SCNCylinder * cylTest = [SCNCylinder cylinderWithRadius:0.2 height:cylHeight];
SCNNode * test = [SCNNode nodeWithGeometry:cylTest];

SCNMaterial *material = [SCNMaterial material];
[[material diffuse] setContents:[SKColor whiteColor]];
material.diffuse.intensity = 60;
material.emission.contents = [SKColor whiteColor];

material.lightingModelName = SCNLightingModelConstant;
[cylTest setMaterials:@[material]];

GLKVector3 u = SCNVector3ToGLKVector3(cooridnateSetOne.position);
GLKVector3 v = SCNVector3ToGLKVector3(cooridnateSetTwo.position);

GLKVector3 w = GLKVector3CrossProduct(u, v);

GLKQuaternion q = GLKQuaternionMakeWithAngleAndVector3Axis(GLKVector3DotProduct(u,v), GLKVector3Normalize(w));
q.w += GLKQuaternionLength(q);
q = GLKQuaternionNormalize(q);
SCNVector4 final = SCNVector4FromGLKVector4(GLKVector4Make(q.x, q.y, q.z, q.w));

test.orientation = final;

Other code I've tried includes this same sort of method, in fact, I even built my own SCNVector3 and SCNVector4 Math libraries in Objective-C to see if my math methods produced different values than using GLKit maths, but I get the same results with both methods. Any help would be awesome, but for now, I'm not looking to jump into anything more complicated than SceneKit. I won't be diving into Metal and/or OpenGL for another month or two. Thanks!
EDIT:
The variables "cooridnateSetOne" and "cooridnateSetTwo" are SCNNodes that are produced by another function that forces a primitive line geometry into this node and then returns it to a subclass implementation of SCNScene.

A: Here's a quick demo using node hierarchy (to get the cylinder situated such that its end is at one point and its length is along the local z-axis) and a constraint (to make that z-axis look at another point).
let root = view.scene!.rootNode

// visualize a sphere
let sphere = SCNSphere(radius: 1)
sphere.firstMaterial?.transparency = 0.5
let sphereNode = SCNNode(geometry: sphere)
root.addChildNode(sphereNode)

// some dummy points opposite each other on the sphere
let rootOneThird = CGFloat(sqrt(1/3.0))
let p1 = SCNVector3(x: rootOneThird, y: rootOneThird, z: rootOneThird)
let p2 = SCNVector3(x: -rootOneThird, y: -rootOneThird, z: -rootOneThird)

// height of the cylinder should be the distance between points
let height = CGFloat(GLKVector3Distance(SCNVector3ToGLKVector3(p1), SCNVector3ToGLKVector3(p2)))

// add a container node for the cylinder to make its height run along the z axis
let zAlignNode = SCNNode()
zAlignNode.eulerAngles.x = CGFloat(M_PI_2)
// and position the zylinder so that one end is at the local origin
let cylinder = SCNNode(geometry: SCNCylinder(radius: 0.1, height: height))
cylinder.position.y = -height/2
zAlignNode.addChildNode(cylinder)

// put the container node in a positioning node at one of the points
p2Node.addChildNode(zAlignNode)
// and constrain the positioning node to face toward the other point
p2Node.constraints = [ SCNLookAtConstraint(target: p1Node) ]

Sorry if you were looking for an ObjC-specific solution, but it was quicker for me to prototype this in an OS X Swift playground. (Also, less CGFloat conversion is needed in iOS, because the element type of SCNVector3 is just Float there.)

A: Just for reference a more elegant SCNCyclinder implementation to connect a start and end position with a given radius:
func makeCylinder(from: SCNVector3, to: SCNVector3, radius: CGFloat) -> SCNNode
{
    let lookAt = to - from
    let height = lookAt.length()

    let y = lookAt.normalized()
    let up = lookAt.cross(vector: to).normalized()
    let x = y.cross(vector: up).normalized()
    let z = x.cross(vector: y).normalized()
    let transform = SCNMatrix4(x: x, y: y, z: z, w: from)

    let geometry = SCNCylinder(radius: radius,
                               height: CGFloat(height))
    let childNode = SCNNode(geometry: geometry)
    childNode.transform = SCNMatrix4MakeTranslation(0.0, height / 2.0, 0.0) *
      transform

    return childNode
}

Needs the following extension:
extension SCNVector3 {
    /**
     * Calculates the cross product between two SCNVector3.
     */
    func cross(vector: SCNVector3) -> SCNVector3 {
        return SCNVector3Make(y * vector.z - z * vector.y, z * vector.x - x * vector.z, x * vector.y - y * vector.x)
    }

    func length() -> Float {
        return sqrtf(x*x + y*y + z*z)
    }

    /**
     * Normalizes the vector described by the SCNVector3 to length 1.0 and returns
     * the result as a new SCNVector3.
     */
    func normalized() -> SCNVector3 {
        return self / length()
    }
}

extension SCNMatrix4 {
    public init(x: SCNVector3, y: SCNVector3, z: SCNVector3, w: SCNVector3) {
        self.init(
            m11: x.x,
            m12: x.y,
            m13: x.z,
            m14: 0.0,

            m21: y.x,
            m22: y.y,
            m23: y.z,
            m24: 0.0,

            m31: z.x,
            m32: z.y,
            m33: z.z,
            m34: 0.0,

            m41: w.x,
            m42: w.y,
            m43: w.z,
            m44: 1.0)
    }
}

/**
 * Divides the x, y and z fields of a SCNVector3 by the same scalar value and
 * returns the result as a new SCNVector3.
 */
func / (vector: SCNVector3, scalar: Float) -> SCNVector3 {
    return SCNVector3Make(vector.x / scalar, vector.y / scalar, vector.z / scalar)
}

func * (left: SCNMatrix4, right: SCNMatrix4) -> SCNMatrix4 {
    return SCNMatrix4Mult(left, right)
}

A: Thank you, Rickster! I have taken it a little further and made a class out of it:
class LineNode: SCNNode
{
    init( parent: SCNNode,     // because this node has not yet been assigned to a parent.
              v1: SCNVector3,  // where line starts
              v2: SCNVector3,  // where line ends
          radius: CGFloat,     // line thicknes
      radSegmentCount: Int,    // number of sides of the line
        material: [SCNMaterial] )  // any material.
    {
        super.init()
        let  height = v1.distance(v2)

        position = v1

        let ndV2 = SCNNode()

        ndV2.position = v2
        parent.addChildNode(ndV2)

        let ndZAlign = SCNNode()
        ndZAlign.eulerAngles.x = Float(M_PI_2)

        let cylgeo = SCNCylinder(radius: radius, height: CGFloat(height))
        cylgeo.radialSegmentCount = radSegmentCount
        cylgeo.materials = material

        let ndCylinder = SCNNode(geometry: cylgeo )
        ndCylinder.position.y = -height/2
        ndZAlign.addChildNode(ndCylinder)

        addChildNode(ndZAlign)

        constraints = [SCNLookAtConstraint(target: ndV2)]
    }

    override init() {
        super.init()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
 }

I have tested this class successfully in an iOS app, using this function,
which draws 100 lines (oops cylinders :o).
    func linesTest3()
    {
        let mat = SCNMaterial()
        mat.diffuse.contents  = UIColor.whiteColor()
        mat.specular.contents = UIColor.whiteColor()

        for _ in 1...100    // draw 100 lines (as cylinders) between random points.
        {
            let v1 =  SCNVector3( x: Float.random(min: -50, max: 50),
                                  y: Float.random(min: -50, max: 50),
                                  z: Float.random(min: -50, max: 50) )

            let v2 =  SCNVector3( x: Float.random(min: -50, max: 50),
                                  y: Float.random(min: -50, max: 50),
                                  z: Float.random(min: -50, max: 50) )

            // Just for testing, add two little spheres to check if lines are drawn correctly:
            // each line should run exactly from a green sphere to a red one:

            root.addChildNode(makeSphere(v1, radius: 0.5, color: UIColor.greenColor()))
            root.addChildNode(makeSphere(v2, radius: 0.5, color: UIColor.redColor()))

            // Have to pass the parentnode because
            // it is not known during class instantiation of LineNode.

            let ndLine = LineNode(
                         parent: scene.rootNode, // ** needed
                             v1: v1,    // line (cylinder) starts here
                             v2: v2,    // line ends here
                         radius: 0.2,   // line thickness
                radSegmentCount: 6,     // hexagon tube
                       material: [mat] )  // any material

            root.addChildNode(ndLine)
        }
    }

Regards. (btw. I can only see 3D objects.. I have never seen a "line" in my life :o)

A: Here's an entire method using Objective-C
First, here's how you use it:
SCNNode * testNode = [self lat1:-35 lon1:108 height1:tall lat2:-35 lon2:30 height2:0];

Inputs:
1rst location
lat1 = latitude of 1rst location
lon1 = longitude of 1rst location
height1 = distance from earth for 1rst location
lat2 = latitude of 2nd location
lon2 = latitude of 2nd location
height2 = distance from earth for 2nd location
The second method creates the SCNVector3 points for each location in question above:
-(SCNNode *)lat1:(double)lat1 lon1:(double)lon1 height1:(float)height1 lat2:(double)lat2 lon2:(double)lon2 height2:(float)height2 {
    SCNVector3 positions[] = {[self lat:lat1 lon:lon1 height:height1], [self lat:lat2 lon:lon2 height:height2]};

    float cylHeight = GLKVector3Distance(SCNVector3ToGLKVector3(positions[0]), SCNVector3ToGLKVector3(positions[1]))/4;

    SCNCylinder * masterCylinderNode = [SCNCylinder cylinderWithRadius:0.05 height:cylHeight];

    SCNMaterial *material = [SCNMaterial material];
    [[material diffuse] setContents:[SKColor whiteColor]];
    material.lightingModelName = SCNLightingModelConstant;
    material.emission.contents = [SKColor whiteColor];
    [masterCylinderNode setMaterials:@[material]];

    SCNNode *mainLocationPointNodeTestA = [mainLocationPointNode clone];
    SCNNode *mainLocationPointNodeTestB = [mainLocationPointNode clone];

    mainLocationPointNodeTestA.position = positions[0];
    mainLocationPointNodeTestB.position = positions[1];

    SCNNode * mainParentNode = [SCNNode node];
    SCNNode * tempNode2 =[SCNNode nodeWithGeometry:masterCylinderNode];

    [mainParentNode addChildNode:mainLocationPointNodeTestA];
    [mainParentNode addChildNode:mainLocationPointNodeTestB];
    [mainParentNode addChildNode:tempNode2];

    [mainParentNode setName:@"parentToLineNode"];

    tempNode2.position = SCNVector3Make((positions[0].x+positions[1].x)/2, (positions[0].y+positions[1].y)/2, (positions[0].z+positions[1].z)/2);
    tempNode2.pivot = SCNMatrix4MakeTranslation(0, cylHeight*1.5, 0);

    GLKVector3 normalizedVectorStartingPosition = GLKVector3Make(0.0, 1.0, 0.0);
    GLKVector3 magicAxis = GLKVector3Normalize(GLKVector3Subtract(GLKVector3Make(positions[0].x/2, positions[0].y/2, positions[0].z/2), GLKVector3Make(positions[1].x/2, positions[1].y/2, positions[1].z/2)));

    GLKVector3 rotationAxis = GLKVector3CrossProduct(normalizedVectorStartingPosition, magicAxis);
    CGFloat rotationAngle = GLKVector3DotProduct(normalizedVectorStartingPosition, magicAxis);

    GLKVector4 rotation = GLKVector4MakeWithVector3(rotationAxis, acos(rotationAngle));
    tempNode2.rotation = SCNVector4FromGLKVector4(rotation);

    return mainParentNode;
}

This second method uses hard coded numbers for earth's radius and curvature, I'm showing this just to show the numbers required for total 100% accuracy, this is how it works. You'll want to change this to the correct dimensions for your scene, obviously, but here's the method. This is an adaptation of methods used by Link. An explanation an be found here: Link. I put this together very quickly but it works and is accurate, feel free to change the number formats to your liking.
-(SCNVector3)lat:(double)lat lon:(double)lon height:(float)height {
    double latd = 0.0174532925;
    double latitude = latd*lat;
    double longitude = latd*lon;

    Float64 rad = (Float64)(6378137.0);
    Float64 f = (Float64)(1.0/298.257223563);

    double cosLat = cos(latitude);

    double sinLat = sin(latitude);

    double FF = pow((1.0-f), 2);
    double C = 1/(sqrt(pow(cosLat,2) + FF * pow(sinLat,2)));
    double S = C * FF;

    double x = ((rad * C)*cosLat * cos(longitude))/(1000000/(1+height));
    double y = ((rad * C)*cosLat * sin(longitude))/(1000000/(1+height));
    double z = ((rad * S)*sinLat)/(1000000/(1+height));

    return SCNVector3Make(y+globeNode.position.x, z+globeNode.position.y, x+globeNode.position.z);
}

A: i use SCNVector3 extensions with:
 func cylVector(from : SCNVector3, to : SCNVector3) -> SCNNode {
    let vector = to - from,
        length = vector.length()

    let cylinder = SCNCylinder(radius: cylsRadius, height: CGFloat(length))
    cylinder.radialSegmentCount = 6
    cylinder.firstMaterial = material

    let node = SCNNode(geometry: cylinder)

    node.position = (to + from) / 2
    node.eulerAngles = SCNVector3Make(CGFloat(Double.pi/2), acos((to.z-from.z)/length), atan2((to.y-from.y), (to.x-from.x) ))

    return node
}

A: I have been looking for a solution to make cylinder between two points and thanks to  rickster, I have used his answer to make SCNNode extension. There, I have added missing conditions for a possible cylinder orientation to avoid its wrong opposite direction.
func makeCylinder(positionStart: SCNVector3, positionEnd: SCNVector3, radius: CGFloat , color: NSColor, transparency: CGFloat) -> SCNNode
{
    let height = CGFloat(GLKVector3Distance(SCNVector3ToGLKVector3(positionStart), SCNVector3ToGLKVector3(positionEnd)))
    let startNode = SCNNode()
    let endNode = SCNNode()

    startNode.position = positionStart
    endNode.position = positionEnd

    let zAxisNode = SCNNode()
    zAxisNode.eulerAngles.x = CGFloat(M_PI_2)

    let cylinderGeometry = SCNCylinder(radius: radius, height: height)
    cylinderGeometry.firstMaterial?.diffuse.contents = color
    let cylinder = SCNNode(geometry: cylinderGeometry)

    cylinder.position.y = -height/2
    zAxisNode.addChildNode(cylinder)

    let returnNode = SCNNode()

    if (positionStart.x > 0.0 && positionStart.y < 0.0 && positionStart.z < 0.0 && positionEnd.x > 0.0 && positionEnd.y < 0.0 && positionEnd.z > 0.0)
    {
        endNode.addChildNode(zAxisNode)
        endNode.constraints = [ SCNLookAtConstraint(target: startNode) ]
        returnNode.addChildNode(endNode)

    }
    else if (positionStart.x < 0.0 && positionStart.y < 0.0 && positionStart.z < 0.0 && positionEnd.x < 0.0 && positionEnd.y < 0.0 && positionEnd.z > 0.0)
    {
        endNode.addChildNode(zAxisNode)
        endNode.constraints = [ SCNLookAtConstraint(target: startNode) ]
        returnNode.addChildNode(endNode)

    }
    else if (positionStart.x < 0.0 && positionStart.y > 0.0 && positionStart.z < 0.0 && positionEnd.x < 0.0 && positionEnd.y > 0.0 && positionEnd.z > 0.0)
    {
        endNode.addChildNode(zAxisNode)
        endNode.constraints = [ SCNLookAtConstraint(target: startNode) ]
        returnNode.addChildNode(endNode)

    }
    else if (positionStart.x > 0.0 && positionStart.y > 0.0 && positionStart.z < 0.0 && positionEnd.x > 0.0 && positionEnd.y > 0.0 && positionEnd.z > 0.0)
    {
        endNode.addChildNode(zAxisNode)
        endNode.constraints = [ SCNLookAtConstraint(target: startNode) ]
        returnNode.addChildNode(endNode)

    }
    else
    {
        startNode.addChildNode(zAxisNode)
        startNode.constraints = [ SCNLookAtConstraint(target: endNode) ]
        returnNode.addChildNode(startNode)
    }

    return returnNode
}


text:
Q: Android: Program type already present: android.arch.lifecycle.LiveData$LifecycleBoundObserver I have looked some answer but related to firebase and live data not compatible or similar. My simple test application have nothing to do with firebase.
This is my gradle file in module level:
    apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "room.exercise.com.myapplication"
        minSdkVersion 19
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'com.android.support:recyclerview-v7:27.1.1'

    //Design for room persistance storage
    implementation 'android.arch.persistence.room:runtime:1.0.0'
    annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'
    /////

    //Design for live data
    implementation "android.arch.lifecycle:extensions:1.0.0"
    annotationProcessor "android.arch.lifecycle:compiler:1.0.0"
    //

    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

This application just a simple test of Room and Live data which I load the data from database to recyclerView.. I know the Room database is working coz this was my first test.
The gradle file was sync without problem. The error occurred when I compile and run the application.

Program type already present: android.arch.lifecycle.LiveData$LifecycleBoundObserver
  Message{kind=ERROR, text=Program type already present: android.arch.lifecycle.LiveData$LifecycleBoundObserver, sources=[Unknown source file], tool name=Optional.of(D8)}

Code:
public class RoomActivity extends AppCompatActivity implements View.OnLongClickListener {

private StudentListViewModel viewModel;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_room);

    //RoomDatabase database = RoomDatabase.getDatabase(RoomActivity.this);
    //RoomDataInitializer.AddSampleDataAsync(database);

    //List<StudentEntity> students = database.studentDAO().getAllStudents();
    //Log.w("Room Activity", "Count = " + students.size());

    RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
    final RecyclerViewAdapter adapter = new RecyclerViewAdapter(new ArrayList<StudentEntity>(), this);
    recyclerView.setAdapter(adapter);

    viewModel = ViewModelProviders.of(this).get(StudentListViewModel.class);

    viewModel.getStudentList().observe(RoomActivity.this, new Observer<List<StudentEntity>>()
    {
        @Override
        public void onChanged(@Nullable List<StudentEntity> studentEntities) {
            adapter.addItems(studentEntities);
        }
    });

}

@Override
public boolean onLongClick(View v) {
    return false;
}

}

A: Just try this:
implementation "android.arch.lifecycle:extensions:1.1.1"
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"

implementation 'android.arch.persistence.room:runtime:1.1.1'
annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'

instead of your versions.
I don't have explainable explanation for this solution, yet, I'll try.
This type of error occurs when one class is defined/brought in by 2 or more dependencies. (In your case it is LifecycleBoundObserver).
And this type of errors occur runtime only. They don't happen during gradle build/sync.
If this type of errors are occurring in firebase/android dependencies, mostly they maybe resolved by upgrading the version. (Or there might be an issue registered in issue tracker for the same.). In other cases, you might have to exclude modules/groups from dependencies bringing in redundant classes.


text:
Q: ASp.net core 2 Identity app sometimes looses claim when kept logged in I have an authorization handler, which is meant to restrict users to accessing info only for the organization they belong to, or ANY if they are of a certain account type (known as SuperAdmin here). Aforementioned account type may or may not have an associated Organization, which happens to be a navigation property. It should be mentioned I am working with "user" classes extended from ApplicationUser in the Identity framework.
Here's the handler:
 public class OrganizationHandler : AuthorizationHandler<SameOrgRequirment,
    Organization>
 {
     protected override Task
       HandleRequirementAsync(AuthorizationHandlerContext context,
       SameOrgRequirment requirement, Organization resource)
    {
        var value = context.User.FindFirst( "OrganizationID").Value;
        long claimValue = long.Parse(value);
        if(claimValue==resource.Id)
        {
            context.Succeed(requirement);
        }
        else
        {
            string orgClaimValue = context.User.FindFirst(c => c.Type ==
            "AccountTypes").Value;
            AccountTypes claimAsType =
             (AccountTypes)Enum.Parse(typeof(AccountTypes), orgClaimValue);
           if(claimAsType == AccountTypes.SuperAdmin)
            {
                context.Succeed(requirement);
            }
        }

        return Task.CompletedTask;
    }
}
public class SameOrgRequirment:IAuthorizationRequirement{}

The problem is I am SOMETIMES getting a NullReferenceException on the line
var value = context.User.FindFirst( "OrganizationID").Value;

which makes no sense as all users in my dev setup have an organizationId navigation property. Inspecting the ClaimsPrincipal I see the AccountTypes claim (see below) exists but the other, OrganizationId does not when this NullReferenceException  is thrown.
I have overridden the AppClaimsPrincipalFactory to create these claims:
 public class AppClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, ApplicationRole>
{
    public AppClaimsPrincipalFactory(
        UserManager<ApplicationUser> userManager
        , RoleManager<ApplicationRole> roleManager
        , IOptions<IdentityOptions> optionsAccessor)
    : base(userManager, roleManager, optionsAccessor)
    { }

    public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
    {
        var principal = await base.CreateAsync(user);

        if (!string.IsNullOrWhiteSpace(user.Type.ToString()))
        {
            ((ClaimsIdentity)principal.Identity).AddClaims(new[]
            {
                new Claim("AccountTypes", user.Type.ToString())
            });
        }

        try
        {
            if (!string.IsNullOrWhiteSpace(user.Organization.Id.ToString()))
            {
                //Used later to restrict data
                ((ClaimsIdentity)principal.Identity).AddClaims(new[]
                {
               new Claim("OrganizationId", user.Organization.Id.ToString()),
             });
            }
        }
        catch(NullReferenceException ex)
        {
            ((ClaimsIdentity)principal.Identity).AddClaims(new[]
               {
               new Claim("OrganizationId", "-1"),
             });
        }

        return principal;
    }
}

The AccountTypes claim doesnt seem to get lost.
The only thing I have narrowed down is that this only seems to happen for an account where Remember Me? is checked and the app is closed and reopened via visual studio. If I log out and log back with the same account, it works fine! All claims are there and the handler works correctly. Being able to stay logged is a customer requirement so I can't really change that.


text:
Q: CMake and Makefile: segmentation fault I'm calling Makefile from CMakeLists.txt. The CMakeLists.txt compiles a main.cpp file that prints "Hello world", and calls the Makefile. The Makefile compiles a test.cpp file that prints "Test". The code is fine. I checked it when I built the test.cpp just with the Makefile.
The problem is when I'm trying to build CMakeLists.txt. The "main" output works fine but the "test" output throws an exception:

"segmentation fault (core dumped)".

Here is the Makefile code:
all:
g++ -shared -fPIC -o test test.cpp

Here is the CMakeLists.txt code:
cmake_minimum_required(VERSION 3.5)
project(Call_Makefile_From_CMake)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(FullPath "/home/orz/ClionProjects/Call_Makefile_From_CMake")

add_custom_command(
        OUTPUT ${FullPath}/Test/test
        COMMAND make -f test.mk
        WORKING_DIRECTORY ${FullPath}/Test
        )
add_custom_target(
   extern_lib
   DEPENDS ${FullPath}/Test/test
   )

add_executable(Call_Makefile_From_CMake main.cpp)
target_link_libraries(Call_Makefile_From_CMake ${FullPath}/Test/test)
add_dependencies(Call_Makefile_From_CMake extern_lib)

Thank's for the helpers.

A: I tried to solve this problem for two days and 5 minutes after i asked for help here i solved it.
I removed the
target_link_libraries(Call_Makefile_From_CMake ${FullPath}/Test/test)
line and it solved the problem. Now it works just fine.


text:
Q: Custom Function from .tld File not working I am pulling my hair out trying to get a custom function working in JSP. I have read other questions on the topic, but I have not made those mistakes and am following a JSP book (Head First Servlets & JSP) in creating my tag.
Here's my login.tld file located in /WEB-INF/:

<tlib-version>1.2</tlib-version>
<uri>/WEB-INF/login.tld</uri>
<function>
    <name>validate</name>
    <function-class>org.patrickslagle.model.LoginManager</function-class>
    <function-signature>
        boolean validate(String username, String password)
    </function-signature>
</function>

The method in LoginManager class:
public static boolean validate(String username, String password) {
    System.out.println("Servlet");
    DatabaseManager dbm = new DatabaseManager();
    boolean valid = false;
    ResultSet rs = null;
    Statement stmt = null;
    dbm.setUrl("jdbc:mysql://localhost:3306/pattycakes");
    dbm.connect();
    try {
        stmt = dbm.getConn().createStatement();
        String sql = "SELECT * FROM users WHERE email = '" + username + "' AND password = '" + password + "'";
        rs = stmt.executeQuery(sql);
        if (rs.next()) {
            valid = true;
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        dbm.disconnect(stmt, dbm.getConn());
    }
    return valid;
}

}

And the tag in index.jsp:
<%@ taglib prefix="lm" uri="/WEB-INF/login.tld"%>

It is called like so:
<c:if test="${ lm.validate(username, password) }">

with these two inputs on the page in a form:
     <input type="text" name="username" id="user_login" class="input"
                placeholder="Email Address" value="" size="20" />

<input type="password" name="password" id="user_pass" class="input"
                    placeholder="Password" value="" size="20" />

If I print to the console, I find that anything inside the test isn't printed and the System.out.println in LoginManager is never printed. It simply skips the test.
Having trouble figuring out the problem in debug mode as well. I am assuming that the expression just isn't being evaluated for some reason and is returning nothing.

A: In your login.tld,  instead of using
boolean validate(String username, String password)

try using
boolean validate(java.lang.String username, java.lang.String password)

also, instead of using
<c:if test="${ lm.validate(username, password) }">

try using
<c:if test="${lm:validate(username, password)}">

if you getting data from request, then you might need
<c:if test="${lm:validate(param.username, param.password)}">


text:
Q: how to move a div with arrow keys I would like to move a div with my arrow keys using jQuery.
So right, left, down and up.
Found a demo of what I want to accomplish here
I would like to be able to move a div around in another div.
How can this be done?

A: @Šime Vidas: Your first solution is simply marvelous. (i think the second one is redundant =)
May i suggest to make two different functions for the vertical and the horizontal width? Because it's highly unlikely that you have to move around a div inside a perfect square and i believe it would be nicer to have something like this:
$(function () {
var pane = $('#pane'),
box = $('#box'),
wh = pane.width() - box.width(),
wv = pane.height() - box.height(),
d = {},
x = 5;

function newh(v,a,b) {
    var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
    return n < 0 ? 0 : n > wh ? wh : n;
}

function newv(v,a,b) {
    var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
    return n < 0 ? 0 : n > wv ? wv : n;
}

$(window).keydown(function(e) { d[e.which] = true; });
$(window).keyup(function(e) { d[e.which] = false; });

setInterval(function() {
    box.css({
        left: function(i,v) { return newh(v, 37, 39); },
        top: function(i,v) { return newv(v, 38, 40); }
    });
}, 20);
});

This would have been exactly what i was looking for.
If you had a responsive design based on % values it would be recommendable to adjust your setInterval like this:
setInterval(function() {
    box.css({
        left: function(i,v) { return newh(v, 37, 39); },
        top: function(i,v) { return newv(v, 38, 40); }
    });
    wh = pane.width() - box.width();
    wv = pane.height() - box.height();
}, 20);

if you do that it adjusts your panes height and width and the box still stops at its border.
i made a fiddle of that here http://jsfiddle.net/infidel/JkQrR/1/
Thanks a lot.

A:

var pane = $('#pane'),
    box = $('#box'),
    w = pane.width() - box.width(),
    d = {},
    x = 3;

function newv(v,a,b) {
    var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
    return n < 0 ? 0 : n > w ? w : n;
}

$(window).keydown(function(e) { d[e.which] = true; });
$(window).keyup(function(e) { d[e.which] = false; });

setInterval(function() {
    box.css({
        left: function(i,v) { return newv(v, 37, 39); },
        top: function(i,v) { return newv(v, 38, 40); }
    });
}, 20);
#pane {
  position: relative;
  width: 300px;
  height: 300px;
  border: 2px solid red;
}

#box {
  position: absolute;
  top: 140px;
  left: 140px;
  width: 20px;
  height: 20px;
  background-color: black;
}

Variable explanations:
w - the maximal left/top value that the box can have (to stay within bounds)
x - the distance (in px) that the box moves in each interval
d - this object stores the information on what key is being pressed. For instance, while the user holds down the LEFT ARROW key, d['37'] is true. Otherwise it's false. BTW, 37 is the key-code for the LEFT ARROW key and this value is stored in the e.which property of the event object. The d object is being updated on each keydown and keyup event.
An setInterval which is executed every 20ms, updates the left and top CSS properties of the box element. The new values are calculated via the newv function.
The newv function will calculate the new left/top value based on a) the old value v and b) the d object.
The expression n < 0 ? 0 : n > w ? w : n ensures that the new value is in the permitted bounds (which are 0 to w). If n is < 0, zero will be returned. If n is > w, w will be returned.

Live demo: http://jsfiddle.net/simevidas/bDMnX/1299/

Update: This code has the same functionality as the original code above. The only difference is that I used more meaningful names for my variables and arguments. As you can see, it looks awful - the original version is clearly better. :P
var pane = $('#pane'),
    box = $('#box'),
    maxValue = pane.width() - box.width(),
    keysPressed = {},
    distancePerIteration = 3;

function calculateNewValue(oldValue, keyCode1, keyCode2) {
    var newValue = parseInt(oldValue, 10)
                   - (keysPressed[keyCode1] ? distancePerIteration : 0)
                   + (keysPressed[keyCode2] ? distancePerIteration : 0);
    return newValue < 0 ? 0 : newValue > maxValue ? maxValue : newValue;
}

$(window).keydown(function(event) { keysPressed[event.which] = true; });
$(window).keyup(function(event) { keysPressed[event.which] = false; });

setInterval(function() {
    box.css({
        left: function(index ,oldValue) {
            return calculateNewValue(oldValue, 37, 39);
        },
        top: function(index, oldValue) {
            return calculateNewValue(oldValue, 38, 40);
        }
    });
}, 20);

A: I can't see your demo, but here's a simple "move the box 1px in the direction of the arrow keys" example:
CSS:
#wrapper {
    background-color: gray;
    height:200px;
    width: 200px;
    position:absolute;
}
#mover {
    background-color: white;
    border: 1px solid red;
    height:20px;
    width: 20px;
    position:relative;
}

Markup:

JS (using jQuery):
$("#wrapper").keydown(function(event) {
    var $mover = $("#mover");
    //if nothing else will move "mover", then track the
    //position instead of recalculating it every time:
    //   var moverPos = $mover.position();
    //   var left = moverPos.left;
    //   var top = moverPos.top;
    var addTop = function(diff) {
        $mover.css("top", ($mover.position().top + diff) + "px");
        //if using tracked position:
        //   top += diff;
        //   $mover.css("top", top) + "px");
    };

    var addLeft = function(diff) {
        $mover.css("left", ($mover.position().left + diff) + "px");
        //if using tracked position:
        //   left += diff;
        //   $mover.css("left", left) + "px");
    };

    switch(event.keyCode) {
        case 37: //left
            addLeft(-1); break;
        case 38: //up
            addTop(-1); break;
        case 39: //right
            addLeft(1); break;
        case 40: //down
            addTop(1); break;
    }
});

This is just an example, you may want to add bounds checking, larger movements, smoother animation, number pad support or any number of other things to it, but it should get you started.

A: try This Code


text:
Q: How to find the last iteration of a "fgetcsv" while() loop in PHP How to find the last iteration:
Here is an example while loop.  I need to find the last iteration so that a comma will not be added to the end.  How is this done?
for($i=0;$i<count($files);$i++){
    if (($handle = fopen($files[$i], "r")) !== FALSE) {
        $isfirst = true;
        while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
            if ($isfirst){
                $isfirst = false;
                continue;
        }
            $timestamp = strtotime($data[0].' '.$data[1]);
            fputs($out, '['.(int)$timestamp.','.(float)$data[2].'],');
        }
        fclose($handle);
    }
}

Answer:
for($i=0;$i<count($files);$i++){
if (($handle = fopen($files[$i], "r")) !== FALSE) {
    $isfirst = true;
    $firstline = true;
    while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
        if ($isfirst){
            $isfirst = false;
            continue;
        }
        if ($firstline) {
            $timestamp = strtotime($data[0].' '.$data[1]);
            fputs($out, '['.(int)$timestamp.','.(float)$data[2].']');
            $firstline = false;
        } else {
            $timestamp = strtotime($data[0].' '.$data[1]);
            fputs($out, ',['.(int)$timestamp.','.(float)$data[2].']');
        }
    }
    fclose($handle);
}

}

A: for($i=0;$i<count($files);$i++){
    if (($handle = fopen($files[$i], "r")) !== FALSE) {
        $firstLine = TRUE;
        while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
            if (!$firstLine) {
                fputs($out, ',');
            } else {
                firstLine = FALSE;
            }
            $timestamp = strtotime($data[0].' '.$data[1]);
            fputs($out, '['.(int)$timestamp.','.(float)$data[2].']');
        }
        fclose($handle);
    }
}


text:
Q: Retrieve modified DateTime of a file from an FTP Server Is there a way to find the modified date/time for files on an FTP server in R? I have found a great way to list all of the files that are available, but I only want to download ones that have been updated since my last check. I tried using:
info<-file.info(url)

However, it returns a pretty ugly list of nothing. My url is made up of:
    "ftp://username:password@FTPServer//filepath.xml"

A: Until we see the output from this particular FTP server (they are all different) for directory listings, here's a path you can follow:
library(curl)
library(stringr)

Get the raw directory listing:
con <- curl("ftp://ftp.FreeBSD.org/pub/FreeBSD/")
dat <- readLines(con)
close(con)
dat

## [1] "-rw-rw-r--    1 ftp      ftp          4259 May 07 16:18 README.TXT"
## [2] "-rw-rw-r--    1 ftp      ftp            35 Sep 09 21:00 TIMESTAMP"
## [3] "drwxrwxr-x    9 ftp      ftp            11 Sep 09 21:00 development"
## [4] "-rw-r--r--    1 ftp      ftp          2566 Sep 09 10:00 dir.sizes"
## [5] "drwxrwxr-x   28 ftp      ftp            52 Aug 23 10:44 doc"
## [6] "drwxrwxr-x    5 ftp      ftp             5 Aug 05 04:16 ports"
## [7] "drwxrwxr-x   10 ftp      ftp            12 Sep 09 21:00 releases"

Filter out the directories:
no_dirs <- grep("^d", dat, value=TRUE, invert=TRUE)
no_dirs

## [1] "-rw-rw-r--    1 ftp      ftp          4259 May 07 16:18 README.TXT"
## [2] "-rw-rw-r--    1 ftp      ftp            35 Sep 09 21:00 TIMESTAMP"
## [3] "-rw-r--r--    1 ftp      ftp          2566 Sep 09 10:00 dir.sizes"

Extract just the timestamp and filename:
date_and_name <- sub("^[[:alnum:][:punct:][:blank:]]{43}", "", no_dirs)
date_ane_name
## [1] "May 07 16:18 README.TXT"
## [2] "Sep 09 21:00 TIMESTAMP"
## [3] "Sep 09 10:00 dir.sizes"

Put them into a data.frame:
do.call(rbind.data.frame,
        lapply(str_match_all(date_and_name, "([[:alnum:] :]{12}) (.*)$"),
               function(x) {
                 data.frame(timestamp=x[2],
                            filename=x[3],
                            stringsAsFactors=FALSE)
})) -> dat
dat

##      timestamp   filename
## 1 May 07 16:18 README.TXT
## 2 Sep 09 21:00  TIMESTAMP
## 3 Sep 09 10:00  dir.sizes

You still need to convert the timestamp to a POSIXct but that's trivial.
This particular example is dependent on that system's FTP directory listing response. Just change the regexes for yours.


text:
Q: How can I convert .osp files to other formats? I'm new to Ubuntu. I recorded a video and edited it with OpenShot Video Editor. It was all good. But then I couldn't upload the video because it's format is .osp. I searched how to convert but I didn't find anything.
How can I convert .osp files?

A: .osp is a project file, not a video file.
To create a video you need to -export- your project. See the "file" options:


text:
Q: Fixing position on DIV while page scrolls I have a page with 2 columns. The left column is quite longer than the right one.
When I start scrolling I'd like the right column to stay where it is so only the left column moves.
This means the right column will always be visible when the page is scrolled.
I thought I needed to set the div as position:fixed;  This works but moves the right div so it sits over the left.
How do I do this properly so the right div stays in place?
I've created a fiddle here
I've also looked at using jquery to animate the scrolling, but that didn't work either..
$(window).scroll(function(){
  $("#right").stop().animate({"marginTop": ($(window).scrollTop()) + "px", "marginLeft":($(window).scrollLeft()) + "px"}, "slow" );
});

A: You need to add position: fixed on the #right div
CSS
#right {
    width: auto;
    float: right;
    top: 40px;
    background-color: #eee;
    border: 1px solid #AAAAAA;
    position: fixed;
}

DEMO
https://jsfiddle.net/wzzopxte/5/

A: it works with position:fixed; on the #right_container but you also have to set right:0;
i also used percentages instead of fixed widths on the containers. it's much more responsive and prevents the divs from overlapping because of the position:fixed but if you really need fixed widths...you can use them but keep in mind that there are some side-effects
see code snippet below. let me know if it helps

body {
 font-family: arial;
 margin: 0px;
}

.drag {
 cursor: move;
 margin: auto;
 background-color: white;
 text-align: center;
 font-size: 10pt;
 opacity: 0.7;
 width: 120px;
 min-height: 24px;
 line-height: 24px;
 border: 2px solid #800000;
}

#drag {
 margin: auto;
 width: 100%;
 display: table;
    position: relative;
 border: 1px solid #d9a300;
}

.list {
 border: 1px solid #00b359;
 min-height: 350px;
    display: table;
 width: 100%;
}

#left_container {
 width: 63%;
 float: left;
 margin-right: 2%;
 border-bottom: 1px solid #F6F6F6;
 border: 1px solid #ff26ff;
    box-sizing:border-box;
}

#left {
 width: 100%;
 display: table-cell;
 border: 1px solid #2d00b3;
}

#right_container {
 width: 33%;
 float: right;
 margin-right: 2%;
 border-bottom: 1px solid #F6F6F6;
 border: 1px solid #ffff00;
    position:fixed;
    right:0;

}

#right {
 width: auto;
 float: right;
 top: 40px;
 background-color: #eee;
 border: 1px solid #AAAAAA;

}

 <fieldset><legend>TITLE</legend>

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget erat non augue vestibulum fringilla. Maecenas fermentum ante mattis interdum vestibulum. Aliquam vel dui ac turpis consectetur accumsan quis eu libero. Sed finibus neque vel ipsum lacinia lobortis. Pellentesque lorem erat, ullamcorper vitae consectetur nec, tempor sit amet nisi. Aenean posuere ante egestas quam rhoncus, ut laoreet dui mattis. Quisque condimentum fermentum metus sit amet posuere. Ut sed lectus orci.
   Cras nec enim faucibus, consectetur eros ut, vulputate est. Maecenas sollicitudin vestibulum eros, sit amet porta enim molestie eget. Etiam commodo ex efficitur ligula ornare iaculis. Aliquam erat volutpat. Nullam mollis eleifend nisl a rhoncus. Sed egestas lacinia est ut mollis. Duis fermentum odio eget diam placerat, eu placerat sapien laoreet. Sed mollis leo id tortor dapibus, in finibus lacus aliquet. Donec semper vel libero eu placerat. Nam hendrerit pretium nunc, vel malesuada nisi tincidunt in. Duis ligula metus, dignissim ac laoreet in, aliquam et ipsum. Maecenas non condimentum leo. Morbi convallis turpis lobortis dignissim mattis.
   Quisque at hendrerit magna. Praesent id ligula eleifend, semper lacus sed, sagittis mauris. Nulla molestie tristique sem, non ultrices nisl mattis ut. Nulla ut nisi quis elit porta tempor. Duis semper sem tellus, nec viverra metus dignissim nec. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla libero lectus, iaculis sit amet enim eget, facilisis blandit enim. Ut dolor massa, imperdiet id lorem a, molestie vestibulum nulla. Fusce non condimentum purus, ut egestas mi. Ut lacinia rutrum nulla a convallis. Vestibulum ac metus urna. In hac habitasse platea dictumst. In ac eleifend mi.
   Duis at cursus mauris, non viverra ipsum. Sed facilisis, arcu eu aliquam volutpat, nisi leo interdum neque, in congue libero purus a eros. Pellentesque posuere tellus ut consequat dapibus. Ut dapibus ultrices sem, in posuere eros. Aliquam tincidunt, arcu a dignissim eleifend, urna diam pulvinar urna, non hendrerit lorem urna ac nibh. Cras eu feugiat enim. Aliquam ornare sapien non orci pellentesque, ac pretium felis finibus.
   Suspendisse potenti. Cras placerat lorem quis purus facilisis pretium. Ut blandit vehicula erat, eget rutrum elit tempus vitae. Nulla placerat aliquet consequat. Phasellus tempus odio et augue congue venenatis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In gravida, odio vitae porttitor gravida, est elit imperdiet orci, nec pretium lectus risus vitae purus. Aenean dictum nisi a orci aliquet, et scelerisque tortor tincidunt.

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed velit metus, euismod quis ante eleifend, tempor euismod turpis. Suspendisse a euismod nibh, nec viverra ipsum. Sed ullamcorper eros in nisi condimentum rhoncus. Nunc suscipit interdum ligula vel tempus. Donec tortor libero, gravida a condimentum at, lobortis at nibh. Pellentesque habitant.

    </fieldset>

A: How's this (comments in the code to what I have changed)

var right = $("#right_container"); // get your right container

$(window).scroll(function() {
  right.css("top", $(this).scrollTop()); // change it's top position - don't need to use animate otherwise it will be too slow
});
body {
  font-family: arial;
  margin: 0px;
}
.drag {
  cursor: move;
  margin: auto;
  background-color: white;
  text-align: center;
  font-size: 10pt;
  opacity: 0.7;
  width: 120px;
  min-height: 24px;
  line-height: 24px;
  border: 2px solid #800000;
}
#drag {
  margin: auto;
  width: 900px;
  display: table;
  position: relative;
  border: 1px solid #d9a300;
}
.list {
  border: 1px solid #00b359;
  min-height: 350px;
  width: 100%;
  position: relative;
  /* make this relative and not a table */
}
#left_container {
  /* remove float left */
  width: 450px;
  margin-right: 20px;
  border-bottom: 1px solid #F6F6F6;
  border: 1px solid #ff26ff;
}
#left {
  width: 100%;
  display: table-cell;
  border: 1px solid #2d00b3;
}
#right_container {
  position: absolute;
  /* remove float right and position this absolutely, remove margin right */
  top: 0;
  width: 300px;
  right: 20px;
  border-bottom: 1px solid #F6F6F6;
  border: 1px solid #ffff00;
}
#right {
  width: auto;
  background-color: #eee;
  border: 1px solid #AAAAAA;
}

  <fieldset>
    <legend>TITLE</legend>

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget erat non augue vestibulum fringilla. Maecenas fermentum ante mattis interdum vestibulum. Aliquam vel dui ac turpis consectetur accumsan quis eu libero. Sed finibus neque vel ipsum lacinia lobortis. Pellentesque lorem erat, ullamcorper vitae consectetur nec, tempor sit amet nisi. Aenean posuere ante egestas quam rhoncus, ut laoreet dui mattis. Quisque condimentum fermentum metus sit amet posuere. Ut sed lectus orci.
   Cras nec enim faucibus, consectetur eros ut, vulputate est. Maecenas sollicitudin vestibulum eros, sit amet porta enim molestie eget. Etiam commodo ex efficitur ligula ornare iaculis. Aliquam erat volutpat. Nullam mollis eleifend nisl a rhoncus. Sed egestas lacinia est ut mollis. Duis fermentum odio eget diam placerat, eu placerat sapien laoreet. Sed mollis leo id tortor dapibus, in finibus lacus aliquet. Donec semper vel libero eu placerat. Nam hendrerit pretium nunc, vel malesuada nisi tincidunt in. Duis ligula metus, dignissim ac laoreet in, aliquam et ipsum. Maecenas non condimentum leo. Morbi convallis turpis lobortis dignissim mattis.
   Quisque at hendrerit magna. Praesent id ligula eleifend, semper lacus sed, sagittis mauris. Nulla molestie tristique sem, non ultrices nisl mattis ut. Nulla ut nisi quis elit porta tempor. Duis semper sem tellus, nec viverra metus dignissim nec. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla libero lectus, iaculis sit amet enim eget, facilisis blandit enim. Ut dolor massa, imperdiet id lorem a, molestie vestibulum nulla. Fusce non condimentum purus, ut egestas mi. Ut lacinia rutrum nulla a convallis. Vestibulum ac metus urna. In hac habitasse platea dictumst. In ac eleifend mi.
   Duis at cursus mauris, non viverra ipsum. Sed facilisis, arcu eu aliquam volutpat, nisi leo interdum neque, in congue libero purus a eros. Pellentesque posuere tellus ut consequat dapibus. Ut dapibus ultrices sem, in posuere eros. Aliquam tincidunt, arcu a dignissim eleifend, urna diam pulvinar urna, non hendrerit lorem urna ac nibh. Cras eu feugiat enim. Aliquam ornare sapien non orci pellentesque, ac pretium felis finibus.
   Suspendisse potenti. Cras placerat lorem quis purus facilisis pretium. Ut blandit vehicula erat, eget rutrum elit tempus vitae. Nulla placerat aliquet consequat. Phasellus tempus odio et augue congue venenatis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In gravida, odio vitae porttitor gravida, est elit imperdiet orci, nec pretium lectus risus vitae purus. Aenean dictum nisi a orci aliquet, et scelerisque tortor tincidunt.

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed velit metus, euismod quis ante eleifend, tempor euismod turpis. Suspendisse a euismod nibh, nec viverra ipsum. Sed ullamcorper eros in nisi condimentum rhoncus. Nunc suscipit interdum ligula vel tempus. Donec tortor libero, gravida a condimentum at, lobortis at nibh. Pellentesque habitant.

    </fieldset>


text:
Q: Error: method in class cannot be applied to given types How do I get rid of this error?
It says:
required: double, double
found: no arguments
reason: actual and formal argument lists differ in length

Code:
public double computeBMI(double kg, double meter)
{
    double bmin;

    bmin= kg/(meter*meter);

    return bmin;
}

public static void main (String args[])
{
    BMI obj = new BMI();
    double bmin = obj.computeBMI();  //error appears here the period is highlighted.
    obj.checkStatus(bmin);
}

A: Well, your computeBMI method requires two doubles. You are not passing any, try entering two doubles in the empty brackets on your error line. The error message tells you just that.


text:
Q: making apache lenya work with mysql I am new to java ... As per the documentation of apache lenya It doesnot use db by default but it can be configured to use db.. can anyone suggest a manual for configuring apache lenya to work with mysql....?

A: Please see the below link, it might provide you a bit insights.
Click Here

A: I don't know of any installations going against a database. There certainly isn't anything in 2.0.3 that would make this easy to do, and would require a fairly extensive rewrite. There may be ways of accomplishing whatever it is that you're after without using a database.


text:
Q: JPA EclipseLink: handle default value I have the following column definition:
@Column(name="active", nullable=false, columnDefinition="BOOLEAN DEFAULT FALSE"
private Boolean active;

In the Postgres database the column active is defined as BOOLEAN NOT NULL DEFAULT FALSE
But when I insert a new record, without setting active, EclipseLink generates a null value for this field and the insert statement obviously fails because Postgres does not allow a null value for the NOT NULL column.
What am I doing wrong?
Well, if I define my field as
private boolean active;

then I will indirectly set the field to false. But I cannot use this trick with Date fields. So, I am looking for a solution which will work for all column types.

A: The columnDefinition is only used for the DDL creation and can be database specific. You may have problems switching the DB if you use it.
Using primitive types ensures that the value is not null, and without explicitly defining a value, the primitive's default is used. However, you can also define default values for non-primitive values by assigning them: private Boolean active = false;
That will also work with Date.
When you need complex default values you can use the PrePersist annotation:
    @PrePersist
    public void setDefaultValues() {
        if (active == null) {
            active = false;
        }
        if (value == null) {
           //do complex stuff
        }
    }

A: If you NEVER are going to set the attribute, you can use  @Column (insertable = false), if you set a value, this will be ignored anyway.
This is a very common setting on Date like
@Column(nullable = false, insertable = false, updatable = false, columnDefinition = "timestamp not null default CURRENT_TIMESTAMP")
    @Temporal(TemporalType.TIMESTAMP)
    private Date systemDate;


text:
Q: How to group the List of Lists by their Name in Java Suppose I have a class
class X {
    String name;
    int value;
}

and I am given multiple ArrayLists of these objects, as an example;
[{A,2}, {B,1}, {C,3}]
[{C,5}, {D,1}]
[{A,3}, {D,1}]

Now I want to merge the list with objects having same name and sum the values so that final output look like
[{A,5}, {B,1}, {C,8}, {D,2}]

This problem I solved using HashMaps (which is not requirement), I want to know if it is possible to merge the lists using list operations and get addition done on the field of the object and show output in ArrayList itself?

A: Extend ArrayList to build the merge capability.
package com.test;
import java.util.ArrayList;

public class MyArrayList<P> extends ArrayList<Pair> {
    public static void main(String[] args) {
       Pair p1 = new Pair ("A", 2);
       Pair p2 = new Pair ("B", 4);
       Pair p3 = new Pair ("C", 1);

       MyArrayList<Pair> l1 = new MyArrayList<Pair>();
       l1.add(p1);
       l1.add(p2);
       l1.add(p3);

       Pair p4 = new Pair ("A", 5);
       Pair p5 = new Pair ("C", 10);
       Pair p6 = new Pair ("D", 12);

       ArrayList<Pair> l2 = new ArrayList<Pair>();
       l2.add(p4);
       l2.add(p5);
       l2.add(p6);

       l1.merge(l2);
       System.out.println(l1.toJson());

    }

   @Override
   public boolean add(Pair e) {
       Pair p = this.getPair(e);
       if (p == null) return super.add(e);
       p.value += e.value;
       return true;
   }

   public void merge (ArrayList<Pair> list) {
       for(Pair p : list) this.add(p);
   }

   public String toJson() {
       StringBuffer s = new StringBuffer("[");
       for(Pair p : this) s.append("{\"name\":").append("\"").append(p.name).append("\",").append("\"value\":").append(p.value).append("},");
       return s.append("]").deleteCharAt(s.length()-2).toString();
   }

   private Pair getPair (Pair e) {
       for(Pair p : this) if (p.name.equals(e.name)) return p;
       return null;
   }
}

Pair Class
package com.test;
public class Pair {
   String name;
   int value;
   public Pair(String name, int value) {
      super();
      this.name = name;
      this.value = value;
   }
}

Here is the output
[{"name":"A","value":7},{"name":"B","value":4},{"name":"C","value":11},{"name":"D","value":12}]

A: You could use stream API, which available after JDK 8+.
As part of below given solution, first I'm merging all sub-list into one where main is the List, which contains List of Lists
  main.stream()
      .flatMap(List::stream)
      .collect(Collectors.toList())

Now, it will be easy to groupingby them by Name and count their values, which will return a Map
.stream()
.collect(Collectors.groupingBy(w -> w.getName(), Collectors.summingInt(w -> w.getValue())))

Now, combine all code together
    //create dummy List
    List<xyz> last = new ArrayList<>();

    //merge all list into one and they apply group by to sum
    Map<String, Integer> map = main.stream()
                                   .flatMap(List::stream)
                                   .collect(Collectors.toList())
                                   .stream()
                                   .collect(Collectors.groupingBy(w -> w.getName(), Collectors.summingInt(w -> w.getValue())));

Since, your final output is as List. So, we traverse though the map and add it to the List.
    //add into dummy List
    map.entrySet().stream().forEach((e) -> {
        last.add(new xyz(e.getKey(), e.getValue()));
    });

I would appreciate any suggestion and/or refinement(s).


text:
Q: Hibernate one to many mapping where one class has a composite primary key on many side I want to query two tables joined by inner join using hibernate.
Two tables are as follows.
CREATE TABLE systemuser (
    system_user_id INT(20) NOT NULL AUTO_INCREMENT,
    user_name VARCHAR(50) NOT NULL DEFAULT '0',
    PRIMARY KEY (system_user_id)
)
CREATE TABLE role (
    system_user_id INT(20) NOT NULL ,
    role_id INT(20) NOT NULL DEFAULT '0',
    PRIMARY KEY (system_user_id,role_id),
     CONSTRAINT FK_SYSTEM_USER_ID FOREIGN KEY (system_user_id) REFERENCES systemuser (system_user_id)
)
These two tables have a one to many relationship.
Bean classes for these tow are as follows.
@Entity(name = "role")
@IdClass(RoleCompositeKey.class)

public class Role extends implements java.io.Serializable {

private int roleId =0;
private int systemUserId =0;
private SystemUser systemUser;

public Role(){

}

public void setRoleId(int roleId){
 this.roleId = roleId;
}

@Id
@Column(name = "role_Id")
public int getRoleId(){
    return roleId;
}

public void setSystemUserId(int systemUserId){
    this.systemUserId = systemUserId;
}

@Id
@Column(name="system_user_id")
public int getSystemUserId(){
    return systemUserId;
}

public void setSystemUser(SystemUser systemUser){
    this.systemUser= systemUser;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "system_user_id", nullable = false)
public SystemUser getSystemUser(){
    return systemUser;
}

}

@Entity
@Table(name = "systemuser",uniqueConstraints = {
    @UniqueConstraint(columnNames = "system_user_id"),
    @UniqueConstraint(columnNames = "user_name") })

public class SystemUser {

private int systemUserId = 0;
private String userName            = null;

private Set<Role> roleList;

public SystemUser(){

}

public void setUserName(String userName) {
    this.userName = userName;
}

@Column(name = "user_name")
public String getUserName() {
    return userName;
}

public void setSystemUserId(int systemUserId){
    this.systemUserId = systemUserId;
}

@Id
@Column(name="system_user_id")
public int getSystemUserId(){
    return systemUserId;
}

public void setRole(Set<Role> roleList){
    this.roleList = roleList;
}

@OneToMany(fetch = FetchType.LAZY, mappedBy = "systemUser")
public Set<Role> getRole(){
    return roleList;
}
}

but I'm getting an error saying
"........Constructor threw exception; nested exception is org.hibernate.MappingException: Repeated column in mapping for entity: ....beans.Role column: system_user_id (should be mapped with insert="false" update="false")"
Please can anyone help me? Any help is highly appreciated!
Thanks in advance!

A: "Repeated column in mapping for entity". You declare in role, the relationship two times. Remove this one.
    @Id
   @Column(name="system_user_id")
   public int getSystemUserId(){
        return systemUserId;
   }

And just leave this one
        @ManyToOne(fetch = FetchType.LAZY)
       @JoinColumn(name = "system_user_id", nullable = false)
       public SystemUser getSystemUser(){
           return systemUser;
       }


text:
Q: Pandas split DataFrame by column value I have DataFrame with column Sales.
How can I split it into 2 based on Sales value?
First DataFrame will have data with 'Sales' < s and second with 'Sales' >= s

A: Using groupby you could split into two dataframes like
In [1047]: df1, df2 = [x for _, x in df.groupby(df['Sales'] < 30)]

In [1048]: df1
Out[1048]:
   A  Sales
2  7     30
3  6     40
4  1     50

In [1049]: df2
Out[1049]:
   A  Sales
0  3     10
1  4     20

A: I like to use this for speeding up searches or rolling average finds .apply(lambda x...) type functions so I split big files into dictionaries of dataframes:
df_dict = {sale_v: df[df['Sales'] == sale_v] for sale_v in df.Sales.unique()}

This should do it if you wanted to go based on categorical groups.

A: Using groupby and list comprehension:
Storing all the split dataframe in list variable and accessing each of the seprated dataframe by their index.
DF = pd.DataFrame({'chr':["chr3","chr3","chr7","chr6","chr1"],'pos':[10,20,30,40,50],})
ans = [y for x, y in DF.groupby('chr')]

accessing the separated DF like this:
ans[0]
ans[1]
ans[len(ans)-1] # this is the last separated DF

accessing the column value of the separated DF like this:
ansI_chr=ans[i].chr

A: You can use boolean indexing:
df = pd.DataFrame({'Sales':[10,20,30,40,50], 'A':[3,4,7,6,1]})
print (df)
   A  Sales
0  3     10
1  4     20
2  7     30
3  6     40
4  1     50

s = 30

df1 = df[df['Sales'] >= s]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

df2 = df[df['Sales'] < s]
print (df2)
   A  Sales
0  3     10
1  4     20

It's also possible to invert mask by ~:
mask = df['Sales'] >= s
df1 = df[mask]
df2 = df[~mask]
print (df1)
   A  Sales
2  7     30
3  6     40
4  1     50

print (df2)
   A  Sales
0  3     10
1  4     20

print (mask)
0    False
1    False
2     True
3     True
4     True
Name: Sales, dtype: bool

print (~mask)
0     True
1     True
2    False
3    False
4    False
Name: Sales, dtype: bool

A: One-liner using the walrus operator (Python 3.8):
df1, df2 = df[(mask:=df['Sales'] >= 30)], df[~mask]

Consider using copy to avoid SettingWithCopyWarning:
df1, df2 = df[(mask:=df['Sales'] >= 30)].copy(), df[~mask].copy()

Alternatively, you can use the method query:
df1, df2 = df.query('Sales >= 30').copy(), df.query('Sales < 30').copy()


text:
Q: Excel VBA. Compare if all letters in a string is in another string I would like to compare if a string has all the characters of another string.
Example:
String 1
Hejslclo
String 2
Hello
True string 2 has all the characters of string one.
I have turned string 1 into an array and I think there should be a loop to check using Instr
My first attempt at this:
Sub StringintoArray()

Dim Temp As String

Dim MyString As String

Dim String2 As String

MyString = "Heaslsflo"

String2 = "Hello"

Temp = StrConv(MyString, vbUnicode)

Temp = Left(Temp, Len(Temp) - 1)

aLetter = Split(Temp, Chr(0))

'Dim StartRow As Integer

Dim i As Integer

 For i = 0 To L(Temp)

   If InStr(i, String2, aLetter(I)) <> 0 Then

        MsgBox ("Yes")

   Else

       MsgBox ("No")

   End If

Next i

End Sub

A: Ok - I got bored and bit. Had a look at your code, you were very nearly there.
Think this should do what you want
Option Explicit
Public Function CompareStrings(string1 As String, string2 As String) As Boolean
    Dim i As Long, j As Long, k As Long
    Dim arr1 As Variant, arr2 As Variant

    ' Set to default
    CompareStrings = False

    ' Split strings into arrays
    arr1 = Split(StrConv(string1, vbUnicode), Chr(0))
    arr2 = Split(StrConv(string2, vbUnicode), Chr(0))
    ' Initialise counter
    k = 0
    ' Loop over both arrays
    For i = LBound(arr2) To UBound(arr2)
        For j = LBound(arr1) To UBound(arr1)
            If LCase(arr2(i)) = LCase(arr1(j)) Then
                k = k + 1
                Exit For
            End If
        Next j
    Next i
    ' Test if counter is equal to array length and set answer if so
    If k - 1 = UBound(arr2) Then CompareStrings = True
End Function

Public Sub TestComparison()
    Dim string1 As String, string2 As String
    string1 = "Hello"
    string2 = "Hejslclo"
    If CompareStrings(string1:=string1, string2:=string2) Then
        Debug.Print string1; " contains "; string2
    Else
        Debug.Print string1; " does not contain "; string2
    End If
End Sub


text:
Q: PHP - get unique strings from array I am new to this place and I have a question about PHP that I can't figure out.
What I am trying to do is create an array of strings, but that's not the problem. The problem is I have no idea how to get the only string that I need.
Example code:
$array = [];
$array[$game] = $string;

I want to keep creating strings for one single game but there will but more and more strings coming in the array from different games. I want to get only the ones from a single game, I don't know if you get what I'm talking about but I hope so because I'm frustrated that I can't figure out a way.

A: You have to create sub array for each game then set strings inside
// checking it sub array already not exits to not overwrite it
if( isset($array[$game]) ){
    $array[$game] = array();
}

then only insert your string inside it
$array[$game][] = $string1;
$array[$game][] = $string2;
...

as result you will have
array('somegame' => array(
                         0 => "some game string 1",
                         1 => "some game string 2",
                         ...
                    )
)

A: Your question is too simple.
You are already appending the strings to array by the key of game id.
$array = [];
$array[$game] = $string;

So, your array will look like:
array(
  1 => array('string 1', 'string 2'),
  2 => array('string 3', 'string 4'),
  3 => array('string 5', 'string 6'),
  //..... and more
)

Where keys 1, 2 and 3 are the game ids.
If you want to retrieve the keys in case of game ids 1 and 2:
$game = 1;
$gameStringsOne = $arr[$game];

$game = 2;
$gameStringsTwo = $arr[$game];

A: Use multi-dimensional array like
$array = [];
$array[$game] = [ $string1, $string2 ];

A: Read the docs Use a multi-dimentional array, push strings to an array and then assign that to another array, that way you can have multiple strings to a game
<?php
    $stringArray = array("str","str2");
    // if needed do array_push($stringArray,"str3","str4");
    array_push($gamelist['game'], $stringArray);
?>

get an array of strings when acessing game from gamelist
read more


text:
Q: How do I save a new graph as png with every iteration of a loop I don't know how to save a new graph png for each iteration of a loop using NetworkX.  I've borrowed the code from this question: in NetworkX cannot save a graph as jpg or png file and manipulated it a bit.  Below is the code:
import networkx as nx
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(12,12))
ax = plt.subplot(111)
ax.set_title('Graph - Shapes', fontsize=10)

G = nx.DiGraph()
G.add_node('shape1', level=1)
G.add_node('shape2', level=2)
G.add_node('shape3', level=2)
G.add_node('shape4', level=3)
G.add_edge('shape1', 'shape2')
G.add_edge('shape1', 'shape3')
G.add_edge('shape3', 'shape4')
pos = nx.spring_layout(G)
n = 0
colorses = ['yellow', 'red', 'blue', 'green']
while n < len(colorses):
    nx.draw(G, pos, node_size=1500, node_color=colorses[n], font_size=8, font_weight='bold')
    plt.tight_layout()
    # plt.show()
    plt.savefig("Graph.png", format="PNG")
    n += 1

Ideally I would like to have four images each one with different color nodes.  Let me know if you need any more information.  Thanks!

A: Just change the name of the output file
while n < len(colorses):
    nx.draw(G, pos, node_size=1500, node_color=colorses[n], font_size=8, font_weight='bold')
    plt.tight_layout()
    # plt.show()
    plt.savefig("Graph" + str(n) +".png", format="PNG")
    n += 1

You should use more descriptive names though.  Maybe instead of n, you could refer to a time
    plt.savefig("Graph" + str(datetime.datetime.now()) +".png", format="PNG")

That isn't great, since the string will have whitespace, but you can tweak it beforehand

A: First suggestion, accessing the colors by their index values is not "Pythonic". Instead, use a for loop:
for color in colors:
    print(color)

Your code is overwriting Graph.png on each iteration of the loop. To save a new file for each iteration, simply rename the output file on each iteration. One way to do this is by using the format() and enumerate() functions:
import networkx as nx
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(12,12))
ax = plt.subplot(111)
ax.set_title('Graph - Shapes', fontsize=10)

G = nx.DiGraph()
G.add_node('shape1', level=1)
G.add_node('shape2', level=2)
G.add_node('shape3', level=2)
G.add_node('shape4', level=3)
G.add_edge('shape1', 'shape2')
G.add_edge('shape1', 'shape3')
G.add_edge('shape3', 'shape4')
pos = nx.spring_layout(G)
colors = ['yellow', 'red', 'blue', 'green']
for i, color in enumerate(colors):
    nx.draw(G, pos, node_size=1500, node_color=color, font_size=8, font_weight='bold')
    plt.tight_layout()
    plt.savefig('Graph_{}.png'.format(i), format="PNG")

A: By the way, I just used this method and I added a step futher for my labels to be from my filename. I hope it helps someone.
    files = glob.glob(folder+'\\'+'*.csv', recursive=False)
    for file in files:
        df1=pd.read_csv(file,header=1,sep=',')
        nslice = (sum(1 for line in open(file))-1)/3
        base = print(os.path.splitext(os.path.basename(file))[0])
        fig = plt.figure()
        ax = plt.subplot(111)
        c = ax.plot(df1.iloc[0:int(nslice)-1,[22]],df1.iloc[0:int(nslice)-1,[4]],label='Cuticle')
        t = ax.plot(df1.iloc[int(nslice):(int(nslice)-1)*2,[22]],df1.iloc[int(nslice):(int(nslice)-1)*2,[4]],label='Tissue')
        p = ax.plot(df1.iloc[int(nslice)*2:(int(nslice)-1)*3,[22]],df1.iloc[int(nslice)*2:(int(nslice)-1)*3,[4]],label='Phenanthrene')
        title_obj = plt.title(base)
        plt.xlabel("Slice #")
        plt.ylabel("Avg MGV")
        ax.legend()
        plt.savefig('plot'+str(os.path.splitext(os.path.basename(file))[0])+'.png')
        plt.show()
        plt.close('all')

Peace


text:
Q: Parameter value depending on another parameter in reports i have a dropdown as parameter in my report which contain 3 values: value1 value2 and none. on clicking on value1 i want another parameter to appear as below:
enter image description here
If i click on none then nothing should display.  Is it possible to achieve this by using filter/dataset? i am not sure how to do it. Any help will be really appreciated. Thanks

A: You cannot change the names or captions of the parameter drop down control at run time. So you cannot have the second parameter labelled as 'Value 1' if 'Value 1 was selected in your first parameter.
You can however, control what is shown in your second parameter and have the list of items be dependent on your first parameter value.
For example, lets say we had a table called products that contained the following..

ProdID
Category
Colour
Location

1
Bike
Red
A

2
Bike
Blue
A

3
Bike
Green
A

4
Car
Red
A

5
Car
Red
B

6
Car
Blue
B

7
Boat
Red
A

8
Boat
White
A

9
Boat
Blue
A

If your first parameter was called p1 had the following value, caption pairs
1 = Category
2 = Colour
3 = Location

Then the dataset query for the seconds parameter would be something like
SELECT DISTINCT
    CASE @p1
        WHEN 1 THEN [Category]
        WHEN 2 THEN [Colour]
        WHEN 3 THEN [Location]
    END as pValues
    FROM [products]
    ORDER BY 1;

If this does not help, please edit your question and explain exactly what you are trying to achieve.


text:
Q: SQL Server Failover Cluster Setup Report Purpose: to find all the SQL Server Failover Cluster installation details for an existing cluster setup. I am trying to document the process for disaster recovery purposes and recreate a mirrored setup on a different group of servers.
(SQL Server 2012)
I am looking for a way to generate a report of all the setup details pertaining to the initial installation of a SQL Server Failover Cluster. Something akin to the SQL Discovery report that details all installed SQL Server features.
In this case, I'd like a report that shows all the details chosen when going through the initial setup wizard for the initial SQL Cluster setup. A report that shows the features selected, instance names, disk assignment, network configuration, etc. Just a summary of every section of the install wizard would be perfect. The Cluster Manager does not display all of the information I need.
Does such a thing exist? If I can't auto generate a report. Is there a log file somewhere that would detail the initial setup?
I have scoured the internet, but there are just too many keywords to return concise results. I'm looking for details of the SQL Cluster setup, not the Windows Cluster setup. I've had my fill of irrelevant articles, and I'm turning to the Stack Overflow community for help!
EDIT:
This query as provided some insight, but it's lacking. I'm looking for something more complete.
SELECT
    SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS ComputerNamePhysicalNetBIOS,
    SERVERPROPERTY('MachineName') AS MachineName,
    SERVERPROPERTY('ServerName') AS ServerName,
    SERVERPROPERTY('Collation') AS Collation,
    SERVERPROPERTY('IsClustered') AS IsClustered

Also, these catalog views have provided some insight.

sys.dm_server_services, sys.configurations, sys.dm_server_registry, sys.dm_server_services, sys.dm_os_cluster_nodes, sys.servers


text:
Q: Using switch-case in manipulating radio button values I have this code that gets the values of the selected radio buttons and is supposed to tally them using a switch-case, then find out which has the highest value. However I am stuck in the switch statement as whenever the value goes inside it, it turns into NaN or undefined. I have tried to use parseInt, but still, whenever it goes inside the switch-case, it ruins the value I have got.
Here is the JS:
$('#submit').click(function() {
    var choice1, choice2, choice3, choice4, choice5, choice6;

    if (($("input[name='qa1']:checked").length == "0")){
        alert("ANSWER ALL QUESTIONS!");
    }

    else{
        var answer1 = parseInt($("input[name='qa1']:checked").val());

        switch(answer1){
            case 1: choice1++;
                    break;
            case 2: choice2++;
                    break;
        }
        alert(choice1);
//Closing braces

Sample HTML:

        <input type="radio" class="button" id="btn1" name="qa1" value="1">

        <input type="radio" class="button" id="btn2" name="qa1" value="2">

<input type="button" id="submit" name="submit" value="View Result" />

Can anyone help me?

A: THis is because you have to assign values like:
var choice1=0, choice2=0, choice3=0, choice4=0, choice5=0, choice6=0;

You have not assigning values to variables but increasing them that's why they showing you NAN
DEMO


text:
Q: How to add a default name space with dom4j? I would like to add a default name space to the root element of a XML document using dom4j, like in the following snippet. What is the correct way to do this with dom4j?
<?xml version="1.0" encoding="utf-8" ?>
<animals xmlns="http://zoo.domain.org/schema/animals" >
    <animal id="1">
        <elephant>
            <name>Jumbo</name>
        </elephant>
    </animal>
</animals>

The dom4j API does provide the method Element#addNamespace but the javadoc tells that the prefix may not be blank.
The following code will result in the expected namespace for animals though:
Document document = DocumentHelper.createDocument();
Element animals = document.addElement("animals")
        .addNamespace("", "http://zoo.domain.org/schema/animals");
Element animal = animals.addElement("animal")
        .addAttribute("id", "1");
animal.addElement("elephant")
        .addElement("name")
        .addText("Jumbo");

// write document to file etc.
...

... but the child element animal gets an empty string as default namespace, which is not what I want:
<?xml version="1.0" encoding="UTF-8"?>
<animals xmlns="http://zoo.domain.org/schema/animals">
    <animal xmlns="" id="1">
        <elephant>
            <name>Jumbo</name>
        </elephant>
    </animal>
</animals>

A: The method Document#addElement (but also Element#addElement) accepts a second parameter namespaceURI. That does the trick, adding the default namespace to the XML element.
The following code will result in the expected XML.
Document document = DocumentHelper.createDocument();
Element animals = document.addElement("animals", "http://zoo.domain.org/schema/animals");
Element animal = animals.addElement("animal")
        .addAttribute("id", "1");
animal.addElement("elephant")
        .addElement("name")
        .addText("Jumbo");

// write document to file etc.
...

Also worth mentioning is that in case you would like to create an Element on its own DocumentFactory#createElement has an overloaded version that accepts a namespaceURI as well. DocumentHelper#createElement does not have such an overloaded method.

A: You are not creating the document (root) element.
Document document = DocumentHelper.createDocument();
Element root = document.addElement( "animals" );
// TODO the rest of your code

Eventually, you'll pass your document to an XML writer to write (save) the document. Also, from Javadoc:

Element addNamespace(java.lang.String prefix, java.lang.String uri)
Adds a namespace to this element for use by its child content
Parameters:
prefix - is the prefix to use, which should not be null or blank

One thing you could try is create an instance of Namespace passing a empty String to the constructor and use the Element.add() method instead. The Javadoc of Namespace doesn't indicate that the prefix can't be blank.


text:
Q: hypsometric colors alà IMHOF, SYDOW or PEUCKNER I need a hypsometric color-map to add it to my multishade-model. (High Mountain between 800 and 4000m) There are a lot of different types explained in IMHOFS "Cartographic Relief Presentation". I want to do it traditionally... :-)
So, where can I find "prebuild" colormaps alà PEUCKNER, IMHOF or SYDOW? (I don't like the "Terrain" or "SRTM" ones from Grass)

A: If you're using gdaldem color-relief there is a colour ramp somewhere near the bottom of this page:
http://fr.wikipedia.org/wiki/Aide:Cartographie
It's not bad for some purposes, but not wonderful. Better perhaps with the colours faded a little? As you know, EI suggests elevation intervals in the sequence 0,25,50,100,250,500,1000...x, it might be possible to sort out some suitable colours from the above ramp. Nick.