问:
Problems with SQL, Arel and filtering out records. Rails. Could use some advice
I suck so bad at SQL and Arel. I don't even know what Arel is or how to use it. Is there a good resource on this?

I have a an issue that I don't know why it took me so long. Perhaps people can point out why this takes me so long to do.

Anyway, I have a Products table and a Restrictions table. A product can have many restrictions. A restriction is a US state. Most of my products have no restrictions, but one of my products has a restriction (it cannot be sold in "CT" because "CT" has insane laws).

I want to return back all products that don't have a restriction in CT. However, this query did not work:

Product.joins(:restrictions).where.not(restrictions: { name: "CT" }).count

So I was expecting that to return all my products except for the ones product with a restriction to CT. However, it returns nothing:

```<code> Product.last.restrictions
  Product Load (0.5ms)  SELECT  "products".* FROM "products"  ORDER BY "products"."id" DESC LIMIT 1
  Restriction Load (0.3ms)  SELECT "restrictions".* FROM "restrictions" INNER JOIN "product_restrictions" ON "restrictions"."id" = "product_restrictions"."restriction_id" WHERE "product_restrictions"."product_id" = $1  [["product_id", 2559]]
[
  #<Restriction:0x007ff0f1dfec58> {
            :id => 11,
      :category => "US State",
          :name => "CT",
    :created_at => Wed, 07 Jun 2017 17:57:42 UTC +00:00,
    :updated_at => Wed, 07 Jun 2017 17:57:42 UTC +00:00
  }
]
[48] pry(main)> Product.count
   (0.6ms)  SELECT COUNT(*) FROM "products"
2494
[49] pry(main)> Product.joins(:restrictions).where.not(restrictions: { name: "AZ" }).count
   (47.8ms)  SELECT COUNT(*) FROM "products" INNER JOIN "product_restrictions" ON "product_restrictions"."product_id" = "products"."id" INNER JOIN "restrictions" ON "restrictions"."id" = "product_restrictions"."restriction_id" WHERE ("restrictions"."name" != $1)  [["name", "AZ"]]
1
[50] pry(main)> Product.joins(:restrictions).where.not(restrictions: { name: "CT" }).count
   (6.7ms)  SELECT COUNT(*) FROM "products" INNER JOIN "product_restrictions" ON "product_restrictions"."product_id" = "products"."id" INNER JOIN "restrictions" ON "restrictions"."id" = "product_restrictions"."restriction_id" WHERE ("restrictions"."name" != $1)  [["name", "CT"]]
0
</code>```

I expected the last query to return 2493 (only that last product has a restriction), not 0. I expected the AZ query to return 2494, not 0.

However, this hood sql works (using NOT EXISTS):

```<code>state = "CT"
Product.where('NOT EXISTS ' \
    '(SELECT 1 from restrictions
        JOIN product_restrictions
          on product_id = products.id
        WHERE restrictions.name = ? AND restrictions.category = ?)', state, 'US State'
    )
  }
</code>```

The aboe query returns back all products EXCEPT for the one with the restriction in CT

Questions

Why does my first query using joins not work?

How do I get better here? Is there a good book on sql?

Is there a better way to write my solution not using like SQL strings?

答:
When you do an INNER JOIN, it creates a join table where it will have entries only for product with associated restrictions. "products without restriction" or "restriction without product_id" will not be included in that.

In the question you mention that "only that last product has a restriction". So when you did a JOIN, it created only 1 entry in the join table, and you got rid of that when you further added the condition on restriction's name. Hence final result is empty.

If you want to include products in the join table even if they do not have a associated restriction, use LEFT OUTER JOIN.
Here is a useful link - Inner Join vs Left Outer Join

Solution:
if using rails5:-

```<code>Product.left_outer_joins(:restrictions).where.not(restrictions: { name: "CT" }).count
</code>```

else

```<code>Product.joins("LEFT OUTER JOIN restrictions on restrictions.product_id = products.id").where.not(restrictions: { name: "CT" }).count
</code>```

Body:
I suck so bad at SQL and Arel. I don't even know what Arel is or how to use it. Is there a good resource on this?

I have a an issue that I don't know why it took me so long. Perhaps people can point out why this takes me so long to do.

Anyway, I have a Products table and a Restrictions table. A product can have many restrictions. A restriction is a US state. Most of my products have no restrictions, but one of my products has a restriction (it cannot be sold in "CT" because "CT" has insane laws).

I want to return back all products that don't have a restriction in CT. However, this query did not work:

Product.joins(:restrictions).where.not(restrictions: { name: "CT" }).count

So I was expecting that to return all my products except for the ones product with a restriction to CT. However, it returns nothing:

 Product.last.restrictions
  Product Load (0.5ms)  SELECT  "products".* FROM "products"  ORDER BY "products"."id" DESC LIMIT 1
  Restriction Load (0.3ms)  SELECT "restrictions".* FROM "restrictions" INNER JOIN "product_restrictions" ON "restrictions"."id" = "product_restrictions"."restriction_id" WHERE "product_restrictions"."product_id" = $1  [["product_id", 2559]]
[
  #<Restriction:0x007ff0f1dfec58> {
            :id => 11,
      :category => "US State",
          :name => "CT",
    :created_at => Wed, 07 Jun 2017 17:57:42 UTC +00:00,
    :updated_at => Wed, 07 Jun 2017 17:57:42 UTC +00:00
  }
]
[48] pry(main)> Product.count
   (0.6ms)  SELECT COUNT(*) FROM "products"
2494
[49] pry(main)> Product.joins(:restrictions).where.not(restrictions: { name: "AZ" }).count
   (47.8ms)  SELECT COUNT(*) FROM "products" INNER JOIN "product_restrictions" ON "product_restrictions"."product_id" = "products"."id" INNER JOIN "restrictions" ON "restrictions"."id" = "product_restrictions"."restriction_id" WHERE ("restrictions"."name" != $1)  [["name", "AZ"]]
1
[50] pry(main)> Product.joins(:restrictions).where.not(restrictions: { name: "CT" }).count
   (6.7ms)  SELECT COUNT(*) FROM "products" INNER JOIN "product_restrictions" ON "product_restrictions"."product_id" = "products"."id" INNER JOIN "restrictions" ON "restrictions"."id" = "product_restrictions"."restriction_id" WHERE ("restrictions"."name" != $1)  [["name", "CT"]]
0

I expected the last query to return 2493 (only that last product has a restriction), not 0. I expected the AZ query to return 2494, not 0.

However, this hood sql works (using NOT EXISTS):

state = "CT"
Product.where('NOT EXISTS ' \
    '(SELECT 1 from restrictions
        JOIN product_restrictions
          on product_id = products.id
        WHERE restrictions.name = ? AND restrictions.category = ?)', state, 'US State'
    )
  }

The aboe query returns back all products EXCEPT for the one with the restriction in CT

Questions

Why does my first query using joins not work?

How do I get better here? Is there a good book on sql?

Is there a better way to write my solution not using like SQL strings?

Body:
When you do an INNER JOIN, it creates a join table where it will have entries only for product with associated restrictions. "products without restriction" or "restriction without product_id" will not be included in that.

In the question you mention that "only that last product has a restriction". So when you did a JOIN, it created only 1 entry in the join table, and you got rid of that when you further added the condition on restriction's name. Hence final result is empty.

If you want to include products in the join table even if they do not have a associated restriction, use LEFT OUTER JOIN.
Here is a useful link - Inner Join vs Left Outer Join

Solution:
if using rails5:-

Product.left_outer_joins(:restrictions).where.not(restrictions: { name: "CT" }).count

else

Product.joins("LEFT OUTER JOIN restrictions on restrictions.product_id = products.id").where.not(restrictions: { name: "CT" }).count


来源: stackexchange

问:
QuickBase: Creating multiple rows in another table based on the contents of a report
Okay, so the setup here might be a little bit long, but I'll try and get to the punch line.

Essentially, I'm trying to enhance QuickBase in order to accommodate tracking of compensation history for employees. Approval for comp changes is done on a quarterly basis, for employees with an anniversary date that falls in that quarter. The idea is that managers would pull up a report with all relevant reviewees for that quarter, enter in their proposed comp changes, and then that would go on to the approvers for confirmation.

To accomplish this, we have an "Employees" table related to a "Comp Records" table, one to many. An example of a Comp Record would be Bob's Q1/2015 review, his Q1/2016 review, his Q3/2016 merit increase, and his Q1/2017 review, etc.

My hope is that the act of filling in proposed compensation changes is a matter of doing a grid-edit of comp records, fill in the proposed "new salary", and hit save. Sounds easy enough.

It's easy enough to create a report around "Employees" that shows all employees with an anniversary date in the coming quarter.
It's easy enough to create a report of all "Comp Records" for a given time period, for a given location, or for a given approver.

However, the problem is that if there are (for example) 20 people up for review in Q2, we'd need to generate 20 blank "Comp Records" for the appropriate dates, for those specific Employees. In other words, I don't necessarily want people to have to go in and hit "New Comp Record", pick an employee name, fill in the information, and hit save, 20 times.

I know the HTTP API has an Add Record function which I've seen other people drive via a button within QuickBase. That doesn't seem to handle it for more than one Employee at a time.

I've also seen that it's possible to host pages within QB and embed javascript on those pages in order to do the dirty work. That seems more likely a solution, but I'm not entirely sure how to go about using this.

Is there a way to use JS to query from QB "all Employee IDs for Employees that have an anniversary date in the coming quarter" and then loop through that list using Add Record to add Comp Records for each employee? I think an example of this is really the core of what I'm looking for.

In that case, I would end up with a button something to the effect of "Start Q2 Comp Reviews", click it one time to add the appropriate blank records, then let managers start filling in their proposed changes. That seems like a pretty reasonable experience.

If there's a more graceful overall solution, I'm also open to that.
Any help is much appreciated :)

答:
Not sure if this is helpful, but saw it when I was looking for an answer to a question I had and had a thought, so I figured I'd share. I agree generally that if you want to generate multiple records programmatically, you generally end up going with embedded javascript. That being said,  two potential alternatives:

Possible

QuickBase Actions - if you're guaranteed to have a record modification (or can force one), then you can use the new QuickBase actions to generate a child record. This is a longer shot, but would be nice if you've got

Better

Editable Embedded Forms - you've mentioned using the grid edit function to add records. If you're open to using grid edit functionality, what you could do is:

Create a new form for employees, which displays only information you want them to view / edit while doing a compensation review

Create an report on the compensation history table which shows the subset of records for an employee you want them to see when adding a new record

embed this report on the form you created above, marking it as "editable"

Create a button for the "employees up for review report" which takes you to the employee's record, and the form you created above

I think editable embedded forms are probably the way to go to get closest to your workflow without custom scripting. That way, a manager can create new records without either the add button or custom scripts. Yeah, it's another click, but a) you can show them other info you'd want them to take into consideration when filling it in, and b) it avoids the custom scripting.

ContentLicense: CC BY-SA 3.0


问:
Is there a visual studio template for creating client side typescript apps without asp.net et al
I want to create a client side app  (AKA a website) without server side be it in Node or ASP.net. Right now I do it by creating a ASP.NET and ignoring all the C# and that is problematic.</p>

答:
Visual Studio 2015 used to have a template for an HTML application with TypeScript. For VS2017 you can get it from here:

https://marketplace.visualstudio.com/items?itemName=Rich-Newman.TypeScriptHTMLApplicationTemplate


问:
Lint node.js code on save
I want to lint my node.js code when saving the file (so I don't have to to run npm run eslint manually). If I were to write the frontend, I'd use webpack to bundle and lint my files on save. However, as I currently don't need to bundle my Node.js code (or do I?), I'm not sure if this is the way to go or if I have any other alternative?

How is this usually done with Node.js? I wasn't able to find any answer to that question using Google's or Stackoverflow's search but I might have looked for the wrong thing.

答:
You could use gulp or grunt or any other build tool to watch your project and run es-lint on save.

Or you could just use a text-editor or ide with a js-lint plugin.

Title: Lint node.js code on save


问:
How to reset Google Cloud Shell user persistent disk?
Ok, folks.  Pushing the limits (of my understanding), I've broken my Google Cloud Shell on Google Cloud Platform.  I can no longer open a shell session.

When I click the shell icon >_ on the tool bar, the shell opens on the lower half of the screen for a moment, stating it is provisioning the instance (if it has been over an hour), established a connection, and then poof, it closes.

I was able to time a screen capture just right to see the following:

```<code>Welcome to Cloud Shell! For help, visit https://cloud.google.com/cloud-shell/help.
-bash: /usr/bin/zsh: No such file or directory
</code>```

I am pretty sure this relates to a naive attempt to install zsh ON A DIFFERENT PROJECT.  My theory is that the 5Gb of persistent disk storage provided by Cloud Shell is per user, not per user per project.  Therefore, my home directory is borked and will no longer load because the OS modifications are not persisted, only user home directories, and my .bashrc now references non-existent files.

So my question is this:  How do I start over, or wipe out the existing persistent disk and settings to obtain a working Shell again?

答:
You can reset the cloud shell like this

Restore your Cloud Shell home directory to a clean state:

Check for personal files in the home directory:

ls -a $HOME

Remove all files from your home directory:

sudo rm -rf $HOME

In the Cloud Shell menu, click the gear icon, then click Restart Cloud Shell. Click Restart Cloud Shell in the confirmation dialog.

From the docs https://cloud.google.com/shell/docs/limitations#resetting_cloud_shell_to_default_state

Body:
Ok, folks.  Pushing the limits (of my understanding), I've broken my Google Cloud Shell on Google Cloud Platform.  I can no longer open a shell session.

When I click the shell icon >_ on the tool bar, the shell opens on the lower half of the screen for a moment, stating it is provisioning the instance (if it has been over an hour), established a connection, and then poof, it closes.

I was able to time a screen capture just right to see the following:

Welcome to Cloud Shell! For help, visit https://cloud.google.com/cloud-shell/help.
-bash: /usr/bin/zsh: No such file or directory

I am pretty sure this relates to a naive attempt to install zsh ON A DIFFERENT PROJECT.  My theory is that the 5Gb of persistent disk storage provided by Cloud Shell is per user, not per user per project.  Therefore, my home directory is borked and will no longer load because the OS modifications are not persisted, only user home directories, and my .bashrc now references non-existent files.

So my question is this:  How do I start over, or wipe out the existing persistent disk and settings to obtain a working Shell again?


问:
using data from java classes and methods
i have an entry level question:

if there is external java class let's say 'Class1' inside this class there is a method called 'method1' inside this method there is Override method 'onResponse' inside this method two variables is being set 'a' and 'b'.

in the android mainActivity i called the method from the class like this:

```<code>Class1.method1();
</code>```

after calling the method how i can retrieve these variables to be used in mainActivity...

thanks..

```<code>public abstract class Class1 extends Context {

final Context mcontext;

public static void method1(final Context mcontext, final String x){

    StringRequest stringRequest = new StringRequest(Request.Method.POST, constants.URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {

                        JSONObject parentObject = new JSONObject(response);
                        JSONObject userDetails = parentObject.getJSONObject("data");

                        //read attributes
                        String a = userDetails.getString("a");
                        String b = userDetails.getString("b");

                    } catch (JSONException e) {

                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(mcontext, error.getMessage() ,Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params = new HashMap<>();
            params.put("x", x);
            return params;
        }
    };

    requestHandler.getInstance(mcontext).addToRequestQueue(stringRequest);
}
</code>```

答:
if you want to return more than one value you should use Android ways called Intent
but if you insist
you can use Array or ArrayList return type for the inner inner method

```<code>  class Class1{
     public static ArrayList<Object> method1(){
         return onResponse();
}
public static ArrayList<Object> onResponse(){
return arrayList<Object>;
</code>```

}
    }

but still i see no reason to not use Intent

Body:
i have an entry level question:

if there is external java class let's say 'Class1' inside this class there is a method called 'method1' inside this method there is Override method 'onResponse' inside this method two variables is being set 'a' and 'b'.

in the android mainActivity i called the method from the class like this:

Class1.method1();

after calling the method how i can retrieve these variables to be used in mainActivity...

thanks..

public abstract class Class1 extends Context {

final Context mcontext;

public static void method1(final Context mcontext, final String x){

    StringRequest stringRequest = new StringRequest(Request.Method.POST, constants.URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {

                        JSONObject parentObject = new JSONObject(response);
                        JSONObject userDetails = parentObject.getJSONObject("data");

                        //read attributes
                        String a = userDetails.getString("a");
                        String b = userDetails.getString("b");

                    } catch (JSONException e) {

                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(mcontext, error.getMessage() ,Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params = new HashMap<>();
            params.put("x", x);
            return params;
        }
    };

    requestHandler.getInstance(mcontext).addToRequestQueue(stringRequest);
}

Body:
if you want to return more than one value you should use Android ways called Intent
but if you insist
you can use Array or ArrayList return type for the inner inner method

  class Class1{
     public static ArrayList<Object> method1(){
         return onResponse();
}
public static ArrayList<Object> onResponse(){
return arrayList<Object>;

}
    }

but still i see no reason to not use Intent


Title: Check which IDs from a set do not exists in a table

Body:
I have a list of user IDs, like this:

757392,733602,749955,744304,746852,753904,755117,636163,564931,740787,751450,743799,643918,
749903,571888,30207,705953,749120,749001,749192,749978,750840,544228,702121,746246,383667,
558790,585628,592771,745818,749375,241209,749235,746860,748318,748016,748951,747321,748684,
748225,565375,748673,747869,748522,748335,744775,672229,578056,713127,740234,632608,711135,
746528,362131,742223,746567,745224,332989,439837,745418,673582,269584,742606,745135,746950,
476134,740830,742949,276934

I have a MySQL table users with the id field.

How do I check - using a query - which IDs of the ones I have do not exists in the users table?

This sounds like a simple problem to me, yet I couldn't find any example on StackOverflow which would address a fixed set of ID values.

Body:
You're looking for the IN clause with a negation. I.e. you can specify your list as the argument to the IN clause like so:

SELECT * FROM users
WHERE id NOT IN ( 757392,733602,749955,744304,746852,753904,755117,636163,564931,740787,751450,743799,643918,749903,571888,30207,705953,749120,749001,749192,749978,750840,544228,702121,746246,383667,558790,585628,592771,745818,749375,241209,749235,746860,748318,748016,748951,747321,748684,748225,565375,748673,747869,748522,748335,744775,672229,578056,713127,740234,632608,711135,746528,362131,742223,746567,745224,332989,439837,745418,673582,269584,742606,745135,746950,476134,740830,742949,276934 );

UPDATE

My bad - I didn't read the question properly.
So the correct way would be to go with UNIONs then outer join and filter by NULL, like this:

SELECT WantedIds.id
FROM users
    RIGHT JOIN (
        SELECT x.id
        FROM (
            SELECT '757392' AS id UNION
            SELECT '733602' UNION
            SELECT '749955' UNION
            SELECT '744304' UNION
            SELECT '746852' UNION
            SELECT '753904' UNION
            SELECT '755117' UNION
            SELECT '636163' UNION
            SELECT '564931' UNION
            .
            .
            .
        ) x
    ) WantedIds
    ON WantedIds.id = users.id
WHERE users.id IS NULL


问:
Curved text rendering in matplotlib
In a project I'm doing, I have to take in a user input from a structured file (xml). The file contains road data of an area, which I have to plot on to the matplotlib canvas. The problem is that along with the road, I also have to render the road name, and most of the roads are curved. I know how to render text in an angle. But I was wondering whether it is possible to change the text angle midway through the string?

Something like this : Draw rotated text on curved path

But using matplotlib.

答:
I found your problem quite interesting, so I made something which comes pretty close using the matplotlib text tool:

```<code>from __future__ import division
import itertools
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

# define figure and axes properties
fig, ax = plt.subplots(figsize=(8,6))
ax.set_xlim(left=0, right=10)
ax.set_ylim(bottom=-1.5, top=1.5)
(xmin, xmax), (ymin, ymax) = ax.get_xlim(), ax.get_ylim()

# calculate a shape factor, more explanation on usage further
# it is a representation of the distortion of the actual image compared to a
# cartesian space:
fshape = abs(fig.get_figwidth()*(xmax - xmin)/(ymax - ymin)/fig.get_figheight())

# the text you want to plot along your line
thetext = 'the text is flowing      '

# generate a cycler, so that the string is cycled through
lettercycler = itertools.cycle(tuple(thetext))

# generate dummy river coordinates
xvals = np.linspace(1, 10, 300)
yvals = np.sin(xvals)**3

# every XX datapoints, a character is printed
markerevery = 10

# calculate the rotation angle for the labels (in degrees)
# the angle is calculated as the slope between two datapoints.
# it is then multiplied by a shape factor to get from the angles in a
# cartesian space to the angles in this figure
# first calculate the slope between two consecutive points, multiply with the
# shape factor, get the angle in radians with the arctangens functions, and
# convert to degrees
angles = np.rad2deg(np.arctan((yvals[1:]-yvals[:-1])/(xvals[1:]-xvals[:-1])*fshape))

# plot the 'river'
ax.plot(xvals, yvals, 'b', linewidth=3)

# loop over the data points, but only plot a character every XX steps
for counter in np.arange(0, len(xvals)-1, step=markerevery):
    # plot the character in between two datapoints
    xcoord = (xvals[counter] + xvals[counter+1])/2.
    ycoord = (yvals[counter] + yvals[counter+1])/2.

    # plot using the text method, set the rotation so it follows the line,
    # aling in the center for a nicer look, optionally, a box can be drawn
    # around the letter
    ax.text(xcoord, ycoord, lettercycler.next(),
            fontsize=25, rotation=angles[counter],
            horizontalalignment='center', verticalalignment='center',
            bbox=dict(facecolor='white', edgecolor='white', alpha=0.5))
</code>```

The implementation is far from perfect, but it is a good starting point in my opinion.

Further, it seems that there is some development in matplotlib on having a scatterplot with rotation of the markers, which would be ideal for this case. However, my programming skills are nearly not as hardcore as they need to be to tackle this issue, so I cannot help here.

matplotlib on github: pull request

matplotlib on github: issue

Title: Curved text rendering in matplotlib

Body:
I found your problem quite interesting, so I made something which comes pretty close using the matplotlib text tool:

from __future__ import division
import itertools
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

# define figure and axes properties
fig, ax = plt.subplots(figsize=(8,6))
ax.set_xlim(left=0, right=10)
ax.set_ylim(bottom=-1.5, top=1.5)
(xmin, xmax), (ymin, ymax) = ax.get_xlim(), ax.get_ylim()

# calculate a shape factor, more explanation on usage further
# it is a representation of the distortion of the actual image compared to a
# cartesian space:
fshape = abs(fig.get_figwidth()*(xmax - xmin)/(ymax - ymin)/fig.get_figheight())

# the text you want to plot along your line
thetext = 'the text is flowing      '

# generate a cycler, so that the string is cycled through
lettercycler = itertools.cycle(tuple(thetext))

# generate dummy river coordinates
xvals = np.linspace(1, 10, 300)
yvals = np.sin(xvals)**3

# every XX datapoints, a character is printed
markerevery = 10

# calculate the rotation angle for the labels (in degrees)
# the angle is calculated as the slope between two datapoints.
# it is then multiplied by a shape factor to get from the angles in a
# cartesian space to the angles in this figure
# first calculate the slope between two consecutive points, multiply with the
# shape factor, get the angle in radians with the arctangens functions, and
# convert to degrees
angles = np.rad2deg(np.arctan((yvals[1:]-yvals[:-1])/(xvals[1:]-xvals[:-1])*fshape))

# plot the 'river'
ax.plot(xvals, yvals, 'b', linewidth=3)

# loop over the data points, but only plot a character every XX steps
for counter in np.arange(0, len(xvals)-1, step=markerevery):
    # plot the character in between two datapoints
    xcoord = (xvals[counter] + xvals[counter+1])/2.
    ycoord = (yvals[counter] + yvals[counter+1])/2.

    # plot using the text method, set the rotation so it follows the line,
    # aling in the center for a nicer look, optionally, a box can be drawn
    # around the letter
    ax.text(xcoord, ycoord, lettercycler.next(),
            fontsize=25, rotation=angles[counter],
            horizontalalignment='center', verticalalignment='center',
            bbox=dict(facecolor='white', edgecolor='white', alpha=0.5))

The implementation is far from perfect, but it is a good starting point in my opinion.

Further, it seems that there is some development in matplotlib on having a scatterplot with rotation of the markers, which would be ideal for this case. However, my programming skills are nearly not as hardcore as they need to be to tackle this issue, so I cannot help here.

matplotlib on github: pull request

matplotlib on github: issue


问:
Automapper - Don't map when a source object has a property with a value
Our entities have a field called "DateDeleted".   At times we might have these loaded into entities and we want to filter them out before sending them to the client.

Our Entities also have child entities which have child entities, all who have a DateDeleted.

What's the best practice to implement this with Automapper - Specifically - how can I map a Null value to the destination (for the entire object) when the source has a Date Deleted property with a value?

答:
You can ignore a specific property when you configure your mappings

```<code>CreateMap<srcType, destType>.ForMember(x => x.DateDeleted, opt => opt.Ignore());
</code>```

EDIT:
To do custom conditional logic during the mapping you will need to implement a custom resolver:

```<code>public class NullCheckResolver : IValueResolver<TSrc, TDest, TProp>
{
    public TProp Resolve(TSrc source, TDest destination, TProp member, ResolutionContext context)
    {
        if (member.DateDeleted == null)
            return member;
        return null;
    }
}

CreateMap<TSrc, TDest>().ForMember(dest => dest.MyOptionalProperty, opt => opt.ResolveUsing<NullCheckResolver>());
</code>```

For more details on custom resolvers, see the AutoMapper documentation

Body:
You can ignore a specific property when you configure your mappings

CreateMap<srcType, destType>.ForMember(x => x.DateDeleted, opt => opt.Ignore());

EDIT:
To do custom conditional logic during the mapping you will need to implement a custom resolver:

public class NullCheckResolver : IValueResolver<TSrc, TDest, TProp>
{
    public TProp Resolve(TSrc source, TDest destination, TProp member, ResolutionContext context)
    {
        if (member.DateDeleted == null)
            return member;
        return null;
    }
}

CreateMap<TSrc, TDest>().ForMember(dest => dest.MyOptionalProperty, opt => opt.ResolveUsing<NullCheckResolver>());

For more details on custom resolvers, see the AutoMapper documentation


问:
javascript date rounding up to next month
I am using below code to create date object after accepting date string from user in MM/DD/YYYY string format.

```<code>var userEnteredDate = '02/31/2015'; //example incorrect date entered by user
var userDate = new Date(userEnteredDate); //Getting rounded to 3rd March instead of throwing error
</code>```

Is there any way to fix this in JavaScript.
I would not like to do all the validations for Leap years, Date missing from Gregorian Calendar etc.

The required behavior is it should return NaN  when passing wrong date.
I do not want to use any third party library for compatibility reason with older version of angularjs.

**Note:**This is different than using Momentjs, this question is about the issue in javascript date functionality

答:
Date parsing using the native Date constructor is unreliable. You should use the Moment.js library instead – it throws errors for invalid dates.

If you're allowing a user to input dates, you may also consider using a datepicker for better UX.

Body:
I am using below code to create date object after accepting date string from user in MM/DD/YYYY string format.

var userEnteredDate = '02/31/2015'; //example incorrect date entered by user
var userDate = new Date(userEnteredDate); //Getting rounded to 3rd March instead of throwing error

Is there any way to fix this in JavaScript.
I would not like to do all the validations for Leap years, Date missing from Gregorian Calendar etc.

The required behavior is it should return NaN  when passing wrong date.
I do not want to use any third party library for compatibility reason with older version of angularjs.

**Note:**This is different than using Momentjs, this question is about the issue in javascript date functionality


问:
ie11 window.location relative paths
I have a bit of javascript...

```<code>function genURL() {
        var searchSubmit = document.getElementById("search").value;
        if(searchSubmit == ""){
            window.location = "webpage/view";
        }
        else{
            window.location = "webpage/view/generate/" + searchSubmit;
        }
</code>```

So this seems to work fine in chrome and Mozilla, however I tested in IE11 and it decided to change the pathing on me. So the redirect looks like this on Mozilla and Chrome...

```<code>www.mywebsite.com/webpage/view/generate
</code>```

However on IE11 is decides to go...

```<code>www.mywebsite.com/webpage/webpage/view/generate
</code>```

The page I am running it from is...

```<code>www.mywebsite.com/webpage/view
</code>```

Any ways around this?

Cheers

答:
Use the html <base> element to tell the application root.

Say, in your , specify the application root:

```<code><base id="myBase" href="//mydomain/myapp" />
</code>```

Then in your Javascript,

```<code>var baseUrl = document.getElementById("myBase").href;
window.location = baseUrl + "webpage/view";
</code>```

Title: ie11 window.location relative paths

Body:
I have a bit of javascript...

function genURL() {
        var searchSubmit = document.getElementById("search").value;
        if(searchSubmit == ""){
            window.location = "webpage/view";
        }
        else{
            window.location = "webpage/view/generate/" + searchSubmit;
        }

So this seems to work fine in chrome and Mozilla, however I tested in IE11 and it decided to change the pathing on me. So the redirect looks like this on Mozilla and Chrome...

www.mywebsite.com/webpage/view/generate

However on IE11 is decides to go...

www.mywebsite.com/webpage/webpage/view/generate

The page I am running it from is...

www.mywebsite.com/webpage/view

Any ways around this?

Cheers

Body:
Use the html <base> element to tell the application root.

Say, in your <head>, specify the application root:

<base id="myBase" href="//mydomain/myapp" />

Then in your Javascript,

var baseUrl = document.getElementById("myBase").href;
window.location = baseUrl + "webpage/view";


问:
Why does my link break (stop navigating to its location) when I use data-toggle attribute?
I am having a play around with Bootstrap 4 in Rails 5 and I am trying to get a data-toggle to work on nav-pills.

With my code below, the pill toggle works and it breaks the link_to part of the code and the link doesn't work.

```<code><div class="card">
  <div class="card-block">
    <ul class="nav nav-pills nav-justified" role="tablist">
      <%= link_to 'All Things', all_things_path, class: 'nav-link nav-item active' %>
      <%= link_to 'Some Things', some_things_path(@things[0]), class: 'nav-link nav-item', "data-toggle" => "pill" %>
    </ul>
  </div>
</div>
</code>```

If I remove the "data-toggle" => "pill" the link works fine and routes to the collection as required.

I have also tried using data: { toggle: "pills" } but this also breaks the link.

Anyone got any ideas?

答:
If by "breaking the link", you mean that browser no longer navigates to a new page, then it's because bootstrap's javascript intercepts the click on the link to do the toggling.

Clicking on a link takes you to its location, a new page. Clicking a toggle element shows/hides some other element on the current page. You can't have both.

Body:
I am having a play around with Bootstrap 4 in Rails 5 and I am trying to get a data-toggle to work on nav-pills.

With my code below, the pill toggle works and it breaks the link_to part of the code and the link doesn't work.

      <%= link_to 'All Things', all_things_path, class: 'nav-link nav-item active' %>
      <%= link_to 'Some Things', some_things_path(@things[0]), class: 'nav-link nav-item', "data-toggle" => "pill" %>

If I remove the "data-toggle" => "pill" the link works fine and routes to the collection as required.

I have also tried using data: { toggle: "pills" } but this also breaks the link.

Anyone got any ideas?


问:
Parsing array C++
Hello guys how can i do this on C++ (98).
It's working good on visual studio or something, but on place where i want to use it doesn't work.

https://image.prntscr.com/image/loIxb-YRRiGh9XAFmZ_0dA.png

I'm trying to send multiple functions with other values in array like:

```<code>Print(xx, parse_array()); // No elements in parsearray all will be 0
Print(xx, parse_array(25)); // First element [0] will be 25, rest of them 0.

int * parse_array(int val1 = 0, int val2 = 0, int val3 = 0, int val4 = 0)
{
    int m_pDataArray[4] = {
        val1, val2, val3, val4
    };

    return m_pDataArray;
}

void Print(bool notImportant, int m_pDataArray[4])
{
    printf("m_pDataArray 0: %d", m_pDataArray[0]);
    printf("m_pDataArray 1: %d", m_pDataArray[1]);
    printf("m_pDataArray 2: %d", m_pDataArray[2]);
    printf("m_pDataArray 3: %d", m_pDataArray[3]);
}

Print(true, parse_array(10, 20, 30);
Print(true, parse_array(10);
Print(true, parse_array());
</code>```

答:
You are returning the address of a local variable in parse_array. This is undefined behavior, the object int m_pDataArray[4] no longer exists after you've returned from your function, the pointer you return is immediately invalidated. Undefined behavior can do anything, including work sometimes on some computer but not on another computers, like you've described.

int [] does not have value semantics, you cannot return it easily. Use std::array instead.

```<code>#include <array>

std::array<int, 4> parse_array(int val1 = 0, int val2 = 0, int val3 = 0, int val4 = 0)
{
    std::array<int, 4> m_pDataArray = {
        val1, val2, val3, val4
    };

    return m_pDataArray;
}
</code>```

Otherwise, you will need to return dynamically allocated buffers and then remember to delete them. The easiest way would be to use std::unique_ptr but those don't exist in C++98.

Edit : It seems I forgot that std::array was added in C++ 11. You can get the same results with std::vector instead.

```<code>#include <vector>

std::vector<int> parse_array(int val1 = 0, int val2 = 0, int val3 = 0, int val4 = 0)
{
    std::vector<int> m_pDataArray;
    m_pDataArray.push_back(val1);
    m_pDataArray.push_back(val2);
    m_pDataArray.push_back(val3);
    m_pDataArray.push_back(val4);

    return m_pDataArray;
}
</code>```

Title: Parsing array C++

Body:
Hello guys how can i do this on C++ (98).
It's working good on visual studio or something, but on place where i want to use it doesn't work.

https://image.prntscr.com/image/loIxb-YRRiGh9XAFmZ_0dA.png

I'm trying to send multiple functions with other values in array like:

Print(xx, parse_array()); // No elements in parsearray all will be 0
Print(xx, parse_array(25)); // First element [0] will be 25, rest of them 0.

int * parse_array(int val1 = 0, int val2 = 0, int val3 = 0, int val4 = 0)
{
    int m_pDataArray[4] = {
        val1, val2, val3, val4
    };

    return m_pDataArray;
}

void Print(bool notImportant, int m_pDataArray[4])
{
    printf("m_pDataArray 0: %d", m_pDataArray[0]);
    printf("m_pDataArray 1: %d", m_pDataArray[1]);
    printf("m_pDataArray 2: %d", m_pDataArray[2]);
    printf("m_pDataArray 3: %d", m_pDataArray[3]);
}

Print(true, parse_array(10, 20, 30);
Print(true, parse_array(10);
Print(true, parse_array());

Body:
You are returning the address of a local variable in parse_array. This is undefined behavior, the object int m_pDataArray[4] no longer exists after you've returned from your function, the pointer you return is immediately invalidated. Undefined behavior can do anything, including work sometimes on some computer but not on another computers, like you've described.

int [] does not have value semantics, you cannot return it easily. Use std::array instead.

#include <array>

std::array<int, 4> parse_array(int val1 = 0, int val2 = 0, int val3 = 0, int val4 = 0)
{
    std::array<int, 4> m_pDataArray = {
        val1, val2, val3, val4
    };

    return m_pDataArray;
}

Otherwise, you will need to return dynamically allocated buffers and then remember to delete them. The easiest way would be to use std::unique_ptr but those don't exist in C++98.

Edit : It seems I forgot that std::array was added in C++ 11. You can get the same results with std::vector instead.

#include <vector>

std::vector<int> parse_array(int val1 = 0, int val2 = 0, int val3 = 0, int val4 = 0)
{
    std::vector<int> m_pDataArray;
    m_pDataArray.push_back(val1);
    m_pDataArray.push_back(val2);
    m_pDataArray.push_back(val3);
    m_pDataArray.push_back(val4);

    return m_pDataArray;
}


问:
Why is my error styling and ajax redirect not working?
My signup form is working perfectly as the data is being passed and checked by the signup.inc.php file but visually it is not displaying the error styling and after the form is successfully validated and the user is added, it does not redirect the user to profile.php. can anyone help me understand? Thanks in advance.

index.php:

```<code><?php
session_start();
include 'dbh.php';
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Yahbang</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {

            $("#signup-form").submit(function(event) {
                event.preventDefault();
                var first = $("#signup-first").val();
                var last = $("#signup-last").val();
                var email = $("#signup-email").val();
                var pwd = $("#signup-pwd").val();
                var submit = $("#signup-submit").val();

                $.ajax({
                    url: 'include/signup.inc.php',
                    type: 'POST',
                    data: {first: first, last: last, email: email, pwd: pwd, submit: submit},
                    dataType: 'json',
                    success: function(respond){

                    if(!respond.status)
                    {
                        alert(respond.message);
                    }
                    else
                        Window.Location.href = respond.redirect;
                    }
        });
    });
});

</script>

</head>
<body>
<header>

    <div class="header_index">
            <div class="headerlogo">
                <nav>
                    <ul>
                        <li><a href="index.php">Yahbang</a></li>
                    </ul>
                </nav>
            </div>

                <form id="login-form" class="loginform" action='include/login.inc.php' method='POST'>
                        <input  id="login-email" type='text' name='email' placeholder='Email'>
                        <input  id="login-pwd" type='password' name='pwd' placeholder='Password'>
                        <p><a href="forgotpassword.php">Forgot Password</a></p>
                        <button id="login-submit" type='submit'>Login</button>
                        <p class="login-message"></p>
                    </form>

</header>

                <form id="signup-form" class="signup" action='include/signup.inc.php' method='POST'>
                    <input id="signup-first" type='text' name='first' placeholder='First Name'><br>
                    <input id="signup-last" type='text' name='last' placeholder='Last Name'><br>
                    <input id="signup-email" type='text' name='email' placeholder='Email'><br>
                    <input id="signup-pwd" type='password' name='pwd' placeholder='Password'><br>
                    <button id="signup-submit" type='submit'>Sign Up</button>
                    <p class="signup-message"></p>
                </form>

<footer>
    <div class="footer_index">
    <nav>
        <ul>
            <li><a href="contact.php">Contact Us</a></li>
            <li><a href="TermsofUse.php">Terms of Use</a></li>
        </ul>
    </nav>
    </div>
</footer>
</body>
</html>
</code>```

signup.inc.php:

```<code><?php
session_start();
include '../dbh.php';

    $respond = array(
    'status'   => true,
    'message'  => 'There was an error',
    'redirect' => '../profile.php'
);

if (isset($_POST['submit'])) {

    $first = $_POST['first'];
    $last = $_POST['last'];
    $email = $_POST['email'];
    $pwd = $_POST['pwd'];

    $errorEmpty = false;
    $errorEmail = false;

if (empty($first) || empty($last) || empty($email) || empty($pwd)) {
    echo "<span class='signup-error'>Please fill out all fields!</span>";
    $errorEmpty = true;
    }

elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "<span class='signup-error'>Please enter a valid email address!</span>";
    $errorEmail = true;
    }

else {
    $sql = "SELECT email FROM user WHERE email='$email'";
    $result = mysqli_query($conn, $sql);
    $emailcheck = mysqli_num_rows($result);

if ($emailcheck > 0) {
    echo "<span class='signup-error'>That email address already exists!</span>";
    $errorEmail = true;
    echo json_encode($respond);
    }

else {
    $encryptpwd = password_hash($pwd, PASSWORD_DEFAULT);
    $sql = "INSERT INTO user (first, last, email, pwd)
    VALUES ('$first', '$last', '$email', '$encryptpwd')";
    $result = mysqli_query($conn, $sql);
    }

}
}
?>

<script>
$("#signup-first, #signup-last, #signup-email, #signup-pwd").removeClass("input-error");

    var errorEmpty = "<?php echo $errorEmpty; ?>";
    var errorEmail = "<?php echo $errorEmail; ?>";

 if (errorEmpty == true) {
  $("#signup-first, #signup-last, #signup-email, #signup-pwd").addClass("input-error");
 }

 if (errorEmail == true) {
  $("#signup-email").addClass("input-error");
 }

 if (errorEmpty == false && errorEmail == false) {
  $("#signup-first, #signup-last, #signup-email, #signup-pwd").val("");
}

 </script>
</code>```

答:
So you can't just dump a full script back in an ajax request and expect it to work. The request is handled by the ajax function, not just glued to the bottom of the current page.

In your case, your script could be moved to the main index.php and called by the ajax callback function. For example:

```<code>if(!respond.status)
{
    alert(respond.message);
    showErrors(respond.errorEmpty, respond.errorEmail);
}
</code>```

The above assumes a couple of things. Firstly, that you would change-up that current script slightly to be a callable function, ie:

```<code>function showErrors(errorEmpty, errorEmail) {
    $("#signup-first, #signup-last, #signup-email, #signup-pwd").removeClass("input-error");

     if (errorEmpty == true) {
      $("#signup-first, #signup-last, #signup-email, #signup-pwd").addClass("input-error");
     }

     if (errorEmail == true) {
      $("#signup-email").addClass("input-error");
     }

     if (errorEmpty == false && errorEmail == false) {
      $("#signup-first, #signup-last, #signup-email, #signup-pwd").val("");
    }
}
</code>```

Now this showErrors function can go in your main index.php script, so that the ajax function can call it as needed.

Second, it assumes you are passing those $errorEmpty and $errorEmail variables in php back to the ajax request in the response, similar to your other response variables. Something like:

```<code>$respond = array(
    'status'   => true,
    'message'  => 'There was an error',
    'redirect' => '../profile.php',
    'errors',
);

if (empty($first) || empty($last) || empty($email) || empty($pwd)) {

    $respond['errors'][] = "Please fill out all fields!";
    $respond['errorEmpty'] = true;

} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

    $respond['errors'][] = "Please enter a valid email address!";
    $respond['errorEmail'] = true;

} else {

    $sql = "SELECT email FROM user WHERE email='$email'";
    $result = mysqli_query($conn, $sql);
    $emailcheck = mysqli_num_rows($result);

    if ($emailcheck > 0) {
        $respond['errors'][] = "That email address already exists!";
        $respond['errorEmail'] = true;

        echo json_encode($respond);

    }
</code>```

So now you can pass respond.errorEmpty to the error handling function.

Body:
My signup form is working perfectly as the data is being passed and checked by the signup.inc.php file but visually it is not displaying the error styling and after the form is successfully validated and the user is added, it does not redirect the user to profile.php. can anyone help me understand? Thanks in advance.

index.php:

<?php
session_start();
include 'dbh.php';
?>

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Yahbang</title>
    <link rel="stylesheet" type="text/css" href="style.css">

Yahbang

                <form id="login-form" class="loginform" action='include/login.inc.php' method='POST'>
                        <input  id="login-email" type='text' name='email' placeholder='Email'>
                        <input  id="login-pwd" type='password' name='pwd' placeholder='Password'>

Forgot Password

                        <button id="login-submit" type='submit'>Login</button>

                    </form>

                <form id="signup-form" class="signup" action='include/signup.inc.php' method='POST'>
                    <input id="signup-first" type='text' name='first' placeholder='First Name'>

                    <input id="signup-last" type='text' name='last' placeholder='Last Name'>

                    <input id="signup-email" type='text' name='email' placeholder='Email'>

                    <input id="signup-pwd" type='password' name='pwd' placeholder='Password'>

                    <button id="signup-submit" type='submit'>Sign Up</button>

                </form>

Contact Us

Terms of Use

signup.inc.php:

<?php
session_start();
include '../dbh.php';

    $respond = array(
    'status'   => true,
    'message'  => 'There was an error',
    'redirect' => '../profile.php'
);

if (isset($_POST['submit'])) {

    $first = $_POST['first'];
    $last = $_POST['last'];
    $email = $_POST['email'];
    $pwd = $_POST['pwd'];

    $errorEmpty = false;
    $errorEmail = false;

if (empty($first) || empty($last) || empty($email) || empty($pwd)) {
    echo "Please fill out all fields!";
    $errorEmpty = true;
    }

elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Please enter a valid email address!";
    $errorEmail = true;
    }

else {
    $sql = "SELECT email FROM user WHERE email='$email'";
    $result = mysqli_query($conn, $sql);
    $emailcheck = mysqli_num_rows($result);

if ($emailcheck > 0) {
    echo "That email address already exists!";
    $errorEmail = true;
    echo json_encode($respond);
    }

else {
    $encryptpwd = password_hash($pwd, PASSWORD_DEFAULT);
    $sql = "INSERT INTO user (first, last, email, pwd)
    VALUES ('$first', '$last', '$email', '$encryptpwd')";
    $result = mysqli_query($conn, $sql);
    }

}
}
?>

Body:
So you can't just dump a full script back in an ajax request and expect it to work. The request is handled by the ajax function, not just glued to the bottom of the current page.

In your case, your script could be moved to the main index.php and called by the ajax callback function. For example:

if(!respond.status)
{
    alert(respond.message);
    showErrors(respond.errorEmpty, respond.errorEmail);
}

The above assumes a couple of things. Firstly, that you would change-up that current script slightly to be a callable function, ie:

function showErrors(errorEmpty, errorEmail) {
    $("#signup-first, #signup-last, #signup-email, #signup-pwd").removeClass("input-error");

     if (errorEmpty == true) {
      $("#signup-first, #signup-last, #signup-email, #signup-pwd").addClass("input-error");
     }

     if (errorEmail == true) {
      $("#signup-email").addClass("input-error");
     }

     if (errorEmpty == false && errorEmail == false) {
      $("#signup-first, #signup-last, #signup-email, #signup-pwd").val("");
    }
}

Now this showErrors function can go in your main index.php script, so that the ajax function can call it as needed.

Second, it assumes you are passing those $errorEmpty and $errorEmail variables in php back to the ajax request in the response, similar to your other response variables. Something like:

$respond = array(
    'status'   => true,
    'message'  => 'There was an error',
    'redirect' => '../profile.php',
    'errors',
);

if (empty($first) || empty($last) || empty($email) || empty($pwd)) {

    $respond['errors'][] = "Please fill out all fields!";
    $respond['errorEmpty'] = true;

} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

    $respond['errors'][] = "Please enter a valid email address!";
    $respond['errorEmail'] = true;

} else {

    $sql = "SELECT email FROM user WHERE email='$email'";
    $result = mysqli_query($conn, $sql);
    $emailcheck = mysqli_num_rows($result);

    if ($emailcheck > 0) {
        $respond['errors'][] = "That email address already exists!";
        $respond['errorEmail'] = true;

        echo json_encode($respond);

    }

So now you can pass respond.errorEmpty to the error handling function.


问:
Constraints on Generics with VB.NET
I have the a function that is declared like so:

```<code>Public Sub Modify(Of SIMType As {New, DAOBase})(ByVal obj As SIMType)
</code>```

I also have a class called Products which is declared like so:

```<code>Public Class Products
Inherits DAOBase
</code>```

So as you can see, if I were to call this function like so:

```<code>Modify(Of Products)(new Products())
</code>```

This would not be an issue. The issue actually arises when I try to cast the object being past in to its real type. For example:

```<code>CType(obj, Products)
</code>```

or

```<code>CType(obj, SIMType)
</code>```

Both do not work. I get this error:

Value of type SIMTYPE cannot be converted to IMS.Products.

I'm assuming this is because I am using generics. Is there a way to adjust my function to allow for a casting operation like I am trying to do? In the end, what I need is a reference of the actual type (Products in this case) to the object.

答:
I recommend using Olivier's answer - this is traditional Object-Oriented programming, where the method in each class knows what to do, based on the class it is in. No casts required; an appropriate Modify is called in all cases.

However, it is useful to know alternatives, so here is a way to accomplish the casting that is asked about in the question:

```<code>Public Sub Modify(Of SIMType As {New, DAOBase})(ByVal obj As SIMType)
    Dim products1 As Products = TryCast(obj, Products)
    If products1 IsNot Nothing Then
        ... ' here you can use products1
    End If
End Sub
</code>```

CAVEAT: Any time you find yourself using TryCast or DirectCast, ask yourself if there isn't some alternative solution that does not require casting. Yes, that alternative likely requires some "refactoring" of your existing code, but in the long run, that refactoring is probably worth it.

Title: Constraints on Generics with VB.NET

Body:
I have the a function that is declared like so:

Public Sub Modify(Of SIMType As {New, DAOBase})(ByVal obj As SIMType)

I also have a class called Products which is declared like so:

Public Class Products
Inherits DAOBase

So as you can see, if I were to call this function like so:

Modify(Of Products)(new Products())

This would not be an issue. The issue actually arises when I try to cast the object being past in to its real type. For example:

CType(obj, Products)

or

CType(obj, SIMType)

Both do not work. I get this error:

Value of type SIMTYPE cannot be converted to IMS.Products.

I'm assuming this is because I am using generics. Is there a way to adjust my function to allow for a casting operation like I am trying to do? In the end, what I need is a reference of the actual type (Products in this case) to the object.

Body:
I recommend using Olivier's answer - this is traditional Object-Oriented programming, where the method in each class knows what to do, based on the class it is in. No casts required; an appropriate Modify is called in all cases.

However, it is useful to know alternatives, so here is a way to accomplish the casting that is asked about in the question:

Public Sub Modify(Of SIMType As {New, DAOBase})(ByVal obj As SIMType)
    Dim products1 As Products = TryCast(obj, Products)
    If products1 IsNot Nothing Then
        ... ' here you can use products1
    End If
End Sub

CAVEAT: Any time you find yourself using TryCast or DirectCast, ask yourself if there isn't some alternative solution that does not require casting. Yes, that alternative likely requires some "refactoring" of your existing code, but in the long run, that refactoring is probably worth it.


问:
SQL Call function foreach row on every record in other table
I have two tables; Table1 (name, latitude, longitude) with 400 records in and Table2 (name, latitude, longitude) with 10,000 records in.

I want to find all records in Table2 that are physically close to the 400 records in Table1. (excluding all the 400 records in Table1).

I have a function that works out the distance between two records. My problem is in SQL I can't figure out how to run it for every record in Table1, on every record in Table2. I am calling my function as below;

```<code>dbo.fnCalcDistanceKM(item1.lat, item2.lat, item1.long, item2.long) < 0.150
</code>```

This gets the distance between the two coordinates and will only return the ones if it is within 150 metres. It works fine but I am struggling with running it for each record in Table1 over every record in Table2.

Any pointers would be greatly appriciated! I think this is fairly simple to do in SQL but my experience is lacking.

答:
Are you able to change the datatypes of the tables? Since you're using SQL 2008+, you can use the GEOGRAPHY datatype and store lat/lon in one column, then easily do a comparison between the two using a CROSS JOIN.

https://learn.microsoft.com/en-us/sql/t-sql/spatial-geography/spatial-types-geography

```<code>SELECT t2.name, t2.loc, t2.loc.STDistance(t1.loc) AS distance
FROM Table2 t2
CROSS JOIN Table1 t1
WHERE  t2.loc.STDistance(t1.loc) < 150
</code>```

Or with your current dataset, maybe:

```<code>SELECT t2.name, t2.latitude, t2.longitude
    , POINT(t2.latitude & ' ' & t2.longitude) AS thePoint
    , (POINT(t2.latitude & ' ' & t2.longitude)).STDistance(POINT(t1.latitude & ' ' & t1.longitude)) AS distance
FROM Table2 t2
CROSS JOIN Table1 t1
WHERE  (POINT(t2.latitude & ' ' & t2.longitude)).STDistance(POINT(t1.latitude & ' ' & t1.longitude)) < 150
</code>```

This will be slow if you don't have an index on the locations, but it will be very accurate. And you won't have to run an extra function on every row. You'll have to test the time.

Body:
I have two tables; Table1 (name, latitude, longitude) with 400 records in and Table2 (name, latitude, longitude) with 10,000 records in.

I want to find all records in Table2 that are physically close to the 400 records in Table1. (excluding all the 400 records in Table1).

I have a function that works out the distance between two records. My problem is in SQL I can't figure out how to run it for every record in Table1, on every record in Table2. I am calling my function as below;

dbo.fnCalcDistanceKM(item1.lat, item2.lat, item1.long, item2.long) < 0.150

This gets the distance between the two coordinates and will only return the ones if it is within 150 metres. It works fine but I am struggling with running it for each record in Table1 over every record in Table2.

Any pointers would be greatly appriciated! I think this is fairly simple to do in SQL but my experience is lacking.

Body:
Are you able to change the datatypes of the tables? Since you're using SQL 2008+, you can use the GEOGRAPHY datatype and store lat/lon in one column, then easily do a comparison between the two using a CROSS JOIN.

https://learn.microsoft.com/en-us/sql/t-sql/spatial-geography/spatial-types-geography

SELECT t2.name, t2.loc, t2.loc.STDistance(t1.loc) AS distance
FROM Table2 t2
CROSS JOIN Table1 t1
WHERE  t2.loc.STDistance(t1.loc) < 150

Or with your current dataset, maybe:

SELECT t2.name, t2.latitude, t2.longitude
    , POINT(t2.latitude & ' ' & t2.longitude) AS thePoint
    , (POINT(t2.latitude & ' ' & t2.longitude)).STDistance(POINT(t1.latitude & ' ' & t1.longitude)) AS distance
FROM Table2 t2
CROSS JOIN Table1 t1
WHERE  (POINT(t2.latitude & ' ' & t2.longitude)).STDistance(POINT(t1.latitude & ' ' & t1.longitude)) < 150

This will be slow if you don't have an index on the locations, but it will be very accurate. And you won't have to run an extra function on every row. You'll have to test the time.


问:
How to efficiently build a tree from a flat structure?
I have a bunch of objects in a flat structure. These objects have an ID and a ParentID property so they can be arranged in trees. They are in no particular order.
Each ParentID property does not necessarily matches with an ID in the structure. Therefore their could be several trees emerging from these objects.

How would you process these objects to create the resulting trees ?

I'm not so far from a solution but I'm sure it is far from optimal...

I need to create these trees to then insert Data into a database, in proper order.

There are no circular references. A Node is a RootNode when ParentID == null or when ParentID can't be found in the other objects

答:
I can do this in 4 lines of code and O(n log n) time, assuming that Dictionary is something like a TreeMap.

```<code>dict := Dictionary new.
ary do: [:each | dict at: each id put: each].
ary do: [:each | (dict at: each parent) addChild: each].
root := dict at: nil.
</code>```

EDIT:
Ok, and now I read that some parentIDs are fake, so forget the above, and do this:

```<code>dict := Dictionary new.
dict at: nil put: OrderedCollection new.
ary do: [:each | dict at: each id put: each].
ary do: [:each |
    (dict at: each parent ifAbsent: [dict at: nil])
          add: each].
roots := dict at: nil.
</code>```

OwnerDisplayName: Costo

LastEditorDisplayName: Costo

Body:
I can do this in 4 lines of code and O(n log n) time, assuming that Dictionary is something like a TreeMap.

dict := Dictionary new.
ary do: [:each | dict at: each id put: each].
ary do: [:each | (dict at: each parent) addChild: each].
root := dict at: nil.

EDIT:
Ok, and now I read that some parentIDs are fake, so forget the above, and do this:

dict := Dictionary new.
dict at: nil put: OrderedCollection new.
ary do: [:each | dict at: each id put: each].
ary do: [:each |
    (dict at: each parent ifAbsent: [dict at: nil])
          add: each].
roots := dict at: nil.

OwnerDisplayName: Niko

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Niko


问:
Open Graph Protocol - how to make it work with multiple stories on a page?
The Open Graph Protocol is a new methodology for storing metadata to make it easier for third party sites (think the Facebook LIKE button) to identify relevant content on your page.

It looks like this:

```<code><title>The Rock (1996)</title>
<meta property="og:title" content="The Rock" />
<meta property="og:type" content="movie" />
<meta property="og:url" content="http://www.imdb.com/title/tt0117500/" />
<meta property="og:image" content="http://ia.media-imdb.com/images/rock.jpg" />
</code>```

The question is, if you have multiple LIKE buttons on a page, each for a different article, how does one differentiate the Open Graph meta tags that belong to the article, not the page itself. Since the tags go in the HEAD is seems you only get one set per page.

Can Open Graph be "namespaced" or associated with content within the page, rather than the page itself?

答:
As far as I know, you're stuck - but if you figure out a way, let me know!

I worked on a project that needed to have multiple Open Graph tags on a page - in the end, we ended up trimming down the number of items we needed OG for, so that we'd only have one story on a page.

Body:
The Open Graph Protocol is a new methodology for storing metadata to make it easier for third party sites (think the Facebook LIKE button) to identify relevant content on your page.

It looks like this:

<title>The Rock (1996)</title>
<meta property="og:title" content="The Rock" />
<meta property="og:type" content="movie" />
<meta property="og:url" content="http://www.imdb.com/title/tt0117500/" />
<meta property="og:image" content="http://ia.media-imdb.com/images/rock.jpg" />

The question is, if you have multiple LIKE buttons on a page, each for a different article, how does one differentiate the Open Graph meta tags that belong to the article, not the page itself. Since the tags go in the HEAD is seems you only get one set per page.

Can Open Graph be "namespaced" or associated with content within the page, rather than the page itself?


问:
Why Do I have to reload the browser in order that my props are no set as Undefined
Hi everyone Im having a little problem. Im building an app with react & redux.

So as an example I have a button that its being display based on a comparison
Here is how my code look like :

```<code>renderExportGuidelinesButton(){
    var { authProfile, guidelines } = this.props;
    if(authProfile.role == "dba"){
      return(
        <button type="button" disabled={this.state.exportGuidelinesBtnDisabled} onClick={this.showConfirmExport.bind(this, guidelines)} id="export-guidelines-btn" className="btn btn-primary">
          Export Guidelines
        </button>
      )
    }
  }
</code>```

In this case the profile role matches and is supposed to render my button.
I have my function bind in the constructor method. Once I reload the browser everything works fine

答:
You need to give your reducer an initial state. http://redux.js.org/docs/recipes/reducers/InitializingState.html

Or alternatively, you can use defaultProps to set initial values for any prop you want:

```<code>defaultProps = {
    authProfile: {},
    guidelines: {}
}
</code>```

Body:
Hi everyone Im having a little problem. Im building an app with react & redux.

So as an example I have a button that its being display based on a comparison
Here is how my code look like :

renderExportGuidelinesButton(){
    var { authProfile, guidelines } = this.props;
    if(authProfile.role == "dba"){
      return(
        <button type="button" disabled={this.state.exportGuidelinesBtnDisabled} onClick={this.showConfirmExport.bind(this, guidelines)} id="export-guidelines-btn" className="btn btn-primary">
          Export Guidelines
        </button>
      )
    }
  }

In this case the profile role matches and is supposed to render my button.
I have my function bind in the constructor method. Once I reload the browser everything works fine

Body:
You need to give your reducer an initial state. http://redux.js.org/docs/recipes/reducers/InitializingState.html

Or alternatively, you can use defaultProps to set initial values for any prop you want:

defaultProps = {
    authProfile: {},
    guidelines: {}
}


问:
Invoking powershell show-command from a batch script
I am trying to give helpdesk staff who are not familiar with Powershell the ability to run one-off Powershell functions by just executing a batch file. In the batch file I launch powershell with bypass executionpolicy, import and run the function. Additionally, I wanted to use Show-Command to give them a graphical UI that would make the parameters more obvious. This runs, but apparently any code that is invoked with the & operator runs in its own child scope. This means when the command with arguments is returned to the "parent" Powershell window, it will have lost knowledge of the function that was imported inside the child scope. Here's what I have in the batch file:

```<code>powershell.exe -noprofile -noexit -executionpolicy bypass -command "& {. \\server\share\New-DriveRemapScript.ps1;Show-Command New-DriveRemapScript}"
</code>```

The launched Powershell windows remains, but when I hit enter on the command text returned by Show-Command, I get "New-DriveRemapScript : The term 'New-DriveRemapScript' is not recognized ...."

答: I wanted to make this work without having to "run" the function within my script file. This way the function file can be shared with savvy Powershell users as well who know how to dot source things in their profile. I don't have a perfect solution, but my workaround was to define the function as Global (Global:New-DriveRemapScript), so that it would still be available after the child scope exits. Then the above batch file code works as expected.

Body:
I am trying to give helpdesk staff who are not familiar with Powershell the ability to run one-off Powershell functions by just executing a batch file. In the batch file I launch powershell with bypass executionpolicy, import and run the function. Additionally, I wanted to use Show-Command to give them a graphical UI that would make the parameters more obvious. This runs, but apparently any code that is invoked with the & operator runs in its own child scope. This means when the command with arguments is returned to the "parent" Powershell window, it will have lost knowledge of the function that was imported inside the child scope. Here's what I have in the batch file:

powershell.exe -noprofile -noexit -executionpolicy bypass -command "& {. \\server\share\New-DriveRemapScript.ps1;Show-Command New-DriveRemapScript}"

The launched Powershell windows remains, but when I hit enter on the command text returned by Show-Command, I get "New-DriveRemapScript : The term 'New-DriveRemapScript' is not recognized ...."


问:
Failed to locate Element from a CheckOut Table
I'm not able to locate an element. I want to getText() from the element then convert it to a float and calculate. However, can't seem to find element.

```<code>String unitPrice = driver.findElement(By.cssSelector(".price")).getText();
        //By.xpath(".//*[@id='product_1_1_0_0']/td[4]")).getText();
String unit = driver.findElement(By.cssSelector(".cart_quantity_input.form-control.grey")).getText();
        //By.xpath(".//*[@id='product_1_1_0_0']/td[5]/input[2]")).getText();
String totalPrice = driver.findElement(By.cssSelector("#total_product_price_1_1_0")).getText();
        //By.xpath(".//*[@id='total_product_price_1_1_0']")).getText();

float unitPriceF = Float.parseFloat(unitPrice);
float unitF = Float.parseFloat(unit);
float TotalPriceF = Float.parseFloat(totalPrice);
</code>```

I've tried both xPath and cssSelector, but getting same error in both cases:

no such element: Unable to locate element: {"method":"css
  selector","selector":"#total_product_price_1_1_0"}(..)

This is the HTML structure :

```<code><div id="order-detail-content" class="table_block table-responsive">
<table id="cart_summary" class="table table-bordered stock-management-on">
<thead>
<tr>
<th class="cart_product first_item">Product</th>
<th class="cart_description item">Description</th>
<th class="cart_avail item">Avail.</th>
<th class="cart_unit item">Unit price</th>
<th class="cart_quantity item">Qty</th>
<th class="cart_total item">Total</th>
<th class="cart_delete last_item"> </th>
</tr>
</thead>
<tfoot>
<tr class="cart_total_price">
<td id="cart_voucher" class="cart_voucher" rowspan="3" colspan="3"> </td>
<td class="text-right" colspan="3">Total products</td>
<td id="total_product" class="price" colspan="2">$39.51</td>
</tr>
<tr style="display: none;">
<tr class="cart_total_delivery">
<tr class="cart_total_voucher" style="display:none">
<tr class="cart_total_price">
</tfoot>
<tbody>
<tr id="product_1_1_0_0" class="cart_item last_item first_item address_0 odd">
<td class="cart_product">
<td class="cart_description">
<td class="cart_avail">
<td class="cart_unit" data-title="Unit price">
<span id="product_price_1_1_0" class="price">
<span class="price">$39.51</span>
</span>
</td>
<td class="cart_quantity text-center">
<td class="cart_total" data-title="Total">
<td class="cart_delete text-center" data-title="Delete">
</tr>
</tbody>
</table>
</div>
</code>```

答:
Get the rows from the table first:

```<code> List <WebElement> rows = driver.findElements(By.tagName("tr"));
</code>```

Use the row number to get the cell in the row:

```<code> String unitPrice= rows.get(1).findElement(By.cssSelector(".price")).getText();
</code>```

The above line would return string $39.51 and you cannot directly convert this to float because of the $ symbol. Split the string before converting to float

Body:
I'm not able to locate an element. I want to getText() from the element then convert it to a float and calculate. However, can't seem to find element.

String unitPrice = driver.findElement(By.cssSelector(".price")).getText();
        //By.xpath(".//*[@id='product_1_1_0_0']/td[4]")).getText();
String unit = driver.findElement(By.cssSelector(".cart_quantity_input.form-control.grey")).getText();
        //By.xpath(".//*[@id='product_1_1_0_0']/td[5]/input[2]")).getText();
String totalPrice = driver.findElement(By.cssSelector("#total_product_price_1_1_0")).getText();
        //By.xpath(".//*[@id='total_product_price_1_1_0']")).getText();

float unitPriceF = Float.parseFloat(unitPrice);
float unitF = Float.parseFloat(unit);
float TotalPriceF = Float.parseFloat(totalPrice);

I've tried both xPath and cssSelector, but getting same error in both cases:

no such element: Unable to locate element: {"method":"css
  selector","selector":"#total_product_price_1_1_0"}(..)

This is the HTML structure :

Product
Description
Avail.
Unit price
Qty
Total

Total products
$39.51

$39.51

Body:
Get the rows from the table first:

 List <WebElement> rows = driver.findElements(By.tagName("tr"));

Use the row number to get the cell in the row:

 String unitPrice= rows.get(1).findElement(By.cssSelector(".price")).getText();

The above line would return string $39.51 and you cannot directly convert this to float because of the $ symbol. Split the string before converting to float


问:
Union within CTE removing records but there are no Duplicates
I have a query with a union within a CTE in oracle.  I am trying to get the sum of a field called P in our database and was checking to make sure the value was accurate as I was writing my view.  I found oracle treating these queries in an unusual way after adding a union

```<code>with CTE_A as
(select  P, 'full' as coverage from Table_A),

CTE_B as
(select  P, 'partial' as coverage from Table_A)
</code>```

Here if I select sum(P) from CTE_A I get 100. However, if i do the following:

```<code>CTE_C as
(select P, coverage from CTE_A

union

select P, coverage from CTE_B)

select sum(P) from CTE_C where coverage='full'
</code>```

I get 78.

When I use union All I get 100 again.  I know that union removes duplicates but there should be no duplicates within CTE_A and CTE_B since I am declaring the field coverage.

答:
The UNION is removing duplicates from the result set.  You must have something like this in CTE_A:

```<code>22 | Full
22 | Full
</code>```

Which, when you SUM() CTE_A, both are counted.  But after you UNION, you will only have one record, lowering the SUM() total from CTE_C to 78 (100-22=78).

UNION ALL does not remove duplicates, which is why this doesn't happen when you include ALL.

Body:
I have a query with a union within a CTE in oracle.  I am trying to get the sum of a field called P in our database and was checking to make sure the value was accurate as I was writing my view.  I found oracle treating these queries in an unusual way after adding a union

with CTE_A as
(select  P, 'full' as coverage from Table_A),

CTE_B as
(select  P, 'partial' as coverage from Table_A)

Here if I select sum(P) from CTE_A I get 100. However, if i do the following:

CTE_C as
(select P, coverage from CTE_A

union

select P, coverage from CTE_B)

select sum(P) from CTE_C where coverage='full'

I get 78.

When I use union All I get 100 again.  I know that union removes duplicates but there should be no duplicates within CTE_A and CTE_B since I am declaring the field coverage.

Body:
The UNION is removing duplicates from the result set.  You must have something like this in CTE_A:

22 | Full
22 | Full

Which, when you SUM() CTE_A, both are counted.  But after you UNION, you will only have one record, lowering the SUM() total from CTE_C to 78 (100-22=78).

UNION ALL does not remove duplicates, which is why this doesn't happen when you include ALL.


问:
how stopped script while procces id exist? Solaris
I want to stall the execution of my script until a process is closed (I have the PID stored in a variable).

```<code>#!/bin/bash

outputl=$( ps -ef | grep $var4 | awk '{print $2}' )  >> $logfile

while [ "ps -p $outputl" ]  > /dev/null;
do
  sleep 1;
done
echo "Stopped $instance" >> $logfile
//command...
</code>```

It stays in the "while" and not continue whit script.

答:
If you have the PID then just wait for it to complete. Try:

```<code>outputl=$( ps -ef | awk -v v="$var4" '$0~v{print $2}' )
wait "$outputl"
echo "Stopped $instance" >> $logfile
</code>```

then look for a better way to find the pid in the first line.

Body:
I want to stall the execution of my script until a process is closed (I have the PID stored in a variable).

#!/bin/bash

outputl=$( ps -ef | grep $var4 | awk '{print $2}' )  >> $logfile

while [ "ps -p $outputl" ]  > /dev/null;
do
  sleep 1;
done
echo "Stopped $instance" >> $logfile
//command...

It stays in the "while" and not continue whit script.

Body:
If you have the PID then just wait for it to complete. Try:

outputl=$( ps -ef | awk -v v="$var4" '$0~v{print $2}' )
wait "$outputl"
echo "Stopped $instance" >> $logfile

then look for a better way to find the pid in the first line.


问:
Directory is created but do not exist on local server - PHP
I'm using PHP 5 and Codeigniter 3 on Ubuntu Linux.

I need to upload and store user files on the server, but before upload I need to create directory for user where files will be stored.
Directory name is based on userdata hashed with md5.

Also Im checking if directory is already created/exists on server, otherwise should be created.

```<code>   public function uploadImage(){

        $id = $this->session->userdata('id');

        $dir_name = md5($id); // create hashed dir name

        $user_dir = base_url() . 'uploads/user' . '/' . $dir_name;

       // print_r($user_dir);

        if(!file_exists($user_dir)){
            mkdir($user_dir, 0777);
            print_r("created");
        }else{
            print_r("directory exists");
        }
 }
</code>```

When I run code, it says created, but  I cant see directory. It does not exist in uploads/users folder.
Please help me, where Im wrong. Many thanks

答:
USE FCPATH </p>

```<code>public function uploadImage(){

   $id = $this->session->userdata('id');

   $dir_name = md5($id); // create hashed dir name

   /*
       You may need / after FCPATH

       $user_dir = FCPATH . '/uploads/user/' . $dir_name;
   */

   $user_dir = FCPATH . 'uploads/user/' . $dir_name;

   // print_r($user_dir);

    if(!file_exists($user_dir)){

        mkdir($user_dir, 0777);

        // @mkdir($user_dir, 0777, true);

        print_r("created");

    } else {

        print_r("directory exists");
    }
}
</code>```

Body:
I'm using PHP 5 and Codeigniter 3 on Ubuntu Linux.

I need to upload and store user files on the server, but before upload I need to create directory for user where files will be stored.
Directory name is based on userdata hashed with md5.

Also Im checking if directory is already created/exists on server, otherwise should be created.

   public function uploadImage(){

        $id = $this->session->userdata('id');

        $dir_name = md5($id); // create hashed dir name

        $user_dir = base_url() . 'uploads/user' . '/' . $dir_name;

       // print_r($user_dir);

        if(!file_exists($user_dir)){
            mkdir($user_dir, 0777);
            print_r("created");
        }else{
            print_r("directory exists");
        }
 }

When I run code, it says created, but  I cant see directory. It does not exist in uploads/users folder.
Please help me, where Im wrong. Many thanks

Body:
USE FCPATH

public function uploadImage(){

   $id = $this->session->userdata('id');

   $dir_name = md5($id); // create hashed dir name

   /*
       You may need / after FCPATH

       $user_dir = FCPATH . '/uploads/user/' . $dir_name;
   */

   $user_dir = FCPATH . 'uploads/user/' . $dir_name;

   // print_r($user_dir);

    if(!file_exists($user_dir)){

        mkdir($user_dir, 0777);

        // @mkdir($user_dir, 0777, true);

        print_r("created");

    } else {

        print_r("directory exists");
    }
}


问:
SQL Server 2008 and Almost-Progressive Sum and Average?
I have a table with several million rows, with an ID column and a DateTimeOffset column. The table simply tracks elapsed time for some operations.

Without touching a cursor or doing RBAR, how can I get the difference between each row, and then the average time among all rows?

For example, if row 1 is 12:00 and row 2 is 12:01 and row 3 is 12:03 then my result set would have row 1 with 0, row 2 with 1, and row 3 with 2. Then my next result set would have a value of 1.5.

Help?

Thanks.

答:
I think you could do this by joining on row numbers, something like:

```<code>WITH datanumbered AS (
   SELECT dateValue, ROW_NUMBER() OVER (ORDER BY dateValue) AS rownum
)
SELECT first.rownum, DATEDIFF(second, first.dateValue, second.dateValue) AS TimeDiff
FROM datenumbered first
    JOIN datenumbered second ON first.rownum = second.rownum - 1
</code>```

Then the calculate average by using the above query as a subquery.

Body:
I think you could do this by joining on row numbers, something like:

WITH datanumbered AS (
   SELECT dateValue, ROW_NUMBER() OVER (ORDER BY dateValue) AS rownum
)
SELECT first.rownum, DATEDIFF(second, first.dateValue, second.dateValue) AS TimeDiff
FROM datenumbered first
    JOIN datenumbered second ON first.rownum = second.rownum - 1

Then the calculate average by using the above query as a subquery.


问:
Proper way to send an Authenticity Token with AJAX to Rails
This works but gets stopped because it lacks an authenticity token:

```<code>$(".ajax-referral").click(function(){
  $.ajax({type: "POST", url: $(this).parent("form").attr("action"), dataType: "script"});
  return false;
});
</code>```

So I tried adding it like so:

```<code>$(".ajax-referral").click(function(){
  $.ajax({type: "POST", url: $(this).parent("form").attr("action") + "?&authenticity_token=" + AUTH_TOKEN, dataType: "script"});
  return false;
});
</code>```

And it passes the auth_token correctly as a param, but seems to lose the rest of my form.

Anyways to accomplish both sending the form data that works, and the authenticity token as well?

This is a rails environment. And I have this in my head.

```<code>= javascript_tag "var AUTH_TOKEN = '#{form_authenticity_token}';" if protect_against_forgery?
</code>```

Things I've tried

1.

```<code>= hidden_field :authenticity_token, :value => form_authenticity_token
</code>```

2.

```<code>$.ajax({type: "POST", url: $(this).parent("form").attr("action"), dataType: "script", authenticity_token: AUTH_TOKEN});
</code>```

3.

```<code>// Always send the authenticity_token with ajax
$(document).ajaxSend(function(event, request, settings) {
    if ( settings.type != 'GET' ) {
        settings.data = (settings.data ? settings.data + "&" : "")
            + "authenticity_token=" + encodeURIComponent( AUTH_TOKEN );
    }
});
</code>```

答: Simply using form_tag automatically includes CSRF token parameter. Rails supports "Unobtrusive Javascript" meaning that the form will still be submitted via AJAX. Controller actions support "respond_to" block, and you can use .js.erb extension to make changes on the web page in response to form submit. </p>

ContentLicense: CC BY-SA 4.0

Body:
This works but gets stopped because it lacks an authenticity token:

$(".ajax-referral").click(function(){
  $.ajax({type: "POST", url: $(this).parent("form").attr("action"), dataType: "script"});
  return false;
});

So I tried adding it like so:

$(".ajax-referral").click(function(){
  $.ajax({type: "POST", url: $(this).parent("form").attr("action") + "?&authenticity_token=" + AUTH_TOKEN, dataType: "script"});
  return false;
});

And it passes the auth_token correctly as a param, but seems to lose the rest of my form.

Anyways to accomplish both sending the form data that works, and the authenticity token as well?

This is a rails environment. And I have this in my head.

= javascript_tag "var AUTH_TOKEN = '#{form_authenticity_token}';" if protect_against_forgery?

Things I've tried

1.

= hidden_field :authenticity_token, :value => form_authenticity_token

2.

$.ajax({type: "POST", url: $(this).parent("form").attr("action"), dataType: "script", authenticity_token: AUTH_TOKEN});

3.

// Always send the authenticity_token with ajax
$(document).ajaxSend(function(event, request, settings) {
    if ( settings.type != 'GET' ) {
        settings.data = (settings.data ? settings.data + "&" : "")
            + "authenticity_token=" + encodeURIComponent( AUTH_TOKEN );
    }
});


问:
Best way to list files in Java, sorted by Date Modified?
I want to get a list of files in a directory, but I want to sort it such that the oldest files are first.  My solution was to call File.listFiles and just resort the list based on File.lastModified, but I was wondering if there was a better way.

Edit: My current solution, as suggested, is to use an anonymous Comparator:

```<code>File[] files = directory.listFiles();

Arrays.sort(files, new Comparator<File>(){
    public int compare(File f1, File f2)
    {
        return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
    } });
</code>```

答:
Elegant solution since Java 8:

```<code>File[] files = directory.listFiles();
Arrays.sort(files, Comparator.comparingLong(File::lastModified));
</code>```

Or, if you want it in descending order, just reverse it:

```<code>File[] files = directory.listFiles();
Arrays.sort(files, Comparator.comparingLong(File::lastModified).reversed());
</code>```

OwnerDisplayName: fezmonkey

Body:
I want to get a list of files in a directory, but I want to sort it such that the oldest files are first.  My solution was to call File.listFiles and just resort the list based on File.lastModified, but I was wondering if there was a better way.

Edit: My current solution, as suggested, is to use an anonymous Comparator:

File[] files = directory.listFiles();

Arrays.sort(files, new Comparator<File>(){
    public int compare(File f1, File f2)
    {
        return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
    } });

LastEditorDisplayName: fezmonkey

Body:
Elegant solution since Java 8:

File[] files = directory.listFiles();
Arrays.sort(files, Comparator.comparingLong(File::lastModified));

Or, if you want it in descending order, just reverse it:

File[] files = directory.listFiles();
Arrays.sort(files, Comparator.comparingLong(File::lastModified).reversed());


问:
Correct microdata markup for breadcrumbs
On researching how to do microdata for webpage breadcrumbs, I've found a couple of methods and I'm not sure which is correct. Firstly, my basic breadcrumbs in the HTML look like this:

```<code><div>
  <a href="/">Root page</a>
  <a href="/category">Category page</a>
  <a href="/category/this-page">This page</a>
</div>
</code>```

Now, do I structure it like this (as I've seen in an example on SchemaOrg:

```<code><ol itemscope itemtype="http://schema.org/BreadcrumbList">
  <li itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">
    <a href="/" itemprop="item">
      <span itemprop="name">Root page</span>
    </a>
  </li>
  <li itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">
    <a href="/category" itemprop="item">
      <span itemprop="name">Category page</span>
    </a>
  </li>
  <li itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">
    <a href="/category/this-page" itemprop="item">
      <span itemprop="name">This page</span>
    </a>
  </li>
</ol>
</code>```

Or do I structure it like the below as I've seen in some Stackoverflow answers:

```<code><div>
  <span itemscope itemtype="http://data-vocabulary.org/Breadcrumb">
    <a href="/" itemprop="url">
      <span itemprop="title">Root page</span>
    </a>
  </span>
  <span itemscope itemtype="http://data-vocabulary.org/Breadcrumb">
    <a href="/category" itemprop="url">
      <span itemprop="title">Category page</span>
    </a>
  </span>
  <span itemscope itemtype="http://data-vocabulary.org/Breadcrumb">
    <a href="/category/this-page" itemprop="url">
      <span itemprop="title">This page</span>
    </a>
  </span>
</div>
</code>```

Or a different method I don't know about yet??

答:
Use Schema.org as data-vocabulary.org is abandoned.

There were a few markups when the idea came up. But since then the standard has arrised as being Schema.org. It's of course supported by Google and given in its examples (one is BreadCrumbs).

Body:
On researching how to do microdata for webpage breadcrumbs, I've found a couple of methods and I'm not sure which is correct. Firstly, my basic breadcrumbs in the HTML look like this:

  Root page
  Category page
  This page

Now, do I structure it like this (as I've seen in an example on SchemaOrg:

      Root page

      Category page

      This page

Or do I structure it like the below as I've seen in some Stackoverflow answers:

      Root page

      Category page

      This page

Or a different method I don't know about yet??


问:
How Spring data jpa checks whether to perform update or save?
Spring data jpa contains only save method unlike hibernate where we have save as well as update method. So how spring data jpa checks whether to update or save the current object .</p>

答:
With Spring data JPA 'save' is for both update and save, and even for adding a new row to a table.

```<code>@Transactional
public void UpdateStudent(Student student) {
    this.studentRepository.save(student);
}
</code>```

For example this method saves the current existing student object with all its changed properties (if any) or if the student object instance is a new one then it will be inserted into the table.

With the @Transactional annotation as soon as the method exits it flushes the instance to the table.

Spring data JPA is able to do both save and update (which are the same) and also inserting a new row since the primary key is immutable.

Body:
With Spring data JPA 'save' is for both update and save, and even for adding a new row to a table.

@Transactional
public void UpdateStudent(Student student) {
    this.studentRepository.save(student);
}

For example this method saves the current existing student object with all its changed properties (if any) or if the student object instance is a new one then it will be inserted into the table.

With the @Transactional annotation as soon as the method exits it flushes the instance to the table.

Spring data JPA is able to do both save and update (which are the same) and also inserting a new row since the primary key is immutable.


问:
how to let the parent view know that the subview has been removed - iphone
My app has a tab view controller as the main access point.
However, when it runs for the first time, I need to check for some basic data, and if that is missing, I need to show a view to capture this information first . The table in the tab view uses this information to display the data.

The way I am doing it is like this:
In my app-delegate, I show the tab view.
Then check for information x. If not present, add subview view2 and show it on top.
In view2, I capture the information, and on click of a button remove it from superview. The required data is stored in global variables in the model.
Now, the control goes back to the tab view which showed it.
The problem is that I need to reload the table data in the tab view so that it reflects the correct information. However, I am not able to capture this in my parent tab view. So, the only way I can do a refresh is by manually clicking a button, which is not ideal. I want it to automatically refresh as soon as the subview is removed from the stack.

答:
A great way to do this is to have your model post a notification when the new data is added to it.  Your table view controller can listen for that notification, and when it receives it, can reload its data.

Check out Apple's explanations of Posting a Notification and Registering for a Notification.


问:
Chrome Extension sendMessage error from content script to background html
I just updated my chrome extension to json version 2, and am trying to get my extension to work again. The problem is sendRequest was depreciated along the way.  So I copy the code from https://developer.chrome.com/extensions/messaging.html  into my script and modify it to my own variable names, and it doesn't work.

So then I go back and put in the original code and it still doesn't work.  I have read multiple questions that are similar [and hopefully this won't get closed as a duplicate, because none of them were the same as my situation].

manifest.json:

```<code>{
   "background": {
        "page": "background.html"
        },
    ... ... ...
   "content_scripts": [ {
      "css": [ "style.css" ],
      "js": [ "jq.js", "script.js" ],
      "matches": [ "http://*.craigslist.org/*/*.htm*" ]
   } ],
   ... ... ...
   "permissions": [ "tabs", "http://*.craigslist.org/*/*.htm*" ],
   "manifest_version": 2,
   "update_url": "http://clients2.google.com/service/update2/crx",
   "version": "3.0"
}
</code>```

background.html:

```<code><html>
<script type='text/javascript'>
   chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
  });
    });
</script>
</html>
</code>```

script.js:

```<code>chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
  console.log(response.farewell);
});
</code>```

Now I run a page [on craigslist], and go to the Console and this is the error:

```<code>Port error: Could not establish connection. Receiving end does not exist.
TypeError: Cannot read property 'farewell' of undefined
    at chrome-extension://dhmjefbokfkjpdbigkadjpgjeflchgea/script.js:9:23
</code>```

I use Chrome Beta on Ubuntu 12.10 64-bit (Google Chrome: 27.0.1453.15 (Official Build 191758) beta)

答:
background script

```<code>chrome.tabs.getAllInWindow(null, function(tabs) {
      $.each(tabs, function() {
        chrome.tabs.sendRequest(this.id, {"action":"action_name"} );
      });
    });
</code>```

content script

```<code>chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
  if(request.action === 'action_name')
  {
    alert('handle event in the content script!!!!')
  }
});
</code>```

Body:
I just updated my chrome extension to json version 2, and am trying to get my extension to work again. The problem is sendRequest was depreciated along the way.  So I copy the code from https://developer.chrome.com/extensions/messaging.html  into my script and modify it to my own variable names, and it doesn't work.

So then I go back and put in the original code and it still doesn't work.  I have read multiple questions that are similar [and hopefully this won't get closed as a duplicate, because none of them were the same as my situation].

manifest.json:

{
   "background": {
        "page": "background.html"
        },
    ... ... ...
   "content_scripts": [ {
      "css": [ "style.css" ],
      "js": [ "jq.js", "script.js" ],
      "matches": [ "http://*.craigslist.org/*/*.htm*" ]
   } ],
   ... ... ...
   "permissions": [ "tabs", "http://*.craigslist.org/*/*.htm*" ],
   "manifest_version": 2,
   "update_url": "http://clients2.google.com/service/update2/crx",
   "version": "3.0"
}

background.html:

script.js:

chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
  console.log(response.farewell);
});

Now I run a page [on craigslist], and go to the Console and this is the error:

Port error: Could not establish connection. Receiving end does not exist.
TypeError: Cannot read property 'farewell' of undefined
    at chrome-extension://dhmjefbokfkjpdbigkadjpgjeflchgea/script.js:9:23

I use Chrome Beta on Ubuntu 12.10 64-bit (Google Chrome: 27.0.1453.15 (Official Build 191758) beta)

Body:
background script

chrome.tabs.getAllInWindow(null, function(tabs) {
      $.each(tabs, function() {
        chrome.tabs.sendRequest(this.id, {"action":"action_name"} );
      });
    });

content script

chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
  if(request.action === 'action_name')
  {
    alert('handle event in the content script!!!!')
  }
});