问:
Using a struct as advanced enum type and attempting to access the properties by index
I followed this guide on making a more complicated enum type for my implementation.
http://www.huristic.co/blog/2018/1/30/c-advanced-enum-value-types

So far so good, however now I need to access the struct properties I have made ideally by index. A use case is if I get in a list of integers, I want to be able to provide a list of strings with the seasons in, e.g. {1,4,7} would get me {"Winter", "Spring", "Summer"} for example.

So in effect, using this example, I would like to be able to select Month where the index is 7 for example and get out the season of "Summer".

My first step was to get the names like so:

```<code>IEnumerable<string> names = typeof(Month).GetProperties(BindingFlags.Static | BindingFlags.Public)
.Select(x => x.Name);
</code>```

I then attempted to get the particular Month with:

```<code>foreach(string name in names) {
  Month m = (Month) typeof(Month).GetType().GetProperties()
  .Single(info => info.Name == name)
  .GetValue(typeof(Month),null);
}
</code>```

however this is going to cause me to iterate over the entire collection for every value I want to get.

Ultimately I think I'm headed in the wrong direction and would really appreciate a pointer. At the moment I'm trying to do this in a method in another class, but don't see why it couldn't be a getter in the struct itself, although that may be complicated given the binding attributes in use.

答:
You could use a static dictionary to associate months with their index:

```<code>public sealed class Month
{
    private static Dictionary<short, Month> instances = new Dictionary<short, Month>();

    private static Month AddInstance(string name, short index, string season)
    {
        instances[index] = new Month(name, index, season);
        return instances[index];
    }

    public static IEnumerable<Month> GetByIndex(params short[] indices)
    {
        return indices.Select(i => instances[i]);
    }

    public static readonly Month January = AddInstance("January", 1, "Winter");
    public static readonly Month February = AddInstance("February", 2, "Winter");
    public static readonly Month March = AddInstance("March", 3, "Spring");
    // ...

    public string Name { get; private set; }
    public short Index { get; private set; }
    public string Season { get; private set; }

    private Month(string name, short index, string season)
    {
        Name = name;
        Index = index;
        Season = season;
    }
}
</code>```

Then use like:

```<code>Month.GetByIndex(1, 4, 7)
    .Select(month => month.Season); // { "Winter", "Spring", "Summer" }
</code>```

Body:
I followed this guide on making a more complicated enum type for my implementation.
http://www.huristic.co/blog/2018/1/30/c-advanced-enum-value-types

So far so good, however now I need to access the struct properties I have made ideally by index. A use case is if I get in a list of integers, I want to be able to provide a list of strings with the seasons in, e.g. {1,4,7} would get me {"Winter", "Spring", "Summer"} for example.

So in effect, using this example, I would like to be able to select Month where the index is 7 for example and get out the season of "Summer".

My first step was to get the names like so:

IEnumerable<string> names = typeof(Month).GetProperties(BindingFlags.Static | BindingFlags.Public)
.Select(x => x.Name);

I then attempted to get the particular Month with:

foreach(string name in names) {
  Month m = (Month) typeof(Month).GetType().GetProperties()
  .Single(info => info.Name == name)
  .GetValue(typeof(Month),null);
}

however this is going to cause me to iterate over the entire collection for every value I want to get.

Ultimately I think I'm headed in the wrong direction and would really appreciate a pointer. At the moment I'm trying to do this in a method in another class, but don't see why it couldn't be a getter in the struct itself, although that may be complicated given the binding attributes in use.

Body:
You could use a static dictionary to associate months with their index:

public sealed class Month
{
    private static Dictionary<short, Month> instances = new Dictionary<short, Month>();

    private static Month AddInstance(string name, short index, string season)
    {
        instances[index] = new Month(name, index, season);
        return instances[index];
    }

    public static IEnumerable<Month> GetByIndex(params short[] indices)
    {
        return indices.Select(i => instances[i]);
    }

    public static readonly Month January = AddInstance("January", 1, "Winter");
    public static readonly Month February = AddInstance("February", 2, "Winter");
    public static readonly Month March = AddInstance("March", 3, "Spring");
    // ...

    public string Name { get; private set; }
    public short Index { get; private set; }
    public string Season { get; private set; }

    private Month(string name, short index, string season)
    {
        Name = name;
        Index = index;
        Season = season;
    }
}

Then use like:

Month.GetByIndex(1, 4, 7)
    .Select(month => month.Season); // { "Winter", "Spring", "Summer" }


来源: stackexchange

问:
Kotlin unresolved reference in IntelliJ
I started off with this tutorial for learning Kotlin in IntelliJ IDEA.

When I tried running the following example,

```<code>fun main(args: Array<String>) {
    println("lol")
}
</code>```

Build fails with the following error:

```<code>Error:(5, 5) Kotlin: Unresolved reference: println
</code>```

This is the first time I am using IntelliJ. I have never worked on a Java project either. Am I missing something?

Edit: I have already seen this other question, though it is not valid for my situation.

答: Check and install Android Studio Updates. This fix the problem.

ContentLicense: CC BY-SA 4.0

Title: Kotlin unresolved reference in IntelliJ

Body:
I started off with this tutorial for learning Kotlin in IntelliJ IDEA.

When I tried running the following example,

fun main(args: Array<String>) {
    println("lol")
}

Build fails with the following error:

Error:(5, 5) Kotlin: Unresolved reference: println

This is the first time I am using IntelliJ. I have never worked on a Java project either. Am I missing something?

Edit: I have already seen this other question, though it is not valid for my situation.


问:
how to open new view on touch even for uitextfield
I am just woundering if it is possible and if so how I could go about loading a new
view when the user touches a uitextfield?

What I am trying to do is load a new view where the user will use a picker to populate the UItextField instead of typing the word.

any help would be greatly appreciated

答: What you need here is the inputView property of UITextField. If you set this for a text field, then instead of the usual keyboard, the inputView object will pop up. I had created this example for a related problem which uses a UIPickerView as an inputView to a UITextField object. You can check it to see if it helps.

ContentLicense: CC BY-SA 3.0


问:
Git error on git pull (unable to update local ref)
I only have branch master and im getting this error every time i try to "git pull":

```<code>error: Couldn't set refs/remotes/origin/master
From /var/lib/git/xxx/project
 ! a0f80ea..49177a3  master     -> origin/master  (unable to update local ref)
</code>```

and when i do "git pull origin master" i get:

```<code>error: Couldn't set ORIG_HEAD
fatal: Cannot update the ref 'ORIG_HEAD'.
</code>```

i have been searching but cant find why

答:
I had the same error, I was updating from within Eclipse and I got many errors.
So I tried updating from a DOS command window, and got the same issue.

Then I tried the solution " git gc --prune=now "
This gave messages that the files were locked in the refs directory.

Eclipse must have had a locked on something in the "refs" directory.

The solution I found was to simply close Eclipse.
Then I updated the repository from DOS with a " git PULL " command, and everything worked fine.

Body:
I only have branch master and im getting this error every time i try to "git pull":

error: Couldn't set refs/remotes/origin/master
From /var/lib/git/xxx/project
 ! a0f80ea..49177a3  master     -> origin/master  (unable to update local ref)

and when i do "git pull origin master" i get:

error: Couldn't set ORIG_HEAD
fatal: Cannot update the ref 'ORIG_HEAD'.

i have been searching but cant find why


问:
multiplying a (N,N) matrix with a vector (V), so that the output is of the shape (N,N,V)
Hei there - I'm a python beginner and I'd like to figure out the following:

I want to multiply a matrix of shape (n,n) with a vector of shape (v), so that the output has the shape (n,n,v).

My code looks something like this but it's far from elegant.

```<code>def D(x,y,B,n):
    # shape of x,y is (n,n) # shape of B is (v)

    a = np.ndarray(shape = (n,n,1), dtype = float)
    b = np.ndarray(shape = (n,n,1), dtype = float)

    a = np.arctan2(y, x)*(B[0])/(2.*math.pi)
    b = np.arctan2(y, x)*(B[1])/(2.*math.pi)
    c, d = ...

    return np.asarray([a,b,c,d]).T
</code>```

x and y are the matrices of a meshgrid and represent a radius.

Any help is much appreciated! Thank you!!

答:
You could do:
def D(x,y,B,n):
    # shape of x,y is (n,n) # shape of B is (v)</p>

```<code>a = np.ndarray(shape = (n,n,1), dtype = float)
b = np.ndarray(shape = (n,n,1), dtype = float)

c = np.arctan2(y, x) * B[None, None, :]
# c.shape == (n, n, v)

return c.T
</code>```

Body:
Hei there - I'm a python beginner and I'd like to figure out the following:

I want to multiply a matrix of shape (n,n) with a vector of shape (v), so that the output has the shape (n,n,v).

My code looks something like this but it's far from elegant.

def D(x,y,B,n):
    # shape of x,y is (n,n) # shape of B is (v)

    a = np.ndarray(shape = (n,n,1), dtype = float)
    b = np.ndarray(shape = (n,n,1), dtype = float)

    a = np.arctan2(y, x)*(B[0])/(2.*math.pi)
    b = np.arctan2(y, x)*(B[1])/(2.*math.pi)
    c, d = ...

    return np.asarray([a,b,c,d]).T

x and y are the matrices of a meshgrid and represent a radius.

Any help is much appreciated! Thank you!!

Body:
You could do:
def D(x,y,B,n):
    # shape of x,y is (n,n) # shape of B is (v)

a = np.ndarray(shape = (n,n,1), dtype = float)
b = np.ndarray(shape = (n,n,1), dtype = float)

c = np.arctan2(y, x) * B[None, None, :]
# c.shape == (n, n, v)

return c.T


问:
How to combine two fields and flag them accordingly
I would like to know how to flag customers who did not purchase some items that are described by two fields (product name and product number). I was able to perform this query for customers that did purchase them, but not the opposite. Thank you in advance for your help!

Here is part of my SQL query.

```<code>Select customer_id, product_name, product_number
from table
where
((PRODUCT_NAME = 'LIAM' AND PRODUCT_NUMBER = '212') OR
 (PRODUCT_NAME = 'ARRAY' AND PRODUCT_NUMBER = '325')
)
</code>```

Here is an example:

```<code>1 LIAM 212

1 STACY 452

1 NEIL 789

1 LIAM 345

2 ROSE 234

2 LIAM 345

2 ARRAY 325

3 STACY 452

3 ARRAY 625
</code>```

Query Result:

```<code>1 ARRAY 325

2 LIAM 212

3 ARRAY 325

3 LIAM 212
</code>```

答:
You seems want not exists :

```<code>select t.*
from table t
where not exists (select 1
                  from table t1
                  where t1.customer_id = t.customer_id and
                        t1.PRODUCT_NAME in ('LIAM', 'ARRAY')
                 );
</code>```

I don't see any advantage using of both Product_name and Product_number in the where clause if they are defined unique in table.

By this way, you will get customer's who never purchased liam or array product.

Body:
I would like to know how to flag customers who did not purchase some items that are described by two fields (product name and product number). I was able to perform this query for customers that did purchase them, but not the opposite. Thank you in advance for your help!

Here is part of my SQL query.

Select customer_id, product_name, product_number
from table
where
((PRODUCT_NAME = 'LIAM' AND PRODUCT_NUMBER = '212') OR
 (PRODUCT_NAME = 'ARRAY' AND PRODUCT_NUMBER = '325')
)

Here is an example:

1 LIAM 212

1 STACY 452

1 NEIL 789

1 LIAM 345

2 ROSE 234

2 LIAM 345

2 ARRAY 325

3 STACY 452

3 ARRAY 625

Query Result:

1 ARRAY 325

2 LIAM 212

3 ARRAY 325

3 LIAM 212

Body:
You seems want not exists :

select t.*
from table t
where not exists (select 1
                  from table t1
                  where t1.customer_id = t.customer_id and
                        t1.PRODUCT_NAME in ('LIAM', 'ARRAY')
                 );

I don't see any advantage using of both Product_name and Product_number in the where clause if they are defined unique in table.

By this way, you will get customer's who never purchased liam or array product.


问:
Java game development - Look and shoot at mouse coordinates
I'm going to make a game where you run around with a character, seen from above. But the problem is how do I make the character look at the mouse all the time? And how do I calculate the angle so that I can shoot towards the mouse(where I'm currently looking). I guess you have to play around with trigonometry and stuff like that to get angles, but I really don't know how.

I'm pretty good at math, so I might figure it out if you guys give me some help.

And sorry for my eventually bad english, I'm swedish :)

Thanks,
Alexandberg

答:
as you said a big hint can be found in trig

```<code>Point pl = getCharacterLox();
Point mouse = getMouseLoc();
double cos = (mouse.getX()-pl.getX());
double sin = (mouse.getY()-pl.getY());
cos/=Math.hypot(cos,sin);//normalize
double angle = Math.copySign(Math.acos(cos),sin);
</code>```

I used a little trick here in the last line: acos is between 0 and PI but if sin is negative it should be negated, if sin is 0 it will evaluate to +0.0 and angle will be 0 or PI regardless

Body:
as you said a big hint can be found in trig

Point pl = getCharacterLox();
Point mouse = getMouseLoc();
double cos = (mouse.getX()-pl.getX());
double sin = (mouse.getY()-pl.getY());
cos/=Math.hypot(cos,sin);//normalize
double angle = Math.copySign(Math.acos(cos),sin);

I used a little trick here in the last line: acos is between 0 and PI but if sin is negative it should be negated, if sin is 0 it will evaluate to +0.0 and angle will be 0 or PI regardless


问:
How can I get a Minecraft player's UUID from their username in NodeJS?
I know there are lots of other posts asking this same questions, but none of the others had the solution to my problem. I am using NodeJS and DiscordJS to create a discord bot, and I need to get the UUID of a Minecraft player from just their username, which will be provided as an argument in the command.

This is the function I have created to do this, however it doesn't seem to be working.

```<code>  function getId(playername) {
    const { data } = fetch(`https://api.mojang.com/users/profiles/minecraft/${args[2]}`)
    .then(data => data.json())
    .then(({ player }) => {
      return player.id;
    });
  }
</code>```

args[2] is the third argument of the command, which is formatted like this: <prefix> id <playername>. fetch is part of the 'node-fetch' npm module, which I have installed. I call the function when the command is sent, and it fetches the data from Mojang's API, but it can't get the UUID. This is the error:

```<code>(node:39416) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undefined
    at C:\Users\archi\OneDrive\Documents\Programming\Discord Bots\Hypixel Discord Bot\index.js:161:21
    at processTicksAndRejections (internal/process/task_queues.js:94:5)
(node:39416) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:39416) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

It is saying it cannot read the property of 'id', which if you use the Mojang API, is the key for the UUID of a player. Any ideas?

答:
Try using the playername instead of args[2] in the request URL, and making it return a promise. There's also no need to use { player }, as the object the API returns doesn't have a player propriety. Just use player as the argument for the arrow function.

function getId(playername) {
  return fetch(`https://api.mojang.com/users/profiles/minecraft/${playername}`)
    .then(data => data.json())
    .then(player => player.id);
}
```

<p>Then call it like so in your code:</p>

<pre class="lang-js prettyprint-override"><code>// Using .then (anywhere)
getId(args[2]).then(id => {
  console.log(`ID is ${id}`)
})
</code>```

// Using await (inside of an async function)
const id = await getId(args[2])
console.log(`ID is ${id}`)
```

Body:
I know there are lots of other posts asking this same questions, but none of the others had the solution to my problem. I am using NodeJS and DiscordJS to create a discord bot, and I need to get the UUID of a Minecraft player from just their username, which will be provided as an argument in the command.

This is the function I have created to do this, however it doesn't seem to be working.

  function getId(playername) {
    const { data } = fetch(`https://api.mojang.com/users/profiles/minecraft/${args[2]}`)
    .then(data => data.json())
    .then(({ player }) => {
      return player.id;
    });
  }

args[2] is the third argument of the command, which is formatted like this: <prefix> id <playername>. fetch is part of the 'node-fetch' npm module, which I have installed. I call the function when the command is sent, and it fetches the data from Mojang's API, but it can't get the UUID. This is the error:

(node:39416) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undefined
    at C:\Users\archi\OneDrive\Documents\Programming\Discord Bots\Hypixel Discord Bot\index.js:161:21
    at processTicksAndRejections (internal/process/task_queues.js:94:5)
(node:39416) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:39416) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

It is saying it cannot read the property of 'id', which if you use the Mojang API, is the key for the UUID of a player. Any ideas?

Body:
Try using the playername instead of args[2] in the request URL, and making it return a promise. There's also no need to use { player }, as the object the API returns doesn't have a player propriety. Just use player as the argument for the arrow function.

function getId(playername) {
  return fetch(`https://api.mojang.com/users/profiles/minecraft/${playername}`)
    .then(data => data.json())
    .then(player => player.id);
}

Then call it like so in your code:

// Using .then (anywhere)
getId(args[2]).then(id => {
  console.log(`ID is ${id}`)
})

// Using await (inside of an async function)
const id = await getId(args[2])
console.log(`ID is ${id}`)


问:
How can a view determine its height based on a function of its width without using an intrinsicContentSize that is dependent on the frame?
I am trying to figure out how best to create a view that determines its own height based on the width it is given. The behaviour I desire is very similar to how a vertical UIStackView behaves in that:

When constrained by its top, leading, and trailing edges, it should determine its own natural height based on its content.

When constrained on all edges, it should fill all the available space by expanding and collapsing as determined by those constraints.

In addition, I am looking to achieve this without using autolayout internally to my view.

To illustrate this, please consider the following example:

class ViewController: UIViewController {

    let v = View()

    override func viewDidLoad() {
        super.viewDidLoad()

        v.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(v)

        NSLayoutConstraint.activate([
            v.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            v.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            v.trailingAnchor.constraint(equalTo: view.trailingAnchor),

            // Toggle this constraint on and off.
            // v.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
        ])
    }
}

class View: UIView {

    // Imagine this came from computing the size of some child views
    // and that it is relative to the width of the bounds.
    var contentHeight: CGFloat { bounds.width * 0.5 }

    var boundsWidth: CGFloat = 0 {
        didSet { if oldValue != boundsWidth { invalidateIntrinsicContentSize() } }
    }

    override var intrinsicContentSize: CGSize {
        .init(width: bounds.width, height: contentHeight)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        boundsWidth = bounds.width
        backgroundColor = .red
    }
}

```

This example achieves the behaviour I've described above but I have a big reservation with it because of how I'm using intrinsicContentSize.

The documentation for instrinsicContentSize states that it must be independent of the content frame, which I have not managed. I am calculating the intrinsic size based on the width of the frame.

How is it possible to achieve this behaviour and not make instrinsicContentSize rely on the bounds?

答:
This can all be done with auto-layout constraints. No need to calculate anything.

All you need to do is make sure your custom view's content has appropriate constraints to define the layout.

For example, a UILabel has an intrinsic size based on its text. You can constrain a "top" label to the top of the view, a "middle" label to the bottom of the "top" label, and a "bottom" label to the bottom of the "middle" label and to the bottom of the view.

Here's an example (all via code):

```<code>class SizeTestViewController: UIViewController {

    let v = ExampleView()

    override func viewDidLoad() {
        super.viewDidLoad()

        v.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(v)

        NSLayoutConstraint.activate([
            v.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            v.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            v.trailingAnchor.constraint(equalTo: view.trailingAnchor),

        ])

        v.topLabel.text = "This is the top label."
        v.middleLabel.text = "This is a bunch of text for the middle label. Since we have it set to numberOfLines = 0, the text will wrap onto mutliple lines (assuming it needs to)."
        v.bottomLabel.text = "This is the bottom label text\nwith embedded newline characters\nso we can see the multiline feature without needing word wrap."

        // so we can see the view's frame
        v.backgroundColor = .red
    }
}

class ExampleView: UIView {
    var topLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .yellow
        v.numberOfLines = 0
        return v
    }()

    var middleLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .cyan
        v.numberOfLines = 0
        return v
    }()

    var bottomLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .green
        v.numberOfLines = 0
        return v
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    func commonInit() -> Void {

        addSubview(topLabel)
        addSubview(middleLabel)
        addSubview(bottomLabel)

        NSLayoutConstraint.activate([

            // constrain topLabel 8-pts from top, leading, trailing
            topLabel.topAnchor.constraint(equalTo: topAnchor, constant: 8.0),
            topLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8.0),
            topLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8.0),

            // constrain middleLabel 8-pts from topLabel
            //  8-pts from leading, trailing
            middleLabel.topAnchor.constraint(equalTo: topLabel.bottomAnchor, constant: 8.0),
            middleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8.0),
            middleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8.0),

            // constrain bottomLabel 8-pts from middleLabel
            //  8-pts from leading, trailing
            //  8-pts from bottom
            bottomLabel.topAnchor.constraint(equalTo: middleLabel.bottomAnchor, constant: 8.0),
            bottomLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8.0),
            bottomLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8.0),
            bottomLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8.0),

        ])

    }

}
</code>```

The result:

and rotated, so you can see the auto-sizing:

Edit

A little clarification on Intrinsic Content Size...

In this image, all 5 subviews have an intrinsicContentSize of 120 x 80:

```<code>class IntrinsicTestView: UIView {
    override var intrinsicContentSize: CGSize {
        return CGSize(width: 120, height: 80)
    }
}
</code>```

As you can see:

If I don't add constraints to specify Width - either with a Width constraint or Leading and Trailing constraints - the view will be 120-pts wide.

If I don't add constraints to specify Height - either with a Height constraint or Top and Bottom constraints - the view will be 80-pts tall.

Otherwise, the width and height will be determined by the constraints I've added.

Here's the complete code for that example:

```<code>class IntrinsicTestView: UIView {
    override var intrinsicContentSize: CGSize {
        return CGSize(width: 120, height: 80)
    }
}

class IntrinsicExampleViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        var iViews: [IntrinsicTestView] = [IntrinsicTestView]()

        var v: IntrinsicTestView

        let colors: [UIColor] = [.red, .green, .blue, .yellow, .purple]

        colors.forEach { c in
            let v = IntrinsicTestView()
            v.backgroundColor = c
            v.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview(v)
            iViews.append(v)
        }

        let g = view.safeAreaLayoutGuide

        // first view at Top: 20 / Leading: 20
        v = iViews[0]
        v.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0).isActive = true
        v.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0).isActive = true

        // second view at Top: 120 / Leading: 20
        //  height: 20
        v = iViews[1]
        v.topAnchor.constraint(equalTo: g.topAnchor, constant: 120.0).isActive = true
        v.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0).isActive = true
        v.heightAnchor.constraint(equalToConstant: 20).isActive = true

        // third view at Top: 160 / Leading: 20
        //  height: 40 / width: 250
        v = iViews[2]
        v.topAnchor.constraint(equalTo: g.topAnchor, constant: 160.0).isActive = true
        v.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0).isActive = true
        v.heightAnchor.constraint(equalToConstant: 40).isActive = true
        v.widthAnchor.constraint(equalToConstant: 250).isActive = true

        // fourth view at Top: 220
        //  trailing: 20 / width: 250
        v = iViews[3]
        v.topAnchor.constraint(equalTo: g.topAnchor, constant: 220.0).isActive = true
        v.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0).isActive = true
        v.widthAnchor.constraint(equalToConstant: 250).isActive = true

        // fourth view at Top: 400 / Leading: 20
        //  trailing: 20 / bottom: 20
        v = iViews[4]
        v.topAnchor.constraint(equalTo: g.topAnchor, constant: 400.0).isActive = true
        v.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0).isActive = true
        v.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0).isActive = true
        v.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -20.0).isActive = true

    }

}
</code>```

Body:
I am trying to figure out how best to create a view that determines its own height based on the width it is given. The behaviour I desire is very similar to how a vertical UIStackView behaves in that:

When constrained by its top, leading, and trailing edges, it should determine its own natural height based on its content.

When constrained on all edges, it should fill all the available space by expanding and collapsing as determined by those constraints.

In addition, I am looking to achieve this without using autolayout internally to my view.

To illustrate this, please consider the following example:

class ViewController: UIViewController {

    let v = View()

    override func viewDidLoad() {
        super.viewDidLoad()

        v.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(v)

        NSLayoutConstraint.activate([
            v.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            v.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            v.trailingAnchor.constraint(equalTo: view.trailingAnchor),

            // Toggle this constraint on and off.
            // v.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
        ])
    }
}

class View: UIView {

    // Imagine this came from computing the size of some child views
    // and that it is relative to the width of the bounds.
    var contentHeight: CGFloat { bounds.width * 0.5 }

    var boundsWidth: CGFloat = 0 {
        didSet { if oldValue != boundsWidth { invalidateIntrinsicContentSize() } }
    }

    override var intrinsicContentSize: CGSize {
        .init(width: bounds.width, height: contentHeight)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        boundsWidth = bounds.width
        backgroundColor = .red
    }
}

This example achieves the behaviour I've described above but I have a big reservation with it because of how I'm using intrinsicContentSize.

The documentation for instrinsicContentSize states that it must be independent of the content frame, which I have not managed. I am calculating the intrinsic size based on the width of the frame.

How is it possible to achieve this behaviour and not make instrinsicContentSize rely on the bounds?

Body:
This can all be done with auto-layout constraints. No need to calculate anything.

All you need to do is make sure your custom view's content has appropriate constraints to define the layout.

For example, a UILabel has an intrinsic size based on its text. You can constrain a "top" label to the top of the view, a "middle" label to the bottom of the "top" label, and a "bottom" label to the bottom of the "middle" label and to the bottom of the view.

Here's an example (all via code):

class SizeTestViewController: UIViewController {

    let v = ExampleView()

    override func viewDidLoad() {
        super.viewDidLoad()

        v.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(v)

        NSLayoutConstraint.activate([
            v.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            v.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            v.trailingAnchor.constraint(equalTo: view.trailingAnchor),

        ])

        v.topLabel.text = "This is the top label."
        v.middleLabel.text = "This is a bunch of text for the middle label. Since we have it set to numberOfLines = 0, the text will wrap onto mutliple lines (assuming it needs to)."
        v.bottomLabel.text = "This is the bottom label text\nwith embedded newline characters\nso we can see the multiline feature without needing word wrap."

        // so we can see the view's frame
        v.backgroundColor = .red
    }
}

class ExampleView: UIView {
    var topLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .yellow
        v.numberOfLines = 0
        return v
    }()

    var middleLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .cyan
        v.numberOfLines = 0
        return v
    }()

    var bottomLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .green
        v.numberOfLines = 0
        return v
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    func commonInit() -> Void {

        addSubview(topLabel)
        addSubview(middleLabel)
        addSubview(bottomLabel)

        NSLayoutConstraint.activate([

            // constrain topLabel 8-pts from top, leading, trailing
            topLabel.topAnchor.constraint(equalTo: topAnchor, constant: 8.0),
            topLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8.0),
            topLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8.0),

            // constrain middleLabel 8-pts from topLabel
            //  8-pts from leading, trailing
            middleLabel.topAnchor.constraint(equalTo: topLabel.bottomAnchor, constant: 8.0),
            middleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8.0),
            middleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8.0),

            // constrain bottomLabel 8-pts from middleLabel
            //  8-pts from leading, trailing
            //  8-pts from bottom
            bottomLabel.topAnchor.constraint(equalTo: middleLabel.bottomAnchor, constant: 8.0),
            bottomLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8.0),
            bottomLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8.0),
            bottomLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8.0),

        ])

    }

}

The result:

and rotated, so you can see the auto-sizing:

Edit

A little clarification on Intrinsic Content Size...

In this image, all 5 subviews have an intrinsicContentSize of 120 x 80:

class IntrinsicTestView: UIView {
    override var intrinsicContentSize: CGSize {
        return CGSize(width: 120, height: 80)
    }
}

As you can see:

If I don't add constraints to specify Width - either with a Width constraint or Leading and Trailing constraints - the view will be 120-pts wide.

If I don't add constraints to specify Height - either with a Height constraint or Top and Bottom constraints - the view will be 80-pts tall.

Otherwise, the width and height will be determined by the constraints I've added.

Here's the complete code for that example:

class IntrinsicTestView: UIView {
    override var intrinsicContentSize: CGSize {
        return CGSize(width: 120, height: 80)
    }
}

class IntrinsicExampleViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        var iViews: [IntrinsicTestView] = [IntrinsicTestView]()

        var v: IntrinsicTestView

        let colors: [UIColor] = [.red, .green, .blue, .yellow, .purple]

        colors.forEach { c in
            let v = IntrinsicTestView()
            v.backgroundColor = c
            v.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview(v)
            iViews.append(v)
        }

        let g = view.safeAreaLayoutGuide

        // first view at Top: 20 / Leading: 20
        v = iViews[0]
        v.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0).isActive = true
        v.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0).isActive = true

        // second view at Top: 120 / Leading: 20
        //  height: 20
        v = iViews[1]
        v.topAnchor.constraint(equalTo: g.topAnchor, constant: 120.0).isActive = true
        v.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0).isActive = true
        v.heightAnchor.constraint(equalToConstant: 20).isActive = true

        // third view at Top: 160 / Leading: 20
        //  height: 40 / width: 250
        v = iViews[2]
        v.topAnchor.constraint(equalTo: g.topAnchor, constant: 160.0).isActive = true
        v.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0).isActive = true
        v.heightAnchor.constraint(equalToConstant: 40).isActive = true
        v.widthAnchor.constraint(equalToConstant: 250).isActive = true

        // fourth view at Top: 220
        //  trailing: 20 / width: 250
        v = iViews[3]
        v.topAnchor.constraint(equalTo: g.topAnchor, constant: 220.0).isActive = true
        v.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0).isActive = true
        v.widthAnchor.constraint(equalToConstant: 250).isActive = true

        // fourth view at Top: 400 / Leading: 20
        //  trailing: 20 / bottom: 20
        v = iViews[4]
        v.topAnchor.constraint(equalTo: g.topAnchor, constant: 400.0).isActive = true
        v.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0).isActive = true
        v.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0).isActive = true
        v.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -20.0).isActive = true

    }

}


问:
Groovy: Create Object for add in LinkedHasMap
I novice in Groovy and Java.
I have function which returns LinkedHashMap from some Object. It works:

```<code>def get_map(Node) {
    nodeRootName = Node.name()
    if (Node.childNodes().size() == 0) {
        return [(nodeRootName): (Node.text())]
    } else {
        subMap = [(nodeRootName):[]]
        for (subNode in Node.childNodes()) {
            if (subNode.name() != "cryptoSigns") {
                subMap.(subMap.keySet()[0]).add(get_map(subNode))
            }
        }
        return subMap
    }
}
</code>```

Call this function in code:

```<code>    nodeMap = [(rootNodeName): [data:[]]]
    for (subNode in node.childNodes()[0].childNodes()) {
            nodeMap.position.data.add(get_map(subNode))
        }
    }
</code>```

Array [data:[]] of LinkedHashMap is formed.

Now, I need from array make one LinkedHasMap.
I try make one map in my function. It can be one map or a map array with a key. For exmple:

```<code>[data:[
 key1: value,
 key2:[
   [key: value],
   [key: [
    [key: value],
    [key: value]
   ]
 ]
]]
</code>```

I try:

```<code>def get_map(Node) {
    nodeRootName = Node.name()
    if (Node.childNodes().size() == 0) {
        Map map = new HashMap()
        map.put((nodeRootName), (Node.text()))
        return map
    } else {
        Map subMap = new HashMap()
        for (subNode in Node.childNodes()) {
            subMap.put((nodeRootName), (get_map(subNode)))
        }
        return subMap
    }
}
</code>```

Call function:

```<code> Map nodeMap = new HashMap()
 Map data = new HashMap()
 for (subNode in node.childNodes()[0].childNodes()) {
      data.put(get_map(subNode))
      nodeMap.put((rootNodeName): (data))
 }
 jsonObject.nsiKTRUs.add(nodeMap)
</code>```

But I have error:
groovy.lang.MissingMethodException: No signature of method: java.util.HashMap.put() is applicable for argument types: (HashMap) values: [[code:01.11.11.111-00001]] at data.put(get_map(subNode))

How correct add my values in map?
My input data:

```<code><xml>
 <data>
   <key>value</key>
     <key2>
       <key21>value</key>
       <key22>value</key>
       <key23>
         <key231>value</key>
       </key>
    </key2>
 </data>
<xml>
</code>```

Custom embedding.

Need output

```<code>[data:[
    key: value,
    key2:[
        key21: value,
        key22: value,
        key23:[
          key231: value
        ]
     ]
 ]
]
</code>```

and output data need add to another LinkedHashMap

答:
It was good for me
nodeMap[(rootNodeName)] << data

Body:
I novice in Groovy and Java.
I have function which returns LinkedHashMap from some Object. It works:

def get_map(Node) {
    nodeRootName = Node.name()
    if (Node.childNodes().size() == 0) {
        return [(nodeRootName): (Node.text())]
    } else {
        subMap = [(nodeRootName):[]]
        for (subNode in Node.childNodes()) {
            if (subNode.name() != "cryptoSigns") {
                subMap.(subMap.keySet()[0]).add(get_map(subNode))
            }
        }
        return subMap
    }
}

Call this function in code:

    nodeMap = [(rootNodeName): [data:[]]]
    for (subNode in node.childNodes()[0].childNodes()) {
            nodeMap.position.data.add(get_map(subNode))
        }
    }

Array [data:[]] of LinkedHashMap is formed.

Now, I need from array make one LinkedHasMap.
I try make one map in my function. It can be one map or a map array with a key. For exmple:

[data:[
 key1: value,
 key2:[
   [key: value],
   [key: [
    [key: value],
    [key: value]
   ]
 ]
]]

I try:

def get_map(Node) {
    nodeRootName = Node.name()
    if (Node.childNodes().size() == 0) {
        Map map = new HashMap()
        map.put((nodeRootName), (Node.text()))
        return map
    } else {
        Map subMap = new HashMap()
        for (subNode in Node.childNodes()) {
            subMap.put((nodeRootName), (get_map(subNode)))
        }
        return subMap
    }
}

Call function:

 Map nodeMap = new HashMap()
 Map data = new HashMap()
 for (subNode in node.childNodes()[0].childNodes()) {
      data.put(get_map(subNode))
      nodeMap.put((rootNodeName): (data))
 }
 jsonObject.nsiKTRUs.add(nodeMap)

But I have error:
groovy.lang.MissingMethodException: No signature of method: java.util.HashMap.put() is applicable for argument types: (HashMap) values: [[code:01.11.11.111-00001]] at data.put(get_map(subNode))

How correct add my values in map?
My input data:

<xml>
 <data>
   <key>value</key>
     <key2>
       <key21>value</key>
       <key22>value</key>
       <key23>
         <key231>value</key>
       </key>
    </key2>
 </data>
<xml>

Custom embedding.

Need output

[data:[
    key: value,
    key2:[
        key21: value,
        key22: value,
        key23:[
          key231: value
        ]
     ]
 ]
]

and output data need add to another LinkedHashMap


问:
Can you explain what this line does in Matlab
I'm new to Matlab and I'm just stuck with this line of code:

```<code>[r,c] = find(abs(fh) <= 2 );
</code>```

Beware: ironically it was easy for me understanding what the right part of the assignment is.

The left part however (which is maybe the definition of a variable)... I don't know how to search because I have too generic results by googling just square brackets with something inside.

My assumption is this line of code is creating some a matrix with r rows and c columns but r and c are nowhere to be found in the rest of the code.... or maybe it's a simple array with two elements... but it doesn't make much sense to me honestly.

Can you guys help me please?

答:
Whenever you see that syntax, it means that the function being called is returning more than one output argument (two in this case).

The best way to learn about the function output arguments is to check the documentation:
https://www.mathworks.com/help/matlab/ref/find.html#d120e368337

[row,col] = find(___) returns the row and column subscripts of each
  nonzero element in array X using any of the input arguments in
  previous syntaxes.

The output arguments are positional, so r is row, c is col.

Body:
I'm new to Matlab and I'm just stuck with this line of code:

[r,c] = find(abs(fh) <= 2 );

Beware: ironically it was easy for me understanding what the right part of the assignment is.

The left part however (which is maybe the definition of a variable)... I don't know how to search because I have too generic results by googling just square brackets with something inside.

My assumption is this line of code is creating some a matrix with r rows and c columns but r and c are nowhere to be found in the rest of the code.... or maybe it's a simple array with two elements... but it doesn't make much sense to me honestly.

Can you guys help me please?


问:
How to get ddl auto generated script in Spring boot JPA/Hibernate?
Is there a way to quickly get initial SQL script for the database that is being generated by hibernating through ddl-auto property?

I would like to get an initial SQL script for the flyway as a quick start.

答:
use property  spring.jpa.show-sql = true and it will print all script on console in format.

use ddl-auto as you did and take backup of schema for your respective DB and use that as initial script

example - mysql , postgres


问:
Timeit.timeit error (name 'func' is not defined)
I tried doing timeit.timeit("func()") (func is a function defined by myself), however, I always get the error name 'func' is not defined. Using Jupyter Notebook (I know about the magic timeit of Jupyter, but I wonder why this doesn't work?).

答:
If you want to use it with first argument a string, that string must contain your full code, e.g.:

```<code>s = """
def func(n=10000):
    return [x ** 2 for x in range(n)]

func(10000)
"""

timeit.timeit(s)
</code>```

or you need to use the setup parameter:

```<code>s = """
def func(n=10000):
    return [x ** 2 for x in range(n)]
"""

timeit.timeit("func()", setup=s)
</code>```

Body:
If you want to use it with first argument a string, that string must contain your full code, e.g.:

s = """
def func(n=10000):
    return [x ** 2 for x in range(n)]

func(10000)
"""

timeit.timeit(s)

or you need to use the setup parameter:

s = """
def func(n=10000):
    return [x ** 2 for x in range(n)]
"""

timeit.timeit("func()", setup=s)


问:
How to create a tiled map in Java?
So I have a tile image tile.png and I'm trying to create a tiled map all across the window. I'm building this as an applet. This is what my paint method looks like, but its not effective. When I run the applet it takes about 2 seconds and the entire screen is painted from left to right with the image, rather than everything rendered at once. Also, it all looks like one large tile.png rather than 40 small instances of tile.png

```<code>public void paint(Graphics g)
{
    Image tile=getImg("tile.png");
    int width=this.getWidth();
    int height=this.getHeight();

    int x;
    int y;
    for (x=0; x<= width; x++)
    {
        for (y=0; y<= height; y++)
        {
            g.drawImage(tile, x, y, this);
        }
    }
}
</code>```

Btw the tile.png file is 10 x 10 pixels, this is the actual img:

tile.png http://img12.imageshack.us/img12/1368/tile.png

Edit: Using the code below and by improving the tile image i fixed this. Here's my new tile img in case it helps someone:

答:
Just as a side note,  you are probably going to want to start checking your "Clip Region" at some point and not drawing stuff outside that region.  Your code is set up pretty well to do that.

The other thing you could do to speed it up is "Double Buffer".  Create a component the size of your map, call getGraphics() for that component, do all your drawing to this new graphics object, then just draw your component to the real Graphics object passed into your paint method.

A nice thing about this is that you can draw your entire map before you ever hit the paint statement, then slap it out instantly.

Google Double Buffering in Java for more info.

OwnerDisplayName: Click Upvote

Title: How to create a tiled map in Java?

Body:
So I have a tile image tile.png and I'm trying to create a tiled map all across the window. I'm building this as an applet. This is what my paint method looks like, but its not effective. When I run the applet it takes about 2 seconds and the entire screen is painted from left to right with the image, rather than everything rendered at once. Also, it all looks like one large tile.png rather than 40 small instances of tile.png

public void paint(Graphics g)
{
    Image tile=getImg("tile.png");
    int width=this.getWidth();
    int height=this.getHeight();

    int x;
    int y;
    for (x=0; x<= width; x++)
    {
        for (y=0; y<= height; y++)
        {
            g.drawImage(tile, x, y, this);
        }
    }
}

Btw the tile.png file is 10 x 10 pixels, this is the actual img:

tile.png http://img12.imageshack.us/img12/1368/tile.png

Edit: Using the code below and by improving the tile image i fixed this. Here's my new tile img in case it helps someone:

LastEditorDisplayName: Click Upvote

OwnerDisplayName: Bill K

ContentLicense: CC BY-SA 2.5


问:
What's the content of the XMLDSIG DigestMethod element?
The XMLDSIG-CORE spec defines the DigestMethod element in a Reference.  The DigestMethod specifies the Algorithm that should be applied to the referenced document to obtain the DigestValue.

What I don't get, is why this DigestMethod has this for its content (in XML schema):

```<code><sequence>
<any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/>
</sequence>
</code>```

What's the point of this content, and how should I interprete it should I receive it?

答:
Check RFC 3075 http://www.ietf.org/rfc/rfc3075.txt -- The value depends on what you have on 'Reference'

There are 3 types of XML Digital Signature: Enveloped, Enveloping and Detached. First identify which one are you working on. As an example, if you are in the enveloped signature case, and your URL of Reference is empty, the digest correspond to the digest of the canonicalization version of your XML without the 'Signature' node. Again, there are several versions of canonicalization, so you have to check in your XML which one is this referring to.

It should not be difficult to calculate, but you need to pay attention to this details before attempting to calculate or figure out where this value comes from.

Hope this helps.

Body:
The XMLDSIG-CORE spec defines the DigestMethod element in a Reference.  The DigestMethod specifies the Algorithm that should be applied to the referenced document to obtain the DigestValue.

What I don't get, is why this DigestMethod has this for its content (in XML schema):

<sequence>
<any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/>
</sequence>

What's the point of this content, and how should I interprete it should I receive it?


问:
Problem with filling 5th column in GridLayout
When I add the 5th column, the button with the number 5 half crawls out of the screen. When I add value to the buttons: android:layout_columnWeight="1", then the button with number 1 is stretched out of the screen.

How can I fit all 5 columns on the screen?

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <GridLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:rowCount="5"
        android:columnCount="5">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="1"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="0"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="2"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="1"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="3"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="2"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="4"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="3"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="5"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="4"/>
    </GridLayout>
</RelativeLayout>
</code>```

答: set android:layout_width="match_parent" in GridLayout</p>

Body:
When I add the 5th column, the button with the number 5 half crawls out of the screen. When I add value to the buttons: android:layout_columnWeight="1", then the button with number 1 is stretched out of the screen.

How can I fit all 5 columns on the screen?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <GridLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:rowCount="5"
        android:columnCount="5">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="1"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="0"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="2"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="1"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="3"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="2"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="4"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="3"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="5"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="4"/>
    </GridLayout>
</RelativeLayout>


问:
How to have an absolute v-overlay boxed inside a v-col?
When an absolute v-overlay is used inside a v-col, the overlay covers all of its grandparent v-row instead of just its parent v-col.

"absolute overlays are positioned absolutely and contained inside of their parent element."

-Vuetify's documentation

Here's a demo on codepen

答:
This happens because elements are by default have a position value of static, and in CSS there's this rule:

absolutely positioned elements are positioned relative to its nearest positioned ancestor (i.e., the nearest ancestor that is not static).

Source: mdn

In our case the nearest positioned ancestor is the v-row.
To fix this, one has simply to add a position: relative; to the parent v-col (you can uncomment this in the codepen to see the difference)


问:
Apply filtering with an array of value instead of one value for a filter in Algolia
I have in my index a list of object, each of them has an objectID value.

On some search, i want to filter OUT a certain number of them, using there objectID.

For the moment it works with one value as a string, i would like to know how to do for multiple value.

```<code>filters = 'NOT objectID:' + objectIDToFilter;
</code>```

This work for one object, what can i do to apply this for an array of ObjectID. because :

```<code>filters = 'NOT objectID:' + arrayObjectID;
</code>```

does not work.

I was thinking of generating a huge string with an arrayId.map with all my 'NOT objectID:1 AND NOT objectID: 2 ...' but i wanted to know if there is a cleaner way to do it.

I unfortunately misunderstood the line in algolia doc :

Array Attributes: Any attribute set up as an array will match the filter as soon as one of the values in the array match.

This apparently refers to the value itself in Algolia and not the filter

答:
So i did not found a solution on algolia doc, i went for the long string, hope there is no limits on how much filter we can add on a query (found nothing about that).

Here is what i did if someone need it :

```<code>let filters = `NOT objectID:${userID}`;
blockedByUsers.map((blockedByUser) => {
   filters = filters + ` AND NOT objectID:${blockedByUser}`;
});
</code>```

If you need to add multiple but don't have a starting point like i do, you can't start the query with an AND , a solution i found  to bypass that:

```<code>let filters = `NOT objectID:${blockedByUsers[0]}`;
blockedByUsers.map((blockedByUser, i) => {
   if (i > 0) filters = filters + ` AND NOT objectID:${blockedByUser}`;
});
</code>```

There is probably a cleaner solution, but this work. If you have found other solution for that problems i'll be happy to see :)

Body:
I have in my index a list of object, each of them has an objectID value.

On some search, i want to filter OUT a certain number of them, using there objectID.

For the moment it works with one value as a string, i would like to know how to do for multiple value.

filters = 'NOT objectID:' + objectIDToFilter;

This work for one object, what can i do to apply this for an array of ObjectID. because :

filters = 'NOT objectID:' + arrayObjectID;

does not work.

I was thinking of generating a huge string with an arrayId.map with all my 'NOT objectID:1 AND NOT objectID: 2 ...' but i wanted to know if there is a cleaner way to do it.

I unfortunately misunderstood the line in algolia doc :

Array Attributes: Any attribute set up as an array will match the filter as soon as one of the values in the array match.

This apparently refers to the value itself in Algolia and not the filter

Body:
So i did not found a solution on algolia doc, i went for the long string, hope there is no limits on how much filter we can add on a query (found nothing about that).

Here is what i did if someone need it :

let filters = `NOT objectID:${userID}`;
blockedByUsers.map((blockedByUser) => {
   filters = filters + ` AND NOT objectID:${blockedByUser}`;
});

If you need to add multiple but don't have a starting point like i do, you can't start the query with an AND , a solution i found  to bypass that:

let filters = `NOT objectID:${blockedByUsers[0]}`;
blockedByUsers.map((blockedByUser, i) => {
   if (i > 0) filters = filters + ` AND NOT objectID:${blockedByUser}`;
});

There is probably a cleaner solution, but this work. If you have found other solution for that problems i'll be happy to see :)


问:
Opencv module is imported in conda and VS Code but Not IDLE & Libs aren't imported in VsCode and IDLE
The OpenCV module runs without errors in Vs code, Spyder
But it runs with errors in python IDEL And doesn't import Libs
When I open The terminal of all these editors
Vscode terminal doesn't import Libs
Python IDEL doesn't import libs
Anaconda Prompt imports Libs

So My Error is
What's the problem with python IDEL and VS code terminal?
And how can I solve this?

```<code>#VS CODE
import cv2
from os import path
video = cv2.VideoCapture(0)
xml_classifier = path.join(path.dirname(cv2.__file__),
                           "data", "haarcascade_frontalface_default.xml")
while True:
    grabbed, frame = video.read()
    frame = cv2.resize(frame, (800, 500))

    def detect_faces(frame):
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        face_calssifier = cv2.CascadeClassifier(xml_classifier)
        rects = face_calssifier.detectMultiScale(gray,
                                                 scaleFactor=1.15,
                                                 minNeighbors=5,
                                                 minSize=(30, 30))
        return rects

    def draw(frame, rects, title):  # , text):
        print("=" * 30)
        print("i found {} people.".format(len(rects)).title())
        print("=" * 30)

        for x, y, w, h in rects:
            cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

        if title:
            cv2.imshow(title, frame)
    draw(frame, detect_faces(frame), "Video")
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video.release()
cv2.destroyAllWindows()

### In Vs code terminal ---------------------------------------------------------------------

PS C:\Users\ASUS> & C:/Users/ASUS/Anaconda3/Anaconda/python.exe c:/Users/ASUS/Computer-Vision-Projects/FDVW.py
==============================
I Found 1 People.
==============================
==============================
I Found 1 People.
==============================
==============================
I Found 1 People.
==============================
==============================
I Found 1 People.
==============================
==============================
I Found 1 People.
==============================
[ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (674) SourceReaderCB::~SourceReaderCB terminating async callback
PS C:\Users\ASUS> python
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> import cv2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'cv2'
>>> import flask
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'flask'
>>> import numpy
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'numpy'
>>> import os
>>>
</code>```

```<code># In python Idle
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import cv2
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import cv2
ModuleNotFoundError: No module named 'cv2'
>>> import numpy
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    import numpy
ModuleNotFoundError: No module named 'numpy'
>>> import flask
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    import flask
ModuleNotFoundError: No module named 'flask'
>>> import os
>>>
=== RESTART: C:\Users\ASUS\Computer-Vision-Projects\#01_face_detection.py ===
Traceback (most recent call last):
  File "C:\Users\ASUS\Computer-Vision-Projects\#01_face_detection.py", line 1, in <module>
    import cv2
ModuleNotFoundError: No module named 'cv2'
>>>
</code>```

But In Anaconda prompt it runs without errors and import libs And Spyder runs without errors

```<code>(base) C:\Windows\system32>python
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> import flask
>>> import numpy
>>> import os
</code>```

The Same error in opencv is be in flask, numpy and etc.
  The python path in Vs code settings:
  "python.pythonPath": "C:\Users\ASUS\Anaconda3\Anaconda\python",

My VSCode settings

```<code>    {

        "editor.fontSize": 22,
        "editor.rulers": [80],
        "editor.fontWeight": "500",
        "debug.console.fontSize": 16,
        "terminal.integrated.fontSize": 16,
        "terminal.integrated.fontWeight": "100",
        // "files.autoSaveDelay": 500,
        "files.autoSave": "onFocusChange",
        "workbench.iconTheme": "material-icon-theme",

        "terminal.integrated.shell.linux": "/usr/bin/zsh",
        // "terminal.integrated.inheritEnv": false,

        //? linux
        // "python.pythonPath": "/usr/bin/python3.8",

        //? py36
        "python.pythonPath": "C:\\Users\\ASUS\\Anaconda3\\Anaconda",

        "python.formatting.provider": "autopep8",
        "[python]": {
          "editor.defaultFormatter": "ms-python.python"
        },
        "workbench.colorCustomizations": {
          "terminal.foreground": "#f0a212",
          "terminal.background": "#161C28",
          // "terminal.background": "#232F34",
          "tab.activeBorder": "#02e039",
          // "activityBar.activeBackground":"#1684b3a9",
          "activityBar.activeBorder": "#02e039",
          // "list.inactiveSelectionBackground": "#86a9fb",
          "statusBar.background": "#333",
          "statusBar.foreground": "#fff",
          "statusBar.noFolderBackground": "#333",
          "statusBar.noFolderForeground": "#fff"
        },
        "gotoNextPreviousMember.symbolKinds": ["function"],
        "editor.formatOnSave": true,
        "editor.showFoldingControls": "mouseover",
        "python.jediEnabled": false,
        // "workbench.statusBar.feedback.visible": false,
        "editor.minimap.enabled": false,
        "workbench.settings.editor": "json",

        //!READ THIS ARTICLE TO CUSTOMIZE THE TERMINAL
        //? https://pascalnaber.wordpress.com/2019/10/05/have-a-great-looking-terminal-and-a-more-effective-shell-with-oh-my-zsh-on-wsl-2-using-windows/
        "terminal.integrated.fontFamily": "Source Code Pro Semibold",
        "terminal.integrated.cursorStyle": "line",
        "terminal.integrated.cursorBlinking": true,
        "workbench.startupEditor": "newUntitledFile",
        "git.autofetch": true,
        "workbench.list.openMode": "singleClick",
        "zenMode.hideLineNumbers": false,
        "zenMode.hideTabs": false,
        "workbench.activityBar.visible": true,
        "git.enableSmartCommit": true,
        "window.zoomLevel": -1,
        "editor.defaultFormatter": "ms-python.python",
        // "terminal.integrated.rendererType": "dom",
        "sync.autoUpload": true,
        "sync.forceUpload": true,
        "sync.gist": "13d7fc3f673defc7dc0cba7f7d3dd8a5",
        "workbench.colorTheme": "Newton (rainglow)",
        "kite.showWelcomeNotificationOnStartup": false,
        "extensions.ignoreRecommendations": false,
        "python.dataScience.sendSelectionToInteractiveWindow": true,
        "vsicons.dontShowNewVersionMessage": true,
        "editor.columnSelection": false,
        "dart.debugExternalLibraries": true,
        "dart.debugSdkLibraries": false,
        "dart.previewHotReloadOnSaveWatcher": true,
        "editor.multiCursorModifier": "alt",
        "editor.formatOnPaste": true,
        "[dart]": {
          "editor.tabSize": 4,
          "editor.insertSpaces": false,
          "editor.formatOnSave": true
        },
        "python.linting.enabled": true,
        "editor.tabSize": 4,

        //!############################################################

        "window.titleBarStyle": "custom",
        "window.enableMenuBarMnemonics": false,
        "window.customMenuBarAltFocus": false,
        //!############################################################
      }
</code>```

答: After My Answer I can import any lib I added it in python by this way so upvote answer if it solved your error and helped you

Body:
The OpenCV module runs without errors in Vs code, Spyder
But it runs with errors in python IDEL And doesn't import Libs
When I open The terminal of all these editors
Vscode terminal doesn't import Libs
Python IDEL doesn't import libs
Anaconda Prompt imports Libs

So My Error is
What's the problem with python IDEL and VS code terminal?
And how can I solve this?

#VS CODE
import cv2
from os import path
video = cv2.VideoCapture(0)
xml_classifier = path.join(path.dirname(cv2.__file__),
                           "data", "haarcascade_frontalface_default.xml")
while True:
    grabbed, frame = video.read()
    frame = cv2.resize(frame, (800, 500))

    def detect_faces(frame):
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        face_calssifier = cv2.CascadeClassifier(xml_classifier)
        rects = face_calssifier.detectMultiScale(gray,
                                                 scaleFactor=1.15,
                                                 minNeighbors=5,
                                                 minSize=(30, 30))
        return rects

    def draw(frame, rects, title):  # , text):
        print("=" * 30)
        print("i found {} people.".format(len(rects)).title())
        print("=" * 30)

        for x, y, w, h in rects:
            cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

        if title:
            cv2.imshow(title, frame)
    draw(frame, detect_faces(frame), "Video")
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video.release()
cv2.destroyAllWindows()

### In Vs code terminal ---------------------------------------------------------------------

PS C:\Users\ASUS> & C:/Users/ASUS/Anaconda3/Anaconda/python.exe c:/Users/ASUS/Computer-Vision-Projects/FDVW.py
==============================
I Found 1 People.
==============================
==============================
I Found 1 People.
==============================
==============================
I Found 1 People.
==============================
==============================
I Found 1 People.
==============================
==============================
I Found 1 People.
==============================
[ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (674) SourceReaderCB::~SourceReaderCB terminating async callback
PS C:\Users\ASUS> python
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> import cv2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'cv2'
>>> import flask
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'flask'
>>> import numpy
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'numpy'
>>> import os
>>>

# In python Idle
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import cv2
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import cv2
ModuleNotFoundError: No module named 'cv2'
>>> import numpy
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    import numpy
ModuleNotFoundError: No module named 'numpy'
>>> import flask
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    import flask
ModuleNotFoundError: No module named 'flask'
>>> import os
>>>
=== RESTART: C:\Users\ASUS\Computer-Vision-Projects\#01_face_detection.py ===
Traceback (most recent call last):
  File "C:\Users\ASUS\Computer-Vision-Projects\#01_face_detection.py", line 1, in <module>
    import cv2
ModuleNotFoundError: No module named 'cv2'
>>>

But In Anaconda prompt it runs without errors and import libs And Spyder runs without errors

(base) C:\Windows\system32>python
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> import flask
>>> import numpy
>>> import os

The Same error in opencv is be in flask, numpy and etc.
  The python path in Vs code settings:
  "python.pythonPath": "C:\Users\ASUS\Anaconda3\Anaconda\python",

My VSCode settings

    {

        "editor.fontSize": 22,
        "editor.rulers": [80],
        "editor.fontWeight": "500",
        "debug.console.fontSize": 16,
        "terminal.integrated.fontSize": 16,
        "terminal.integrated.fontWeight": "100",
        // "files.autoSaveDelay": 500,
        "files.autoSave": "onFocusChange",
        "workbench.iconTheme": "material-icon-theme",

        "terminal.integrated.shell.linux": "/usr/bin/zsh",
        // "terminal.integrated.inheritEnv": false,

        //? linux
        // "python.pythonPath": "/usr/bin/python3.8",

        //? py36
        "python.pythonPath": "C:\\Users\\ASUS\\Anaconda3\\Anaconda",

        "python.formatting.provider": "autopep8",
        "[python]": {
          "editor.defaultFormatter": "ms-python.python"
        },
        "workbench.colorCustomizations": {
          "terminal.foreground": "#f0a212",
          "terminal.background": "#161C28",
          // "terminal.background": "#232F34",
          "tab.activeBorder": "#02e039",
          // "activityBar.activeBackground":"#1684b3a9",
          "activityBar.activeBorder": "#02e039",
          // "list.inactiveSelectionBackground": "#86a9fb",
          "statusBar.background": "#333",
          "statusBar.foreground": "#fff",
          "statusBar.noFolderBackground": "#333",
          "statusBar.noFolderForeground": "#fff"
        },
        "gotoNextPreviousMember.symbolKinds": ["function"],
        "editor.formatOnSave": true,
        "editor.showFoldingControls": "mouseover",
        "python.jediEnabled": false,
        // "workbench.statusBar.feedback.visible": false,
        "editor.minimap.enabled": false,
        "workbench.settings.editor": "json",

        //!READ THIS ARTICLE TO CUSTOMIZE THE TERMINAL
        //? https://pascalnaber.wordpress.com/2019/10/05/have-a-great-looking-terminal-and-a-more-effective-shell-with-oh-my-zsh-on-wsl-2-using-windows/
        "terminal.integrated.fontFamily": "Source Code Pro Semibold",
        "terminal.integrated.cursorStyle": "line",
        "terminal.integrated.cursorBlinking": true,
        "workbench.startupEditor": "newUntitledFile",
        "git.autofetch": true,
        "workbench.list.openMode": "singleClick",
        "zenMode.hideLineNumbers": false,
        "zenMode.hideTabs": false,
        "workbench.activityBar.visible": true,
        "git.enableSmartCommit": true,
        "window.zoomLevel": -1,
        "editor.defaultFormatter": "ms-python.python",
        // "terminal.integrated.rendererType": "dom",
        "sync.autoUpload": true,
        "sync.forceUpload": true,
        "sync.gist": "13d7fc3f673defc7dc0cba7f7d3dd8a5",
        "workbench.colorTheme": "Newton (rainglow)",
        "kite.showWelcomeNotificationOnStartup": false,
        "extensions.ignoreRecommendations": false,
        "python.dataScience.sendSelectionToInteractiveWindow": true,
        "vsicons.dontShowNewVersionMessage": true,
        "editor.columnSelection": false,
        "dart.debugExternalLibraries": true,
        "dart.debugSdkLibraries": false,
        "dart.previewHotReloadOnSaveWatcher": true,
        "editor.multiCursorModifier": "alt",
        "editor.formatOnPaste": true,
        "[dart]": {
          "editor.tabSize": 4,
          "editor.insertSpaces": false,
          "editor.formatOnSave": true
        },
        "python.linting.enabled": true,
        "editor.tabSize": 4,

        //!############################################################

        "window.titleBarStyle": "custom",
        "window.enableMenuBarMnemonics": false,
        "window.customMenuBarAltFocus": false,
        //!############################################################
      }


问:
SessionStorage.getitem not working when loading page
I am having an issue trying to use storagesession.  I have gotten it to work, but as soon as I insert some ifthen logic, it breaks.  Below is the working code.  The bottom code is when I update the window.onload function that makes it break.  Does anybody know why its breaking and how I can fix this?  I am using only html/javascript and no server is being used. Thanks so much!</p>

```<code><!DOCTYPE html>
<!-- saved from url=(0014)about:internet -->
<html lang="en">
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="container">

<ul class="vertical-nav">

<li><a href="">Fruit</a>
<ul class="sub-menu">
<li><a href="test.html" onclick="ChangeToApple()">Apple</a></li>
<li><a href="test.html" onclick="ChangeToGrape()">Grape</a></li>
</ul>
</li>
</ul>

<div id="ShowDept">

</div>
</div>
</body>
</code>```

```<code><script>

  window.onload = function() {
  var x = sessionStorage.getItem("Dept");

document.getElementById("ShowDept").innerHTML = x;
 }

function ChangeToApple() {
sessionStorage.Dept = "Apple";
}

function ChangeToGrape() {
sessionStorage.Dept = "Grape";
}

 </script>
</code>```

```<code>  window.onload = function() {
  var x = sessionStorage.getItem("Dept");

      if (x = "Apple") {

} else if (x = "Grape") {

}
document.getElementById("ShowDept").innerHTML = x;
 }
</code>```

答:
instead of

```<code>sessionStorage.Dept = "Apple";
</code>```

try

```<code>sessionStorage.setItem("Dept", "Grape");
</code>```

Body:
I am having an issue trying to use storagesession.  I have gotten it to work, but as soon as I insert some ifthen logic, it breaks.  Below is the working code.  The bottom code is when I update the window.onload function that makes it break.  Does anybody know why its breaking and how I can fix this?  I am using only html/javascript and no server is being used. Thanks so much!

<!DOCTYPE html>

<title>Test</title>

Fruit

Apple

Grape

  window.onload = function() {
  var x = sessionStorage.getItem("Dept");

      if (x = "Apple") {

} else if (x = "Grape") {

}
document.getElementById("ShowDept").innerHTML = x;
 }

Body:
instead of

sessionStorage.Dept = "Apple";

try

sessionStorage.setItem("Dept", "Grape");


问:
Retrieving distinct relationships of relationships using Eloquent in Laravel
Lets assume I have a model for: Race, Participant, Team

And these relations: Race 1-N Participant N-1 Team

See in another way :

```<code>races  1 - N  participants
teams  1 - N  participants
</code>```

In Laravel terms:

```<code>/* Inside Race model */
public function participants()
{
    return $this->hasMany(Participant::class);
}

/* Inside Team model */
public function participants()
{
    return $this->hasMany(Participant::class);
}

/* Inside Participant model */
public function race()
{
    return $this->belongsTo(Race::class);
}
public function team()
{
    return $this->belongsTo(Team::class);
}
</code>```

In the participants table, It looks like this:

```<code>id | team_id | race_id | [a lot of other columns...]
------------------------------
 1 |    1    |    1    |
 2 |    1    |    1    |
 3 |    2    |    1    |
 4 |    2    |    1    |
</code>```

In the above example, I know that the race ID 1 has 2 teams.

I can count them by doing this:

```<code>$race = Race::find(1);
$number = $race->participants()->distinct()->count('team_id');
</code>```

The problem

Counting the number of teams is cool, but I want to access to the list of corresponding Team model instances, so that I can use them for further operations (within a foreach loop for example).

I tried a lot of things without success.

Something like this:

```<code>$teams = $race->participants()->distinct()->[...] // Don't know what to put here
</code>```

The working equivalent SQL query is:

```<code>SELECT teams.* FROM teams
INNER JOIN participants ON participants.team_id = teams.id
INNER JOIN races ON races.id = participants.race_id
WHERE races.id = 1
GROUP BY teams.id
</code>```

Resulting in this:

When the participants table contains this:

I want to know if I can do it with Eloquent instead of using Query/Builder DB:: methods directly ?

EDIT 1

My closest result:

```<code>$race->participants()->distinct()->get('team_id')
</code>```

And then using this list of team_id I can access to the teams using Team::find([list of IDs]) but it looks greedy to me.

EDIT 2

I forgot some information:

The participants.team_id column is NULLABLE because:

There are races with teams of participants

There are races with participants (without team)

答:
You can directly use hasManyThrough relationship inside Race model for fetching distinct teams associated with the race.

```<code>public function distinctTeams()
{
    return $this->hasManyThrough(Team::class, Participant::class, 'race_id', 'id', 'id', 'team_id')->distinct();
}
</code>```

Now, you can loop over the teams of a race by using $race->distinctTeams

Hopefully this helps.

Body:
Lets assume I have a model for: Race, Participant, Team

And these relations: Race 1-N Participant N-1 Team

See in another way :

races  1 - N  participants
teams  1 - N  participants

In Laravel terms:

/* Inside Race model */
public function participants()
{
    return $this->hasMany(Participant::class);
}

/* Inside Team model */
public function participants()
{
    return $this->hasMany(Participant::class);
}

/* Inside Participant model */
public function race()
{
    return $this->belongsTo(Race::class);
}
public function team()
{
    return $this->belongsTo(Team::class);
}

In the participants table, It looks like this:

id | team_id | race_id | [a lot of other columns...]
------------------------------
 1 |    1    |    1    |
 2 |    1    |    1    |
 3 |    2    |    1    |
 4 |    2    |    1    |

In the above example, I know that the race ID 1 has 2 teams.

I can count them by doing this:

$race = Race::find(1);
$number = $race->participants()->distinct()->count('team_id');

The problem

Counting the number of teams is cool, but I want to access to the list of corresponding Team model instances, so that I can use them for further operations (within a foreach loop for example).

I tried a lot of things without success.

Something like this:

$teams = $race->participants()->distinct()->[...] // Don't know what to put here

The working equivalent SQL query is:

SELECT teams.* FROM teams
INNER JOIN participants ON participants.team_id = teams.id
INNER JOIN races ON races.id = participants.race_id
WHERE races.id = 1
GROUP BY teams.id

Resulting in this:

When the participants table contains this:

I want to know if I can do it with Eloquent instead of using Query/Builder DB:: methods directly ?

EDIT 1

My closest result:

$race->participants()->distinct()->get('team_id')

And then using this list of team_id I can access to the teams using Team::find([list of IDs]) but it looks greedy to me.

EDIT 2

I forgot some information:

The participants.team_id column is NULLABLE because:

There are races with teams of participants

There are races with participants (without team)

Body:
You can directly use hasManyThrough relationship inside Race model for fetching distinct teams associated with the race.

public function distinctTeams()
{
    return $this->hasManyThrough(Team::class, Participant::class, 'race_id', 'id', 'id', 'team_id')->distinct();
}

Now, you can loop over the teams of a race by using $race->distinctTeams

Hopefully this helps.


问:
pandas: TypeError: unhashable type: 'list'
I have the following df:

```<code>df = pd.DataFrame(
    [
        [["John Muller"], "person", [8866155845]],
        [["Innovation Division"], "company", np.nan],
        [["Carol Sway"], "person", [8866155845]],
    ],
    columns=["name", "kind", "phone"],
)

# Out:
#                     name     kind         phone
# 0          [John Muller]   person  [8866155845]
# 1  [Innovation Division]  company           NaN
# 2           [Carol Sway]   person  [8866155845]
</code>```

and I want to find duplicates of a phone number. But the objects in df are lists, so using:

```<code>df.duplicated('phone')
</code>```

will generate the error:

```<code>TypeError: unhashable type: 'list'
</code>```

答:
Use can use the hashable_df package:

from hashable_df import hashable_df
hashable_df(df).duplicated('phone')
```

This will make all unhashable cell values hashable and these kind of operations to work.

Body:
I have the following df:

df = pd.DataFrame(
    [
        [["John Muller"], "person", [8866155845]],
        [["Innovation Division"], "company", np.nan],
        [["Carol Sway"], "person", [8866155845]],
    ],
    columns=["name", "kind", "phone"],
)

# Out:
#                     name     kind         phone
# 0          [John Muller]   person  [8866155845]
# 1  [Innovation Division]  company           NaN
# 2           [Carol Sway]   person  [8866155845]

and I want to find duplicates of a phone number. But the objects in df are lists, so using:

df.duplicated('phone')

will generate the error:

TypeError: unhashable type: 'list'

Body:
Use can use the hashable_df package:

from hashable_df import hashable_df
hashable_df(df).duplicated('phone')

This will make all unhashable cell values hashable and these kind of operations to work.


问:
Dynamic CSS for ASP.NET MVC?
It looks like the .NET community in general has not picked up on CSS compilers. In searching Google I've not found anything even remotely relevant.  </p>

<p>Has anyone that is using ASP.NET MVC figured out a scheme to more intelligently generate their CSS? I'd love to be able to run my CSS through Razor for example, or for SASS to get ported over or what have you. Maybe I have a new side project on my hands :) </p>

答:
I know this is an old thread, I am fairly new to ASP.NET.

Working with ASP.NET Core, I am trying to use @Darin Dimitrov's answer to allow me to set custom styles using data from an external API. To the OP's question, I know you said "Dynamic" but it seems as though you really want "Compiled". I am looking for "Dynamic".

It appears the technique of returning a partial view with response type text/css works pretty well for this solution. However, the syntax used here does not work for me in ASP.NET Core 3.1. Here is the solution I used:

Instead of HomeController I am using ThemeController as it is relevant to me.

In ThemeController.cs

```<code>public async Task<IActionResult> Index()
    {
        var colors = await _apiService.GetThemeColors();
        Response.ContentType = "text/css";
        return PartialView(colors);
    }
</code>```

In the view ~/Views/Theme/Index.cshtml

```<code>@model ThemeColors
@{
    var color = Model.primaryColor;
}
.btn-primary {
    background-color: @color;
}
</code>```

And then in my _Layout.cshtml

```<code><link href="@Url.Action("Index", "Theme")" rel="stylesheet" type="text/css" />
</code>```

I hope this helps someone, if anyone who is more knowledgeable around this topic can point to more relevant resources that would be greatly appreciated.

Title: Dynamic CSS for ASP.NET MVC?

Body:
It looks like the .NET community in general has not picked up on CSS compilers. In searching Google I've not found anything even remotely relevant.

Has anyone that is using ASP.NET MVC figured out a scheme to more intelligently generate their CSS? I'd love to be able to run my CSS through Razor for example, or for SASS to get ported over or what have you. Maybe I have a new side project on my hands :)

Body:
I know this is an old thread, I am fairly new to ASP.NET.

Working with ASP.NET Core, I am trying to use @Darin Dimitrov's answer to allow me to set custom styles using data from an external API. To the OP's question, I know you said "Dynamic" but it seems as though you really want "Compiled". I am looking for "Dynamic".

It appears the technique of returning a partial view with response type text/css works pretty well for this solution. However, the syntax used here does not work for me in ASP.NET Core 3.1. Here is the solution I used:

Instead of HomeController I am using ThemeController as it is relevant to me.

In ThemeController.cs

public async Task<IActionResult> Index()
    {
        var colors = await _apiService.GetThemeColors();
        Response.ContentType = "text/css";
        return PartialView(colors);
    }

In the view ~/Views/Theme/Index.cshtml

@model ThemeColors
@{
    var color = Model.primaryColor;
}
.btn-primary {
    background-color: @color;
}

And then in my _Layout.cshtml

<link href="@Url.Action("Index", "Theme")" rel="stylesheet" type="text/css" />

I hope this helps someone, if anyone who is more knowledgeable around this topic can point to more relevant resources that would be greatly appreciated.


问:
convert opengl Window to std::size_t and back again works in Linux, but not OS X
I have successfully converted an OpenGL Window to an std::size_t variable and then converted it back to an OpenGL Window in Linux.  However, when I try to do the same thing in Mac OS X it isn't working.  Here's what I'm doing:

```<code>/* our window instance(This is an X Window System Window!) */
    Window window_;
.
.

.
.
std::size_t OSXGLWindow::getWindowHandle() {
    return window_;
}
.
.
</code>```

Calling 'getWindowHandle()' just returns the Window as an std::size_t.

I pass this size_t window handle into the following function:

```<code>IInputManager* InputFactory::getInputMgr(std::size_t winHandle) {

    IInputManager* retObj = 0;
#ifdef _WIN32
    // todo: windows input implementation
#endif

#ifdef linux
    Window win = winHandle;
    retObj = new lwis::linuxos::LinuxInputManager(win);
#endif

#ifdef __APPLE__
    Window win = winHandle;
    retObj = new lwis::osx::OSXInputManager(win);
#endif

    return retObj;
}
</code>```

The LinuxInputManager and OSXInputManager both call the following bit of code:

```<code>XSelectInput(display_, theWindow,
            KeyPressMask | KeyReleaseMask | KeymapStateMask) == BadWindow)
</code>```

where 'theWindow' is the Window that was sent to the respective objects' constructor from the 'InputFactory::getInputMgr(..)' function.

The 'XSelectInput' is successful in the LinuxInputManager object for Linux, but not in the OSXInputManager for OS X.

Another important piece of information is that the Window is being passed between 2 static libraries, which is why it is converted to an std::size_t in the first place (to make it easy to pass between the libraries).

Anyone have any idea why this is?  Is there a better way to pass a handle between libraries?  Would a 'void*' be a better option?

答: void* would be a fine option if you can't provide GL type information to getInputMgr. I assume you are trying to hide OpenGL definitions from the rest of your code? </p>

Body:
I have successfully converted an OpenGL Window to an std::size_t variable and then converted it back to an OpenGL Window in Linux.  However, when I try to do the same thing in Mac OS X it isn't working.  Here's what I'm doing:

/* our window instance(This is an X Window System Window!) */
    Window window_;
.
.

.
.
std::size_t OSXGLWindow::getWindowHandle() {
    return window_;
}
.
.

Calling 'getWindowHandle()' just returns the Window as an std::size_t.

I pass this size_t window handle into the following function:

IInputManager* InputFactory::getInputMgr(std::size_t winHandle) {

    IInputManager* retObj = 0;
#ifdef _WIN32
    // todo: windows input implementation
#endif

#ifdef linux
    Window win = winHandle;
    retObj = new lwis::linuxos::LinuxInputManager(win);
#endif

#ifdef __APPLE__
    Window win = winHandle;
    retObj = new lwis::osx::OSXInputManager(win);
#endif

    return retObj;
}

The LinuxInputManager and OSXInputManager both call the following bit of code:

XSelectInput(display_, theWindow,
            KeyPressMask | KeyReleaseMask | KeymapStateMask) == BadWindow)

where 'theWindow' is the Window that was sent to the respective objects' constructor from the 'InputFactory::getInputMgr(..)' function.

The 'XSelectInput' is successful in the LinuxInputManager object for Linux, but not in the OSXInputManager for OS X.

Another important piece of information is that the Window is being passed between 2 static libraries, which is why it is converted to an std::size_t in the first place (to make it easy to pass between the libraries).

Anyone have any idea why this is?  Is there a better way to pass a handle between libraries?  Would a 'void*' be a better option?


问:
DB and java time date comparison and conversion
I am getting a variable newValue in java as

```<code>public void reTrigger() {
    Date date1 = new Date();
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH.mm.ss");

    squery: "select newValue from SAVE_TXN WHERE ROWID = 1"
(newValue is of type nvarchar2)

    String vidtime = sdf.format(parser.getValueOf("newValue")); //parser is another method which parses the squery
String currentDate = sdf.format(date1);
}
</code>```

Now newvalue contains date and time like: '2020/05/17 18.30.44' in DB, which I am fetching into vidtime.

Now I want to subtract this vidtime with currentDate  in java and check whether it is greater than or equals to 120 hours or not. How to proceed ?

答:
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes with the adoption of JSR 310.

You should be retrieving date-time values from the database as date-time objects rather than strings. As of JDBC 4.2, we can exchange java.time classes with the database. See PreparedStatement::setObject and ResultSet::getObject.

For a database column of type:

TIMESTAMP WITH TIME ZONE, retrieve as a OffsetDateTime (support for the more commonly used Instant and ZonedDateTime classes was unfortunately and mysteriously omitted from JDBC 4.2).

TIMESTAMP WITHOUT TIME ZONE, retrieve as a LocalDateTime.

If faced with a string input, parse using DateTimeFormatter class.

Your input lacks an indicator of time zone or offset-from-UTC. So we must parse as a LocalDateTime.

```<code>DateTimeFormatter f = DateTimeFormatter.ofPattern(  "uuuu/MM/dd HH.mm.ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
</code>```

Capturing the current moment requires a time zone. For any given moment, the date and the time-of-day vary around the globe by zone.

```<code>ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;
</code>```

We cannot compare this current moment (zdt) to your input, the ldt. Your input and a LocalDateTime object do not represent a moment, are not a specific point on the timeline. Take your example, 2020/05/17 18.30.44. We cannot know if that means 6:30 PM on the 17th in Tokyo, in Toulouse, or in Toledo – all different moments, several hours apart on the timeline.

So your Question as written cannot be solved.

If you know for certain that a time zone was intended for your input string, apply a time zone to produce a ZonedDateTime.

```<code>ZoneId zIntended = ZoneOf.( "Africa/Tunis" ) ;
ZonedDateTime then = ldt.atZone( zIntended ) ;
</code>```

Calculate elapsed time as a Duration.

```<code>Duration d = Duration.between( now , then ) ;
if( d.toHours() > 120 ) { … }
</code>```

Body:
I am getting a variable newValue in java as

public void reTrigger() {
    Date date1 = new Date();
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH.mm.ss");

    squery: "select newValue from SAVE_TXN WHERE ROWID = 1"
(newValue is of type nvarchar2)

    String vidtime = sdf.format(parser.getValueOf("newValue")); //parser is another method which parses the squery
String currentDate = sdf.format(date1);
}

Now newvalue contains date and time like: '2020/05/17 18.30.44' in DB, which I am fetching into vidtime.

Now I want to subtract this vidtime with currentDate  in java and check whether it is greater than or equals to 120 hours or not. How to proceed ?

Body:
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes with the adoption of JSR 310.

You should be retrieving date-time values from the database as date-time objects rather than strings. As of JDBC 4.2, we can exchange java.time classes with the database. See PreparedStatement::setObject and ResultSet::getObject.

For a database column of type:

TIMESTAMP WITH TIME ZONE, retrieve as a OffsetDateTime (support for the more commonly used Instant and ZonedDateTime classes was unfortunately and mysteriously omitted from JDBC 4.2).

TIMESTAMP WITHOUT TIME ZONE, retrieve as a LocalDateTime.

If faced with a string input, parse using DateTimeFormatter class.

Your input lacks an indicator of time zone or offset-from-UTC. So we must parse as a LocalDateTime.

DateTimeFormatter f = DateTimeFormatter.ofPattern(  "uuuu/MM/dd HH.mm.ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;

Capturing the current moment requires a time zone. For any given moment, the date and the time-of-day vary around the globe by zone.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;

We cannot compare this current moment (zdt) to your input, the ldt. Your input and a LocalDateTime object do not represent a moment, are not a specific point on the timeline. Take your example, 2020/05/17 18.30.44. We cannot know if that means 6:30 PM on the 17th in Tokyo, in Toulouse, or in Toledo – all different moments, several hours apart on the timeline.

So your Question as written cannot be solved.

If you know for certain that a time zone was intended for your input string, apply a time zone to produce a ZonedDateTime.

ZoneId zIntended = ZoneOf.( "Africa/Tunis" ) ;
ZonedDateTime then = ldt.atZone( zIntended ) ;

Calculate elapsed time as a Duration.

Duration d = Duration.between( now , then ) ;
if( d.toHours() > 120 ) { … }