问:
Why does this line from "The Julia Language Documentation" define an outside constructor for a case where input parameteres are different types?
I'm re-reading The Julia Language Documentation in interest for building a performance sound queue application, and the section regarding parametric constructors and outer constructors has me confused. The example they show is as follows:

```<code>julia> struct OurRational{T<:Integer} <: Real
           num::T
           den::T
           function OurRational{T}(num::T, den::T) where T<:Integer
               if num == 0 && den == 0
                    error("invalid rational: 0//0")
               end
               g = gcd(den, num)
               num = div(num, g)
               den = div(den, g)
               new(num, den)
           end
       end

julia> OurRational(n::T, d::T) where {T<:Integer} = OurRational{T}(n,d)
OurRational

julia> OurRational(n::Integer, d::Integer) = OurRational(promote(n,d)...)
OurRational

julia> OurRational(n::Integer) = OurRational(n,one(n))
OurRational
</code>```

The documentation states:

The first is the "standard" general (outer) constructor that infers the type parameter T from the type of the numerator and denominator when they have the same type.

From this I come to understand this constructor handles the case of two parameters. It infers T from (num and den)'s type, then supplies it to the OurRational internal constructor.

The documentation goes on to say:

The second applies when the given numerator and denominator values have different types: it promotes them to a common type and then delegates construction to the outer constructor for arguments of matching type.

Looking at the code, I do not see how this is case. Based on how I think Julia is evaluating, wouldn't the second constructor handle the case where both n and d are explicit Integers? If otherwise, I am seriously having trouble seeing how Julia sees this line. Also, the ellipses in the assignment suffix means something like "now go to the outer constructor for when both parameters have the same type" right?

I understand the third outer constructor well.

答:
The first and second outer constructors differ because the second one handles a case where the numerator and denomenator are both integers, but are two different concrete subtypes, both of the abstract type Integer.

Julia as you know has many builtin Integer types. Consider for example UInt8,
which is the default type for single byte syntax, such as 0x1f. Look at the results when
we mix UInt8 and the default Integer type, Int64:

```<code>julia> struct OurRational{T<:Integer} <: Real
           num::T
           den::T
           function OurRational{T}(num::T, den::T) where T<:Integer
               println("Inner")
               if num == 0 && den == 0
                   error("invalid rational: 0//0")
               end
               g = gcd(den, num)
               num = div(num, g)
               den = div(den, g)
               new(num, den)
           end
       end

julia>

julia> OurRational(n::T, d::T) where {T<:Integer} = begin println("Outer 1"); OurRational{T}(n,d) end
OurRational

julia> OurRational(n::Integer, d::Integer) = begin println("Outer 2"); OurRational(promote(n,d)...) end
OurRational

julia> OurRational(n::Integer) = begin println("Outer 3"); OurRational(n,one(n)) end
OurRational

julia> OurRational{UInt8}(0x2, 0x5)
Inner
OurRational{UInt8}(0x02, 0x05)

julia> OurRational(2, 5)
Outer 1
Inner
OurRational{Int64}(2, 5)

julia> OurRational(0x2, 5)
Outer 2
Outer 1
Inner
OurRational{Int64}(2, 5)

julia> OurRational(0x3)
Outer 3
Outer 1
Inner
OurRational{UInt8}(0x03, 0x01)
</code>```

So, the second outer constructor promotes the arguments to same type and then hands them off to the first outer constructor, which then hands off to the inner constructor.

Body:
I'm re-reading The Julia Language Documentation in interest for building a performance sound queue application, and the section regarding parametric constructors and outer constructors has me confused. The example they show is as follows:

julia> struct OurRational{T<:Integer} <: Real
           num::T
           den::T
           function OurRational{T}(num::T, den::T) where T<:Integer
               if num == 0 && den == 0
                    error("invalid rational: 0//0")
               end
               g = gcd(den, num)
               num = div(num, g)
               den = div(den, g)
               new(num, den)
           end
       end

julia> OurRational(n::T, d::T) where {T<:Integer} = OurRational{T}(n,d)
OurRational

julia> OurRational(n::Integer, d::Integer) = OurRational(promote(n,d)...)
OurRational

julia> OurRational(n::Integer) = OurRational(n,one(n))
OurRational

The documentation states:

The first is the "standard" general (outer) constructor that infers the type parameter T from the type of the numerator and denominator when they have the same type.

From this I come to understand this constructor handles the case of two parameters. It infers T from (num and den)'s type, then supplies it to the OurRational internal constructor.

The documentation goes on to say:

The second applies when the given numerator and denominator values have different types: it promotes them to a common type and then delegates construction to the outer constructor for arguments of matching type.

Looking at the code, I do not see how this is case. Based on how I think Julia is evaluating, wouldn't the second constructor handle the case where both n and d are explicit Integers? If otherwise, I am seriously having trouble seeing how Julia sees this line. Also, the ellipses in the assignment suffix means something like "now go to the outer constructor for when both parameters have the same type" right?

I understand the third outer constructor well.

Body:
The first and second outer constructors differ because the second one handles a case where the numerator and denomenator are both integers, but are two different concrete subtypes, both of the abstract type Integer.

Julia as you know has many builtin Integer types. Consider for example UInt8,
which is the default type for single byte syntax, such as 0x1f. Look at the results when
we mix UInt8 and the default Integer type, Int64:

julia> struct OurRational{T<:Integer} <: Real
           num::T
           den::T
           function OurRational{T}(num::T, den::T) where T<:Integer
               println("Inner")
               if num == 0 && den == 0
                   error("invalid rational: 0//0")
               end
               g = gcd(den, num)
               num = div(num, g)
               den = div(den, g)
               new(num, den)
           end
       end

julia>

julia> OurRational(n::T, d::T) where {T<:Integer} = begin println("Outer 1"); OurRational{T}(n,d) end
OurRational

julia> OurRational(n::Integer, d::Integer) = begin println("Outer 2"); OurRational(promote(n,d)...) end
OurRational

julia> OurRational(n::Integer) = begin println("Outer 3"); OurRational(n,one(n)) end
OurRational

julia> OurRational{UInt8}(0x2, 0x5)
Inner
OurRational{UInt8}(0x02, 0x05)

julia> OurRational(2, 5)
Outer 1
Inner
OurRational{Int64}(2, 5)

julia> OurRational(0x2, 5)
Outer 2
Outer 1
Inner
OurRational{Int64}(2, 5)

julia> OurRational(0x3)
Outer 3
Outer 1
Inner
OurRational{UInt8}(0x03, 0x01)

So, the second outer constructor promotes the arguments to same type and then hands them off to the first outer constructor, which then hands off to the inner constructor.


来源: stackexchange

问:
Axis averages for 2D plots in matplotlib
I am plotting a 3 dimensional data set (x, y, and a value - so effectively a gray-scale image) with matplotlib. I want to create a bar to the side of the plot with the average row-wise Y values, and a bar to the bottom with the average column-wise X values. The net result should be similar scatter hist (but instead of histograms on the side it is just a bar of color representing that particular row/column).

I have seen these plots before and would like to use one, I just can't figure out the name of the function.

Thanks for the help :)

i.e.

```<code>[1,2,3,4] |  [5
[4,3,2,1] |  5
[1,1,4,4] |  2.5]
----------
[2,2,3,3]
</code>```

答:
Here is a way to draw the images in different subplots. xticks in the main image are moved to the top, and removed from the right bar.

A test function is chosen to have identifiable features in both directions.

vmin and vmax are used to set the color range: image values at vmin get mapped to the lowest color (black-alike for the inferno colormap, or white for the Greys colormap), while image values at vmax get mapped to the highest color (yellow for inferno, black for Greys). Image values between vmin and vmax get gradually mapped to the colors inbetween.  Image values lower than vmin get mapped to the same lowest color.

It is important that the vmin and vmax for the 3 images is equal, so all three get the same color transformation. If vminand vmax are not set, matplotlib calculates the lowest and highest value from the data. But the means typically have a smaller range of values, so corresponding values wouldn't be colored equally anymore.

Instead of setting vmin and vmax, a norm could be given. A norm has a similar function, but is more powerful, for example when a logarithmic transformation is needed.

from matplotlib import pyplot as plt
import numpy as np

x, y = np.meshgrid(np.linspace(-10, 10, 200), np.linspace(-10, 10, 200))
z = np.where((x < 7) & (y < 9), np.sin(x) + np.cos(y) ** 2, 2-np.cos(x) ** 2)

z1 = np.mean(z, axis=1).reshape(x.shape[0], 1)
z0 = np.mean(z, axis=0).reshape(1, x.shape[1])

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(7, 7),
                         gridspec_kw={'width_ratios': [10, 1], 'height_ratios': [10, 1], 'wspace': 0.1, 'hspace': 0.1})

vmin, vmax = -1, 2
cmap = plt.cm.inferno
extent=[-10, 10, -10, 10]

axes[0][0].imshow(z, cmap=cmap, extent=extent, vmin=vmin, vmax=vmax, aspect=1, origin='lower')
axes[0][0].xaxis.tick_top()

axes[0][1].imshow(z1, cmap=cmap, extent=extent, vmin=vmin, vmax=vmax, aspect=10, origin='lower')
axes[0][1].set_xticks([])
axes[0][1].yaxis.tick_right()

axes[1][0].imshow(z0, cmap=cmap, extent=extent, vmin=vmin, vmax=vmax, aspect=1 / 10, origin='lower')
axes[1][0].set_yticks([])

axes[1][1].axis('off')

plt.tight_layout()
plt.show()
```

ContentLicense: CC BY-SA 4.0

Body:
I am plotting a 3 dimensional data set (x, y, and a value - so effectively a gray-scale image) with matplotlib. I want to create a bar to the side of the plot with the average row-wise Y values, and a bar to the bottom with the average column-wise X values. The net result should be similar scatter hist (but instead of histograms on the side it is just a bar of color representing that particular row/column).

I have seen these plots before and would like to use one, I just can't figure out the name of the function.

Thanks for the help :)

i.e.

[1,2,3,4] |  [5
[4,3,2,1] |  5
[1,1,4,4] |  2.5]
----------
[2,2,3,3]


问:
In python, headings not in the same row
I extracted three columns from a larger data frame (recent_grads) as follows...

```<code>df = recent_grads.groupby('Major_category')['Men', 'Women'].sum()
</code>```

However, when I print df, it comes up as follows...

```<code>                                         Men    Women
Major_category
Agriculture & Natural Resources      40357.0    35263.0
Arts                                134390.0    222740.0
Biology & Life Science              184919.0    268943.0
Business                            667852.0    634524.0
Communications & Journalism         131921.0    260680.0
Computers & Mathematics             208725.0    90283.0
Education                           103526.0    455603.0
Engineering                         408307.0    129276.0
Health                               75517.0    387713.0
Humanities & Liberal Arts           272846.0    440622.0
Industrial Arts & Consumer Services 103781.0    126011.0
Interdisciplinary                     2817.0    9479.0
Law & Public Policy                  91129.0    87978.0
Physical Sciences                    95390.0    90089.0
Psychology & Social Work             98115.0    382892.0
Social Science                       256834.0   273132.0
</code>```

How do I get Major_category heading in the same row as Men and Women headings? I tried to put the three columns in a new data frame as follows...

```<code>df1 = df[['Major_category', 'Men', 'Women']].copy()
</code>```

This gives me an error (Major_category not in index)

答:
Seems like you want to convert the groupby object back to a dataframe try:</p>

```<code>df['Major_category'].apply(pd.DataFrame)
</code>```

Title: In python, headings not in the same row

Body:
I extracted three columns from a larger data frame (recent_grads) as follows...

df = recent_grads.groupby('Major_category')['Men', 'Women'].sum()

However, when I print df, it comes up as follows...

                                         Men    Women
Major_category
Agriculture & Natural Resources      40357.0    35263.0
Arts                                134390.0    222740.0
Biology & Life Science              184919.0    268943.0
Business                            667852.0    634524.0
Communications & Journalism         131921.0    260680.0
Computers & Mathematics             208725.0    90283.0
Education                           103526.0    455603.0
Engineering                         408307.0    129276.0
Health                               75517.0    387713.0
Humanities & Liberal Arts           272846.0    440622.0
Industrial Arts & Consumer Services 103781.0    126011.0
Interdisciplinary                     2817.0    9479.0
Law & Public Policy                  91129.0    87978.0
Physical Sciences                    95390.0    90089.0
Psychology & Social Work             98115.0    382892.0
Social Science                       256834.0   273132.0

How do I get Major_category heading in the same row as Men and Women headings? I tried to put the three columns in a new data frame as follows...

df1 = df[['Major_category', 'Men', 'Women']].copy()

This gives me an error (Major_category not in index)

Body:
Seems like you want to convert the groupby object back to a dataframe try:

df['Major_category'].apply(pd.DataFrame)


问:
Changing line width of Cartopy borders
I am trying to make a basic map of North America, but I cannot figure out how to make the line width of the coastline and the administrative border smaller. There does not seem to be a built in option for this. Is there an easy work around? Below is my code thus far.</p>

```<code>import matplotlib.pyplot as plt
import cartopy.feature as cfeature
import cartopy.crs as ccrs

east = -63
west = -123
north = 55
south = 20
fig = plt.figure()
ax=fig.add_subplot(1,1,1,projection=ccrs.AlbersEqualArea)
ax.set_extent([west, east, south, north])
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.LAND,color='grey')
ax.add_feature(cfeature.BORDERS)
ax.add_feature(cfeature.COASTLINE)
</code>```

答:
The outline for your map is part of the ax.outline_patch method. As mentioned here:

https://scitools.org.uk/cartopy/docs/latest/matplotlib/geoaxes.html

https://scitools.org.uk/cartopy/docs/latest/matplotlib/geoaxes.html#cartopy.mpl.geoaxes.GeoAxes.outline_patch

https://github.com/SciTools/cartopy/issues/1077

using a modified version of:

https://matplotlib.org/api/_as_gen/matplotlib.patches.Patch.html#matplotlib.patches.Patch

Working code example:

```<code>import matplotlib.pyplot as plt
import cartopy.feature as cfeature
import cartopy.crs as ccrs

east = -63
west = -123
north = 55
south = 20
fig = plt.figure()
ax = plt.subplot(1,1,1, projection=ccrs.AlbersEqualArea())
ax.set_extent([west, east, south, north])
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.LAND,color='grey')
ax.add_feature(cfeature.BORDERS)
ax.add_feature(cfeature.COASTLINE)

#Add your line modifications here
ax.outline_patch.set_linewidth(5)
ax.outline_patch.set_linestyle(':')
</code>```

ContentLicense: CC BY-SA 3.0

Title: Changing line width of Cartopy borders

Body:
I am trying to make a basic map of North America, but I cannot figure out how to make the line width of the coastline and the administrative border smaller. There does not seem to be a built in option for this. Is there an easy work around? Below is my code thus far.

import matplotlib.pyplot as plt
import cartopy.feature as cfeature
import cartopy.crs as ccrs

east = -63
west = -123
north = 55
south = 20
fig = plt.figure()
ax=fig.add_subplot(1,1,1,projection=ccrs.AlbersEqualArea)
ax.set_extent([west, east, south, north])
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.LAND,color='grey')
ax.add_feature(cfeature.BORDERS)
ax.add_feature(cfeature.COASTLINE)

Body:
The outline for your map is part of the ax.outline_patch method. As mentioned here:

https://scitools.org.uk/cartopy/docs/latest/matplotlib/geoaxes.html

https://scitools.org.uk/cartopy/docs/latest/matplotlib/geoaxes.html#cartopy.mpl.geoaxes.GeoAxes.outline_patch

https://github.com/SciTools/cartopy/issues/1077

using a modified version of:

https://matplotlib.org/api/_as_gen/matplotlib.patches.Patch.html#matplotlib.patches.Patch

Working code example:

import matplotlib.pyplot as plt
import cartopy.feature as cfeature
import cartopy.crs as ccrs

east = -63
west = -123
north = 55
south = 20
fig = plt.figure()
ax = plt.subplot(1,1,1, projection=ccrs.AlbersEqualArea())
ax.set_extent([west, east, south, north])
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.LAND,color='grey')
ax.add_feature(cfeature.BORDERS)
ax.add_feature(cfeature.COASTLINE)

#Add your line modifications here
ax.outline_patch.set_linewidth(5)
ax.outline_patch.set_linestyle(':')


问:
is there a function in lodash to replace matched item
I wonder if there is a simpler method in lodash to replace an item in a JavaScript collection? (Possible duplicate but I did not understand the answer there:)

I looked at their documentation but could not find anything

My code is:

```<code>var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];
// Can following code be reduced to something like _.XX(arr, {id:1}, {id:1, name: "New Name"});
_.each(arr, function(a, idx){
  if(a.id === 1){
    arr[idx] = {id:1, name: "Person New Name"};
    return false;
  }
});

_.each(arr, function(a){
  document.write(a.name);
});
</code>```

Update:
The object I'm trying to replace with has many properties like

{id: 1, Prop1: ..., Prop2:..., and so on}

Solution:

Thanks to dfsq but I found a proper solution within lodash that seems to work fine and is pretty neat and I put it in a mixin as well since I've this requirement at many places. JSBin

```<code>var update = function(arr, key, newval) {
  var match = _.find(arr, key);
  if(match)
    _.merge(match, newval);
  else
    arr.push(newval);
};

_.mixin({ '$update': update });

var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];

_.$update(arr, {id:1}, {id:1, name: "New Val"});

document.write(JSON.stringify(arr));
</code>```

Faster Solution
As pointed out by @dfsq, following is way faster

```<code>var upsert = function (arr, key, newval) {
    var match = _.find(arr, key);
    if(match){
        var index = _.indexOf(arr, _.find(arr, key));
        arr.splice(index, 1, newval);
    } else {
        arr.push(newval);
    }
};
</code>```

答:
Immutable, suitable for ReactJS:

Assume:

```<code>cosnt arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];
</code>```

The updated item is the second and name is changed to Special Person:

```<code>const updatedItem = {id:2, name:"Special Person"};
</code>```

Hint: the lodash has useful tools but now we have some of them on Ecmascript6+, so I just use map function that is existed on both of lodash and ecmascript6+:

```<code>const newArr = arr.map(item => item.id === 2 ? updatedItem : item);
</code>```

Body:
I wonder if there is a simpler method in lodash to replace an item in a JavaScript collection? (Possible duplicate but I did not understand the answer there:)

I looked at their documentation but could not find anything

My code is:

var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];
// Can following code be reduced to something like _.XX(arr, {id:1}, {id:1, name: "New Name"});
_.each(arr, function(a, idx){
  if(a.id === 1){
    arr[idx] = {id:1, name: "Person New Name"};
    return false;
  }
});

_.each(arr, function(a){
  document.write(a.name);
});

Update:
The object I'm trying to replace with has many properties like

{id: 1, Prop1: ..., Prop2:..., and so on}

Solution:

Thanks to dfsq but I found a proper solution within lodash that seems to work fine and is pretty neat and I put it in a mixin as well since I've this requirement at many places. JSBin

var update = function(arr, key, newval) {
  var match = _.find(arr, key);
  if(match)
    _.merge(match, newval);
  else
    arr.push(newval);
};

_.mixin({ '$update': update });

var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];

_.$update(arr, {id:1}, {id:1, name: "New Val"});

document.write(JSON.stringify(arr));

Faster Solution
As pointed out by @dfsq, following is way faster

var upsert = function (arr, key, newval) {
    var match = _.find(arr, key);
    if(match){
        var index = _.indexOf(arr, _.find(arr, key));
        arr.splice(index, 1, newval);
    } else {
        arr.push(newval);
    }
};

Body:
Immutable, suitable for ReactJS:

Assume:

cosnt arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];

The updated item is the second and name is changed to Special Person:

const updatedItem = {id:2, name:"Special Person"};

Hint: the lodash has useful tools but now we have some of them on Ecmascript6+, so I just use map function that is existed on both of lodash and ecmascript6+:

const newArr = arr.map(item => item.id === 2 ? updatedItem : item);


问:
Detect Changes to Iframe Content
if it possible tell if an Iframe content has changed after the page has loaded?

```<code>$('iframe').on('load' function () {
alert('iframe loaded')
})
</code>```

will only alert once th page has loaded.

```<code>$('iframe').on('change' function () {
alert('iframe changed')
})
</code>```

is not called if addition content is added to the iframe

答:
If the content of the iframe is on the same domain as the parent page, or if you have access to the iframed page so you can set its CORS policy to allow requests from the parent page, then you can watch for changes to specific elements or use MutationOberver to watch for changes to the iframe's DOM.

If not, then there's no way that I'm aware of to monitor the iframe for changes.

Title: Detect Changes to Iframe Content

Body:
if it possible tell if an Iframe content has changed after the page has loaded?

$('iframe').on('load' function () {
alert('iframe loaded')
})

will only alert once th page has loaded.

$('iframe').on('change' function () {
alert('iframe changed')
})

is not called if addition content is added to the iframe


问:
How to check if a value exists in an object using JavaScript
I have an object in JavaScript:

```<code>var obj = {
   "a": "test1",
   "b": "test2"
}
</code>```

How do I check that test1 exists in the object as a value?

答:
The simple answer to this is given below.

This is working because every JavaScript type has a “constructor” property on it prototype”.

let array = []
array.constructor === Array
// => true

let data = {}
data.constructor === Object
// => true
```

Body:
I have an object in JavaScript:

var obj = {
   "a": "test1",
   "b": "test2"
}

How do I check that test1 exists in the object as a value?


问:
adding info to DataNavigateUrlFormatString not in the datagrid
I have a datagrid that has a DataNavigateUrlFormatString that passes info on to the next page when the user clicks on the link.  However I am trying to add some functionality to the next page and want to add some data to the url that is not in the bound columns.  Is there a way to do this?   Right now it looks like

```<code> DataNavigateUrlFormatString="~/cakes/PaymentHistory.aspx?id={0}"
</code>```

and I would like it to look like

```<code> DataNavigateUrlFormatString="~/Taxes/PaymentHistory.aspx?id={0}&year="
</code>```

Thanks

答:
You can do like this:

```<code>DataNavigateUrlFormatString="~/Taxes/PaymentHistory.aspx?id={0}&year={1}"
</code>```

and then retrieve like this :

```<code>Dim id  As String = Request.QueryString("id")
Dim year As String = Request.QueryString("year")
</code>```

Body:
I have a datagrid that has a DataNavigateUrlFormatString that passes info on to the next page when the user clicks on the link.  However I am trying to add some functionality to the next page and want to add some data to the url that is not in the bound columns.  Is there a way to do this?   Right now it looks like

 DataNavigateUrlFormatString="~/cakes/PaymentHistory.aspx?id={0}"

and I would like it to look like

 DataNavigateUrlFormatString="~/Taxes/PaymentHistory.aspx?id={0}&year="

Thanks

Body:
You can do like this:

DataNavigateUrlFormatString="~/Taxes/PaymentHistory.aspx?id={0}&year={1}"

and then retrieve like this :

Dim id  As String = Request.QueryString("id")
Dim year As String = Request.QueryString("year")


问:
jQuery Multiple Ifs
I want to be able to have something check if a CSS class exists somewhere and do something, then be able to check if another CSS class exists somewhere and do something. So if .bp2 exists, do this, but also check if .bp3 exists and if it does, do this other thing. They don't need to both exist and if the first exists, the second should still check itself and run too. Do I need to just copy/paste this code each time or is there a way to condense it all together?

```<code>$('.lot2').click(function () {
    if ($('.bp2').hasClass('showbp')) {
        $('.bp2').removeClass('showbp');
    } else {
        $('.bp2').addClass('showbp');
    }
});
</code>```

答:
You can perform multiple if statements.

```<code>$('.lot2').click(function() {
  if($(".bp2").length) {
    $(".bp2").each(function(){
      $(this).toggleClass("showbp");
    });
  }
  if($('.bp3').length){
    // Do a thing
  }
});
</code>```

Using the .length will help us determine if any elements of that selector exist. It will result in 0 or a number greater than 0. An if statement will evaluate a 0 as False and 1 or higher as True.

Using .each() we can iterate each item of that collection. We can then use .toggleClass() to add or remove a specific class.

See More:

https://api.jquery.com/length/

https://api.jquery.com/each/

https://api.jquery.com/toggleClass/

Title: jQuery Multiple Ifs

Body:
I want to be able to have something check if a CSS class exists somewhere and do something, then be able to check if another CSS class exists somewhere and do something. So if .bp2 exists, do this, but also check if .bp3 exists and if it does, do this other thing. They don't need to both exist and if the first exists, the second should still check itself and run too. Do I need to just copy/paste this code each time or is there a way to condense it all together?

$('.lot2').click(function () {
    if ($('.bp2').hasClass('showbp')) {
        $('.bp2').removeClass('showbp');
    } else {
        $('.bp2').addClass('showbp');
    }
});

Body:
You can perform multiple if statements.

$('.lot2').click(function() {
  if($(".bp2").length) {
    $(".bp2").each(function(){
      $(this).toggleClass("showbp");
    });
  }
  if($('.bp3').length){
    // Do a thing
  }
});

Using the .length will help us determine if any elements of that selector exist. It will result in 0 or a number greater than 0. An if statement will evaluate a 0 as False and 1 or higher as True.

Using .each() we can iterate each item of that collection. We can then use .toggleClass() to add or remove a specific class.

See More:

https://api.jquery.com/length/

https://api.jquery.com/each/

https://api.jquery.com/toggleClass/


问:
Problems with a constraint in Julia JuMP
I'm having troubles with the following constraint in JuMP

```<code>@constraint(m, rBalance[h in H, k in P, m in M], sum(X[i,h,k,m] for i in SO) == (sum(X[h,h,k,r] for r in M if r!=m) + sum(X[h,j,k,m] for j in SD if j!= h)).
</code>```

I got the following error msg

"No method matching add_Contraint(::String, ::ScalarConstraint{GenericAffExpr{Float64,VariableRef},MathOptInterface.EqualTo{Float64}},::String)" (see attached screenshot for more details)

Any thoughts?

Cheers
Guillermo

答: Both your model and your index are named m. This is a common error; it's why we removed all instances of m = Model() from the examples that we provide.

Body:
I'm having troubles with the following constraint in JuMP

@constraint(m, rBalance[h in H, k in P, m in M], sum(X[i,h,k,m] for i in SO) == (sum(X[h,h,k,r] for r in M if r!=m) + sum(X[h,j,k,m] for j in SD if j!= h)).

I got the following error msg

"No method matching add_Contraint(::String, ::ScalarConstraint{GenericAffExpr{Float64,VariableRef},MathOptInterface.EqualTo{Float64}},::String)" (see attached screenshot for more details)

Any thoughts?

Cheers
Guillermo


问:
Deserialize list of ids for many-to-many PUT operation
I have a User and Role model with a many-to-many relationship

```<code>class User(BaseModel, TimestampableMixin):

    username = Column(String(MEDIUM_STRING_LENGTH), nullable=False, unique=True)

    roles = relationship('Role', secondary='user_roles', back_populates='users')

class Role(BaseModel, TimestampableMixin):

    label = Column(String(MEDIUM_STRING_LENGTH), nullable=False, unique=True)

    users = relationship('User', secondary='user_roles', back_populates='roles')

class UserRole(BaseModel, TimestampableMixin):

    user_id = Column(ForeignKey('users.id', ondelete=CASCADE, onupdate=CASCADE), nullable=False, index=True)
    role_id = Column(ForeignKey('roles.id', onupdate=CASCADE), nullable=False, index=True)
</code>```

I then defined schemas for User to nest Roles.

```<code>class RoleSchema(BaseSchema):
    class Meta:
        model = models.Role

class UserSchema(BaseSchema):
    class Meta:
        model = models.User

    roles = fields.Nested('RoleSchema', many=True, exclude=['users'])
</code>```

For serialization this is working great where a list of role objects are included in a user GET request. What also works is POSTing a user with new role objects embedded in the request. What I have not been able to figure out is how to POST/PUT a list of existing role ids rather than create new objects.
For example, this request works:

```<code>{
    "username": "testuser12",
    "roles": [
        {
            "label": "newrole"
        }
    ]
}
</code>```

Response:

```<code>{
  "createdTime": "2020-02-06T19:13:29Z",
  "id": 4,
  "modifiedTime": "2020-02-06T19:13:29Z",
  "roles": [
    {
      "createdTime": "2020-02-06T19:13:29Z",
      "id": 2,
      "label": "newrole",
      "modifiedTime": "2020-02-06T19:13:29Z"
    }
  ],
  "username": "testuser12"
}
</code>```

But neither of these requests work:

```<code>{
    "username": "testuser13",
    "roles": [
        1
    ]
}

{
    "username": "testuser13",
    "roles": [
        {
            "id": 1
        }
    ]
}
</code>```

I'm getting this response:

```<code>{
  "errors": {
    "error": [
      "Unprocessable Entity"
    ],
    "message": [
      "The request was well-formed but was unable to be followed due to semantic errors."
    ]
  }
}
</code>```

I can tell I'm missing something in the schema to be able to ingest ids rather than objects, and I suspect I need to make use of dump_only/load_only and potentially a separate schema for PUT. But, I haven't been able to find an example anywhere online for this use case.

It may also be helpful to mention that I'm using flask-smorest for the request validation and schema argument ingestion.

```<code>@B_API.route('/user/<user_id>')
class UserByIdResource(MethodView):

    @B_API.response(schemas.UserSchema)
    def get(self, user_id):
        """
        Get a single user by id
        """
        return models.User.query.get(user_id)

    @B_API.arguments(schemas.UserSchema)
    @B_API.response(schemas.UserSchema)
    def put(self, updated_user, user_id):
        """
        Update fields of an existing user
        """
        models.User.query.get_or_404(user_id, description=f'User with id {user_id} not found')
        user = updated_user.update_with_db(user_id)
        return user
</code>```

update_with_db looks like:

```<code>    def update_with_db(self, id: int):
        self.id = id
        DB.session.merge(self)
        DB.session.commit()
        return self.query.get(id)
</code>```

Thanks for any assistance.

答:
I ended up resolving this by creating a separate PUT schema and using Pluck for role ids.

```<code>class UserSchema(BaseModelSchema):
    class Meta:
        model = models.User

    roles = fields.Nested('RoleSchema', many=True, exclude=['users'])

class UserPutSchema(BaseModelSchema):
    class Meta:
        model = models.User

    roles = fields.Pluck('RoleSchema', 'id', many=True)
</code>```

These schemas are implemented with the following resource, taking in PUT schema for input validation, and returning a standard User Schema to comply with the GET and POST responses. This seems to work well, with the only downside being having to define a separate schema.

```<code>    @B_API.arguments(schemas.UserPutSchema(partial=True))
    @B_API.response(schemas.UserSchema)
    def put(self, updated_user, user_id):
        """
        Update fields of an existing user
        """
        get_by_id(models.User, user_id)
        user = updated_user.update_with_db(user_id)
        return user
</code>```

I can now make a PUT request like

```<code>PUT /user/1
{
    "roles": [
        1,
        2
    ]
}
</code>```

and get a response like

```<code>{
  "createdTime": "2020-02-20T01:33:42Z",
  "historys": [],
  "id": 1,
  "modifiedTime": "2020-02-20T01:33:42Z",
  "roles": [
    {
      "createdTime": "2020-02-19T23:43:06Z",
      "description": null,
      "historys": [],
      "id": 1,
      "key": "TEST_ROLE_1",
      "label": "role 1",
      "modifiedTime": "2020-02-19T23:43:06Z"
    },
    {
      "createdTime": "2020-02-19T23:43:06Z",
      "description": null,
      "historys": [],
      "id": 2,
      "key": "TEST_ROLE_2",
      "label": "role 2",
      "modifiedTime": "2020-02-19T23:43:06Z"
    }
  ],
  "username": "testuser1"
}
</code>```

which is what I was aiming for.

Body:
I have a User and Role model with a many-to-many relationship

class User(BaseModel, TimestampableMixin):

    username = Column(String(MEDIUM_STRING_LENGTH), nullable=False, unique=True)

    roles = relationship('Role', secondary='user_roles', back_populates='users')

class Role(BaseModel, TimestampableMixin):

    label = Column(String(MEDIUM_STRING_LENGTH), nullable=False, unique=True)

    users = relationship('User', secondary='user_roles', back_populates='roles')

class UserRole(BaseModel, TimestampableMixin):

    user_id = Column(ForeignKey('users.id', ondelete=CASCADE, onupdate=CASCADE), nullable=False, index=True)
    role_id = Column(ForeignKey('roles.id', onupdate=CASCADE), nullable=False, index=True)

I then defined schemas for User to nest Roles.

class RoleSchema(BaseSchema):
    class Meta:
        model = models.Role

class UserSchema(BaseSchema):
    class Meta:
        model = models.User

    roles = fields.Nested('RoleSchema', many=True, exclude=['users'])

For serialization this is working great where a list of role objects are included in a user GET request. What also works is POSTing a user with new role objects embedded in the request. What I have not been able to figure out is how to POST/PUT a list of existing role ids rather than create new objects.
For example, this request works:

{
    "username": "testuser12",
    "roles": [
        {
            "label": "newrole"
        }
    ]
}

Response:

{
  "createdTime": "2020-02-06T19:13:29Z",
  "id": 4,
  "modifiedTime": "2020-02-06T19:13:29Z",
  "roles": [
    {
      "createdTime": "2020-02-06T19:13:29Z",
      "id": 2,
      "label": "newrole",
      "modifiedTime": "2020-02-06T19:13:29Z"
    }
  ],
  "username": "testuser12"
}

But neither of these requests work:

{
    "username": "testuser13",
    "roles": [
        1
    ]
}

{
    "username": "testuser13",
    "roles": [
        {
            "id": 1
        }
    ]
}

I'm getting this response:

{
  "errors": {
    "error": [
      "Unprocessable Entity"
    ],
    "message": [
      "The request was well-formed but was unable to be followed due to semantic errors."
    ]
  }
}

I can tell I'm missing something in the schema to be able to ingest ids rather than objects, and I suspect I need to make use of dump_only/load_only and potentially a separate schema for PUT. But, I haven't been able to find an example anywhere online for this use case.

It may also be helpful to mention that I'm using flask-smorest for the request validation and schema argument ingestion.

@B_API.route('/user/<user_id>')
class UserByIdResource(MethodView):

    @B_API.response(schemas.UserSchema)
    def get(self, user_id):
        """
        Get a single user by id
        """
        return models.User.query.get(user_id)

    @B_API.arguments(schemas.UserSchema)
    @B_API.response(schemas.UserSchema)
    def put(self, updated_user, user_id):
        """
        Update fields of an existing user
        """
        models.User.query.get_or_404(user_id, description=f'User with id {user_id} not found')
        user = updated_user.update_with_db(user_id)
        return user

update_with_db looks like:

    def update_with_db(self, id: int):
        self.id = id
        DB.session.merge(self)
        DB.session.commit()
        return self.query.get(id)

Thanks for any assistance.

Body:
I ended up resolving this by creating a separate PUT schema and using Pluck for role ids.

class UserSchema(BaseModelSchema):
    class Meta:
        model = models.User

    roles = fields.Nested('RoleSchema', many=True, exclude=['users'])

class UserPutSchema(BaseModelSchema):
    class Meta:
        model = models.User

    roles = fields.Pluck('RoleSchema', 'id', many=True)

These schemas are implemented with the following resource, taking in PUT schema for input validation, and returning a standard User Schema to comply with the GET and POST responses. This seems to work well, with the only downside being having to define a separate schema.

    @B_API.arguments(schemas.UserPutSchema(partial=True))
    @B_API.response(schemas.UserSchema)
    def put(self, updated_user, user_id):
        """
        Update fields of an existing user
        """
        get_by_id(models.User, user_id)
        user = updated_user.update_with_db(user_id)
        return user

I can now make a PUT request like

PUT /user/1
{
    "roles": [
        1,
        2
    ]
}

and get a response like

{
  "createdTime": "2020-02-20T01:33:42Z",
  "historys": [],
  "id": 1,
  "modifiedTime": "2020-02-20T01:33:42Z",
  "roles": [
    {
      "createdTime": "2020-02-19T23:43:06Z",
      "description": null,
      "historys": [],
      "id": 1,
      "key": "TEST_ROLE_1",
      "label": "role 1",
      "modifiedTime": "2020-02-19T23:43:06Z"
    },
    {
      "createdTime": "2020-02-19T23:43:06Z",
      "description": null,
      "historys": [],
      "id": 2,
      "key": "TEST_ROLE_2",
      "label": "role 2",
      "modifiedTime": "2020-02-19T23:43:06Z"
    }
  ],
  "username": "testuser1"
}

which is what I was aiming for.


问:
reshape circle in canvas
Hi I'm facing a problem with canvas.

I try to make a circle that can be reshape like this.
In the demo the circle can be reshape

the problem is to drag and drop the circle point to reshape it.

I know how to drag and drop point in the javascript canvas but how to reshape the cirle line to follow the point.

const DEBUG = true;

const WIDTH = window.innerWidth;
const HEIGHT = window.innerHeight;

const MIN_DIMENSION = WIDTH < HEIGHT ? WIDTH : HEIGHT;
const DEFAULT_RADIUS = MIN_DIMENSION * 0.45;
let canvas, ctx;

let cos = Math.cos;
let sin = Math.sin;
let pi = Math.PI;
let pi2 = pi * 2;

class Point {
  constructor(x,y) {
    this.x = x;
    this.y = y;
  }
}

function block(c, cb) {
  c.save();
  c.beginPath();
  cb(c);
  c.closePath();
  c.restore();
}

function circle(c,r) {
  c.arc(0, 0, r, 0, pi2);
}

function debugPoints(c, points) {
  points.forEach((p,i) => {
    if(i % 2 === 0) {
      c.fillStyle = 'red';
    } else {
      c.fillStyle = 'black';
    }
    c.beginPath();
    c.arc(p.x, p.y, 2, 0, pi2);
    c.fill();
    c.closePath();
  })
}

function bezierCirclePoints(r, n) {
  let a = pi2/(2*n);
  let R = r/cos(a);

  let points = new Array(2 * n);

  console.log('n:', n);
  console.log('a:', a);
  console.log('r:', r);
  console.log('R:', R);

  // calculate even bezier points
  for(let i = 0; i < n; i++) {
    let i2 = 2*i;
    let x = r * sin(i2 * a);
    let y = -r * cos(i2 * a);
    points[i2] =  new Point(x, y);
  }

  // calculate odd bezier points
  for(let i = 0; i < n; i++) {
    let i2 = 2*i + 1;
    let x = R * sin(i2 * a);
    let y = -R * cos(i2 * a);
    points[i2] =  new Point(x, y);
  }

  points.push(points[0]);
  return points;
}

function bezierCircle(c, r = DEFAULT_RADIUS, n = 7) {
  let points = bezierCirclePoints(r,n);

  c.translate(WIDTH * 0.5,HEIGHT * 0.5);

  if(DEBUG) {
    debugPoints(c, points);
  }

  c.fillStyle = 'red';
  c.strokeStyle = 'red';

  // draw circle
  c.beginPath();
  let p = points[0];
  c.moveTo(p.x, p.y);

  for(let i = 1; i < points.length; i+=2){
      let p1 = points[i];
      let i2 = i + 1;
      if(i2 >= points.length) {
        i2 = 0;
      }
      let p2 = points[i2];
      c.quadraticCurveTo(p1.x, p1.y, p2.x, p2.y);
  }

  c.stroke();
  c.closePath();
}

function redCircle(c) {
  c.fillStyle = 'red';
  c.translate(200,200);
  circle(c, 100);
  c.fill();
}

canvas = document.getElementById('circle');
canvas.width = WIDTH;
canvas.height = HEIGHT;
ctx = canvas.getContext('2d');

block(ctx, bezierCircle)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="circle"></canvas></code>```

答:
As you already realized a circle can be composed out of four bézier curves. I'm going to use a cubic instead of a quadratic though since it offers two control points.

Let's start by looking at the following illustration:

As we can see the red curve consists of start point A, end point B and two control points c1 & c2 respectively.

So if we want to have a circle at x, y with a radius of r we can say:

Ax = x ; Ay = y - r

Bx = x + r ; By = y

c1x = x + r / 2 ; c1y = y - r

c2x = x + r ; c2y = y - r / 2

Of course the missing three curves can be constructed in the same way.

What we can also see from the above illustration is that the start point for the red segment is also the end point for the orange segment. Likewise the orange segment's control point c8 is connected to the start point of the red segment.

So if we're about to move point A we need to move the orange segment's end point, the red segment's start point AND the two control points c8 and c1.

To do this I'd write a general Arc class which consists of the start point, the end point, the two control points and additionally to which arc the start point is connected to. Then it goes a little something like this:

if someone clicks on point A, B, C or D store the current mouse position

store the position of the arc's control point as well as the connected arc's control point

if the mouse is moved, move the start point, it's control point and the connected arc's end point and it's control point relative to the mouse movement

repaint the circle

Here's an example:

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

class Arc {
  constructor(pointA, pointB, controlPointA, controlPointB) {
    this.pointA = pointA;
    this.pointB = pointB;

    this.controlPointA = controlPointA;
    this.controlPointB = controlPointB;
    this.controlPointOldA = null;
    this.controlPointOldB = null;
  }

  update(x, y, x2, y2) {
    this.pointA.x = x;
    this.pointA.y = y;

    this.connectedArc.pointB.x = x;
    this.connectedArc.pointB.y = y;

    this.controlPointA.x = this.controlPointOldA.x + x2;
    this.controlPointA.y = this.controlPointOldA.y + y2;

    this.connectedArc.controlPointB.x = this.controlPointOldB.x + x2;
    this.connectedArc.controlPointB.y = this.controlPointOldB.y + y2;
  }

  connect(connectedArc) {
    this.connectedArc = connectedArc;
  }

  saveControlPoints() {
    this.controlPointOldA = new Point(this.controlPointA.x, this.controlPointA.y);
    this.controlPointOldB = new Point(this.connectedArc.controlPointB.x, this.connectedArc.controlPointB.y);
  }
}

class Circle {
  constructor(x, y, radius) {

    this.arcA = new Arc(new Point(x, y - radius), new Point(x + radius, y), new Point(x + radius / 2, y - radius), new Point(x + radius, y - radius / 2));
    this.arcB = new Arc(new Point(x + radius, y), new Point(x, y + radius), new Point(x + radius, y + radius / 2), new Point(x + radius / 2, y + radius));
    this.arcC = new Arc(new Point(x, y + radius), new Point(x - radius, y), new Point(x - radius / 2, y + radius), new Point(x - radius, y + radius / 2));
    this.arcD = new Arc(new Point(x - radius, y), new Point(x, y - radius), new Point(x - radius, y - radius / 2), new Point(x - radius / 2, y - radius));

    this.arcA.connect(this.arcD);
    this.arcB.connect(this.arcA);
    this.arcC.connect(this.arcB);
    this.arcD.connect(this.arcC);
  }

}
var circle = new Circle(150, 150, 75);

var mouseX, mouseY, selectedArc;
var width = 5;
var height = 5;
var dragging = false;
var canvas = document.getElementById("canvas");

var ctx = canvas.getContext("2d");

var arcs = [circle.arcA, circle.arcB, circle.arcC, circle.arcD];

var points = document.getElementsByClassName("point");
var arc;
for (var a = 0; a < points.length; a++) {
  arc = arcs[a];
  points[a].setAttribute('data-linkedID', a);
  points[a].style.left = (arc.pointA.x - width) + "px";
  points[a].style.top = (arc.pointA.y - height) + "px";
  points[a].addEventListener("mousedown", dragStarted);

}
document.addEventListener("mousemove", drag);
document.addEventListener("mouseup", dragStop);

function dragStarted(e) {
  mouseX = e.pageX;
  mouseY = e.pageY;
  selectedArc = arcs[e.target.parentElement.getAttribute("data-linkedID")];
  selectedArc.saveControlPoints();
  dragging = true;
}

function drag(e) {
  if (dragging) {
    selectedArc.update(e.pageX - width, e.pageY - height, e.pageX - mouseX, e.pageY - mouseY);
    update();

    var arc;
    for (var a = 0; a < points.length; a++) {
      arc = arcs[a];
      points[a].style.left = (arc.pointA.x - width) + "px";
      points[a].style.top = (arc.pointA.y - height) + "px";
    }
  }
}

function dragStop(e) {
  dragging = false;
}

function update() {
  ctx.fillStyle = "#eeeeee";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  arcs.forEach(function(arc) {
    ctx.moveTo(arc.pointA.x, arc.pointA.y);
    ctx.bezierCurveTo(arc.controlPointA.x, arc.controlPointA.y, arc.controlPointB.x, arc.controlPointB.y, arc.pointB.x, arc.pointB.y);
  });
  ctx.stroke();
}

update();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
  position: absolute;
}

#canvas {
  position: absolute;
  top: 0px;
  left: 0px;
}

.point {
  position: absolute;
  width: 10px;
  height: 10px;
}</code>```

  <canvas id="canvas" width=300 height=300></canvas>
  <svg class="point" id="pointA">
    <circle cx="5" cy="5" r="5" fill="red" />
  </svg>
  <svg class="point" id="pointB">
    <circle cx="5" cy="5" r="5" fill="red" />
  </svg>
  <svg class="point" id="pointC">
    <circle cx="5" cy="5" r="5" fill="red" />
  </svg>
  <svg class="point" id="pointD">
    <circle cx="5" cy="5" r="5" fill="red" />
  </svg>

```

Title: reshape circle in canvas

Body:
Hi I'm facing a problem with canvas.

I try to make a circle that can be reshape like this.
In the demo the circle can be reshape

the problem is to drag and drop the circle point to reshape it.

I know how to drag and drop point in the javascript canvas but how to reshape the cirle line to follow the point.

const DEBUG = true;

const WIDTH = window.innerWidth;
const HEIGHT = window.innerHeight;

const MIN_DIMENSION = WIDTH < HEIGHT ? WIDTH : HEIGHT;
const DEFAULT_RADIUS = MIN_DIMENSION * 0.45;
let canvas, ctx;

let cos = Math.cos;
let sin = Math.sin;
let pi = Math.PI;
let pi2 = pi * 2;

class Point {
  constructor(x,y) {
    this.x = x;
    this.y = y;
  }
}

function block(c, cb) {
  c.save();
  c.beginPath();
  cb(c);
  c.closePath();
  c.restore();
}

function circle(c,r) {
  c.arc(0, 0, r, 0, pi2);
}

function debugPoints(c, points) {
  points.forEach((p,i) => {
    if(i % 2 === 0) {
      c.fillStyle = 'red';
    } else {
      c.fillStyle = 'black';
    }
    c.beginPath();
    c.arc(p.x, p.y, 2, 0, pi2);
    c.fill();
    c.closePath();
  })
}

function bezierCirclePoints(r, n) {
  let a = pi2/(2*n);
  let R = r/cos(a);

  let points = new Array(2 * n);

  console.log('n:', n);
  console.log('a:', a);
  console.log('r:', r);
  console.log('R:', R);

  // calculate even bezier points
  for(let i = 0; i < n; i++) {
    let i2 = 2*i;
    let x = r * sin(i2 * a);
    let y = -r * cos(i2 * a);
    points[i2] =  new Point(x, y);
  }

  // calculate odd bezier points
  for(let i = 0; i < n; i++) {
    let i2 = 2*i + 1;
    let x = R * sin(i2 * a);
    let y = -R * cos(i2 * a);
    points[i2] =  new Point(x, y);
  }

  points.push(points[0]);
  return points;
}

function bezierCircle(c, r = DEFAULT_RADIUS, n = 7) {
  let points = bezierCirclePoints(r,n);

  c.translate(WIDTH * 0.5,HEIGHT * 0.5);

  if(DEBUG) {
    debugPoints(c, points);
  }

  c.fillStyle = 'red';
  c.strokeStyle = 'red';

  // draw circle
  c.beginPath();
  let p = points[0];
  c.moveTo(p.x, p.y);

  for(let i = 1; i < points.length; i+=2){
      let p1 = points[i];
      let i2 = i + 1;
      if(i2 >= points.length) {
        i2 = 0;
      }
      let p2 = points[i2];
      c.quadraticCurveTo(p1.x, p1.y, p2.x, p2.y);
  }

  c.stroke();
  c.closePath();
}

function redCircle(c) {
  c.fillStyle = 'red';
  c.translate(200,200);
  circle(c, 100);
  c.fill();
}

canvas = document.getElementById('circle');
canvas.width = WIDTH;
canvas.height = HEIGHT;
ctx = canvas.getContext('2d');

block(ctx, bezierCircle)

<canvas id="circle"></canvas>

Body:
As you already realized a circle can be composed out of four bézier curves. I'm going to use a cubic instead of a quadratic though since it offers two control points.

Let's start by looking at the following illustration:

As we can see the red curve consists of start point A, end point B and two control points c1 & c2 respectively.

So if we want to have a circle at x, y with a radius of r we can say:

Ax = x ; Ay = y - r

Bx = x + r ; By = y

c1x = x + r / 2 ; c1y = y - r

c2x = x + r ; c2y = y - r / 2

Of course the missing three curves can be constructed in the same way.

What we can also see from the above illustration is that the start point for the red segment is also the end point for the orange segment. Likewise the orange segment's control point c8 is connected to the start point of the red segment.

So if we're about to move point A we need to move the orange segment's end point, the red segment's start point AND the two control points c8 and c1.

To do this I'd write a general Arc class which consists of the start point, the end point, the two control points and additionally to which arc the start point is connected to. Then it goes a little something like this:

if someone clicks on point A, B, C or D store the current mouse position

store the position of the arc's control point as well as the connected arc's control point

if the mouse is moved, move the start point, it's control point and the connected arc's end point and it's control point relative to the mouse movement

repaint the circle

Here's an example:

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

class Arc {
  constructor(pointA, pointB, controlPointA, controlPointB) {
    this.pointA = pointA;
    this.pointB = pointB;

    this.controlPointA = controlPointA;
    this.controlPointB = controlPointB;
    this.controlPointOldA = null;
    this.controlPointOldB = null;
  }

  update(x, y, x2, y2) {
    this.pointA.x = x;
    this.pointA.y = y;

    this.connectedArc.pointB.x = x;
    this.connectedArc.pointB.y = y;

    this.controlPointA.x = this.controlPointOldA.x + x2;
    this.controlPointA.y = this.controlPointOldA.y + y2;

    this.connectedArc.controlPointB.x = this.controlPointOldB.x + x2;
    this.connectedArc.controlPointB.y = this.controlPointOldB.y + y2;
  }

  connect(connectedArc) {
    this.connectedArc = connectedArc;
  }

  saveControlPoints() {
    this.controlPointOldA = new Point(this.controlPointA.x, this.controlPointA.y);
    this.controlPointOldB = new Point(this.connectedArc.controlPointB.x, this.connectedArc.controlPointB.y);
  }
}

class Circle {
  constructor(x, y, radius) {

    this.arcA = new Arc(new Point(x, y - radius), new Point(x + radius, y), new Point(x + radius / 2, y - radius), new Point(x + radius, y - radius / 2));
    this.arcB = new Arc(new Point(x + radius, y), new Point(x, y + radius), new Point(x + radius, y + radius / 2), new Point(x + radius / 2, y + radius));
    this.arcC = new Arc(new Point(x, y + radius), new Point(x - radius, y), new Point(x - radius / 2, y + radius), new Point(x - radius, y + radius / 2));
    this.arcD = new Arc(new Point(x - radius, y), new Point(x, y - radius), new Point(x - radius, y - radius / 2), new Point(x - radius / 2, y - radius));

    this.arcA.connect(this.arcD);
    this.arcB.connect(this.arcA);
    this.arcC.connect(this.arcB);
    this.arcD.connect(this.arcC);
  }

}
var circle = new Circle(150, 150, 75);

var mouseX, mouseY, selectedArc;
var width = 5;
var height = 5;
var dragging = false;
var canvas = document.getElementById("canvas");

var ctx = canvas.getContext("2d");

var arcs = [circle.arcA, circle.arcB, circle.arcC, circle.arcD];

var points = document.getElementsByClassName("point");
var arc;
for (var a = 0; a < points.length; a++) {
  arc = arcs[a];
  points[a].setAttribute('data-linkedID', a);
  points[a].style.left = (arc.pointA.x - width) + "px";
  points[a].style.top = (arc.pointA.y - height) + "px";
  points[a].addEventListener("mousedown", dragStarted);

}
document.addEventListener("mousemove", drag);
document.addEventListener("mouseup", dragStop);

function dragStarted(e) {
  mouseX = e.pageX;
  mouseY = e.pageY;
  selectedArc = arcs[e.target.parentElement.getAttribute("data-linkedID")];
  selectedArc.saveControlPoints();
  dragging = true;
}

function drag(e) {
  if (dragging) {
    selectedArc.update(e.pageX - width, e.pageY - height, e.pageX - mouseX, e.pageY - mouseY);
    update();

    var arc;
    for (var a = 0; a < points.length; a++) {
      arc = arcs[a];
      points[a].style.left = (arc.pointA.x - width) + "px";
      points[a].style.top = (arc.pointA.y - height) + "px";
    }
  }
}

function dragStop(e) {
  dragging = false;
}

function update() {
  ctx.fillStyle = "#eeeeee";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  arcs.forEach(function(arc) {
    ctx.moveTo(arc.pointA.x, arc.pointA.y);
    ctx.bezierCurveTo(arc.controlPointA.x, arc.controlPointA.y, arc.controlPointB.x, arc.controlPointB.y, arc.pointB.x, arc.pointB.y);
  });
  ctx.stroke();
}

update();

#container {
  position: absolute;
}

#canvas {
  position: absolute;
  top: 0px;
  left: 0px;
}

.point {
  position: absolute;
  width: 10px;
  height: 10px;
}

<div id="container">
  <canvas id="canvas" width=300 height=300></canvas>
  <svg class="point" id="pointA">
    <circle cx="5" cy="5" r="5" fill="red" />
  </svg>
  <svg class="point" id="pointB">
    <circle cx="5" cy="5" r="5" fill="red" />
  </svg>
  <svg class="point" id="pointC">
    <circle cx="5" cy="5" r="5" fill="red" />
  </svg>
  <svg class="point" id="pointD">
    <circle cx="5" cy="5" r="5" fill="red" />
  </svg>
</div>


问:
Control access to files based on DB values with PHP/Apache

What i want

I'm making a system where, when a user uploads an image it goes to the folder images, where there is two copies of the image, a thumb and a bigger one.

Now, when a user uploads an image it's done alongside insertion of a row in a MySQL database, where the image gets an id, and the row holds a value that determines if the images is available to the public or not (1 for only thumb available, 2 for both) along with the owner(admin) of the image.

What i wan't to do is, if a user tries to reach the image by going to the image's URL, and the value in the database says that it should not be publicly available, and the session of that user is not the owner of the image, (admin not logged in) it should either say image not found or access denied.

What i imagine

If it could be done with php i imagine something like this:

```<code>//User tries to go to URL "images/IMAGE-ID_thumb.jpg"
if($img['access'] >= 1 || $_SESSION['admin_ID'] == $img['owner_ID']) {
  //Show image thumb
}
else {
  //Access denied
}
</code>```

I could maybe hide the images in a .htaccess protected folder, make a imgae_get.php that accepts URL variables, sees if the image is available, and loads the image if so. I just want to avoid having to de/re-compile the image and other server power consuming processes.

My question is, can i control the image like this? Is there a way to make a php script appear as an image it loads internally?
Or is there maybe some other/better way than through PHP? (Apache maybe?) Any suggestions is much appreciated.

答:
.htaccess

```<code>#mod_rewrite
RewriteRule ^(.*)_(full|thumb).(jpg|png|gif)$ image.php?i=$1&type=$2&ext=$3
</code>```

HTML

```<code><img src="http://example.com/image-1_thumb.png" />
=
<img src="image.php?i=image-1&type=thumb&ext=png" />
</code>```

PHP (image.php)

```<code><?php
// do basic sanity checks on input
$_GET['i'] = isset($_GET['i']) ? basename($_GET['i']) : null;
$_GET['type'] = isset($_GET['type']) ? basename($_GET['type']) : null;
//unsafe way
//$_GET['ext'] = isset($_GET['ext']) ?  basename($_GET['ext']) : null;
//safe way
$_GET['ext'] = in_array($_GET['ext'], array('png','gif', 'png')) ? $_GET['ext'] : null;

## Do DB Checks on session to owner ect
/* $_GET
    [i] => image-1
    [type] => thumb
    [ext] => png
*/

// then output
if (file_exists('hiddenimagesfolder/images/'.$_GET['i'].'_'.$_GET['type'].'.'.$_GET['ext'])) {
    header("Content-Type:image/png");
    readfile('hiddenimagesfolder/images/'.$_GET['i'].'_'.$_GET['type'].'.'.$_GET['ext']);
} else {
    //not found
}
?>
</code>```

Body:
What i want

I'm making a system where, when a user uploads an image it goes to the folder images, where there is two copies of the image, a thumb and a bigger one.

Now, when a user uploads an image it's done alongside insertion of a row in a MySQL database, where the image gets an id, and the row holds a value that determines if the images is available to the public or not (1 for only thumb available, 2 for both) along with the owner(admin) of the image.

What i wan't to do is, if a user tries to reach the image by going to the image's URL, and the value in the database says that it should not be publicly available, and the session of that user is not the owner of the image, (admin not logged in) it should either say image not found or access denied.

What i imagine

If it could be done with php i imagine something like this:

//User tries to go to URL "images/IMAGE-ID_thumb.jpg"
if($img['access'] >= 1 || $_SESSION['admin_ID'] == $img['owner_ID']) {
  //Show image thumb
}
else {
  //Access denied
}

I could maybe hide the images in a .htaccess protected folder, make a imgae_get.php that accepts URL variables, sees if the image is available, and loads the image if so. I just want to avoid having to de/re-compile the image and other server power consuming processes.

My question is, can i control the image like this? Is there a way to make a php script appear as an image it loads internally?
Or is there maybe some other/better way than through PHP? (Apache maybe?) Any suggestions is much appreciated.

Body:
.htaccess

#mod_rewrite
RewriteRule ^(.*)_(full|thumb).(jpg|png|gif)$ image.php?i=$1&type=$2&ext=$3

HTML

<img src="http://example.com/image-1_thumb.png" />
=
<img src="image.php?i=image-1&type=thumb&ext=png" />

PHP (image.php)

<?php
// do basic sanity checks on input
$_GET['i'] = isset($_GET['i']) ? basename($_GET['i']) : null;
$_GET['type'] = isset($_GET['type']) ? basename($_GET['type']) : null;
//unsafe way
//$_GET['ext'] = isset($_GET['ext']) ?  basename($_GET['ext']) : null;
//safe way
$_GET['ext'] = in_array($_GET['ext'], array('png','gif', 'png')) ? $_GET['ext'] : null;

## Do DB Checks on session to owner ect
/* $_GET
    [i] => image-1
    [type] => thumb
    [ext] => png
*/

// then output
if (file_exists('hiddenimagesfolder/images/'.$_GET['i'].'_'.$_GET['type'].'.'.$_GET['ext'])) {
    header("Content-Type:image/png");
    readfile('hiddenimagesfolder/images/'.$_GET['i'].'_'.$_GET['type'].'.'.$_GET['ext']);
} else {
    //not found
}
?>


问:
Typescript - keyof values of array
I have a list

export const list = [
  {
    name: 'parentTitle',
  },
  {
    name: 'anotherTitle',
  },
  {
    name: 'whatever',
  },
];
```

<p>Now I want to create dynamically a union type which describes the following:</p>

<pre class="lang-js prettyprint-override"><code>type Title = 'parentTitle' | 'anotherTitle' | 'whatever';
</code>```

Is there a way to do this?

I tried to adapt the idea here: Keyof nested child objects
But I can't figuring it out

答:
The type of list in your example gets inferred by the compiler to be Array<{name: string}>, and thus the compiler has completely forgotten the particular string literal types of the name properties by the time you try to define Title.

You'll have to change how you assign list, at least somewhat.  The easiest thing to do (which may or may not meet your needs) is to use a const assertion, which asks the compiler to infer the narrowest type possible:

```<code>export const list = [
    { name: 'parentTitle', },
    { name: 'anotherTitle', },
    { name: 'whatever', },
] as const;
</code>```

Now list is inferred to be of type:

```<code>/*
const list: readonly [
    { readonly name: "parentTitle";},
    { readonly name: "anotherTitle";},
    { readonly name: "whatever";}
]
*/
</code>```

which is a readonly tuple of readonly objects with particular name properties in a particular order.  From that we can use lookup types to define Title:

```<code>type Title = typeof list[number]["name"];
// type Title = "parentTitle" | "anotherTitle" | "whatever"
</code>```

Okay, hope that helps; good luck!

Playground link to code

Title: Typescript - keyof values of array

Body:
I have a list

export const list = [
  {
    name: 'parentTitle',
  },
  {
    name: 'anotherTitle',
  },
  {
    name: 'whatever',
  },
];

Now I want to create dynamically a union type which describes the following:

type Title = 'parentTitle' | 'anotherTitle' | 'whatever';

Is there a way to do this?

I tried to adapt the idea here: Keyof nested child objects
But I can't figuring it out

Body:
The type of list in your example gets inferred by the compiler to be Array<{name: string}>, and thus the compiler has completely forgotten the particular string literal types of the name properties by the time you try to define Title.

You'll have to change how you assign list, at least somewhat.  The easiest thing to do (which may or may not meet your needs) is to use a const assertion, which asks the compiler to infer the narrowest type possible:

export const list = [
    { name: 'parentTitle', },
    { name: 'anotherTitle', },
    { name: 'whatever', },
] as const;

Now list is inferred to be of type:

/*
const list: readonly [
    { readonly name: "parentTitle";},
    { readonly name: "anotherTitle";},
    { readonly name: "whatever";}
]
*/

which is a readonly tuple of readonly objects with particular name properties in a particular order.  From that we can use lookup types to define Title:

type Title = typeof list[number]["name"];
// type Title = "parentTitle" | "anotherTitle" | "whatever"

Okay, hope that helps; good luck!

Playground link to code


问:
Github (SSH) via public WIFI, port 22 blocked
I'm currently on a public WIFI spot and I'm unable to use SSH (they probably blocked that port). However, I need that connection to do a git push.

```<code>➜ ssh -T git@github.com
ssh: connect to host github.com port 22: Connection refused
</code>```

Is it possible to bypass this restriction by setting up a SSH tunnel via port 80 and tell github push to use that connection? How to do that? I'm on OSX (lion). This must be a common problem?

答:
No need to modify the ~/.ssh/config. You can add another remote repository via git remote add ...

```<code>// github
git remote add ssh://git@ssh.github.com:443/repo/name.git

// gitlab
git remote add ssh://git@altssh.gitlab.com:443/repo/name.git
</code>```

Body:
I'm currently on a public WIFI spot and I'm unable to use SSH (they probably blocked that port). However, I need that connection to do a git push.

➜ ssh -T git@github.com
ssh: connect to host github.com port 22: Connection refused

Is it possible to bypass this restriction by setting up a SSH tunnel via port 80 and tell github push to use that connection? How to do that? I'm on OSX (lion). This must be a common problem?

Body:
No need to modify the ~/.ssh/config. You can add another remote repository via git remote add ...

// github
git remote add ssh://git@ssh.github.com:443/repo/name.git

// gitlab
git remote add ssh://git@altssh.gitlab.com:443/repo/name.git


问:
How can I get rid of this error which I am getting with a code to find nearest neighbors?
I have written the following function which takes data, number of peers to find, and index to find the top N nearest neighbors :

```<code>def fit_nearest_neighbors(data, number_of_peers, index):
    peer_data = FindPeers.filt_data(data)
    peer_data_array = np.array(peer_data)
    knn = NearestNeighbors(algorithm = 'auto', n_neighbors = number_of_peers, metric = 'minkowski', p = 2)
    knn.fit(peer_data_array)
    return knn.kneighbors(peer_data_array[index], return_distance = False)
</code>```

But I am getting the following error with the last line of code after return which says :

```<code>ValueError: Expected 2D array, got 1D array instead:
array=[2.86839521e-01 7.63588709e-01 1.00000000e+00 1.73483898e-01
 0.00000000e+00 1.25068828e-02 1.66424454e-17 4.38357126e-01
 7.55219585e-03 6.03820534e-02 2.72387749e-01].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
</code>```

The error array that It prints is basically the datapoint present at that particular index.
I understand the error but I don't understand how do I make it right. Any type of leads/answers would be helpful.

答:
The error message is clear. You need to reshape your data from 1D to 2D using the numpy function np.reshape().

You can accomplish this with

```<code>peer_data_array = np.array(peer_data).reshape(-1, 1)
</code>```

Body:
I have written the following function which takes data, number of peers to find, and index to find the top N nearest neighbors :

def fit_nearest_neighbors(data, number_of_peers, index):
    peer_data = FindPeers.filt_data(data)
    peer_data_array = np.array(peer_data)
    knn = NearestNeighbors(algorithm = 'auto', n_neighbors = number_of_peers, metric = 'minkowski', p = 2)
    knn.fit(peer_data_array)
    return knn.kneighbors(peer_data_array[index], return_distance = False)

But I am getting the following error with the last line of code after return which says :

ValueError: Expected 2D array, got 1D array instead:
array=[2.86839521e-01 7.63588709e-01 1.00000000e+00 1.73483898e-01
 0.00000000e+00 1.25068828e-02 1.66424454e-17 4.38357126e-01
 7.55219585e-03 6.03820534e-02 2.72387749e-01].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

The error array that It prints is basically the datapoint present at that particular index.
I understand the error but I don't understand how do I make it right. Any type of leads/answers would be helpful.

Body:
The error message is clear. You need to reshape your data from 1D to 2D using the numpy function np.reshape().

You can accomplish this with

peer_data_array = np.array(peer_data).reshape(-1, 1)


问:
Easiest way to subclass a widget in Python for use with Qt Designer
I'm building an app using PyQt5, with (most of) the GUI being built using Qt Designer.  I have a few UI elements that do mostly the same thing and it seems sensible to move their code into classes that inherit from a base class (which in turn inherits from QTableWidget).

This seems really straightforward except that I'm not sure how to get Qt Designer to use these classes when generating its UI files.  I've found a guide for doing this in PyQt4 and another one that's for Qt 5 but with native C++ code and yet another one that's for PyQt5 but doesn't deal with the (most complicated) aspect of making the subclasses available in Qt Designer.

How do I make a subclass of a widget created using PyQt5 available for use in Qt Designer?

Alternatively, is there an easier way to do this?  I don't need to change the appearance or functionality of the widgets—I'm mostly just looking for an organized place to store some code that makes their data easier to set and access.

答:
While creating plugins for Qt Designer is possible, it's not an easy task: the official documentation is outdated and sometimes incomplete, and some functions have not been fully ported for a transparent PyQt usage.

The easiest way is to use promoted widgets.

Let's say you have a widget that displays the current time in a fancy way:

```<code>from PyQt5 import QtCore, QtGui, QtWidgets, uic

class TimeFrame(QtWidgets.QFrame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.updateTimer = QtCore.QTimer(interval=60000, timeout=self.update)
        self._time = None

    @QtCore.pyqtProperty(QtCore.QTime)
    def time(self):
        return self._time

    @time.setter
    def time(self, time):
        self._time = time
        self.update()

    def paintEvent(self, event):
        super().paintEvent(event)
        size = min(self.width(), self.height()) - 10
        rect = QtCore.QRect(0, 0, size, size)
        rect.moveCenter(self.rect().center())
        qp = QtGui.QPainter(self)
        qp.setRenderHints(qp.Antialiasing)
        qp.drawEllipse(rect)
        qp.setPen(QtCore.Qt.NoPen)
        qp.setBrush(QtCore.Qt.blue)
        time = self._time or QtCore.QTime.currentTime()
        minuteAngle = time.minute() * 6
        qp.drawPie(rect, 1440, -minuteAngle * 16)
        qp.setBrush(QtCore.Qt.red)
        hourAngle = (time.hour() % 12 + time.minute() / 60) * 30
        qp.drawPie(rect.adjusted(30, 30, -30, -30), 1440, -hourAngle * 16)
</code>```

This is a simple clock widget that shows a pair of "pies", the bigger for minutes, the smaller for hours (in this screenshot, the time is 2:03):

Now, to be able to add that widget from Designer, you'll need to promote a widget. Promoting widgets is a way for Qt to expand the features and functionalities of a widget added to a UI.

This is very useful, because you can expand any standard widget class in your own way: for example, if you add a QTableView to the UI and promote it, it allows you to set the standard QTableView properties from the Designer interface, and then implement other features from your code.

The procedure is pretty simple, once you know how it works.

Create the UI and add a widget based on the class you want to expand

In this case, I'm using a QFrame, to show how that class properties can be expanded.
Just create your interface, and add a QFrame to the layout.

As you can see, the class reported from the Object Inspector is still a QFrame.

Promote the widget

Right click on the widget you want to use for your class, and select Promote to..., then set the "Promoted class name" to the widget class name created before, and the "Header file" to the module name that contains that class. I saved the python file as promoted.py, so the field value will be promoted. Consider that header file paths are relative to the path from where the UI file will be loaded.

Then click "Add" to create the new promoted widget "class", and finally "Promote" to officially promote it. After that, you can promote any widget to a previously set promoted class, as long as the base class is compatible: if you have another QFrame in your interface, you can right click on it and select the promoted class from the "Promote to" submenu.

Now the class displayed in the Object Inspector is TimeFrame.

Set object properties, save, create the code and run

Since we're using a QFrame, we can set its frame (this is because we also called the base class implementation in the paintEvent(event) method before).

Now you just have to implement the base class for the main widget. Remember that each time a promoted widget is loaded, its "header file" will be loaded, which means that its code will always be run. That's why it's important that an if __name__ == '__main__': code block is placed in the file as long as it contains both the main "program" and the promoted widget class.

promoted.py code:

```<code>class Test(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        uic.loadUi('test.ui', self)

        self.timeEdit.timeChanged.connect(self.updateTimeFrame)

        self.timeEdit.setTime(QtCore.QTime.currentTime())

    def updateTimeFrame(self):
        self.timeFrame.time = self.timeEdit.time()

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Test()
    w.show()
    sys.exit(app.exec())
</code>```

Now, obviously there won't be anything shown in Designer anyway, but as soon as we run our code, the promoted widget will be displayed as expected!

And now you can also know the actual time it took me to create this answer, cool ;-)

Body:
While creating plugins for Qt Designer is possible, it's not an easy task: the official documentation is outdated and sometimes incomplete, and some functions have not been fully ported for a transparent PyQt usage.

The easiest way is to use promoted widgets.

Let's say you have a widget that displays the current time in a fancy way:

from PyQt5 import QtCore, QtGui, QtWidgets, uic

class TimeFrame(QtWidgets.QFrame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.updateTimer = QtCore.QTimer(interval=60000, timeout=self.update)
        self._time = None

    @QtCore.pyqtProperty(QtCore.QTime)
    def time(self):
        return self._time

    @time.setter
    def time(self, time):
        self._time = time
        self.update()

    def paintEvent(self, event):
        super().paintEvent(event)
        size = min(self.width(), self.height()) - 10
        rect = QtCore.QRect(0, 0, size, size)
        rect.moveCenter(self.rect().center())
        qp = QtGui.QPainter(self)
        qp.setRenderHints(qp.Antialiasing)
        qp.drawEllipse(rect)
        qp.setPen(QtCore.Qt.NoPen)
        qp.setBrush(QtCore.Qt.blue)
        time = self._time or QtCore.QTime.currentTime()
        minuteAngle = time.minute() * 6
        qp.drawPie(rect, 1440, -minuteAngle * 16)
        qp.setBrush(QtCore.Qt.red)
        hourAngle = (time.hour() % 12 + time.minute() / 60) * 30
        qp.drawPie(rect.adjusted(30, 30, -30, -30), 1440, -hourAngle * 16)

This is a simple clock widget that shows a pair of "pies", the bigger for minutes, the smaller for hours (in this screenshot, the time is 2:03):

Now, to be able to add that widget from Designer, you'll need to promote a widget. Promoting widgets is a way for Qt to expand the features and functionalities of a widget added to a UI.

This is very useful, because you can expand any standard widget class in your own way: for example, if you add a QTableView to the UI and promote it, it allows you to set the standard QTableView properties from the Designer interface, and then implement other features from your code.

The procedure is pretty simple, once you know how it works.

Create the UI and add a widget based on the class you want to expand

In this case, I'm using a QFrame, to show how that class properties can be expanded.
Just create your interface, and add a QFrame to the layout.

As you can see, the class reported from the Object Inspector is still a QFrame.

Promote the widget

Right click on the widget you want to use for your class, and select Promote to..., then set the "Promoted class name" to the widget class name created before, and the "Header file" to the module name that contains that class. I saved the python file as promoted.py, so the field value will be promoted. Consider that header file paths are relative to the path from where the UI file will be loaded.

Then click "Add" to create the new promoted widget "class", and finally "Promote" to officially promote it. After that, you can promote any widget to a previously set promoted class, as long as the base class is compatible: if you have another QFrame in your interface, you can right click on it and select the promoted class from the "Promote to" submenu.

Now the class displayed in the Object Inspector is TimeFrame.

Set object properties, save, create the code and run

Since we're using a QFrame, we can set its frame (this is because we also called the base class implementation in the paintEvent(event) method before).

Now you just have to implement the base class for the main widget. Remember that each time a promoted widget is loaded, its "header file" will be loaded, which means that its code will always be run. That's why it's important that an if __name__ == '__main__': code block is placed in the file as long as it contains both the main "program" and the promoted widget class.

promoted.py code:

class Test(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        uic.loadUi('test.ui', self)

        self.timeEdit.timeChanged.connect(self.updateTimeFrame)

        self.timeEdit.setTime(QtCore.QTime.currentTime())

    def updateTimeFrame(self):
        self.timeFrame.time = self.timeEdit.time()

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Test()
    w.show()
    sys.exit(app.exec())

Now, obviously there won't be anything shown in Designer anyway, but as soon as we run our code, the promoted widget will be displayed as expected!

And now you can also know the actual time it took me to create this answer, cool ;-)


问:
Making an rest api call from angular 9 service class
I have written an Api as part of a coding exercise and am testing it in Postman as below. I'm content with how this works for now.

So now I'm wanting to call it from an Angular 9 project and I've written a service with code below but don't know how to assign the three parameters to the parameter 'model'

This is my service class

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class CalcService {

  baseUrl = 'http://localhost:5000/api/Calculator/';

  constructor(private http: HttpClient) { }

  calculate(model: any) {
    return this.http.get(this.baseUrl, model)
      .pipe(map((response: any) => {
        const val = response;
      }));
  }

}

</code>```

This is my component, and I'm wanting to call the service within getAnswerFromApi() but am not sure how to assign the three parameters

```<code>import { Component, OnInit } from '@angular/core';
import { CalcService } from '../_services/calc.service';

@Component({
  selector: 'app-calculator',
  templateUrl: './calculator.component.html',
  styleUrls: ['./calculator.component.css']
})
export class CalculatorComponent implements OnInit {
  title = 'Ofgem Calculator';

  model: any = {};

  subText = ''; // The text that should appear in the sub-display
  mainText = ''; // The text that should appear in the main display
  firstNumber: number; // The first operand
  secondNumber: number; // The second operand
  operator = ''; // The operator
  calculationString = '';
  // This is the string that denotes the operation being performed
  answered = false;
  operatorSet = false;

  answer = '';

  constructor(private calcService: CalcService) { }

  ngOnInit() {
  }

  pressKey(key: string) {
    if (key === '/' || key === 'x' || key === '-' || key === '+') {
       const lastKey = this.mainText[this.mainText.length - 1];
       if (lastKey === '/' || lastKey === 'x' || lastKey === '-' || lastKey === '+')  {
         this.operatorSet = true;
       }
       if ((this.operatorSet) || (this.mainText === '')) {
         return;
       }
       this.firstNumber = parseFloat(this.mainText);
       this.operator = key;
       this.operatorSet = true;
    }
    if (this.mainText.length === 10) {
      return;
    }
    this.mainText += key;
 }

 getAnswerFromApi() {
   this.calculationString = this.mainText;
   this.secondNumber = parseFloat(this.mainText.split(this.operator)[1]);

   this.calcService.calculate(this.model).subscribe(next => {
     console.log('did calc');
   }, error => {
     console.log('failed calc');
   });

 }
  allClear() {
    this.subText = '';
    this.mainText = '';
    this.operator = '';
    this.calculationString = '';
    this.answered = false;
    this.operatorSet = false;
  }
}

</code>```

答:
this is how to do it </p>

```<code>// service file

 .....

calculate() {
    return this.http.get(this.baseUrl)
  }

......

// component ts file

getAnswerFromApi() {
   ....

   this.calcService.calculate()
    .subscribe((next : any) => {
     this.model = next;
   }, error => {
     console.log('failed calc', error);
   });

 }
</code>```

Body:
I have written an Api as part of a coding exercise and am testing it in Postman as below. I'm content with how this works for now.

So now I'm wanting to call it from an Angular 9 project and I've written a service with code below but don't know how to assign the three parameters to the parameter 'model'

This is my service class

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class CalcService {

  baseUrl = 'http://localhost:5000/api/Calculator/';

  constructor(private http: HttpClient) { }

  calculate(model: any) {
    return this.http.get(this.baseUrl, model)
      .pipe(map((response: any) => {
        const val = response;
      }));
  }

}

This is my component, and I'm wanting to call the service within getAnswerFromApi() but am not sure how to assign the three parameters

import { Component, OnInit } from '@angular/core';
import { CalcService } from '../_services/calc.service';

@Component({
  selector: 'app-calculator',
  templateUrl: './calculator.component.html',
  styleUrls: ['./calculator.component.css']
})
export class CalculatorComponent implements OnInit {
  title = 'Ofgem Calculator';

  model: any = {};

  subText = ''; // The text that should appear in the sub-display
  mainText = ''; // The text that should appear in the main display
  firstNumber: number; // The first operand
  secondNumber: number; // The second operand
  operator = ''; // The operator
  calculationString = '';
  // This is the string that denotes the operation being performed
  answered = false;
  operatorSet = false;

  answer = '';

  constructor(private calcService: CalcService) { }

  ngOnInit() {
  }

  pressKey(key: string) {
    if (key === '/' || key === 'x' || key === '-' || key === '+') {
       const lastKey = this.mainText[this.mainText.length - 1];
       if (lastKey === '/' || lastKey === 'x' || lastKey === '-' || lastKey === '+')  {
         this.operatorSet = true;
       }
       if ((this.operatorSet) || (this.mainText === '')) {
         return;
       }
       this.firstNumber = parseFloat(this.mainText);
       this.operator = key;
       this.operatorSet = true;
    }
    if (this.mainText.length === 10) {
      return;
    }
    this.mainText += key;
 }

 getAnswerFromApi() {
   this.calculationString = this.mainText;
   this.secondNumber = parseFloat(this.mainText.split(this.operator)[1]);

   this.calcService.calculate(this.model).subscribe(next => {
     console.log('did calc');
   }, error => {
     console.log('failed calc');
   });

 }
  allClear() {
    this.subText = '';
    this.mainText = '';
    this.operator = '';
    this.calculationString = '';
    this.answered = false;
    this.operatorSet = false;
  }
}

Body:
this is how to do it

// service file

 .....

calculate() {
    return this.http.get(this.baseUrl)
  }

......

// component ts file

getAnswerFromApi() {
   ....

   this.calcService.calculate()
    .subscribe((next : any) => {
     this.model = next;
   }, error => {
     console.log('failed calc', error);
   });

 }


问:
Switch behavior -ON -OFF using an Image or label -Binding an image inside a listview in xamarin forms
I would like to change the image source from white.png to blue.png when it gets tapped , I need to access each comannd when the image schange to white.png and when it is blue.png , also .it will be helpful to set it true or false , depending on the image result.

all this will come inside a list . and I need to access each individual tapped.

I tried :

IValueConveter

```<code>public class ConverterAddRemoveImage : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool isAddedToCart = (bool)value;
            if (isAddedToCart)
            {
                return "FilledIcon"; //This will be a string
            }
            else
            {
                return "EmptyIcon";  //This will be a string
            }
        }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
</code>```

Xaml

```<code><Image Source="{Binding IsAddedToCart, Converter={StaticResource AddRemoveImage}}"/>
</code>```

This only shows me the else , never gets to true. Ideally I would like to access each of them and add logic to it and obviously change the image on each tapped.

Second approach- the issue here is - gets tapped only one time and I can not get back to the previous image with the second tapped , and also , I dont know how to access each command. (I want to imitate a switch on and off and on each of them do something)

```<code>public ImageSource ColorImage { get; set; }
</code>```

View Model

```<code>public ICommand SwitchIMGCommand
            {
                get;
                set;
            }

private void AddImg(object obj)
  {
     var selection = obj as ExistingModel;
     selection.ColorImage = "FilledIcon.png";**
     ColorImage= "FilledIcon.png";**I tried this and it doesnt change
     to this img
  }

private ImageSource imagePath = "white.png";
        public ImageSource ColorImage
        {
            get { return imagePath; }
            set
            {
                imagePath = value;
                PropertyChanged(this, new PropertyChangedEventArgs("ColorImage"));
            }
        }
</code>```

Constructor

```<code>SwitchIMGCommand = new Command(AddImg);
</code>```

XAML

```<code><Image
    Source="{Binding ColorImage}">
    <Image.GestureRecognizers>
    <TapGestureRecognizer
    Command="{Binding Source={x:Reference listView}, Path=BindingContext.SwitchIMGCommand}" CommandParameter="{Binding .} "
     NumberOfTapsRequired="1" />
     </Image.GestureRecognizers>
  </Image>
</code>```

答:
It seems that the the Image is in the ViewCell of a listview  .

You should define the ColorImage in your model .

```<code>public class MyModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private string imagePath;
    public string ColorImage
    {
        get { return imagePath; }
        set
        {
            imagePath = value;
            NotifyPropertyChanged("ColorImage");
        }
    }

    //...other properties

    public MyModel()
    {
       ColorImage = "white.png";
    }
}
</code>```

in your view model

```<code>private void AddImg(object obj)
{
   var model = obj as MyModel;

   model.ColorImage = "imgcolorblue.png";

}
</code>```

Body:
I would like to change the image source from white.png to blue.png when it gets tapped , I need to access each comannd when the image schange to white.png and when it is blue.png , also .it will be helpful to set it true or false , depending on the image result.

all this will come inside a list . and I need to access each individual tapped.

I tried :

IValueConveter

public class ConverterAddRemoveImage : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool isAddedToCart = (bool)value;
            if (isAddedToCart)
            {
                return "FilledIcon"; //This will be a string
            }
            else
            {
                return "EmptyIcon";  //This will be a string
            }
        }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

Xaml

<Image Source="{Binding IsAddedToCart, Converter={StaticResource AddRemoveImage}}"/>

This only shows me the else , never gets to true. Ideally I would like to access each of them and add logic to it and obviously change the image on each tapped.

Second approach- the issue here is - gets tapped only one time and I can not get back to the previous image with the second tapped , and also , I dont know how to access each command. (I want to imitate a switch on and off and on each of them do something)

public ImageSource ColorImage { get; set; }

View Model

public ICommand SwitchIMGCommand
            {
                get;
                set;
            }

private void AddImg(object obj)
  {
     var selection = obj as ExistingModel;
     selection.ColorImage = "FilledIcon.png";**
     ColorImage= "FilledIcon.png";**I tried this and it doesnt change
     to this img
  }

private ImageSource imagePath = "white.png";
        public ImageSource ColorImage
        {
            get { return imagePath; }
            set
            {
                imagePath = value;
                PropertyChanged(this, new PropertyChangedEventArgs("ColorImage"));
            }
        }

Constructor

SwitchIMGCommand = new Command(AddImg);

XAML

<Image
    Source="{Binding ColorImage}">
    <Image.GestureRecognizers>
    <TapGestureRecognizer
    Command="{Binding Source={x:Reference listView}, Path=BindingContext.SwitchIMGCommand}" CommandParameter="{Binding .} "
     NumberOfTapsRequired="1" />
     </Image.GestureRecognizers>
  </Image>

Body:
It seems that the the Image is in the ViewCell of a listview  .

You should define the ColorImage in your model .

public class MyModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private string imagePath;
    public string ColorImage
    {
        get { return imagePath; }
        set
        {
            imagePath = value;
            NotifyPropertyChanged("ColorImage");
        }
    }

    //...other properties

    public MyModel()
    {
       ColorImage = "white.png";
    }
}

in your view model

private void AddImg(object obj)
{
   var model = obj as MyModel;

   model.ColorImage = "imgcolorblue.png";

}


问:
regex expression for string.split() that splits a string on urls
I have a regex expression for finding url's in a string, but when I use it with String.prototype.split() it returns undefined's.

const regex = /(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g;
const str = "yay http://www.google.com woo www.google.com haha google.com";

console.log(str.match(regex));
// [ 'http://www.google.com', 'www.google.com', 'google.com' ]

console.log(str.split(regex));
// [ 'yay ','http://w',undefined,undefined,'',' woo ',undefined,undefined,'www.','',' haha ',undefined,undefined,undefined,'','' ]```
</div>
</div>
</p>

<p>After some research it appears that this has to do with capturing groups. I attempted adding <code>:?</code> to all the capturing groups (parts wrapped in parenthesis) and it removed the undefined's.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const reg2 = /(?:http(?:s)?:\/\/.)?(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b(?:[-a-zA-Z0-9@:%_\+.~#?&//=]*)/g

const str = "yay http://www.google.com woo www.google.com haha google.com";

console.log(str.split(reg2));
// [ 'yay ', ' woo ', ' haha ', '' ]</code>```

But it is omitting the urls. I am looking to return:

```<code>[ 'yay ', 'http://www.google.com', ' woo ', 'www.google.com', ' haha ', 'google.com' ]
</code>```

答:
You might be able to just split on whitespace here:

var str = "yay http://www.google.com woo www.google.com haha google.com";
var parts = str.split(/\s+/);
console.log(parts);```
</div>
</div>
</p>

<p>If the leading/trailing whitespace are really required here, then try matching on the pattern:</p>

```<URL>|\s*\S+\s*
```

<p>This would match either a URL, or a series of non word characters, with surrounding whitespace.  Consider:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var str = "yay http://www.google.com woo www.google.com haha google.com";
console.log(str.match(/(?:http(s)?:\/\/.)?(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b(?:[-a-zA-Z0-9@:%_\+.~#?&//=]*)|\s*\S+\s*/g));</code>```

This uses an alternation trick to first try to selectively consume a URL, with no surrounding whitespace.  That failing, the fallback pattern is \s*\S\s*, i.e. any other word with the leading/trailing whitespace.

Body:
I have a regex expression for finding url's in a string, but when I use it with String.prototype.split() it returns undefined's.

const regex = /(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g;
const str = "yay http://www.google.com woo www.google.com haha google.com";

console.log(str.match(regex));
// [ 'http://www.google.com', 'www.google.com', 'google.com' ]

console.log(str.split(regex));
// [ 'yay ','http://w',undefined,undefined,'',' woo ',undefined,undefined,'www.','',' haha ',undefined,undefined,undefined,'','' ]

After some research it appears that this has to do with capturing groups. I attempted adding :? to all the capturing groups (parts wrapped in parenthesis) and it removed the undefined's.

const reg2 = /(?:http(?:s)?:\/\/.)?(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b(?:[-a-zA-Z0-9@:%_\+.~#?&//=]*)/g

const str = "yay http://www.google.com woo www.google.com haha google.com";

console.log(str.split(reg2));
// [ 'yay ', ' woo ', ' haha ', '' ]

But it is omitting the urls. I am looking to return:

[ 'yay ', 'http://www.google.com', ' woo ', 'www.google.com', ' haha ', 'google.com' ]

Body:
You might be able to just split on whitespace here:

var str = "yay http://www.google.com woo www.google.com haha google.com";
var parts = str.split(/\s+/);
console.log(parts);

If the leading/trailing whitespace are really required here, then try matching on the pattern:

<URL>|\s*\S+\s*

This would match either a URL, or a series of non word characters, with surrounding whitespace.  Consider:

var str = "yay http://www.google.com woo www.google.com haha google.com";
console.log(str.match(/(?:http(s)?:\/\/.)?(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b(?:[-a-zA-Z0-9@:%_\+.~#?&//=]*)|\s*\S+\s*/g));

This uses an alternation trick to first try to selectively consume a URL, with no surrounding whitespace.  That failing, the fallback pattern is \s*\S\s*, i.e. any other word with the leading/trailing whitespace.