问:
What the difference between "arrays of parameterized type( List<String>[] )" and "array of type variable( T[] )"?
Update: Although I have got the answer, it seems my description of the question is not very clear. So I changed a lot to make others understand my question.

My understanding of the reason why arrays of a parameterized type not allowed:

Integer[] b = {1,2,3};
Object[] a = b;
String[] c = {"123"};
a[0] = c; // Exception in thread "main" java.lang.ArrayStoreException
Integer i = b[0];
```
```// Not really allowed.
List<String>[] lsa = new List<String>[10];
Object o = lsa;
Object[] oa = (Object[]) o;
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
// Unsound, but passes run time store check
oa[1] = li;

// Run-time error: ClassCastException.
String s = lsa[1].get(0);
```
<p>These two pieces of code has the same structure.</p>
<p>In piece 1, <code>Object[] a = b</code> makes both <code>a</code> and <code>b</code> point to the same variable <code>b</code>. So <code>a[0] = c</code> is actually changing <code>b</code>. This kind of operation won't cause any warning while compiling but will throw an ArrayStoreException.</p>
<p>In piece 2,<code>Object o = lsa; Object[] oa = (Object[]) o;</code> makes both <code>oa</code> and <code>lsa</code> point to the same variable <code>lsa</code>, and <code>oa[1] = li;</code>
is actually changing <code>lsa</code>.</p>
<p>So I think it's this reason why not allow using arrays of parameterized type.</p>
<p>If my understanding is right, the case like <code>T[] myArray</code> should also be rejected. Because the code below also has the same structure.</p>
```import java.util.*;

public class Test {
    public static <T> void test(T[] t) {
        Object[] a = t;
        String[] c = {"123"};
        a[0] = c;
        T i = t[0];
    }

    public static void main(String[] args) {
        Integer[] t = {1,2,3};
        test(t);
    }
}
```
<p>But in the Java tutorial,</p>
```<T> T[] makeArray(T t) {
    return new T[100]; // Error.
}
```
<p>The reason it gives is</p>
<blockquote>
<p>Since type variables don't exist at run time, there is no way to determine what the actual array type would be.</p>
</blockquote>
<p>Not the reason I expect.</p>
<p>It also says</p>
<blockquote>
<p>The way to work around these kinds of limitations is to use class literals as run-time type tokens</p>
</blockquote>
<p>So I found an example at Generics gotchas. The code at "The road not taken" section:</p>
```public class ArrayList<V> implements List<V> {
  private V[] backingArray;
  private Class<V> elementType;

  public ArrayList(Class<V> elementType) {
    this.elementType = elementType;
    backingArray = (V[]) Array.newInstance(elementType, DEFAULT_LENGTH);
  }
}
```

It seems using class literals already solve the problem of using array of type variable( T[] ). But the problem of the structure I mentioned at the beginning is still exist. Recall I think the structure of the three pieces of code all lead to no compiling warning but runtime error.

So, what's wrong with my understanding?

Thank you so much for your time :)

答:
As you have found, you can't assign an element to an array of reifiable type:

```<code>String[] ss = {""};
Object[] oo = ss;
oo[0] = 0; // ArrayStoreException
</code>```

This is because the type of the array element is checked at runtime, and it can be because all the type information is still available.

But with a generic array, say List<String>[], the "String" bit isn't available at runtime. So, this would (notionally) work:

```<code>List<String>[] lss = {Arrays.asList()};
Object[] oo = lss;
List<Integer> is = Arrays.asList(0);
oo[0] = is;
</code>```

This would work fine, because all that can be checked is that you are storing an instance of List.

But this would then fail if you did:

```<code>String s = lss[0].get(0); // ClassCastException
</code>```

And this failure might happen far away from the assignment that caused it.

As such, generic array creation is disallowed.

In terms of the difference between List<String>[] and T[]: there is no difference, really. List<String> is a valid type for T to have.

The point is that you simply can't create an instance of the former: the only value a reference of that type can safely take is null.

It seems using class literals already solve the problem "type variables don't exist at run time"

No, because class literals only exist for the unparameterized type: you can create an ArrayList<String> in this way, by passing String.class as the element type; you couldn't create an ArrayList<ArrayList<String>>, because there is no ArrayList<String>.class.

Body:
Update: Although I have got the answer, it seems my description of the question is not very clear. So I changed a lot to make others understand my question.

My understanding of the reason why arrays of a parameterized type not allowed:

Integer[] b = {1,2,3};
Object[] a = b;
String[] c = {"123"};
a[0] = c; // Exception in thread "main" java.lang.ArrayStoreException
Integer i = b[0];

// Not really allowed.
List<String>[] lsa = new List<String>[10];
Object o = lsa;
Object[] oa = (Object[]) o;
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
// Unsound, but passes run time store check
oa[1] = li;

// Run-time error: ClassCastException.
String s = lsa[1].get(0);

These two pieces of code has the same structure.

In piece 1, Object[] a = b makes both a and b point to the same variable b. So a[0] = c is actually changing b. This kind of operation won't cause any warning while compiling but will throw an ArrayStoreException.

In piece 2,Object o = lsa; Object[] oa = (Object[]) o; makes both oa and lsa point to the same variable lsa, and oa[1] = li;
is actually changing lsa.

So I think it's this reason why not allow using arrays of parameterized type.

If my understanding is right, the case like T[] myArray should also be rejected. Because the code below also has the same structure.

import java.util.*;

public class Test {
    public static <T> void test(T[] t) {
        Object[] a = t;
        String[] c = {"123"};
        a[0] = c;
        T i = t[0];
    }

    public static void main(String[] args) {
        Integer[] t = {1,2,3};
        test(t);
    }
}

But in the Java tutorial,

<T> T[] makeArray(T t) {
    return new T[100]; // Error.
}

The reason it gives is

Since type variables don't exist at run time, there is no way to determine what the actual array type would be.

Not the reason I expect.

It also says

The way to work around these kinds of limitations is to use class literals as run-time type tokens

So I found an example at Generics gotchas. The code at "The road not taken" section:

public class ArrayList<V> implements List<V> {
  private V[] backingArray;
  private Class<V> elementType;

  public ArrayList(Class<V> elementType) {
    this.elementType = elementType;
    backingArray = (V[]) Array.newInstance(elementType, DEFAULT_LENGTH);
  }
}

It seems using class literals already solve the problem of using array of type variable( T[] ). But the problem of the structure I mentioned at the beginning is still exist. Recall I think the structure of the three pieces of code all lead to no compiling warning but runtime error.

So, what's wrong with my understanding?

Thank you so much for your time :)

Body:
As you have found, you can't assign an element to an array of reifiable type:

String[] ss = {""};
Object[] oo = ss;
oo[0] = 0; // ArrayStoreException

This is because the type of the array element is checked at runtime, and it can be because all the type information is still available.

But with a generic array, say List<String>[], the "String" bit isn't available at runtime. So, this would (notionally) work:

List<String>[] lss = {Arrays.asList()};
Object[] oo = lss;
List<Integer> is = Arrays.asList(0);
oo[0] = is;

This would work fine, because all that can be checked is that you are storing an instance of List.

But this would then fail if you did:

String s = lss[0].get(0); // ClassCastException

And this failure might happen far away from the assignment that caused it.

As such, generic array creation is disallowed.

In terms of the difference between List<String>[] and T[]: there is no difference, really. List<String> is a valid type for T to have.

The point is that you simply can't create an instance of the former: the only value a reference of that type can safely take is null.

It seems using class literals already solve the problem "type variables don't exist at run time"

No, because class literals only exist for the unparameterized type: you can create an ArrayList<String> in this way, by passing String.class as the element type; you couldn't create an ArrayList<ArrayList<String>>, because there is no ArrayList<String>.class.


来源: stackexchange

问:
There any way to open *UberEats* app in a specific restaurant page using URL Schemes or anything else?
There any way to open UberEats app in a specific restaurant page using URL Schemes, Deep link, SDK or anything else?

答:
I found that and works with current version. Url schema:

ubereats://

on the current app you can share a store item and the deeplink is:

ubereats://store/browse?client_id=eats&storeUUID={STORE_UUID}&itemUUID={ITEM_UUID}

or simply open the store:

ubereats://store/browse?client_id=eats&storeUUID={STORE_UUID}

or apply a promo code:

ubereats://promo/apply?client_id=eats&promoCode={PROMO_CODE}

I hope to help

ContentLicense: CC BY-SA 4.0


问:
RQ AttributeError: 'module' object has no attribute
I am trying to create a background job with RQ:

```<code>import django_rq

    def _send_password_reset_email_async(email):
        print(email)

    # Django admin action to send reset password emails
    def send_password_reset_email(modeladmin, request, queryset):
        for user in queryset:
            django_rq.enqueue(_send_password_reset_email_async, user.email)
    send_password_reset_email.short_description = 'Send password reset email'
</code>```

I keep getting this error though, and it seems like I am doing something silly?

```<code>Traceback (most recent call last):
  File "/home/lee/Code/cas/venv/lib/python3.4/site-packages/rq/worker.py", line 568, in perform_job
    rv = job.perform()
  File "/home/lee/Code/cas/venv/lib/python3.4/site-packages/rq/job.py", line

495, in perform
    self._result = self.func(*self.args, **self.kwargs)
  File "/home/lee/Code/cas/venv/lib/python3.4/site-packages/rq/job.py", line 206, in func
    return import_attribute(self.func_name)
  File "/home/lee/Code/cas/venv/lib/python3.4/site-packages/rq/utils.py", line 151, in import_attribute
    return getattr(module, attribute)
AttributeError: 'module' object has no attribute '_send_password_reset_email_async
</code>```

'

答:
try to write your function in another file, import it as a module

```<code># in my_utility.py
def send_password_reset_email_async(email):
    print(email)
</code>```

then

```<code>import django_rq
from my_utility import send_password_reset_email_async

#def _send_password_reset_email_async(email):
#   print(email)

# Django admin action to send reset password emails
def send_password_reset_email(modeladmin, request, queryset):
    for user in queryset:
        django_rq.enqueue(send_password_reset_email_async, user.email)
send_password_reset_email.short_description = 'Send password reset email'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create a background job with RQ:

import django_rq

    def _send_password_reset_email_async(email):
        print(email)

    # Django admin action to send reset password emails
    def send_password_reset_email(modeladmin, request, queryset):
        for user in queryset:
            django_rq.enqueue(_send_password_reset_email_async, user.email)
    send_password_reset_email.short_description = 'Send password reset email'

I keep getting this error though, and it seems like I am doing something silly?

Traceback (most recent call last):
  File "/home/lee/Code/cas/venv/lib/python3.4/site-packages/rq/worker.py", line 568, in perform_job
    rv = job.perform()
  File "/home/lee/Code/cas/venv/lib/python3.4/site-packages/rq/job.py", line

495, in perform
    self._result = self.func(*self.args, **self.kwargs)
  File "/home/lee/Code/cas/venv/lib/python3.4/site-packages/rq/job.py", line 206, in func
    return import_attribute(self.func_name)
  File "/home/lee/Code/cas/venv/lib/python3.4/site-packages/rq/utils.py", line 151, in import_attribute
    return getattr(module, attribute)
AttributeError: 'module' object has no attribute '_send_password_reset_email_async

'

Body:
try to write your function in another file, import it as a module

# in my_utility.py
def send_password_reset_email_async(email):
    print(email)

then

import django_rq
from my_utility import send_password_reset_email_async

#def _send_password_reset_email_async(email):
#   print(email)

# Django admin action to send reset password emails
def send_password_reset_email(modeladmin, request, queryset):
    for user in queryset:
        django_rq.enqueue(send_password_reset_email_async, user.email)
send_password_reset_email.short_description = 'Send password reset email'


问:
How to create Custom UITableViewCell with dynamic number of labels
each custom cell in tableview can either have one or two or three or more labels depending on the number of data return from api.

I've tried creating dynamic number of labels into cell in cellForRowAtIndexPath method. But every time I scroll, all these labels overlap each other..Is there any other way to create a dynamic number of labels into a cell?

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PracLabelCell", for: indexPath) as! PracLabelCell

    let w : CGFloat = CGFloat(self.tableview.frame.size.width/3)
    var x : CGFloat = 0

    for index in 0...2
    {
        let label = UILabel(frame: CGRect(x: x, y: cell.frame.origin.y, width: w , height: cell.frame.size.height))
        let str = String(index)
        print(str)
        label.text = str
        cell.contentView.addSubview(label)
        print("x is" , x)
        x += w

    }

    return cell
}
</code>```

答:
Use constraints to increase the height of the cells. Add a vertical stackview in the cell. And create a function in cell class to append labels based on argument values.

```<code>class PracLabelCell: UITableViewCell {
    let titleLabel = UILabel()
    let stackView = UIStackView()
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        commonInit()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }
    func commonInit() {
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        addSubview(titleLabel)

        stackView.axis = .vertical
        stackView.distribution = .fillEqually
        stackView.alignment = .fill
        stackView.spacing = 2
        stackView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(stackView)

        titleLabel.topAnchor.constraint(equalTo: topAnchor).isActive = true
        titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
        titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        titleLabel.heightAnchor.constraint(equalToConstant: 30).isActive = true

        stackView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor).isActive = true
        stackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
        stackView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        stackView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    }
    func setup(names: [String]) {
        stackView.arrangedSubviews.forEach { stackView.removeArrangedSubview($0);$0.removeFromSuperview() }
        names.forEach {
            let label = UILabel()
            label.text = $0
            stackView.addArrangedSubview(label)
        }
    }
}
</code>```

And pass the values in tableView cellForRowAt method.

```<code>class TableViewController: UITableViewController {
    var namesArray = [["a","b","c"],["d","e"],["f"],["g","h"],[],["j"]]
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        tableView.register(PracLabelCell.self, forCellReuseIdentifier: "PracLabelCell")
    }
    // MARK: - Table view data source
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return namesArray.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PracLabelCell", for: indexPath) as! PracLabelCell
        cell.titleLabel.text = "This cell has \(namesArray[indexPath.row].count) labels"
        cell.setup(names: namesArray[indexPath.row])
        return cell
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
}
</code>```

Body:
each custom cell in tableview can either have one or two or three or more labels depending on the number of data return from api.

I've tried creating dynamic number of labels into cell in cellForRowAtIndexPath method. But every time I scroll, all these labels overlap each other..Is there any other way to create a dynamic number of labels into a cell?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PracLabelCell", for: indexPath) as! PracLabelCell

    let w : CGFloat = CGFloat(self.tableview.frame.size.width/3)
    var x : CGFloat = 0

    for index in 0...2
    {
        let label = UILabel(frame: CGRect(x: x, y: cell.frame.origin.y, width: w , height: cell.frame.size.height))
        let str = String(index)
        print(str)
        label.text = str
        cell.contentView.addSubview(label)
        print("x is" , x)
        x += w

    }

    return cell
}

Body:
Use constraints to increase the height of the cells. Add a vertical stackview in the cell. And create a function in cell class to append labels based on argument values.

class PracLabelCell: UITableViewCell {
    let titleLabel = UILabel()
    let stackView = UIStackView()
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        commonInit()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }
    func commonInit() {
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        addSubview(titleLabel)

        stackView.axis = .vertical
        stackView.distribution = .fillEqually
        stackView.alignment = .fill
        stackView.spacing = 2
        stackView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(stackView)

        titleLabel.topAnchor.constraint(equalTo: topAnchor).isActive = true
        titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
        titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        titleLabel.heightAnchor.constraint(equalToConstant: 30).isActive = true

        stackView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor).isActive = true
        stackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
        stackView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        stackView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    }
    func setup(names: [String]) {
        stackView.arrangedSubviews.forEach { stackView.removeArrangedSubview($0);$0.removeFromSuperview() }
        names.forEach {
            let label = UILabel()
            label.text = $0
            stackView.addArrangedSubview(label)
        }
    }
}

And pass the values in tableView cellForRowAt method.

class TableViewController: UITableViewController {
    var namesArray = [["a","b","c"],["d","e"],["f"],["g","h"],[],["j"]]
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        tableView.register(PracLabelCell.self, forCellReuseIdentifier: "PracLabelCell")
    }
    // MARK: - Table view data source
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return namesArray.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PracLabelCell", for: indexPath) as! PracLabelCell
        cell.titleLabel.text = "This cell has \(namesArray[indexPath.row].count) labels"
        cell.setup(names: namesArray[indexPath.row])
        return cell
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
}


问:
How filter GroupVariables by variable name in the Rest API
Based on the documentation I can get a specific variable group using the below request

```<code>GET .../_apis/distributedtask/variablegroups?groupName={groupName}
</code>```

This returns all the variables for a specific Variable Group.

I'd like to get the details for a specific variable so I don't have to download all of them.
e.g

```<code>GET .../_apis/distributedtask/variablegroups?groupName={groupName}&VariableName={MyName}
</code>```

I've searched but I haven't found anything.

答:
I don't think it's possible to get only one variable, all the idea that it's a group and currently the Rest API let you get the group.

But if you use PowerShell you can filter the results easily when you perform the Rest:

```<code>$url = "https://dev.azure.com/{organization}/{project}/_apis/distributedtask/variablegroups?groupName={name}&api-version=5.0"
$varName = "MyName"
$varValue = (Invoke-RestMethod -Uri $url -Method Get -ContentType application/json).value.variables.$varName
</code>```

Body:
Based on the documentation I can get a specific variable group using the below request

GET .../_apis/distributedtask/variablegroups?groupName={groupName}

This returns all the variables for a specific Variable Group.

I'd like to get the details for a specific variable so I don't have to download all of them.
e.g

GET .../_apis/distributedtask/variablegroups?groupName={groupName}&VariableName={MyName}

I've searched but I haven't found anything.

Body:
I don't think it's possible to get only one variable, all the idea that it's a group and currently the Rest API let you get the group.

But if you use PowerShell you can filter the results easily when you perform the Rest:

$url = "https://dev.azure.com/{organization}/{project}/_apis/distributedtask/variablegroups?groupName={name}&api-version=5.0"
$varName = "MyName"
$varValue = (Invoke-RestMethod -Uri $url -Method Get -ContentType application/json).value.variables.$varName


问:
C# WPF Check-up a ListView Item By Index?
I use C# WPF. I want to checkup list view items by their index. How do I accomplish that?

Code I tried-

```<code>int index= 10;
this.lstView1.Items[index].Checked=true;
</code>```

It worked in WinForms, but not working anymore after migrating to XAML.

My XAML:

```<code>    <ListView Height="400" Width="400"
      Name="lstView1"
      ItemsSource="{Binding}"
      IsSynchronizedWithCurrentItem="True">
        <ListView.View>
            <GridView>
                <GridView.Columns>
                    <GridViewColumn>
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <CheckBox Name="chk" IsChecked="{Binding IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></CheckBox>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}"/>
                    <GridViewColumn Header="File" DisplayMemberBinding="{Binding File}"/>
                    <GridViewColumn Header="Author" DisplayMemberBinding="{Binding Author}"/>
                </GridView.Columns>
            </GridView>
        </ListView.View>
        <ListView.GroupStyle>
            <GroupStyle>
                <GroupStyle.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock FontWeight="Bold" Text="Group"/>
                    </DataTemplate>
                </GroupStyle.HeaderTemplate>
            </GroupStyle>
        </ListView.GroupStyle>
    </ListView>
</code>```

答:
you have Model class?
if you use data Binding, you need to Model calss</p>

```<code>int index= 10;
(this.lstView1.ItemsSource[index] as YourModel).Checked=true;

</code>```

Body:
I use C# WPF. I want to checkup list view items by their index. How do I accomplish that?

Code I tried-

int index= 10;
this.lstView1.Items[index].Checked=true;

It worked in WinForms, but not working anymore after migrating to XAML.

My XAML:

    <ListView Height="400" Width="400"
      Name="lstView1"
      ItemsSource="{Binding}"
      IsSynchronizedWithCurrentItem="True">
        <ListView.View>
            <GridView>
                <GridView.Columns>
                    <GridViewColumn>
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <CheckBox Name="chk" IsChecked="{Binding IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></CheckBox>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}"/>
                    <GridViewColumn Header="File" DisplayMemberBinding="{Binding File}"/>
                    <GridViewColumn Header="Author" DisplayMemberBinding="{Binding Author}"/>
                </GridView.Columns>
            </GridView>
        </ListView.View>
        <ListView.GroupStyle>
            <GroupStyle>
                <GroupStyle.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock FontWeight="Bold" Text="Group"/>
                    </DataTemplate>
                </GroupStyle.HeaderTemplate>
            </GroupStyle>
        </ListView.GroupStyle>
    </ListView>

Body:
you have Model class?
if you use data Binding, you need to Model calss

int index= 10;
(this.lstView1.ItemsSource[index] as YourModel).Checked=true;


问:
Use dynamic list in whiptail
I need to build a dynamic list with checkboxes in whiptail.
But using a variable\dynamic bash output doesn't help me.

I tryed used this command

```<code>whiptail --title "Operations" --checklist "Select Operation" 22 80 14 $array
</code>```

Output of variable array is

```<code>"cash3" "54311 May 25 10:10 22A763D0-8203-11E9-39BE-0007321A6EB4" OFF "cash10" "10475 May 28 18:23 22A763D0-8203-11E9-82FE-0007321A6EB4" OFF "cash14" "9905 May 27 15:55 22A763D0-8203-11E9-86FD-0007321A6EB4" OFF "cash13" "11780 May 29 09:32 22A763D0-8203-11E9-66AD-0007321A6EB4" OFF
</code>```

what fully corresponds to the whiptail syntax of the command, but this command is not executed.

When using the same data, but not through a variable whiptail works

答:
You only use the first element with $array. You can make use of the entire array with ${array[@]}.

This will work:

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

array=("cash3" "54311 May 25 10:10 22A763D0-8203-11E9-39BE-0007321A6EB4" OFF "cash10" "10475 May 28 18:23 22A763D0-8203-11E9-82FE-0007321A6EB4" OFF "cash14" "9905 May 27 15:55 22A763D0-8203-11E9-86FD-0007321A6EB4" OFF "cash13" "11780 May 29 09:32 22A763D0-8203-11E9-66AD-0007321A6EB4" OFF)

whiptail --title "Operations" --checklist "Select Operation" 22 80 14 "${array[@]}"
</code>```

Note that without quoting the array ("), whiptail will not work correctly.

Title: Use dynamic list in whiptail

Body:
I need to build a dynamic list with checkboxes in whiptail.
But using a variable\dynamic bash output doesn't help me.

I tryed used this command

whiptail --title "Operations" --checklist "Select Operation" 22 80 14 $array

Output of variable array is

"cash3" "54311 May 25 10:10 22A763D0-8203-11E9-39BE-0007321A6EB4" OFF "cash10" "10475 May 28 18:23 22A763D0-8203-11E9-82FE-0007321A6EB4" OFF "cash14" "9905 May 27 15:55 22A763D0-8203-11E9-86FD-0007321A6EB4" OFF "cash13" "11780 May 29 09:32 22A763D0-8203-11E9-66AD-0007321A6EB4" OFF

what fully corresponds to the whiptail syntax of the command, but this command is not executed.

When using the same data, but not through a variable whiptail works

Body:
You only use the first element with $array. You can make use of the entire array with ${array[@]}.

This will work:

#! /bin/bash

array=("cash3" "54311 May 25 10:10 22A763D0-8203-11E9-39BE-0007321A6EB4" OFF "cash10" "10475 May 28 18:23 22A763D0-8203-11E9-82FE-0007321A6EB4" OFF "cash14" "9905 May 27 15:55 22A763D0-8203-11E9-86FD-0007321A6EB4" OFF "cash13" "11780 May 29 09:32 22A763D0-8203-11E9-66AD-0007321A6EB4" OFF)

whiptail --title "Operations" --checklist "Select Operation" 22 80 14 "${array[@]}"

Note that without quoting the array ("), whiptail will not work correctly.


问:
Send a message to a Facebook profile using an iPhone application
I am creating an iPhone application using the Facebook SDK. How do I post a message to a selected friend such that the message can be found in their profile?

I have no idea how to implement this.

答: Facebook does not allow messages to be sent via the API at this time. Applications can send notifications, but nothing but Facebook has access to the message/inbox API yet.</p>


问:
Amazon Advertising API is not working with custom VPC endpoint policy for S3
Amazon Advertising API is not working with custom VPC endpoint policy for S3.

I have two S3 buckets and two EC2 instances in two VPCs. Created VPC endpoints to access S3 bucket.

I need to connect bucket test1 from EC2-1 in VPC1 and bucket test2 from EC2-2 in VPC2. Need to block access from EC2-1 to bucket test2 and EC2-2 to bucket test1.

These 2 buckets are under an AWS account and using same IAM user credentials to access these buckets.

Policy which I used for VPC Endpoint for S3 in VPC1:

```<code>{
    "Statement": [
        {
            "Sid": "Access-to-specific-bucket-only",
            "Principal": "*",
            "Action": [
                "s3:GetObject",
                "s3:ListBucket",
                "s3:PutObject"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::test1",
                "arn:aws:s3:::test1/*"
            ]
        }
    ]
}
</code>```

This policy is working fine. But, I need to access Amazon Advertising API from my EC2 instances. Now, which gives a connection error. It will work when I give Full Access, that I do not want. Please help me to set up a custom policy.

Note: Amazon Advertising API URL start with https://amazon-advertising-api-reports-prod-usamazon.s3.amazonaws.com

答:
That looks like a URL where you can retrieve reports rather than an actual URL to the Advertising API.

Your VPC Endpoint for S3 policy is permitting access to the test1 bucket, but it is not granting access to the amazon-advertising-api-reports-prod-usamazon bucket.

If you add that to your policy it be able to access the reports.

Body:
Amazon Advertising API is not working with custom VPC endpoint policy for S3.

I have two S3 buckets and two EC2 instances in two VPCs. Created VPC endpoints to access S3 bucket.

I need to connect bucket test1 from EC2-1 in VPC1 and bucket test2 from EC2-2 in VPC2. Need to block access from EC2-1 to bucket test2 and EC2-2 to bucket test1.

These 2 buckets are under an AWS account and using same IAM user credentials to access these buckets.

Policy which I used for VPC Endpoint for S3 in VPC1:

{
    "Statement": [
        {
            "Sid": "Access-to-specific-bucket-only",
            "Principal": "*",
            "Action": [
                "s3:GetObject",
                "s3:ListBucket",
                "s3:PutObject"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::test1",
                "arn:aws:s3:::test1/*"
            ]
        }
    ]
}

This policy is working fine. But, I need to access Amazon Advertising API from my EC2 instances. Now, which gives a connection error. It will work when I give Full Access, that I do not want. Please help me to set up a custom policy.

Note: Amazon Advertising API URL start with https://amazon-advertising-api-reports-prod-usamazon.s3.amazonaws.com


问:
Summing split dataframe columns in an iterative process
I have a dataframe "fpd" which is split on unique values in column ['View'] using

```<code>bookuniques = fpd['View'].unique()

fpdict = {elem: pd.DataFrame for elem in bookuniques}

for key in fpdict.keys():
    fpdict[key] = fpd[:][fpd['View'] == key]
</code>```

The dataframe looks like:

```<code>    Product PG Location Row Group   Ph DD                   Pd TC   Variance
    C4      CL          01.1 OI     OpeningInventory        200     200
            PU          01.1 OI     OpeningInventory        400     400
            MR          01.1 OI     OpeningInventory        600     600
            NP          01.1 OI     OpeningInventory        200     200
            PR          01.1 OI     OpeningInventory        400     400
            PS          01.1 OI     OpeningInventory        600     600
            PW          01.1 OI     OpeningInventory        200     200
</code>```

I am attempting to append a sum row for each of these dataframes individually. I have tried including the process on the output to excel using

```<code>with pd.ExcelWriter('check2.xlsx') as writer:
    for key in fpdict.keys():
        fpdict[key].drop(['View'], axis = 1)
        fpdict[key].append(fpdict[key].sum(numeric_only = True), ignore_index=True)
        temp = fpdict[key]
        temp.to_excel(writer, sheet_name = key)
</code>```

Unfortunately, doing so removes the index columns [['Product'],['PG'],['Location']]

I would like the output to be

```<code>        Product PG Location Row Group   Ph DD                   Pd TC   Variance
        C4      CL          01.1 OI     OpeningInventory        200     200
                PU          01.1 OI     OpeningInventory        400     400
                MR          01.1 OI     OpeningInventory        600     600
                NP          01.1 OI     OpeningInventory        200     200
                PR          01.1 OI     OpeningInventory        400     400
                PS          01.1 OI     OpeningInventory        600     600
                PW          01.1 OI     OpeningInventory        200     200
                TOTAL                                           2600    2600
</code>```

答:
Here are the assumptions I have to do because this is not clearly stated in the question:

the dataframe has a multi-index on columns Product, PG, Location

the new row will have PG=Total and all other non numeric fields set to an empty string

fpdict[key] will have View column removed

You have to change your code to:

```<code>with pd.ExcelWriter('check2.xlsx') as writer:
    for key in fpdict.keys():
        temp = fpdict[key].drop(['View'], axis = 1).reset_index()
        temp.append(fpdict[key].sum(numeric_only = True), ignore_index=True) # add sum row
        temp.iloc[-1] = temp.iloc[-1].fillna(' ')      # replace NaNs with ''
        temp.iloc[-1, 1] = 'TOTAL'
        fpdict[key] = temp.set_index(['Product', 'PG', 'Location'])
        temp.to_excel(writer, sheet_name = key)
</code>```

Body:
I have a dataframe "fpd" which is split on unique values in column ['View'] using

bookuniques = fpd['View'].unique()

fpdict = {elem: pd.DataFrame for elem in bookuniques}

for key in fpdict.keys():
    fpdict[key] = fpd[:][fpd['View'] == key]

The dataframe looks like:

    Product PG Location Row Group   Ph DD                   Pd TC   Variance
    C4      CL          01.1 OI     OpeningInventory        200     200
            PU          01.1 OI     OpeningInventory        400     400
            MR          01.1 OI     OpeningInventory        600     600
            NP          01.1 OI     OpeningInventory        200     200
            PR          01.1 OI     OpeningInventory        400     400
            PS          01.1 OI     OpeningInventory        600     600
            PW          01.1 OI     OpeningInventory        200     200

I am attempting to append a sum row for each of these dataframes individually. I have tried including the process on the output to excel using

with pd.ExcelWriter('check2.xlsx') as writer:
    for key in fpdict.keys():
        fpdict[key].drop(['View'], axis = 1)
        fpdict[key].append(fpdict[key].sum(numeric_only = True), ignore_index=True)
        temp = fpdict[key]
        temp.to_excel(writer, sheet_name = key)

Unfortunately, doing so removes the index columns [['Product'],['PG'],['Location']]

I would like the output to be

        Product PG Location Row Group   Ph DD                   Pd TC   Variance
        C4      CL          01.1 OI     OpeningInventory        200     200
                PU          01.1 OI     OpeningInventory        400     400
                MR          01.1 OI     OpeningInventory        600     600
                NP          01.1 OI     OpeningInventory        200     200
                PR          01.1 OI     OpeningInventory        400     400
                PS          01.1 OI     OpeningInventory        600     600
                PW          01.1 OI     OpeningInventory        200     200
                TOTAL                                           2600    2600

Body:
Here are the assumptions I have to do because this is not clearly stated in the question:

the dataframe has a multi-index on columns Product, PG, Location

the new row will have PG=Total and all other non numeric fields set to an empty string

fpdict[key] will have View column removed

You have to change your code to:

with pd.ExcelWriter('check2.xlsx') as writer:
    for key in fpdict.keys():
        temp = fpdict[key].drop(['View'], axis = 1).reset_index()
        temp.append(fpdict[key].sum(numeric_only = True), ignore_index=True) # add sum row
        temp.iloc[-1] = temp.iloc[-1].fillna(' ')      # replace NaNs with ''
        temp.iloc[-1, 1] = 'TOTAL'
        fpdict[key] = temp.set_index(['Product', 'PG', 'Location'])
        temp.to_excel(writer, sheet_name = key)


问:
Angular 7 hide particular attribute inside ngFor loop
I'm using a ngFor loop angular 7 I need to a hidden particular attribute(example userNo and UserType ) inside a ngFor loop.</p>

```<code>emailId: "afsageg@dgvsf"
groupName: "dfsfgfdg"
mobileNo: "+91fyrtyrtyty"
userId: "ttrur"
userName: "srurttuidharan"
userNo: 2
userType: "rrhjty"
userTypeDisplay: "Operator Maker"

<tr *ngFor="let key of formData | keyvalue" >
    <td [hidden]="key.userNo">{{key.key | titlecase}}</td>
    <td>{{key.value}}</td>
</tr>
</code>```

答:
```<code><td [hidden]="key.key==='userNo'">{{key.key | titlecase}}</td>
<td [hidden]="key.key==='userNo'">{{key.value}}</td> <!--if you also want to hide the value -->
</code>```

Or you can use *ngIf instead of [hidden]

I would also suggest to rename your key to object (or something less generic even) as each iteration of the *ngFor holds an object and not just the key (hence why you can access key AND value)

So something like:

```<code><tr *ngFor="let obj of formData | keyvalue" >
    <td [hidden]="obj.key==='userNo'">{{obj.key | titlecase}}</td>
    <td [hidden]="obj.key==='userNo'">{{obj.value}}</td>
</tr>
</code>```

Small Stackblitz to illustrate

Body:
I'm using a ngFor loop angular 7 I need to a hidden particular attribute(example userNo and UserType ) inside a ngFor loop.

emailId: "afsageg@dgvsf"
groupName: "dfsfgfdg"
mobileNo: "+91fyrtyrtyty"
userId: "ttrur"
userName: "srurttuidharan"
userNo: 2
userType: "rrhjty"
userTypeDisplay: "Operator Maker"

    {{key.key | titlecase}}
    {{key.value}}

Body:
<td [hidden]="key.key==='userNo'">{{key.key | titlecase}}</td>
<td [hidden]="key.key==='userNo'">{{key.value}}</td> <!--if you also want to hide the value -->

Or you can use *ngIf instead of [hidden]

I would also suggest to rename your key to object (or something less generic even) as each iteration of the *ngFor holds an object and not just the key (hence why you can access key AND value)

So something like:

<tr *ngFor="let obj of formData | keyvalue" >
    <td [hidden]="obj.key==='userNo'">{{obj.key | titlecase}}</td>
    <td [hidden]="obj.key==='userNo'">{{obj.value}}</td>
</tr>

Small Stackblitz to illustrate


问:
How to exit a running unit test programmatically (with Visual Studio c#, and unit test framework)
If I have an automated test that is currently executing, I need the automation to exit if it runs into a problem, such as a network stoppage or when the System Under Test (SUT) is down.

If I try to Assert.Inconclusive("some message"), it doesn't handle the exception gracefully. I want the framework to log the info to the logger, exit the test gracefully, and go on to the next test.

Has anyone dealt with this issue?  I need it to do something like this -- (the driver is the Chrome WebDriver (selenium)).

```<code>// ---- check for services down warning  -----
        bool isDown = await CheckForServicesWarning(driver);
        if (isDown == true)
        {
            Log("XYZ is currently experiencing technical difficulties.");
            return;
        }
</code>```

答:
You are right in the sense that you should test for an external resource availability. However, you don't touch this resource directly. Instead, you mock it.

Lets assume that your service reaches out to a database and has a method ReadCustomerNameById(int id). First, extract it to an interface that we will call IMyService. Your service (lets call it MyService) should now implement this interface. Both the interface and your service look like:

```<code>public interface IMyService
{
    string ReadCustomerNameById(int id);
}

public class MyService : IMyService
{
    public string ReadCustomerNameById(int id)
    {
        return "Gixabel"; //replace this with your actual implementation
    }
}
</code>```

Now we have to write a class where we can use MyService and have all the business logic we might need. Lets call this class Customer and it looks like:

```<code>public class Customer
{
    private readonly IMyService _service;

    public Customer(IMyService service)
    {
        _service = service;
    }

    public string CustomerNameById(int id)
    {
        var result = _service.ReadCustomerNameById(id);
        //validate, massage and do whatever you need to do to your response
        return result;
    }
}
</code>```

I'm taking advantage of some dependency injection here. Out of scope.

Now we are ready to write some tests. Find and install a Nuget called Moq. I personally like nUnit but you can easily translate this sample to MSTest or any other.

We start declaring our Customer class and a mock of MyService. Then we create an instance of Customer and a mock of IMyService on our setup.

Now we do a normal test where we assume MyService is working properly.

The last test is the interesting one. We force the service to throw an exception and we assert it actually does.

```<code>[TestFixture]
public class CustomerTests
{
    private Customer _customer;
    private Mock<IMyService> _myService;

    [SetUp]
    public void Initialize()
    {
        _myService = new Mock<IMyService>();
        _customer = new Customer(_myService.Object);
    }

    [Test]
    public void GivenIdWhenCustomerNameByIdThenCustomerNameReturned()
    {
        const int id = 10;
        const string customerName = "Victoria";
        _myService.Setup(s => s.ReadCustomerNameById(id)).Returns(customerName);
        var result = _customer.CustomerNameById(id);
        Assert.AreEqual(result, customerName);
    }

    [Test]
    public void GivenIdWhenCustomerNameByIdThenException()
    {
        _myService.Setup(s => s.ReadCustomerNameById(It.IsAny<int>())).Throws<Exception>();
        Assert.Throws<Exception>(() => _customer.CustomerNameById(10));
    }
}
</code>```

Now you are completely decoupled from the service you are trying to use. Now you can commit to GitHub, Azure Devops, etc. and run tests without any external dependency.

Additionally you could try/catch, handle error messages and test them. But this should get you going.

As a side note, try FluentAssertions. It reads better than 'Assert.AreEqual...'

Body:
If I have an automated test that is currently executing, I need the automation to exit if it runs into a problem, such as a network stoppage or when the System Under Test (SUT) is down.

If I try to Assert.Inconclusive("some message"), it doesn't handle the exception gracefully. I want the framework to log the info to the logger, exit the test gracefully, and go on to the next test.

Has anyone dealt with this issue?  I need it to do something like this -- (the driver is the Chrome WebDriver (selenium)).

// ---- check for services down warning  -----
        bool isDown = await CheckForServicesWarning(driver);
        if (isDown == true)
        {
            Log("XYZ is currently experiencing technical difficulties.");
            return;
        }

Body:
You are right in the sense that you should test for an external resource availability. However, you don't touch this resource directly. Instead, you mock it.

Lets assume that your service reaches out to a database and has a method ReadCustomerNameById(int id). First, extract it to an interface that we will call IMyService. Your service (lets call it MyService) should now implement this interface. Both the interface and your service look like:

public interface IMyService
{
    string ReadCustomerNameById(int id);
}

public class MyService : IMyService
{
    public string ReadCustomerNameById(int id)
    {
        return "Gixabel"; //replace this with your actual implementation
    }
}

Now we have to write a class where we can use MyService and have all the business logic we might need. Lets call this class Customer and it looks like:

public class Customer
{
    private readonly IMyService _service;

    public Customer(IMyService service)
    {
        _service = service;
    }

    public string CustomerNameById(int id)
    {
        var result = _service.ReadCustomerNameById(id);
        //validate, massage and do whatever you need to do to your response
        return result;
    }
}

I'm taking advantage of some dependency injection here. Out of scope.

Now we are ready to write some tests. Find and install a Nuget called Moq. I personally like nUnit but you can easily translate this sample to MSTest or any other.

We start declaring our Customer class and a mock of MyService. Then we create an instance of Customer and a mock of IMyService on our setup.

Now we do a normal test where we assume MyService is working properly.

The last test is the interesting one. We force the service to throw an exception and we assert it actually does.

[TestFixture]
public class CustomerTests
{
    private Customer _customer;
    private Mock<IMyService> _myService;

    [SetUp]
    public void Initialize()
    {
        _myService = new Mock<IMyService>();
        _customer = new Customer(_myService.Object);
    }

    [Test]
    public void GivenIdWhenCustomerNameByIdThenCustomerNameReturned()
    {
        const int id = 10;
        const string customerName = "Victoria";
        _myService.Setup(s => s.ReadCustomerNameById(id)).Returns(customerName);
        var result = _customer.CustomerNameById(id);
        Assert.AreEqual(result, customerName);
    }

    [Test]
    public void GivenIdWhenCustomerNameByIdThenException()
    {
        _myService.Setup(s => s.ReadCustomerNameById(It.IsAny<int>())).Throws<Exception>();
        Assert.Throws<Exception>(() => _customer.CustomerNameById(10));
    }
}

Now you are completely decoupled from the service you are trying to use. Now you can commit to GitHub, Azure Devops, etc. and run tests without any external dependency.

Additionally you could try/catch, handle error messages and test them. But this should get you going.

As a side note, try FluentAssertions. It reads better than 'Assert.AreEqual...'


问:
Updating python 2 code to python 3 code for googleads api
I'm trying to use the google ads api with python 3 and I'm facing an issue with their generate_refresh_token.py file. The file has been updated for python 3 but I need to debug it as it still has some python 2 code in it. For example, print statements didn't have () in them and there was an instance of using raw_input() instead of input().

Anyway, I'm getting an error message that I can't figure out. Can someone please help me out here?

I've tried googling the solution but I'm a bit lost here.

The code starts from line 110 and ends at line 122:

```<code>print ('Access token: %s') % flow.credentials.token
print ('Refresh token: %s') % flow.credentials.refresh_token

if __name__ == '__main__':
  args = parser.parse_args()
  configured_scopes = [SCOPE]
  if not (any([args.client_id, DEFAULT_CLIENT_ID]) and
          any([args.client_secret, DEFAULT_CLIENT_SECRET])):
    raise AttributeError('No client_id or client_secret specified.')
  if args.additional_scopes:
    configured_scopes.extend(args.additional_scopes.replace(' ', '').split(','))
  main(args.client_id, args.client_secret, configured_scopes)
</code>```

The code is supposed to throw out an access token that I can use but it's giving me this error:

```<code>Access token: %s
Traceback (most recent call last):
  File "generate_refresh_token.py", line 122, in <module>
    main(args.client_id, args.client_secret, configured_scopes)
  File "generate_refresh_token.py", line 110, in main
    print ('Access token: %s') % flow.credentials.token
TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'
</code>```

I believe that this is also a python 2 vs python 3 problem and i would appreciate it if someone could help me out with this!

答:
You have a typo with your parentheses. Print should be:

```<code>print('Access token: %s'% flow.credentials.token)
print('Refresh token: %s' % flow.credentials.refresh_token)
</code>```

To be safe use format:

```<code>print('Access token: {}'.format(flow.credentials.token))
print('Refresh token: {}'.format(flow.credentials.refresh_token))
</code>```

Body:
I'm trying to use the google ads api with python 3 and I'm facing an issue with their generate_refresh_token.py file. The file has been updated for python 3 but I need to debug it as it still has some python 2 code in it. For example, print statements didn't have () in them and there was an instance of using raw_input() instead of input().

Anyway, I'm getting an error message that I can't figure out. Can someone please help me out here?

I've tried googling the solution but I'm a bit lost here.

The code starts from line 110 and ends at line 122:

print ('Access token: %s') % flow.credentials.token
print ('Refresh token: %s') % flow.credentials.refresh_token

if __name__ == '__main__':
  args = parser.parse_args()
  configured_scopes = [SCOPE]
  if not (any([args.client_id, DEFAULT_CLIENT_ID]) and
          any([args.client_secret, DEFAULT_CLIENT_SECRET])):
    raise AttributeError('No client_id or client_secret specified.')
  if args.additional_scopes:
    configured_scopes.extend(args.additional_scopes.replace(' ', '').split(','))
  main(args.client_id, args.client_secret, configured_scopes)

The code is supposed to throw out an access token that I can use but it's giving me this error:

Access token: %s
Traceback (most recent call last):
  File "generate_refresh_token.py", line 122, in <module>
    main(args.client_id, args.client_secret, configured_scopes)
  File "generate_refresh_token.py", line 110, in main
    print ('Access token: %s') % flow.credentials.token
TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'

I believe that this is also a python 2 vs python 3 problem and i would appreciate it if someone could help me out with this!

Body:
You have a typo with your parentheses. Print should be:

print('Access token: %s'% flow.credentials.token)
print('Refresh token: %s' % flow.credentials.refresh_token)

To be safe use format:

print('Access token: {}'.format(flow.credentials.token))
print('Refresh token: {}'.format(flow.credentials.refresh_token))


答:
Update the print statements.</p>

```<code>print ('Access token: {}'.format(flow.credentials.token))
print ('Refresh token: {}'.format(flow.credentials.refresh_token))
</code>```

Title: Updating python 2 code to python 3 code for googleads api

Body:
Update the print statements.

print ('Access token: {}'.format(flow.credentials.token))
print ('Refresh token: {}'.format(flow.credentials.refresh_token))


问:
Image file upload using angular 7 with php codeigniter

php-codeigniter

```<code>public function upload(){
    $image = base64_decode($this->input->post("p_image"));
    $image_name = md5(uniqid(rand(), true));
    $filename = $image_name . '.' . 'png';
    //rename file name with random number
    $path = "./uploads/images/".$filename;
    //image uploading folder path
    file_put_contents($path , $image);
    // image is bind and upload to respective folder

    $data_insert = array('p_image'=>$filename);
    if(!empty($data_insert )){
    $success=$this->db->insert('projects', $data_insert);

    }else{ }
    if($success){
        $b = "User Registered Successfully..";
    }
    else
    {
        $b = "Some Error Occured. Please Try Again..";
    }
    echo json_encode($b);

}

</code>```

In the above code i can't understand why the path is inserting 2 times in the database with 2 different paths and either 2 paths are not showing any image, iam not getting what's wrong with the code, iam new to this ,plz help me to sort out this...

Angular

component.html

```<code><div class="admin-page">
  <div class="add-projects-form">
    <form [formGroup]="myForm"  enctype="multipart/form-data">
    <!-- image upload start -->
        <div class="form-group">
        <div class="upload-image">
        <div #image class="image-wrapper"></div>
        <div class="browse-btn">
        <input type="file" name="cameraImg" id="cameraImg" (change)="onSelectedFile($event)" >
        </div>
        </div>
        </div>
        <div style="text-align: center;margin-top:40px;">
        <button class="btn btn-success" type="submit" (click)="addProject()">Add Project</button>
      </div>
  </form>
</div>
</div>
</code>```

component.ts

```<code>onSelectedFile(event) {
  if (event.target.files.length > 0) {
  const productImage = event.target.files[0];
  const formData = new FormData();
  formData.append('p_image', productImage);
  console.log(productImage.name);
  console.log(productImage);
  this.adminService.uploadImage(productImage).subscribe(
  res => {
  if (res){
  console.log('success')
  this.uploadError = '';
  } else {
  // this.uploadError = res.response.message;
  }
  },
  err => this.error = err
  );
  }
  }
</code>```

service.ts

```<code>  uploadImage(p_image){
    return this.http.post(`${CONFIG.API_URL}/Welcome/upload`, p_image);
  }
</code>```

This is my angular code for the image file upload,i have no issue with this code it is getting correct output on console but the only thing is issue with the backend codeigniter code.

答:
Every time that you insert a image in the input it will upload to the backend(maybe you want to move that after click a button)

You only want to upload 1 image or multiple?

You are decoding the image in your php you should omit that because you are uploading a binary with formData not a string(im not expert with php maybe im wrong but in node just save the binary in a folder).

Body:
php-codeigniter

public function upload(){
    $image = base64_decode($this->input->post("p_image"));
    $image_name = md5(uniqid(rand(), true));
    $filename = $image_name . '.' . 'png';
    //rename file name with random number
    $path = "./uploads/images/".$filename;
    //image uploading folder path
    file_put_contents($path , $image);
    // image is bind and upload to respective folder

    $data_insert = array('p_image'=>$filename);
    if(!empty($data_insert )){
    $success=$this->db->insert('projects', $data_insert);

    }else{ }
    if($success){
        $b = "User Registered Successfully..";
    }
    else
    {
        $b = "Some Error Occured. Please Try Again..";
    }
    echo json_encode($b);

}

In the above code i can't understand why the path is inserting 2 times in the database with 2 different paths and either 2 paths are not showing any image, iam not getting what's wrong with the code, iam new to this ,plz help me to sort out this...

Angular

component.html

    <form [formGroup]="myForm"  enctype="multipart/form-data">

        <input type="file" name="cameraImg" id="cameraImg" (change)="onSelectedFile($event)" >

        <button class="btn btn-success" type="submit" (click)="addProject()">Add Project</button>

  </form>

component.ts

onSelectedFile(event) {
  if (event.target.files.length > 0) {
  const productImage = event.target.files[0];
  const formData = new FormData();
  formData.append('p_image', productImage);
  console.log(productImage.name);
  console.log(productImage);
  this.adminService.uploadImage(productImage).subscribe(
  res => {
  if (res){
  console.log('success')
  this.uploadError = '';
  } else {
  // this.uploadError = res.response.message;
  }
  },
  err => this.error = err
  );
  }
  }

service.ts

  uploadImage(p_image){
    return this.http.post(`${CONFIG.API_URL}/Welcome/upload`, p_image);
  }

This is my angular code for the image file upload,i have no issue with this code it is getting correct output on console but the only thing is issue with the backend codeigniter code.


问:
Activating Anaconda Environment in VsCode
I have Anaconda working on my system and VsCode working, but how do I get VsCode to activate a specific environment when running my python script?</p>

答:
Setting python.pythonPath in VSCode's settings.json file doesn't work for me, but another method does. According to the Anaconda documentation at Microsoft Visual Studio Code (VS Code):

When you launch VS Code from Navigator, VS Code is configured to use the Python interpreter in the currently selected environment.


问:
How to trim only white space but not \n in Java
I have a string like

String str = " hello world\n "

when I call str.trim(),
it returns

"hello world"

However, I need the string looks like

"hello world\n"

How could I do it for only remove leading and trailing white space in a string?

答:
Try using this but replace Character.isWhitespace with your own implementation of what should be tracked as whitespace</p>

```<code>public static String trim(String s) {
     return ltrim(rtrim(s));
}

public static Boolean isWhitespace(char c) {
     return Character.isWhitespace(c);
}

public static String ltrim(String s) {
     int i = 0;
     while (i < s.length() && isWhitespace(s.charAt(i))) {
         i++;
     }
     return s.substring(i);
}

public static String rtrim(String s) {
    int i = s.length()-1;
    while (i >= 0 &&  isWhitespace(s.charAt(i))) {
        i--;
    }
    return s.substring(0,i+1);
}
</code>```

Body:
Try using this but replace Character.isWhitespace with your own implementation of what should be tracked as whitespace

public static String trim(String s) {
     return ltrim(rtrim(s));
}

public static Boolean isWhitespace(char c) {
     return Character.isWhitespace(c);
}

public static String ltrim(String s) {
     int i = 0;
     while (i < s.length() && isWhitespace(s.charAt(i))) {
         i++;
     }
     return s.substring(i);
}

public static String rtrim(String s) {
    int i = s.length()-1;
    while (i >= 0 &&  isWhitespace(s.charAt(i))) {
        i--;
    }
    return s.substring(0,i+1);
}


问:
If x-axis labels are string values then they are not showing up in d3 chart
I am having one d3 scatter chart. It is working fine if I will give numeric value for x and y axis. But if x-axis contains string values then nothing is getting shown up in chart.

```<code>var data = [[Project1,3], [Project2,17]];

var margin = {top: 20, right: 15, bottom: 60, left: 60}
  , width = 300 - margin.left - margin.right
  , height = 200 - margin.top - margin.bottom;

var x = d3.scale.linear()
          .domain([0, d3.max(data, function(d) { return d[0]; })])
          .range([ 0, width ]);

var y = d3.scale.linear()
          .domain([0, d3.max(data, function(d) { return d[1]; })])
          .range([ height, 0 ]);

var chart = d3.select('#cognitiveChartDiv')
.append('svg:svg')
.attr('width', width + margin.right + margin.left)
.attr('height', height + margin.top + margin.bottom)
.attr('class', 'chart')

var colors = d3.scale.linear()
.domain([5, 20])
.range(['#4577bc','#4577bc'])

var main = chart.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
.attr('width', width)
.attr('height', height)
.attr('class', 'main')

// draw the x axis
var xAxis = d3.svg.axis()
.scale(x)
.orient('bottom');

main.append('g')
.attr('transform', 'translate(0,' + height + ')')
.attr('class', 'main axis date')
.call(xAxis);

// draw the y axis
var yAxis = d3.svg.axis()
.scale(y)
.orient('left');

main.append('g')
.attr('transform', 'translate(0,0)')
.attr('class', 'main axis date')
.call(yAxis);

var g = main.append("svg:g");

g.selectAll("scatter-dots")
  .data(data)
  .enter().append("svg:circle")
      .attr("cx", function (d,i) { return x(d[0]); } )
      .attr("cy", function (d) { return y(d[1]); } )
      .attr("r", 8)
      .style('stroke', function(d,i) {
        return colors(i);
    })
    .style('fill', function(d,i) {
        return colors(i);
    })
</code>```

If var data = [[1,10],[2,20]] then it is working as expected. I want the chart to work for string value as well. Please suggest me what I should do. I have tried to use ordinal() function in place of linear function, but that didn't help.

答:
"If x-axis labels are string values...". Actually, the axes labels are always strings.

You have a different question, as you describe in the body: you want to pass strings as well in your data array. That being the case, you have to change the scale. Specifically, an ordinal scale:

```<code>var x = d3.scale.ordinal()
  .domain(data.map(function(d) {
    return d[0];
  }))
  .rangePoints([0, width], 0.5)
</code>```

Here is your code with that change:

var data = [
  ["Project1", 3],
  ["Project2", 17]
];

var margin = {
    top: 20,
    right: 15,
    bottom: 60,
    left: 60
  },
  width = 300 - margin.left - margin.right,
  height = 200 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
  .domain(data.map(function(d) {
    return d[0];
  }))
  .rangePoints([0, width], 0.5)

var y = d3.scale.linear()
  .domain([0, d3.max(data, function(d) {
    return d[1];
  })])
  .range([height, 0]);

var chart = d3.select('#cognitiveChartDiv')
  .append('svg:svg')
  .attr('width', width + margin.right + margin.left)
  .attr('height', height + margin.top + margin.bottom)
  .attr('class', 'chart')

var colors = d3.scale.linear()
  .domain([5, 20])
  .range(['#4577bc', '#4577bc'])

var main = chart.append('g')
  .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
  .attr('width', width)
  .attr('height', height)
  .attr('class', 'main')

// draw the x axis
var xAxis = d3.svg.axis()
  .scale(x)
  .orient('bottom');

main.append('g')
  .attr('transform', 'translate(0,' + height + ')')
  .attr('class', 'main axis date')
  .call(xAxis);

// draw the y axis
var yAxis = d3.svg.axis()
  .scale(y)
  .orient('left');

main.append('g')
  .attr('transform', 'translate(0,0)')
  .attr('class', 'main axis date')
  .call(yAxis);

var g = main.append("svg:g");

g.selectAll("scatter-dots")
  .data(data)
  .enter().append("svg:circle")
  .attr("cx", function(d, i) {
    return x(d[0]);
  })
  .attr("cy", function(d) {
    return y(d[1]);
  })
  .attr("r", 8)
  .style('stroke', function(d, i) {
    return colors(i);
  })
  .style('fill', function(d, i) {
    return colors(i);
  })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.axis path,
.axis line {
  fill: none;
  stroke: black;
}</code>```

```

Body:
I am having one d3 scatter chart. It is working fine if I will give numeric value for x and y axis. But if x-axis contains string values then nothing is getting shown up in chart.

var data = [[Project1,3], [Project2,17]];

var margin = {top: 20, right: 15, bottom: 60, left: 60}
  , width = 300 - margin.left - margin.right
  , height = 200 - margin.top - margin.bottom;

var x = d3.scale.linear()
          .domain([0, d3.max(data, function(d) { return d[0]; })])
          .range([ 0, width ]);

var y = d3.scale.linear()
          .domain([0, d3.max(data, function(d) { return d[1]; })])
          .range([ height, 0 ]);

var chart = d3.select('#cognitiveChartDiv')
.append('svg:svg')
.attr('width', width + margin.right + margin.left)
.attr('height', height + margin.top + margin.bottom)
.attr('class', 'chart')

var colors = d3.scale.linear()
.domain([5, 20])
.range(['#4577bc','#4577bc'])

var main = chart.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
.attr('width', width)
.attr('height', height)
.attr('class', 'main')

// draw the x axis
var xAxis = d3.svg.axis()
.scale(x)
.orient('bottom');

main.append('g')
.attr('transform', 'translate(0,' + height + ')')
.attr('class', 'main axis date')
.call(xAxis);

// draw the y axis
var yAxis = d3.svg.axis()
.scale(y)
.orient('left');

main.append('g')
.attr('transform', 'translate(0,0)')
.attr('class', 'main axis date')
.call(yAxis);

var g = main.append("svg:g");

g.selectAll("scatter-dots")
  .data(data)
  .enter().append("svg:circle")
      .attr("cx", function (d,i) { return x(d[0]); } )
      .attr("cy", function (d) { return y(d[1]); } )
      .attr("r", 8)
      .style('stroke', function(d,i) {
        return colors(i);
    })
    .style('fill', function(d,i) {
        return colors(i);
    })

If var data = [[1,10],[2,20]] then it is working as expected. I want the chart to work for string value as well. Please suggest me what I should do. I have tried to use ordinal() function in place of linear function, but that didn't help.

Body:
"If x-axis labels are string values...". Actually, the axes labels are always strings.

You have a different question, as you describe in the body: you want to pass strings as well in your data array. That being the case, you have to change the scale. Specifically, an ordinal scale:

var x = d3.scale.ordinal()
  .domain(data.map(function(d) {
    return d[0];
  }))
  .rangePoints([0, width], 0.5)

Here is your code with that change:

var data = [
  ["Project1", 3],
  ["Project2", 17]
];

var margin = {
    top: 20,
    right: 15,
    bottom: 60,
    left: 60
  },
  width = 300 - margin.left - margin.right,
  height = 200 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
  .domain(data.map(function(d) {
    return d[0];
  }))
  .rangePoints([0, width], 0.5)

var y = d3.scale.linear()
  .domain([0, d3.max(data, function(d) {
    return d[1];
  })])
  .range([height, 0]);

var chart = d3.select('#cognitiveChartDiv')
  .append('svg:svg')
  .attr('width', width + margin.right + margin.left)
  .attr('height', height + margin.top + margin.bottom)
  .attr('class', 'chart')

var colors = d3.scale.linear()
  .domain([5, 20])
  .range(['#4577bc', '#4577bc'])

var main = chart.append('g')
  .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
  .attr('width', width)
  .attr('height', height)
  .attr('class', 'main')

// draw the x axis
var xAxis = d3.svg.axis()
  .scale(x)
  .orient('bottom');

main.append('g')
  .attr('transform', 'translate(0,' + height + ')')
  .attr('class', 'main axis date')
  .call(xAxis);

// draw the y axis
var yAxis = d3.svg.axis()
  .scale(y)
  .orient('left');

main.append('g')
  .attr('transform', 'translate(0,0)')
  .attr('class', 'main axis date')
  .call(yAxis);

var g = main.append("svg:g");

g.selectAll("scatter-dots")
  .data(data)
  .enter().append("svg:circle")
  .attr("cx", function(d, i) {
    return x(d[0]);
  })
  .attr("cy", function(d) {
    return y(d[1]);
  })
  .attr("r", 8)
  .style('stroke', function(d, i) {
    return colors(i);
  })
  .style('fill', function(d, i) {
    return colors(i);
  })

.axis path,
.axis line {
  fill: none;
  stroke: black;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<div id="cognitiveChartDiv"></div>


问:
How to show each of the selected value from single select option in input tag
I am new to javascript and I want to use the select option to list each selected value in the input tag.

I have tried to use javascript to show the selected value but when I select for the second time the first value dismiss and show the second selected. I was expected to show each selected value in the input tag separately without dismissing other previous selected.

function getSelectedValue() {
  var selectedValue = document.getElementById("list").value;
  document.getElementById("myValues").innerHTML = selectedValue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="" onchange="getSelectedValue();" class="form-control" id="list">
  <option value="Option1">Option1</option>
  <option value="Option2">Option2</option>
  <option value="Option3">Option3</option>
  <option value="Option4">Option4</option>
</select>
<input type="text" name="value[]" id="myValue" value=""></code>```

I expected the output of

<input type="text" name="value[]" id="myValue" value="Option1">

<input type="text" name="value[]" id="myValue" value="Option3">

thus in the input should show

Option1
  Option3

答:
You can use Select2 jQuery plugin for that.

$(document).ready(function() {
        $('.js-example-basic-multiple').select2({
    width: '100%'
});
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>

<select class="js-example-basic-multiple" name="options[]" multiple="multiple">
<option>Option1</option>
<option>Option2</option>
<option>Option3</option>
<option>Option4</option>
</select></code>```

Body:
I am new to javascript and I want to use the select option to list each selected value in the input tag.

I have tried to use javascript to show the selected value but when I select for the second time the first value dismiss and show the second selected. I was expected to show each selected value in the input tag separately without dismissing other previous selected.

function getSelectedValue() {
  var selectedValue = document.getElementById("list").value;
  document.getElementById("myValues").innerHTML = selectedValue;
}

<select name="" onchange="getSelectedValue();" class="form-control" id="list">
  <option value="Option1">Option1</option>
  <option value="Option2">Option2</option>
  <option value="Option3">Option3</option>
  <option value="Option4">Option4</option>
</select>
<input type="text" name="value[]" id="myValue" value="">

I expected the output of

<input type="text" name="value[]" id="myValue" value="Option1">

<input type="text" name="value[]" id="myValue" value="Option3">

thus in the input should show

Option1
  Option3

Body:
You can use Select2 jQuery plugin for that.

$(document).ready(function() {
        $('.js-example-basic-multiple').select2({
    width: '100%'
});
    });

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>

<select class="js-example-basic-multiple" name="options[]" multiple="multiple">
<option>Option1</option>
<option>Option2</option>
<option>Option3</option>
<option>Option4</option>
</select>


问:
How to create a directory in a function
Editing:

I'm trying to build a simple function that print out a name, then creates a directory. I'm new at building function in bash, so I have the below script that didn't work:

```<code>dest_path=/home/all/todo
line="name"

mkdir_for_name() {
echo $1
mkdir $2
}

mkdir_for_name $name
mkdir_for_name $dest_path/$name
</code>```

What is wrong with that syntax?

答: Your function uses $2, but you're only calling it with one argument, so $2 is empty.

Title: How to create a directory in a function

Body:
Editing:

I'm trying to build a simple function that print out a name, then creates a directory. I'm new at building function in bash, so I have the below script that didn't work:

dest_path=/home/all/todo
line="name"

mkdir_for_name() {
echo $1
mkdir $2
}

mkdir_for_name $name
mkdir_for_name $dest_path/$name

What is wrong with that syntax?


问:
Check whether domain is registered
I'm trying to make a script that returns unregistered domains. I'm working in Python 2.7. I've read that the module whois should be able to do that but the code I've written raises an error.

Code:

```<code>import whois
domains = ['http://www.example.com']

for dom in domains:
    domain = whois.Domain(dom)
    print domain.registrar
</code>```

Error:

```<code>  domain = whois.Domain(dom)
  File "C:\Python27\lib\site-packages\whois\_3_adjust.py", line 12, in __init__
    self.name               = data['domain_name'][0].strip().lower()
TypeError: string indices must be integers, not str
</code>```

Have you any idea what could be wrong? Or can you give me a better solution?

EDIT: I tried the pythonwhois module but it returns an error too.

EDIT2: According to one solution here, on SO, I've tried to use pywhois, this code raises an error too.

```<code>import pywhois
w = pywhois.whois('google.com')
w.expiration_date
</code>```

ERROR:

```<code>w = pywhois.whois('google.com')
AttributeError: 'module' object has no attribute 'whois'
</code>```

答:
Installation

```<code>pip install pythonwhois
</code>```

You might need to execute pip3 install pythonwhois --user or something similar.

Code

```<code>import pythonwhois

def is_registered(site):
    """Check if a domain has an WHOIS record."""
    details = pythonwhois.get_whois(site)
    return not details['raw'][0].startswith('No match for')

names = ['google', 'af35foobar90']
for name in names:
    site = '{}.com'.format(name)
    print('{}: {}'.format(site, is_registered(site)))
</code>```

Title: Check whether domain is registered

Body:
I'm trying to make a script that returns unregistered domains. I'm working in Python 2.7. I've read that the module whois should be able to do that but the code I've written raises an error.

Code:

import whois
domains = ['http://www.example.com']

for dom in domains:
    domain = whois.Domain(dom)
    print domain.registrar

Error:

  domain = whois.Domain(dom)
  File "C:\Python27\lib\site-packages\whois\_3_adjust.py", line 12, in __init__
    self.name               = data['domain_name'][0].strip().lower()
TypeError: string indices must be integers, not str

Have you any idea what could be wrong? Or can you give me a better solution?

EDIT: I tried the pythonwhois module but it returns an error too.

EDIT2: According to one solution here, on SO, I've tried to use pywhois, this code raises an error too.

import pywhois
w = pywhois.whois('google.com')
w.expiration_date

ERROR:

w = pywhois.whois('google.com')
AttributeError: 'module' object has no attribute 'whois'

Body:
Installation

pip install pythonwhois

You might need to execute pip3 install pythonwhois --user or something similar.

Code

import pythonwhois

def is_registered(site):
    """Check if a domain has an WHOIS record."""
    details = pythonwhois.get_whois(site)
    return not details['raw'][0].startswith('No match for')

names = ['google', 'af35foobar90']
for name in names:
    site = '{}.com'.format(name)
    print('{}: {}'.format(site, is_registered(site)))


问:
Maven could not find artifact command in eclipse spring-boot-starter-parent
I get an error when I try to run any Maven command on eclipse.

The error message:

```<code>[ERROR] Some problems were encountered while processing the POMs:
[FATAL] Non-resolvable parent POM for com.me.learn:first-application:0.0.1-SNAPSHOT:
Failure to find org.springframework.boot:spring-boot-starter-parent:pom:2.1.5-RELEASE
in https://repo.maven.apache.org/maven2 was cached in the local repository,
resolution will not be reattempted until the update
interval of central has elapsed or updates are forced and 'parent.relativePath'
points at wrong local POM @ line 6, column 10
</code>```

Things that I checked:

Project build error: Non-resolvable parent POM. Failure to transfer org.springframework.boot:spring-boot-starter-parent

The directory /home/{anonymous}/.m2/repository/home/{anonymous}/.m2/repository/org/springframework/boot/spring-boot-starter-parent

contains the file: spring-boot-starter-parent-2.1.5-RELEASE.pom.lastUpdated

Manually cleaning the repository, and running clean on eclipse.

My configuration of settings.xml in eclipse is set to the correct place, and my configuration of eclipse to my local repository is defined good as well.

No proxy is defined.

Information about my configurations and environment:

I'm using eclipse over Ubuntu.

settings.xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">

  <localRepository>/home/{anonymous}/.m2/repository</localRepository>
  <interactiveMode>true</interactiveMode>
  <usePluginRegistry>false</usePluginRegistry>
  <offline>false</offline>

</settings>
</code>```

pom.xml file:

```<code>   <project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>

        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.5-RELEASE</version>
        </parent>

        <groupId>com.me.learn</groupId>
        <artifactId>first-application</artifactId>
        <packaging>pom</packaging>
        <version>0.0.1-SNAPSHOT</version>
        <name>first-application</name>
        <url>http://maven.apache.org</url>

        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
        </dependencies>

        <build>
            <finalName>first-application</finalName>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    </project>
</code>```

Maven version:

```<code>Apache Maven 3.5.2
Maven home: /usr/share/maven
Java version: 1.8.0_171, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-8-oracle/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.10.0-37-generic", arch: "amd64", family: "unix"
</code>```

答:
Brute force / clean your ~/.m2/repository directory / just delete it and it will be repopulated on next build.

settings.xml : check into the "updatePolicy" for repositories.  Generally, releases never check for updates and SNAPSHOT have a default.  I often set interval:13 (13 minutes)

http://maven.apache.org/settings.html

Body:
I get an error when I try to run any Maven command on eclipse.

The error message:

[ERROR] Some problems were encountered while processing the POMs:
[FATAL] Non-resolvable parent POM for com.me.learn:first-application:0.0.1-SNAPSHOT:
Failure to find org.springframework.boot:spring-boot-starter-parent:pom:2.1.5-RELEASE
in https://repo.maven.apache.org/maven2 was cached in the local repository,
resolution will not be reattempted until the update
interval of central has elapsed or updates are forced and 'parent.relativePath'
points at wrong local POM @ line 6, column 10

Things that I checked:

Project build error: Non-resolvable parent POM. Failure to transfer org.springframework.boot:spring-boot-starter-parent

The directory /home/{anonymous}/.m2/repository/home/{anonymous}/.m2/repository/org/springframework/boot/spring-boot-starter-parent

contains the file: spring-boot-starter-parent-2.1.5-RELEASE.pom.lastUpdated

Manually cleaning the repository, and running clean on eclipse.

My configuration of settings.xml in eclipse is set to the correct place, and my configuration of eclipse to my local repository is defined good as well.

No proxy is defined.

Information about my configurations and environment:

I'm using eclipse over Ubuntu.

settings.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">

  <localRepository>/home/{anonymous}/.m2/repository</localRepository>
  <interactiveMode>true</interactiveMode>
  <usePluginRegistry>false</usePluginRegistry>
  <offline>false</offline>

</settings>

pom.xml file:

   <project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>

        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.5-RELEASE</version>
        </parent>

        <groupId>com.me.learn</groupId>
        <artifactId>first-application</artifactId>
        <packaging>pom</packaging>
        <version>0.0.1-SNAPSHOT</version>
        <name>first-application</name>
        <url>http://maven.apache.org</url>

        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
        </dependencies>

        <build>
            <finalName>first-application</finalName>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    </project>

Maven version:

Apache Maven 3.5.2
Maven home: /usr/share/maven
Java version: 1.8.0_171, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-8-oracle/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.10.0-37-generic", arch: "amd64", family: "unix"


问:
Flutter layout with circular image icons
I am a web dev in MS stack trying flutter for a personal project of mine. I want to create a layout like in the below URL in the meeve app with circular images with text below the image button/icon.
https://www.thedroidsonroids.com/blog/apps-made-with-flutter#meeve
I tried the layout given in the example on flutter docs below but it is not what I am looking for and I am not able to re purpose this for my case. https://flutter.dev/docs/cookbook/lists/grid-lists

Any leads in this respect is appreciated.

答:
You can use CircleAvatar in a Column.

```<code>@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          CircleAvatar(backgroundImage: AssetImage("assets/images/chocolate_pic.png"), radius: 40),
          SizedBox(height: 12),
          Text("Chocolate"),
        ],
      ),
    ),
  );
}
</code>```

Body:
You can use CircleAvatar in a Column.

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          CircleAvatar(backgroundImage: AssetImage("assets/images/chocolate_pic.png"), radius: 40),
          SizedBox(height: 12),
          Text("Chocolate"),
        ],
      ),
    ),
  );
}


问:
Best Clustering Algorithm for High Dimensional Vectors
I am attempting to use some sort of clustering method on a set of datapoint vectors which have 45 dimensions. I'm fairly new to clustering data points and was wondering if anyone could point out appropriate methods to utilize? I was attempted using K-Means Clustering but was wondering if the dimensionality of my data might be too large for this?</p>

答:
45 dimensions is not particularly high. It's at best "medium" dimensionality, so most algorithms could work.

Usually it's not so much a matter of the number of dimensions, but rather how well they are preprocessed. With bad preprocessing, 2 dimensions can be a problem if the signal in one attribute is drowned by the noise in the other.

There is no automatic way to get this right, otherwise it would be in all the libraries. Scaling can help, but can also harm. It's up to the user to prepare the data and choose parameters (such as distance functions and algorithms) to achieve the desired effect, because there is no computable equation fot "desirable".


问:
Python: Why does Python TCP-client receive data so slowly on different compared to same PC?
I have two Python scripts, one TCP-server sending data (at a rate of 1/256 times a second) and a TCP-client receiving data. In the client script, I print the length of the received data.
I sent the string "5.8" from the server (thus data of length 3).

When client and server are on the same machine:
The length of data received is always 3.
When client and server are on different machines in the same local network:
The length of data differs but is around 39 (13 times the data sent).

Is there a possible explanation for this discrepancy?

I think the network adding this much latency is unlikely, because the command line "ping" prints at most 2 ms latency with the largest amount of data.

IMPORTANT: I'm using Python 2.7.

import socket

def server():
    host = 'localhost' # replace with IP address in case client is on another machine
    port = 5051

    s = socket.socket()
    s.bind((host, port))
    s.listen(1)
    client_socket, adress = s.accept()

    while True:
        client_socket.send('a'.encode())
    client_socket.close()

if __name__ == '__main__':
    server()
```

<pre class="lang-py prettyprint-override"><code>import socket, random, time

def client():
    host = 'localhost' # replace with IP address in case client is on another machine
    port = 5051

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s_err = s.connect_ex((host, port))
    print(s_err)

    while True:
        data = s.recv(2048)
        print(len(data)) # returns different values depending on client location
    s.close()

if __name__ == '__main__':
    client()
</code>```

答:
I would assume that the TCP/IP stack of the server has just concatenated small packets to have a better network throughput. To send only 3 data of payload, you would have a large overhead: TCP encapsulation + IP encapsulation. Many TCP/IP stacks use that.

Anyway, you should neither worry for that, nor be surprised that it happens or not: TCP is a stream protocol and the only guarantee is that all the bytes sent from one side will arrive in same order at the other side. Any equipment (sender receiver or any other on the network) may concatenate of fragment packets.

Body:
I have two Python scripts, one TCP-server sending data (at a rate of 1/256 times a second) and a TCP-client receiving data. In the client script, I print the length of the received data.
I sent the string "5.8" from the server (thus data of length 3).

When client and server are on the same machine:
The length of data received is always 3.
When client and server are on different machines in the same local network:
The length of data differs but is around 39 (13 times the data sent).

Is there a possible explanation for this discrepancy?

I think the network adding this much latency is unlikely, because the command line "ping" prints at most 2 ms latency with the largest amount of data.

IMPORTANT: I'm using Python 2.7.

import socket

def server():
    host = 'localhost' # replace with IP address in case client is on another machine
    port = 5051

    s = socket.socket()
    s.bind((host, port))
    s.listen(1)
    client_socket, adress = s.accept()

    while True:
        client_socket.send('a'.encode())
    client_socket.close()

if __name__ == '__main__':
    server()

import socket, random, time

def client():
    host = 'localhost' # replace with IP address in case client is on another machine
    port = 5051

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s_err = s.connect_ex((host, port))
    print(s_err)

    while True:
        data = s.recv(2048)
        print(len(data)) # returns different values depending on client location
    s.close()

if __name__ == '__main__':
    client()


问:
Couldn't Calculate Price and Qty on table using Php Ajax
I am creating a ecommerce site for my final year project.while I am creating a project I ran in to the problem with product shall be able add the  card but when I view the card product shown which I added into the card.my problem is if the give qty it will auto calculation  and display result on the total textbox.and final totel show display below. I attached image below what i tried so far. But couldn’t calculate the total and final total.
Display the Products

```<code><script>
getProducts();

    function getProducts() {
        $.ajax({
            type: 'GET',
            url: 'all_cart.php',
            dataType: 'JSON',
            success: function(data) {
                data.forEach(function(element) {
                    var id = element.id;
                    var product_name = element.product_name;
                    var price = element.price;
                   $('#mytable tbody').after
                   (
                        '<tr> ' +
                        '<td>' + id + '</td>' +
                        '<td>' + product_name + '</td>' +
                        '<td>' + price + '</td>' +
                        "<input type='hidden' name='price' value='" + price + "'>" +
                        '<td>' + "<input type = 'text' id='qty' name='qty'/>" + '</td>' +
                        '<td>' + "<input type = 'text' id='amount'/>" + '</td>' +
                        '</tr>');
                  });
            },
            error: function(xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    }
</code>```

Auto calcaltion the price * qty

```<code>$(function() {
    $("#price, #qty").on("keydown keyup click", qty);
    function qty() {
        var sum = (
        Number($("#price").val()) * Number($("#qty").val())
        );

        $('#amount').val(sum);
        console.log(sum);
    }
});
</code>```

答:
When you get $("#price").val() and $("#qty").val() in jQuery but you have many $("#price") & $("#qty") duplicate. You should be run this in console.
I hope it's helpful for you


问:
How do I POST JSON data with cURL?
I use Ubuntu and installed cURL on it. I want to test my Spring REST application with cURL. I wrote my POST code at the Java side. However, I want to test it with cURL. I am trying to post a JSON data. Example data is like this:

```<code>{"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true}
</code>```

I use this command:

curl -i \
    -H "Accept: application/json" \
    -H "X-HTTP-Method-Override: PUT" \
    -X POST -d "value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true \
    http://localhost:8080/xx/xxx/xxxx
```
<p>It returns this error:</p>
<pre class="lang-none prettyprint-override"><code>HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 1051
Date: Wed, 24 Aug 2011 08:50:17 GMT
</code>```

The error description is this:

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().

Tomcat log:
"POST /ui/webapp/conf/clear HTTP/1.1" 415 1051

What is the right format of the cURL command?

This is my Java side PUT code (I have tested GET and DELETE and they work):

```<code>@RequestMapping(method = RequestMethod.PUT)
public Configuration updateConfiguration(HttpServletResponse response, @RequestBody Configuration configuration) { //consider @Valid tag
    configuration.setName("PUT worked");
    //todo If error occurs response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return configuration;
}
</code>```

答:
You can use Postman to convert to CURL:

Note:

The latest Postman version has some UI upgrades and now the code link is available in the sidebar.

Title: How do I POST JSON data with cURL?

Body:
I use Ubuntu and installed cURL on it. I want to test my Spring REST application with cURL. I wrote my POST code at the Java side. However, I want to test it with cURL. I am trying to post a JSON data. Example data is like this:

{"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true}

I use this command:

curl -i \
    -H "Accept: application/json" \
    -H "X-HTTP-Method-Override: PUT" \
    -X POST -d "value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true \
    http://localhost:8080/xx/xxx/xxxx

It returns this error:

HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 1051
Date: Wed, 24 Aug 2011 08:50:17 GMT

The error description is this:

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().

Tomcat log:
"POST /ui/webapp/conf/clear HTTP/1.1" 415 1051

What is the right format of the cURL command?

This is my Java side PUT code (I have tested GET and DELETE and they work):

@RequestMapping(method = RequestMethod.PUT)
public Configuration updateConfiguration(HttpServletResponse response, @RequestBody Configuration configuration) { //consider @Valid tag
    configuration.setName("PUT worked");
    //todo If error occurs response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return configuration;
}


问:
Relationships between multiple aggregate roots
In many applications, I deal with users and finance companies (as an example) and I have long been struggling to model the relationship between the two according to Domain Driven Design principles.

In my system I can do the following:

Add a user to an existing finance company.

Add a finance company to an existing user.

I believe both are aggregate roots... Finance Company and User.

How do I model the relationship between the 2?  Is it FinanceCompany.Users? or User.FinanceCompanies?  Is it neither?  Or am I missing knowledge of some key DDD concept(s)?  The problem is if I choose one way over the other, the code is more understandable / clear from one aggregate root entry point, but not the other.  Sometimes there are cases where it makes more sense to navigate to a Finance Company and add users to it, and other times there are cases where it makes more sense to navigate to a specific user and add finance companies to the user.

Is there some better way to approach this, maybe through repository methods?  Is there some key concept I am not getting or understanding here?  It doesn't feel right to assume the relationship between Finance Company and User belongs under either of the 2 ARs.  When I store the relationship I have to store it in a table named FinanceCompanyUsers or UserFinanceCompanies, but it still doesn't seem clear.

Would I have code such as FinanceCompany.AddUser() and User.AddFinanceCompany()? or is there some completely different approach for relationships such as this?

答:
You have already determined that both User and FinanceCompany are aggregates so each has its own life-cycle.

The problem with many domains is that we don't have a complete understanding of the relationships.  As another example we can take an Order and a Product.  Both are aggregates but would we have Order.AddProduct() or Product.AddOrder()?  In this case it seems pretty obvious in that an Order contains a limited subset of Product entries whereas a Product may very well contain many orders and we are not really too interested in that relationship since it is a rather weak relationship.  A Product can exist and be valid without any orders attached but an Order is pretty useless without at least one product entry.  This means that the Order has an invariant imposed in terms of its OrderItem entries.  In addition to this we have enough knowledge about this hackneyed example that we know we are going to need an associative entity (in relational theory speak) since we need additional information regarding the relationship and entering the fray would be our OrderItem table.  Curiously I have not seen it called OrderProduct.

The guidance I would suggest is to pick the most appropriate side.

However, if no side is a true winner and both aggregates can exist without a relationship to the other in terms of an invariant perhaps the relationship itself is an aggregate as you have certainly alluded to.  Perhaps it isn't only a UserFinanceCompany aggregate but perhaps there is a concept that is missing from the ubiquitous language that the domain experts refer to.  Perhaps something like Auditor or some such that represents that relationship.  This is akin to the OrderItem or OrderLine concept as opposed to OrderProduct.