问:
Need powershell script to enable diagnostic logging for Storage account and Key vault
I'm using below script to create a storage account, Key Vault and ADF. I would also like to enable diagnostic logging on both Storage account and Key Vault. Script runs fine and creates the resources however it does not enable the diagnostic logs for KV and Storage account. Would appreciate if you can help.</p>

```<code>$subscription="Azure subscription 1"
$rgName = "Test"
$location = "eastus"
$storageaccountName = "tempaccountlogs"
$adfName = "tempdpadf"
$department = "Testtemp"
$kvname = "kvnamAkbt"

$sa = New-AzStorageAccount -ResourceGroupName $rgName -AccountName $storageaccountName -Location $location -SkuName Standard_LRS -Kind BlobStorage -AccessTier Hot -Tag @{department=$department}
$DataFactory = Set-AzDataFactoryV2 -Name $adfName -ResourceGroupName $rgName -Location $location -Tag @{chargecode=$chargeCode;department=$department;environment=$environment;project=$project}
$kv = New-AzKeyVault -VaultName $kvname -ResourceGroupName $rgName -Location $location

set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -Enabled $true -Categories AuditEvent
set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -RetentionEnabled $true -RetentionInDays 90
</code>```

答:
The problem with your script is that it gives error:

A parameter cannot be found that matches parameter name 'Categories'.

You are using "Categories" parameter instead of "Category". If you check this documentation correct parameter is -Category, use this as shown below:

```<code>set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -Enabled $true -Category AuditEvent
set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -RetentionEnabled $true -RetentionInDays 90
</code>```

To enable logging for storage account, Please look at this documentation.

Body:
I'm using below script to create a storage account, Key Vault and ADF. I would also like to enable diagnostic logging on both Storage account and Key Vault. Script runs fine and creates the resources however it does not enable the diagnostic logs for KV and Storage account. Would appreciate if you can help.

$subscription="Azure subscription 1"
$rgName = "Test"
$location = "eastus"
$storageaccountName = "tempaccountlogs"
$adfName = "tempdpadf"
$department = "Testtemp"
$kvname = "kvnamAkbt"

$sa = New-AzStorageAccount -ResourceGroupName $rgName -AccountName $storageaccountName -Location $location -SkuName Standard_LRS -Kind BlobStorage -AccessTier Hot -Tag @{department=$department}
$DataFactory = Set-AzDataFactoryV2 -Name $adfName -ResourceGroupName $rgName -Location $location -Tag @{chargecode=$chargeCode;department=$department;environment=$environment;project=$project}
$kv = New-AzKeyVault -VaultName $kvname -ResourceGroupName $rgName -Location $location

set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -Enabled $true -Categories AuditEvent
set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -RetentionEnabled $true -RetentionInDays 90

Body:
The problem with your script is that it gives error:

A parameter cannot be found that matches parameter name 'Categories'.

You are using "Categories" parameter instead of "Category". If you check this documentation correct parameter is -Category, use this as shown below:

set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -Enabled $true -Category AuditEvent
set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -RetentionEnabled $true -RetentionInDays 90

To enable logging for storage account, Please look at this documentation.


来源: stackexchange

问:
What's the best way to get rid of nested ifs in code while checking for conditions?
I'm developing a BlackBerry app in Java and I have an Options class where all user settings are stored. The problem is I need to check some conditions in order to know how to react. As I keep adding more features, more GUI options are shown to the user, more settings are stored in the Options class and more conditions need to be checked for.

Take the following code for example:

```<code>private void doCallMonitoring(int callId){
    /*This is the part that I want to avoid. Having
      multiple nested ifs. Here's just two conditions
      but as I add more, it will get unmantainable
      very quickly.*/
    if(Options.isActive().booleanValue()){
        callTime = new Timer();
        TimerTask callTimeTask = new TimerTask(){
            public void run(){
                callTimeSeconds++;
        if((callTimeSeconds == Options.getSoftLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                    injectDTMFTone(Phone.getActiveCall());
        }else if((callTimeSeconds >= Options.getHardLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                    injectEndCall();
                }
             }
        };
        callTime.schedule(callTimeTask, 0,1000);
    }else{
    System.out.println("Service not active");
    }
}
</code>```

How I would want it to work is to verify all options with a single call and from there determine the curse of action. How can I achieve such a design?

答:
Other option is to do some sort of "replace conditional with polymorphism".

Although it seems like just writing more code you could replace all those rules with a "validator" object and have all the validations in some array and loop through them.

Something like this scratch code.

```<code>  private void doCallMonitoring(int callId){
     // Iterate the valiators and take action if needed.

      for( Validation validation : validationRules ) {
          if( validation.succeed() ) {
              validation.takeAction();
          }
      }
   }
</code>```

And you implement them like this:

```<code>abstract class Validation {

      public boolean suceed();
      public void takeAction();
}

class InjectDTMFToneValidation extends Validation {
    public boolean suceed() {
        return (callTimeSeconds == Options.getSoftLimit().intValue())
               && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)
     }
     public void takeAction() {
         injectDTMFTone(Phone.getActiveCall());
     }
}

class InjectEndCallValidation extends Validation {
    public boolean suceed() {
        return (callTimeSeconds >= Options.getHardLimit().intValue())
                && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)
     }
     public void takeAction() {
         injectEndCall();
     }
}
</code>```

And finally install them in a list:

```<code>private List<Validation> validationRules = new ArrayList<Validation>();{
   validationrules.add( new InjectDTMFToneValidation() );
   validationrules.add( new InjectEndCallValidation () );
   ...
   ...
}
</code>```

The idea here is to move the logic to subclasses. Of course, you will get a better structure and probably suceed and takeAction could be replaced for other more meaningful methods, the objective is to pull the validation from where it is.

It becomes more abstract? .. yes.

BTW, I why do yo use Options and Phone classes invoking their static methods instead of using instances?

OwnerDisplayName: Cesar

ContentLicense: CC BY-SA 2.5

Body:
I'm developing a BlackBerry app in Java and I have an Options class where all user settings are stored. The problem is I need to check some conditions in order to know how to react. As I keep adding more features, more GUI options are shown to the user, more settings are stored in the Options class and more conditions need to be checked for.

Take the following code for example:

private void doCallMonitoring(int callId){
    /*This is the part that I want to avoid. Having
      multiple nested ifs. Here's just two conditions
      but as I add more, it will get unmantainable
      very quickly.*/
    if(Options.isActive().booleanValue()){
        callTime = new Timer();
        TimerTask callTimeTask = new TimerTask(){
            public void run(){
                callTimeSeconds++;
        if((callTimeSeconds == Options.getSoftLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                    injectDTMFTone(Phone.getActiveCall());
        }else if((callTimeSeconds >= Options.getHardLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                    injectEndCall();
                }
             }
        };
        callTime.schedule(callTimeTask, 0,1000);
    }else{
    System.out.println("Service not active");
    }
}

How I would want it to work is to verify all options with a single call and from there determine the curse of action. How can I achieve such a design?

Body:
Other option is to do some sort of "replace conditional with polymorphism".

Although it seems like just writing more code you could replace all those rules with a "validator" object and have all the validations in some array and loop through them.

Something like this scratch code.

  private void doCallMonitoring(int callId){
     // Iterate the valiators and take action if needed.

      for( Validation validation : validationRules ) {
          if( validation.succeed() ) {
              validation.takeAction();
          }
      }
   }

And you implement them like this:

abstract class Validation {

      public boolean suceed();
      public void takeAction();
}

class InjectDTMFToneValidation extends Validation {
    public boolean suceed() {
        return (callTimeSeconds == Options.getSoftLimit().intValue())
               && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)
     }
     public void takeAction() {
         injectDTMFTone(Phone.getActiveCall());
     }
}

class InjectEndCallValidation extends Validation {
    public boolean suceed() {
        return (callTimeSeconds >= Options.getHardLimit().intValue())
                && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)
     }
     public void takeAction() {
         injectEndCall();
     }
}

And finally install them in a list:

private List<Validation> validationRules = new ArrayList<Validation>();{
   validationrules.add( new InjectDTMFToneValidation() );
   validationrules.add( new InjectEndCallValidation () );
   ...
   ...
}

The idea here is to move the logic to subclasses. Of course, you will get a better structure and probably suceed and takeAction could be replaced for other more meaningful methods, the objective is to pull the validation from where it is.

It becomes more abstract? .. yes.

BTW, I why do yo use Options and Phone classes invoking their static methods instead of using instances?

OwnerDisplayName: Oscar Reyes


问:
Python: Uexpected an indented block
I am not sure why I am getting this error.

I am getting this error:
Error on line 24:
    tempmax = ans
    ^
IndentationError: expected an indented block

Here what I´ve have so far:

```<code> def __init__(self, init_name, init_population, init_voters):
  self.name = init_name
  self.population = init_population
  self.voters = init_voters

def get_init_population(self):
 return self.population

def get_init_voters(self):
 return self.voters

def get_name(self):
 return self.name

def highest_turnout(data):
 tempcounty = ""
 tempmax = 0

for county in data:
 ans = (county.get_init_voters()/county.get_init_population())
 if ans > tempmax:

tempmax = ans
tempcounty = county
 return [(tempcounty.get_name(), tempmax)]

allegheny = County("allegheny", 1000490, 645469)
philadelphia = County("philadelphia", 1134081, 539069)
montgomery = County("montgomery", 568952, 399591)
lancaster = County("lancaster", 345367, 230278)
delaware = County("delaware", 414031, 284538)
chester = County("chester", 319919, 230823)
bucks = County("bucks", 444149, 319816)
data = [allegheny, philadelphia, montgomery, lancaster, delaware, chester, bucks]
result = highest_turnout(data) # do not change this line!
print(result) # prints the output of the function

# do not remove this line!```
```

答:
The indentation is not correct, try:

class County:
    def __init__(self, init_name, init_population, init_voters):
        self.name = init_name
        self.population = init_population
        self.voters = init_voters

    def get_init_population(self):
        return self.population

    def get_init_voters(self):
        return self.voters

    def get_name(self):
        return self.name

def highest_turnout(data):
    tempcounty = ""
    tempmax = 0
    for county in data:
        ans = (county.get_init_voters()/county.get_init_population())
        if ans > tempmax:
            tempmax = ans
            tempcounty = county
    return [(tempcounty.get_name(), tempmax)]

allegheny = County("allegheny", 1000490, 645469)
philadelphia = County("philadelphia", 1134081, 539069)
montgomery = County("montgomery", 568952, 399591)
lancaster = County("lancaster", 345367, 230278)
delaware = County("delaware", 414031, 284538)
chester = County("chester", 319919, 230823)
bucks = County("bucks", 444149, 319816)
data = [allegheny, philadelphia, montgomery, lancaster, delaware, chester, bucks]
result = highest_turnout(data) # do not change this line!
print(result) # prints the output of the function
```

<p>Output:</p>

```[('chester', 0.7215045058280377)]
```

ContentLicense: CC BY-SA 4.0

Title: Python: Uexpected an indented block

Body:
I am not sure why I am getting this error.

I am getting this error:
Error on line 24:
    tempmax = ans
    ^
IndentationError: expected an indented block

Here what I´ve have so far:

 def __init__(self, init_name, init_population, init_voters):
  self.name = init_name
  self.population = init_population
  self.voters = init_voters

def get_init_population(self):
 return self.population

def get_init_voters(self):
 return self.voters

def get_name(self):
 return self.name

def highest_turnout(data):
 tempcounty = ""
 tempmax = 0

for county in data:
 ans = (county.get_init_voters()/county.get_init_population())
 if ans > tempmax:

tempmax = ans
tempcounty = county
 return [(tempcounty.get_name(), tempmax)]

allegheny = County("allegheny", 1000490, 645469)
philadelphia = County("philadelphia", 1134081, 539069)
montgomery = County("montgomery", 568952, 399591)
lancaster = County("lancaster", 345367, 230278)
delaware = County("delaware", 414031, 284538)
chester = County("chester", 319919, 230823)
bucks = County("bucks", 444149, 319816)
data = [allegheny, philadelphia, montgomery, lancaster, delaware, chester, bucks]
result = highest_turnout(data) # do not change this line!
print(result) # prints the output of the function

# do not remove this line!```

Body:
The indentation is not correct, try:

class County:
    def __init__(self, init_name, init_population, init_voters):
        self.name = init_name
        self.population = init_population
        self.voters = init_voters

    def get_init_population(self):
        return self.population

    def get_init_voters(self):
        return self.voters

    def get_name(self):
        return self.name

def highest_turnout(data):
    tempcounty = ""
    tempmax = 0
    for county in data:
        ans = (county.get_init_voters()/county.get_init_population())
        if ans > tempmax:
            tempmax = ans
            tempcounty = county
    return [(tempcounty.get_name(), tempmax)]

allegheny = County("allegheny", 1000490, 645469)
philadelphia = County("philadelphia", 1134081, 539069)
montgomery = County("montgomery", 568952, 399591)
lancaster = County("lancaster", 345367, 230278)
delaware = County("delaware", 414031, 284538)
chester = County("chester", 319919, 230823)
bucks = County("bucks", 444149, 319816)
data = [allegheny, philadelphia, montgomery, lancaster, delaware, chester, bucks]
result = highest_turnout(data) # do not change this line!
print(result) # prints the output of the function

Output:

[('chester', 0.7215045058280377)]


问:
ASP.Net XUnit check if list of objects cointains a specific object
I am trying to add unit tests to my project. Some of these tests are checking if a list of objects does of does not contain an object. For checking if a list contains an object i've tried Assert.Contains(MyList, ExpectedObject), but it still gives an error that says that the list does not contain this object. Even when i debug the test i can see that the object is correctly added to the list.

The same happens with Assert.DoesNotContain(MyList, ExpectedObject). When i remove an item from the list and do this check it does say that it not in the list. But when i no longer remove the item, it still says that it is no longer in the list. Even though it is still in the list.

When i try it with a test list:List<string>. and do the same operations of adding and removing items, and then checking if these items are in the list or not. It does work.
Maybe Assert.Contains does not work for lists of objects. But the compiler does not give any errors. And i've also already checked if the ExpectedObject is the same type as the objects in the list.

Is there maybe another way of checking if an object is or isn't in a list.
any help is appreciated.

答:
In your test, is ExpectedObject the actual object in the list or an object with the same values? In C# two objects with the same property values are not actually equal. I suspect this is why your test is failing. Two strings with the same value are considered equal because the string object implements the Equals method (and some more), like @dorukerenaktas points out.

There's multiple ways to go about this. The easiest is by checking if an object with the expected property values is in the collection.

There's an overload of Assert.Contains that allows you to specify a predicate, for example:

```<code>Assert.Contains(MyList, item => item.Id == expectedId)
</code>```

Another option is to override the Equals method on your object, like @dorukerenaktas explains, but I would only recommend that if it really makes sense for your class. I would definitely not do that just so you can use this in a test.

Body:
In your test, is ExpectedObject the actual object in the list or an object with the same values? In C# two objects with the same property values are not actually equal. I suspect this is why your test is failing. Two strings with the same value are considered equal because the string object implements the Equals method (and some more), like @dorukerenaktas points out.

There's multiple ways to go about this. The easiest is by checking if an object with the expected property values is in the collection.

There's an overload of Assert.Contains that allows you to specify a predicate, for example:

Assert.Contains(MyList, item => item.Id == expectedId)

Another option is to override the Equals method on your object, like @dorukerenaktas explains, but I would only recommend that if it really makes sense for your class. I would definitely not do that just so you can use this in a test.


问:
Docker Gelf driver custom fields
I can see in Docker documentation:
https://docs.docker.com/config/containers/logging/gelf/

In GELF, every log message is a dict with the following fields:
...
any custom fields you configure yourself

Does it mean that this driver support custom fields?

I'd like to add custom field environment to each GELF message.
How can I do that?

答:
The documentation is indeed not very clear about that, but as explained here there's a way to add extra fields to your GELF message, that worked for me :

You need to provide the name of the extra fields you want to add through the --log-opt env=... option, and then provide the fields values through your docker env, like so :

docker run --log-driver gelf --log-opt env=mycustomfield --log-opt gelf-address=udp://<your-domain>:12201 --env mycustomfield=mycustomvalue alpine echo hello world
```

Your resulting log message will contain the extra field "mycustomfield": "mycustomvalue".

Title: Docker Gelf driver custom fields

Body:
The documentation is indeed not very clear about that, but as explained here there's a way to add extra fields to your GELF message, that worked for me :

You need to provide the name of the extra fields you want to add through the --log-opt env=... option, and then provide the fields values through your docker env, like so :

docker run --log-driver gelf --log-opt env=mycustomfield --log-opt gelf-address=udp://<your-domain>:12201 --env mycustomfield=mycustomvalue alpine echo hello world

Your resulting log message will contain the extra field "mycustomfield": "mycustomvalue".


问:
In laravel, how can I echo out form results in json format, after submitting?
In laravel, how can I echo out form results in JSON format, after submitting; without saving to the database first? This is to check the data the form is holding.</p>

答:
This would not be in json but it'd serve your purpose of checking data.
You can simply do this in your controller to check what your request contains:

```<code>dd($request->all());
</code>```

This would work for almost all version in Laravel.

Body:
This would not be in json but it'd serve your purpose of checking data.
You can simply do this in your controller to check what your request contains:

dd($request->all());

This would work for almost all version in Laravel.


问:
Dynamically added tablerow only last row not visible
I have created a tablelayout with the header row added in the XML file and the remaining content rows filled in dynamically.
For some reason, the last row is not visible.
I looked through other related posts and everything seems okay in my code.
Appreciate if someone could take a look and point out the problem.

XML code:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.bluechipsys.mcpackagemanager.PMActivity"
    android:id="@+id/view_layout">

    <ProgressBar
        android:id="@+id/installProgressBar"
        android:indeterminate="true"
        style="@android:style/Widget.Holo.ProgressBar.Large"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </ProgressBar>

    <ScrollView
        android:id="@+id/textAreaScroller"
        android:layout_above="@+id/btn_reload"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:scrollbars="vertical"
        android:fadeScrollbars="false"
        android:singleLine="false">
    <TextView
        android:text="@string/msg_default"
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:id="@+id/viewLog"
        android:maxLines="1000"
        android:scrollHorizontally="false"
        android:scrollbars="vertical"
        android:singleLine="false"
        android:background="@drawable/border" />
    </ScrollView>

    <TextView
        android:id="@+id/versionInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tableLayoutScroller"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/tableLayoutScroller"
        android:text="@string/tv_versioninfo"
        android:textStyle="bold" />

    <ScrollView
        android:id="@+id/tableLayoutScroller"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="false"
        android:layout_alignParentRight="false"
        android:layout_alignParentTop="true"
        android:layout_alignWithParentIfMissing="false"
        android:layout_centerHorizontal="false"
        android:layout_centerInParent="false"
        android:layout_alignParentStart="@+id/textAreaScroller"
        android:layout_alignRight="@+id/textAreaScroller"
        android:layout_alignEnd="@+id/textAreaScroller"
        android:layout_above="@+id/textAreaScroller"
        android:fadeScrollbars="false"
        android:scrollbars="vertical">

    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scrollbars="vertical"
        android:id="@+id/tbl_packagelist"
        android:orientation="vertical"
        android:layout_alignParentLeft="false"
        android:layout_alignParentRight="false"
        android:layout_alignParentTop="true"
        android:layout_alignWithParentIfMissing="false"
        android:layout_centerHorizontal="false"
        android:layout_centerInParent="false"
        android:layout_marginTop="30dp"
        android:layout_alignParentStart="@+id/textAreaScroller"
        android:layout_alignRight="@+id/textAreaScroller"
        android:layout_alignEnd="@+id/textAreaScroller"
        android:layout_above="@+id/textAreaScroller"
        android:scrollHorizontally="false"
        android:stretchColumns="1,2,3,4,5"
        android:shrinkColumns="2"
        android:background="@drawable/border_table">

        <TableRow
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:focusable="true"
            android:focusableInTouchMode="false"
            android:background="@android:drawable/list_selector_background">

            <CheckBox
                android:id="@+id/cbSelect"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/title_cell_shape"
                android:onClick="onCheckboxClicked" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:id="@+id/tvState"
                android:background="@drawable/title_cell_shape"
                android:editable="false" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="@string/tv_package"
                android:id="@+id/tvPackage"
                android:background="@drawable/title_cell_shape"
                android:textColor="#000"
                android:textStyle="bold"
                android:gravity="fill"
                android:textAlignment="center"
                android:paddingLeft="2dp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="@string/tv_instver"
                android:id="@+id/tvInstver"
                android:singleLine="false"
                android:background="@drawable/title_cell_shape"
                android:textColor="#000"
                android:textStyle="bold"
                android:gravity="fill"
                android:textAlignment="center"
                android:paddingLeft="2dp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="@string/tv_latestver"
                android:id="@+id/tvLatestver"
                android:background="@drawable/title_cell_shape"
                android:textColor="#000"
                android:textStyle="bold"
                android:gravity="fill"
                android:paddingLeft="2dp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="@string/tv_size"
                android:id="@+id/tvSize"
                android:background="@drawable/title_cell_shape"
                android:textColor="#000"
                android:textStyle="bold"
                android:gravity="fill"
                android:paddingLeft="2dp" />

        </TableRow>
    </TableLayout>
    </ScrollView>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_reload"
        android:id="@+id/btn_reload"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/reload"
        android:layout_marginTop="7dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_apply"
        android:id="@+id/btn_apply"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/apply"
        android:layout_alignTop="@+id/btn_reload"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_close"
        android:id="@+id/btn_close"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/close"
        android:layout_alignTop="@+id/btn_reload"
        android:layout_alignParentBottom="true"
        android:layout_alignRight="@+id/textAreaScroller"
        android:layout_alignEnd="@+id/textAreaScroller" />

</RelativeLayout>
</code>```

Java Code:

```<code>private void clearTableRows() {
        Logger.d(TAG, "Clearing table rows");

        TableLayout main_table = (TableLayout) findViewById(R.id.tbl_packagelist);
        int rowCount = main_table.getChildCount();
        main_table.removeViews(1, rowCount - 1);    // Leave header row intact
    }

    // Create table rows and add to the GUI
    private void createTableRows() {
        Logger.d(TAG, "Creating table rows");

        final TableLayout main_table = (TableLayout) findViewById(R.id.tbl_packagelist);
        Drawable background;

        // Define layout parameters
        TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        TableRow.LayoutParams itemCBParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        TableRow.LayoutParams itemIVParams = new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        itemIVParams.gravity = Gravity.CENTER;      // Centre the image display
        TableRow.LayoutParams itemParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        ViewGroup.MarginLayoutParams mLayoutItemParams = new ViewGroup.MarginLayoutParams (itemParams);
        MarginLayoutParamsCompat.setMarginStart(mLayoutItemParams, 4);  // Need this workaround for API level < 17

        for (MCPackage pkg: list_packages) {
            // Create the TableRow and widgets to add to the TableRow
            TableRow tbl_row = new TableRow(this);
            CheckBox cb_select = new CheckBox(this);
            ImageView iv_state = new ImageView(this);
            TextView tv_package = new TextView(this);
            TextView tv_instver = new TextView(this);
            TextView tv_currver = new TextView(this);
            TextView tv_pkgsize = new TextView(this);

            int index = list_packages.indexOf(pkg);
            if(index % 2 == 0) {
                background = getResources().getDrawable(R.drawable.cell_shape_white);
            } else {
                background = getResources().getDrawable(R.drawable.cell_shape_grey);
            }

            // Set GUI parameters for the TableRow
            tbl_row.setLayoutParams(rowParams);
            tbl_row.setBackground(background);
            tbl_row.setId(index);           // Set ID to match index of list_packages

            // Initialize the cells
            cb_select.setLayoutParams(itemCBParams);
            cb_select.setId(index + CHECKBOX_ID);
            cb_ids[index] = (index + CHECKBOX_ID);
            cb_select.setOnClickListener(checkboxOnClick());
            cb_select.setOnCheckedChangeListener(checkboxOnCheckChange());

            iv_state.setLayoutParams(itemIVParams);
            iv_state.setImageResource(pkg.getState().getImageResourceId());
            iv_state.setId(index + IVSTATE_ID);
            iv_state_ids[index] = (index + IVSTATE_ID);

            tv_package.setLayoutParams(itemParams);
            tv_package.setText(pkg.getPackageName());
            tv_package.setGravity(Gravity.FILL);
            tv_package.setTextAppearance(this, android.R.style.TextAppearance_Small);
            tv_package.setTextSize(12);
            tv_package.setTextColor(Color.DKGRAY);
            tv_package.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

            tv_instver.setLayoutParams(itemParams);
            tv_instver.setText(pkg.getInstalledVersion());
            tv_instver.setGravity(Gravity.FILL);
            tv_instver.setTextSize(12);
            tv_instver.setTextColor(Color.BLUE);
            tv_instver.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

            tv_currver.setLayoutParams(itemParams);
            tv_currver.setText(pkg.getUpdateVersion());
            tv_currver.setGravity(Gravity.FILL);
            tv_currver.setTextSize(12);
            tv_currver.setTextColor(Color.DKGRAY);
            tv_currver.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

            tv_pkgsize.setLayoutParams(itemParams);
            tv_pkgsize.setText(String.valueOf(((int) pkg.getPackageSize()) / KBINBYTES) + "K");
            tv_pkgsize.setGravity(Gravity.FILL);
            tv_pkgsize.setTextSize(12);
            tv_pkgsize.setTextColor(Color.BLUE);
            tv_pkgsize.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

            // Add the cells to the row
            tbl_row.addView(cb_select);
            tbl_row.addView(iv_state);
            tbl_row.addView(tv_package);
            tbl_row.addView(tv_instver);
            tbl_row.addView(tv_currver);
            tbl_row.addView(tv_pkgsize);

            main_table.addView(tbl_row);        // Add the row to the table
            tbl_row.setOnClickListener(rowClickListener);
            tbl_row.setOnLongClickListener(rowLongClickListener);
            registerForContextMenu(tbl_row);    // Register the table row for context menu
            Logger.d(TAG, "Added package: " + pkg.getPackageName());
        }
    }
</code>```

答: I'm not sure if it is still a problem, but try to use NestedScrollView instead of ScrollView.

ContentLicense: CC BY-SA 3.0

Body:
I have created a tablelayout with the header row added in the XML file and the remaining content rows filled in dynamically.
For some reason, the last row is not visible.
I looked through other related posts and everything seems okay in my code.
Appreciate if someone could take a look and point out the problem.

XML code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.bluechipsys.mcpackagemanager.PMActivity"
    android:id="@+id/view_layout">

    <ProgressBar
        android:id="@+id/installProgressBar"
        android:indeterminate="true"
        style="@android:style/Widget.Holo.ProgressBar.Large"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </ProgressBar>

    <ScrollView
        android:id="@+id/textAreaScroller"
        android:layout_above="@+id/btn_reload"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:scrollbars="vertical"
        android:fadeScrollbars="false"
        android:singleLine="false">
    <TextView
        android:text="@string/msg_default"
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:id="@+id/viewLog"
        android:maxLines="1000"
        android:scrollHorizontally="false"
        android:scrollbars="vertical"
        android:singleLine="false"
        android:background="@drawable/border" />
    </ScrollView>

    <TextView
        android:id="@+id/versionInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tableLayoutScroller"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/tableLayoutScroller"
        android:text="@string/tv_versioninfo"
        android:textStyle="bold" />

    <ScrollView
        android:id="@+id/tableLayoutScroller"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="false"
        android:layout_alignParentRight="false"
        android:layout_alignParentTop="true"
        android:layout_alignWithParentIfMissing="false"
        android:layout_centerHorizontal="false"
        android:layout_centerInParent="false"
        android:layout_alignParentStart="@+id/textAreaScroller"
        android:layout_alignRight="@+id/textAreaScroller"
        android:layout_alignEnd="@+id/textAreaScroller"
        android:layout_above="@+id/textAreaScroller"
        android:fadeScrollbars="false"
        android:scrollbars="vertical">

    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scrollbars="vertical"
        android:id="@+id/tbl_packagelist"
        android:orientation="vertical"
        android:layout_alignParentLeft="false"
        android:layout_alignParentRight="false"
        android:layout_alignParentTop="true"
        android:layout_alignWithParentIfMissing="false"
        android:layout_centerHorizontal="false"
        android:layout_centerInParent="false"
        android:layout_marginTop="30dp"
        android:layout_alignParentStart="@+id/textAreaScroller"
        android:layout_alignRight="@+id/textAreaScroller"
        android:layout_alignEnd="@+id/textAreaScroller"
        android:layout_above="@+id/textAreaScroller"
        android:scrollHorizontally="false"
        android:stretchColumns="1,2,3,4,5"
        android:shrinkColumns="2"
        android:background="@drawable/border_table">

        <TableRow
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:focusable="true"
            android:focusableInTouchMode="false"
            android:background="@android:drawable/list_selector_background">

            <CheckBox
                android:id="@+id/cbSelect"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/title_cell_shape"
                android:onClick="onCheckboxClicked" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:id="@+id/tvState"
                android:background="@drawable/title_cell_shape"
                android:editable="false" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="@string/tv_package"
                android:id="@+id/tvPackage"
                android:background="@drawable/title_cell_shape"
                android:textColor="#000"
                android:textStyle="bold"
                android:gravity="fill"
                android:textAlignment="center"
                android:paddingLeft="2dp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="@string/tv_instver"
                android:id="@+id/tvInstver"
                android:singleLine="false"
                android:background="@drawable/title_cell_shape"
                android:textColor="#000"
                android:textStyle="bold"
                android:gravity="fill"
                android:textAlignment="center"
                android:paddingLeft="2dp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="@string/tv_latestver"
                android:id="@+id/tvLatestver"
                android:background="@drawable/title_cell_shape"
                android:textColor="#000"
                android:textStyle="bold"
                android:gravity="fill"
                android:paddingLeft="2dp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="@string/tv_size"
                android:id="@+id/tvSize"
                android:background="@drawable/title_cell_shape"
                android:textColor="#000"
                android:textStyle="bold"
                android:gravity="fill"
                android:paddingLeft="2dp" />

        </TableRow>
    </TableLayout>
    </ScrollView>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_reload"
        android:id="@+id/btn_reload"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/reload"
        android:layout_marginTop="7dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_apply"
        android:id="@+id/btn_apply"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/apply"
        android:layout_alignTop="@+id/btn_reload"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_close"
        android:id="@+id/btn_close"
        android:background="@android:color/transparent"
        android:drawableTop="@drawable/close"
        android:layout_alignTop="@+id/btn_reload"
        android:layout_alignParentBottom="true"
        android:layout_alignRight="@+id/textAreaScroller"
        android:layout_alignEnd="@+id/textAreaScroller" />

</RelativeLayout>

Java Code:

private void clearTableRows() {
        Logger.d(TAG, "Clearing table rows");

        TableLayout main_table = (TableLayout) findViewById(R.id.tbl_packagelist);
        int rowCount = main_table.getChildCount();
        main_table.removeViews(1, rowCount - 1);    // Leave header row intact
    }

    // Create table rows and add to the GUI
    private void createTableRows() {
        Logger.d(TAG, "Creating table rows");

        final TableLayout main_table = (TableLayout) findViewById(R.id.tbl_packagelist);
        Drawable background;

        // Define layout parameters
        TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        TableRow.LayoutParams itemCBParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        TableRow.LayoutParams itemIVParams = new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        itemIVParams.gravity = Gravity.CENTER;      // Centre the image display
        TableRow.LayoutParams itemParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        ViewGroup.MarginLayoutParams mLayoutItemParams = new ViewGroup.MarginLayoutParams (itemParams);
        MarginLayoutParamsCompat.setMarginStart(mLayoutItemParams, 4);  // Need this workaround for API level < 17

        for (MCPackage pkg: list_packages) {
            // Create the TableRow and widgets to add to the TableRow
            TableRow tbl_row = new TableRow(this);
            CheckBox cb_select = new CheckBox(this);
            ImageView iv_state = new ImageView(this);
            TextView tv_package = new TextView(this);
            TextView tv_instver = new TextView(this);
            TextView tv_currver = new TextView(this);
            TextView tv_pkgsize = new TextView(this);

            int index = list_packages.indexOf(pkg);
            if(index % 2 == 0) {
                background = getResources().getDrawable(R.drawable.cell_shape_white);
            } else {
                background = getResources().getDrawable(R.drawable.cell_shape_grey);
            }

            // Set GUI parameters for the TableRow
            tbl_row.setLayoutParams(rowParams);
            tbl_row.setBackground(background);
            tbl_row.setId(index);           // Set ID to match index of list_packages

            // Initialize the cells
            cb_select.setLayoutParams(itemCBParams);
            cb_select.setId(index + CHECKBOX_ID);
            cb_ids[index] = (index + CHECKBOX_ID);
            cb_select.setOnClickListener(checkboxOnClick());
            cb_select.setOnCheckedChangeListener(checkboxOnCheckChange());

            iv_state.setLayoutParams(itemIVParams);
            iv_state.setImageResource(pkg.getState().getImageResourceId());
            iv_state.setId(index + IVSTATE_ID);
            iv_state_ids[index] = (index + IVSTATE_ID);

            tv_package.setLayoutParams(itemParams);
            tv_package.setText(pkg.getPackageName());
            tv_package.setGravity(Gravity.FILL);
            tv_package.setTextAppearance(this, android.R.style.TextAppearance_Small);
            tv_package.setTextSize(12);
            tv_package.setTextColor(Color.DKGRAY);
            tv_package.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

            tv_instver.setLayoutParams(itemParams);
            tv_instver.setText(pkg.getInstalledVersion());
            tv_instver.setGravity(Gravity.FILL);
            tv_instver.setTextSize(12);
            tv_instver.setTextColor(Color.BLUE);
            tv_instver.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

            tv_currver.setLayoutParams(itemParams);
            tv_currver.setText(pkg.getUpdateVersion());
            tv_currver.setGravity(Gravity.FILL);
            tv_currver.setTextSize(12);
            tv_currver.setTextColor(Color.DKGRAY);
            tv_currver.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

            tv_pkgsize.setLayoutParams(itemParams);
            tv_pkgsize.setText(String.valueOf(((int) pkg.getPackageSize()) / KBINBYTES) + "K");
            tv_pkgsize.setGravity(Gravity.FILL);
            tv_pkgsize.setTextSize(12);
            tv_pkgsize.setTextColor(Color.BLUE);
            tv_pkgsize.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

            // Add the cells to the row
            tbl_row.addView(cb_select);
            tbl_row.addView(iv_state);
            tbl_row.addView(tv_package);
            tbl_row.addView(tv_instver);
            tbl_row.addView(tv_currver);
            tbl_row.addView(tv_pkgsize);

            main_table.addView(tbl_row);        // Add the row to the table
            tbl_row.setOnClickListener(rowClickListener);
            tbl_row.setOnLongClickListener(rowLongClickListener);
            registerForContextMenu(tbl_row);    // Register the table row for context menu
            Logger.d(TAG, "Added package: " + pkg.getPackageName());
        }
    }


问:
Two Database tables related in two different ways...?
Im sort of scratching my head on this one.  Here's the scenario.  Im using Doctrine and YAML schema files:

I have a table User and a table Event

User looks like this:

```<code>User:
    columns:
        id:
            type: integer(7)
        email:
            type: string(100)
        display_name:
            type: string(255)
        fb_id:
            type: string(100)
    relations:
        Event:
            type: many
            refClass: UserEvent
</code>```

Event looks like this:

```<code>Event:
    columns:
        id:
            type: integer(7)
        initiator_id:
            type: integer(7)
        loc_latitude:
            type: decimal(11)
        loc_longitude:
            type: decimal(11)
        4sq_id:
            type: integer(11)
    relations:
        User:
            type: one
            local: initiator_id
            foreign: id
        User:
            type: many
            refClass: UserEvent
</code>```

As you can see the problem is this: A User (or 'initiator') can start many events, and an event can belong to one User ('initiator').  However, an event can also have many Users who join it, and a User can Join many events.

So Event and User end up being related in two different fashions.  How does this work?  Is it possible to do it this way or am i missing something?

答: You can just add an event_attendees table with the event id and user id as the two columns? Or is this not the question</p>

Body:
Im sort of scratching my head on this one.  Here's the scenario.  Im using Doctrine and YAML schema files:

I have a table User and a table Event

User looks like this:

User:
    columns:
        id:
            type: integer(7)
        email:
            type: string(100)
        display_name:
            type: string(255)
        fb_id:
            type: string(100)
    relations:
        Event:
            type: many
            refClass: UserEvent

Event looks like this:

Event:
    columns:
        id:
            type: integer(7)
        initiator_id:
            type: integer(7)
        loc_latitude:
            type: decimal(11)
        loc_longitude:
            type: decimal(11)
        4sq_id:
            type: integer(11)
    relations:
        User:
            type: one
            local: initiator_id
            foreign: id
        User:
            type: many
            refClass: UserEvent

As you can see the problem is this: A User (or 'initiator') can start many events, and an event can belong to one User ('initiator').  However, an event can also have many Users who join it, and a User can Join many events.

So Event and User end up being related in two different fashions.  How does this work?  Is it possible to do it this way or am i missing something?


问:
How to delete all the reference of id in mongoose nodejs?
shopSchema

```<code>const shopSchema = new Schema({
  shopName: {
    type: String,
    required: true
  },
  foodId: [{
    type: Schema.Types.ObjectId,
    ref: 'Food',
  }]
});
</code>```

foodSchema

```<code>const foodSchema = new Schema({
  foodName: {
    type: String,
    required: true
  },
  image: {
    type: String,
    required: true
  },
  price: {
    type: String,
    required: true
  },
  shopName: {
    type: String,
    required: true
  },
  shopId:{
    type: Schema.Types.ObjectId,
    ref: 'Shop',
    required: true
  }

});
</code>```

In this if i delete the food from foodschema how to delete the foodid referenced in shopschema

```<code>    exports.postdelfood=(req,res,next)=>{
  const fid=req.params.foodId;
  console.log(fid);
  return Food.deleteOne({_id:fid})
  .then(result=>{
    console.log('deleted');
    res.status(200).json({message:'success'});
  })
  .catch(err=>{
    res.status(500).json({message:'failed'});
  })

};
</code>```

is there any function in mongoose to delete all the reference id if we delete anyone of the id?

答:
```<code>exports.postdelfood=(req,res,next)=>{
  const fid=req.params.foodId;
  const sid=req.params.shopId;

  return Food.deleteOne({_id:fid})
  .then(result=>{
    console.log(fid);
    Shop.update({_id:sid},{ $pull: { foodId: fid }})
    .then(resu=>{
      console.log(resu);
        console.log('deleted');
      res.status(200).json({message:'success'});

      });
  })
  .catch(err=>{
    res.status(500).json({message:'failed'});
  });

};
</code>```

I got the answer but is there any any function in mongoose to delete all the reference id if we delete anyone of the id?

Body:
shopSchema

const shopSchema = new Schema({
  shopName: {
    type: String,
    required: true
  },
  foodId: [{
    type: Schema.Types.ObjectId,
    ref: 'Food',
  }]
});

foodSchema

const foodSchema = new Schema({
  foodName: {
    type: String,
    required: true
  },
  image: {
    type: String,
    required: true
  },
  price: {
    type: String,
    required: true
  },
  shopName: {
    type: String,
    required: true
  },
  shopId:{
    type: Schema.Types.ObjectId,
    ref: 'Shop',
    required: true
  }

});

In this if i delete the food from foodschema how to delete the foodid referenced in shopschema

    exports.postdelfood=(req,res,next)=>{
  const fid=req.params.foodId;
  console.log(fid);
  return Food.deleteOne({_id:fid})
  .then(result=>{
    console.log('deleted');
    res.status(200).json({message:'success'});
  })
  .catch(err=>{
    res.status(500).json({message:'failed'});
  })

};

is there any function in mongoose to delete all the reference id if we delete anyone of the id?

Body:
exports.postdelfood=(req,res,next)=>{
  const fid=req.params.foodId;
  const sid=req.params.shopId;

  return Food.deleteOne({_id:fid})
  .then(result=>{
    console.log(fid);
    Shop.update({_id:sid},{ $pull: { foodId: fid }})
    .then(resu=>{
      console.log(resu);
        console.log('deleted');
      res.status(200).json({message:'success'});

      });
  })
  .catch(err=>{
    res.status(500).json({message:'failed'});
  });

};

I got the answer but is there any any function in mongoose to delete all the reference id if we delete anyone of the id?


问:
How do I pass a JSONObject from Android application to a PHP file?
I want to send a simple JSON object to PHP server, but when I try to retrieve that object on the server side, there is nothing I mean my $_POST variable is empty. The server side is PHP 5.2 and I'm using android emulator 10... Could someone have a look on my code and tell me what is going wrong?
Thanks a lot

```<code>public void uploadJSon() throws ClientProtocolException, IOException, JSONException{
       HttpClient httpclient = new DefaultHttpClient();
       String url = "http://so-dev-deb.niv2.com/suivi_activite/test.php";
       HttpPost httppost = new HttpPost(url);
       JSONObject json = new JSONObject();

       json.put("username", "bob");
       json.put("email", "test@testsite.com");
       List <NameValuePair> nvps = new ArrayList <NameValuePair>();

       nvps.add(new BasicNameValuePair("value", json.toString()));
       httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

       URL test_url = new URL(url);
       URLConnection connection = test_url.openConnection();
       connection.setDoOutput(true);

       HttpResponse response;
       response = httpclient.execute(httppost);
       Log.i("NVPS",nvps.get(0).toString());
       Log.i("JSON",json.toString());
       Log.i("response", response.getEntity().getContent().toString());
       Log.i("response status",response.getStatusLine().toString());

       BufferedReader in = new BufferedReader(
             new InputStreamReader(
             connection.getInputStream()));

       String decodedString;

       while ((decodedString = in.readLine()) != null) {
          //System.out.println(decodedString);
          Log.i("info 10",decodedString);
       }
       in.close();

    }
</code>```

The server side test.php is :

```<code><?php
    $tmp = json_decode($_POST['value']);
    var_dump($tmp);
?>
</code>```

答:
I'm no expert in PHP, However, a project I worked on decoded the json that I submitted like this.

```<code>$jsonData = file_get_contents("php://input");
</code>```

if(isset($jsonData) && !empty($jsonData)) {
      $this->data = json_decode($jsonData,true);
 }

Body:
I want to send a simple JSON object to PHP server, but when I try to retrieve that object on the server side, there is nothing I mean my $_POST variable is empty. The server side is PHP 5.2 and I'm using android emulator 10... Could someone have a look on my code and tell me what is going wrong?
Thanks a lot

public void uploadJSon() throws ClientProtocolException, IOException, JSONException{
       HttpClient httpclient = new DefaultHttpClient();
       String url = "http://so-dev-deb.niv2.com/suivi_activite/test.php";
       HttpPost httppost = new HttpPost(url);
       JSONObject json = new JSONObject();

       json.put("username", "bob");
       json.put("email", "test@testsite.com");
       List <NameValuePair> nvps = new ArrayList <NameValuePair>();

       nvps.add(new BasicNameValuePair("value", json.toString()));
       httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

       URL test_url = new URL(url);
       URLConnection connection = test_url.openConnection();
       connection.setDoOutput(true);

       HttpResponse response;
       response = httpclient.execute(httppost);
       Log.i("NVPS",nvps.get(0).toString());
       Log.i("JSON",json.toString());
       Log.i("response", response.getEntity().getContent().toString());
       Log.i("response status",response.getStatusLine().toString());

       BufferedReader in = new BufferedReader(
             new InputStreamReader(
             connection.getInputStream()));

       String decodedString;

       while ((decodedString = in.readLine()) != null) {
          //System.out.println(decodedString);
          Log.i("info 10",decodedString);
       }
       in.close();

    }

The server side test.php is :

<?php
    $tmp = json_decode($_POST['value']);
    var_dump($tmp);
?>

Body:
I'm no expert in PHP, However, a project I worked on decoded the json that I submitted like this.

$jsonData = file_get_contents("php://input");

if(isset($jsonData) && !empty($jsonData)) {
      $this->data = json_decode($jsonData,true);
 }


问:
Extend "local" storage on proxmox
There is Proxmox VE 3.0 with 2x1Tb HDD in mirror:

I have 1 huge container (~430Gb), that is located in local. I need to:

extend local with new 2x1Tb disks.

or create new storage (with new disks) and migrate container to new storage

How it can be done without reinstalling Proxmox?
Thanks!

P.S. I can create new storage item as LVM, but LVM is not suitable for containers

答:
update to latest release should be fixed ;)

https://forum.proxmox.com/threads/proxmox-ve-6-2-released.69647/

Title: Extend "local" storage on proxmox


问:
Why can't I import COUNTRIES from pygal.i18n
I'm trying to import COUNTRIES from pygal.i18n by using the piece of code below.

     from pygal.i18n import COUNTRIES
```
<p>After I run this, I get the following error.</p>
<pre class="lang-py prettyprint-override"><code>    ImportError: No module named 'pygal.i18n'.
</code>```

Can anyone tell me what the problem is?

Thanks

答:
```<code>from pygal_maps_world import i18n

# выводим код страны и ее название в принятом международном формате
for country_code in sorted(i18n.COUNTRIES.keys()):
    print(f"{country_code} - {i18n.COUNTRIES[country_code]}")
</code>```

For example,
th - Thailand
tj - Tajikistan
tl - Timor-Leste
tm - Turkmenistan

Body:
I'm trying to import COUNTRIES from pygal.i18n by using the piece of code below.

     from pygal.i18n import COUNTRIES

After I run this, I get the following error.

    ImportError: No module named 'pygal.i18n'.

Can anyone tell me what the problem is?

Thanks

Body:
from pygal_maps_world import i18n

# выводим код страны и ее название в принятом международном формате
for country_code in sorted(i18n.COUNTRIES.keys()):
    print(f"{country_code} - {i18n.COUNTRIES[country_code]}")

For example,
th - Thailand
tj - Tajikistan
tl - Timor-Leste
tm - Turkmenistan


问:
Volley to get data everytime from SERVER not cache
How do I make volley fetch data (e.g. JSON) everytime from SERVER, not at all from previous cache.</p>

```<code>RequestQueue requestQueue = Volley.newRequestQueue(context);
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, "https://example.com/example.json", null,
                response -> {
                    DataModel model = new Gson().fromJson(response.toString(), PrivacyModel.class);
                    new AlertDialog.Builder(context).setTitle("Data")
                            .setMessage(Model.getData())
                            .setPositiveButton("Okay", (dialog, which) -> dialog.dismiss())
                            .setIcon(R.drawable.status).show();
                },
                error -> // Show a toast
        requestQueue.add(request);
</code>```

答:
In order to not use cache, I has to set

```<code>request.setShouldCache(false);
</code>```

setShouldCache to false before making request.

Body:
How do I make volley fetch data (e.g. JSON) everytime from SERVER, not at all from previous cache.

RequestQueue requestQueue = Volley.newRequestQueue(context);
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, "https://example.com/example.json", null,
                response -> {
                    DataModel model = new Gson().fromJson(response.toString(), PrivacyModel.class);
                    new AlertDialog.Builder(context).setTitle("Data")
                            .setMessage(Model.getData())
                            .setPositiveButton("Okay", (dialog, which) -> dialog.dismiss())
                            .setIcon(R.drawable.status).show();
                },
                error -> // Show a toast
        requestQueue.add(request);

Body:
In order to not use cache, I has to set

request.setShouldCache(false);

setShouldCache to false before making request.


问:
Scala "belongsTo" function
I am often in the situation of doing this type of filtering:

```<code>allPeople
  .filter(person => englishPeopleIds contains person.id)

</code>```

and it would make my life easier and my code more readable if there was some sort of "belongsTo" function to do the following:

```<code>allPeople
  .filter(_.id belongsTo englishPeopleIds)
</code>```

belongsTo function would have this kind of behaviour (but would be a method of the element):

```<code>def belongsTo[T](element: T, list: List[T]): Boolean = list contains element
</code>```

Do you know if such function is already implemented in Scala?

答:
Perhaps define a right-associative operator on a sequential collections like so

```<code>implicit class ElementOf[A](l: Seq[A]) {
  def ∈: (a: A): Boolean = l contains a
}
</code>```

using mathematical symbol element of ∈ which falls under Scala operator characters, and then call-site becomes

```<code>allPeople filter (_.id ∈: englishPeopleIds)
</code>```

To make it work also for Set and Map as well try defining in terms of Iterable#exists like so

```<code>implicit class ElementOf[A](cc: Iterable[A]) {
  def ∈: (a: A): Boolean = cc exists (_ == a)
}
</code>```

Title: Scala "belongsTo" function

Body:
I am often in the situation of doing this type of filtering:

allPeople
  .filter(person => englishPeopleIds contains person.id)

and it would make my life easier and my code more readable if there was some sort of "belongsTo" function to do the following:

allPeople
  .filter(_.id belongsTo englishPeopleIds)

belongsTo function would have this kind of behaviour (but would be a method of the element):

def belongsTo[T](element: T, list: List[T]): Boolean = list contains element

Do you know if such function is already implemented in Scala?

Body:
Perhaps define a right-associative operator on a sequential collections like so

implicit class ElementOf[A](l: Seq[A]) {
  def ∈: (a: A): Boolean = l contains a
}

using mathematical symbol element of ∈ which falls under Scala operator characters, and then call-site becomes

allPeople filter (_.id ∈: englishPeopleIds)

To make it work also for Set and Map as well try defining in terms of Iterable#exists like so

implicit class ElementOf[A](cc: Iterable[A]) {
  def ∈: (a: A): Boolean = cc exists (_ == a)
}


问:
jQuery scroll calls a function multiple times
I have a jquery scroll function as below :

```<code>$(window).scroll(function() {
if (($(window).scrollTop() + $(window).height()) >= ($('body').height() * 0.7)) {
        alert('call me');
     }
});
</code>```

And the HTML:

```<code><div style="height:450px;">BOX</div>
</code>```

When I scroll, instead of just one call me I am getting multiple times call me. Why so and whats wrong ?
JSFiddle Example Here

答:
There is a nice and clean(er) solution on Stackoverflow here</p>

```<code>var timer;

$(window).scroll(function(){

    if ( timer ) clearTimeout(timer);

    timer = setTimeout(function(){
        // Make your AJAX request here...
    }, 10000);
});
</code>```

Body:
I have a jquery scroll function as below :

$(window).scroll(function() {
if (($(window).scrollTop() + $(window).height()) >= ($('body').height() * 0.7)) {
        alert('call me');
     }
});

And the HTML:

BOX

When I scroll, instead of just one call me I am getting multiple times call me. Why so and whats wrong ?
JSFiddle Example Here

Body:
There is a nice and clean(er) solution on Stackoverflow here

var timer;

$(window).scroll(function(){

    if ( timer ) clearTimeout(timer);

    timer = setTimeout(function(){
        // Make your AJAX request here...
    }, 10000);
});


问:
SQL: How to increase SQL query performance of a view?
issue:

Update & query (using Power BI) of my Sales Weekly View takes forever (>30min) and I would like to understand how I could improve it

Current setup:

Sales Daily View: View containing aggregation and joins of two main sales tables and a date table

Sales Weekly View: View joining the "Sales Daily View", a sales table and two dimension tables and containing extensive logic (mainly aggregations)

Please let me know if you have any idea how to streamline this and improve the performance of the view.

答:
As @Tim mentioned the view will have the same performance as the underlying query. so check if you can optimize the Select query in the view.

You could try using Common table expression (CTEs) for some aggregated results in the view instead of calculating in the select itself and then join the main query with the CTE.

You can try using a materialized view if you have the capability to refresh it every day/ week based on your need and then create indexes on the materialized view and use it as a source in your power BI.


问:
Google Kubernetes Engine ingress annotations
I configure Ingress on google Kubernetes engine. I am new on ingress but as i understood ingress can serve different Loadbalancers and different LBs should be differently configured.

I have started with a simple ingress config on GKE :

```<code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: basic-ingress

spec:
  rules:
  - http:
      paths:
      - path: /*
        backend:
          serviceName: web-np
          servicePort: 8080
      - path: /v2/keys
        backend:
          serviceName: etcd-np
          servicePort: 2379
</code>```

And it works fine so I have 2 different NodePort services web-np and etcd-np . But now I need to extend this logic with some rewrite rules so that request that points to /service1 - will be redirected to the other service1-np service but before /service1/hello.html must be replaced to /hello.html. That's why I have the following questions:

How can I configure rewrite in ingress and if it is possible with default load balancer.

What is default load balancer on GKE.

Where can I find a list of all annotations to it. I have thought that the full list is on https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/ but there is a completly different list and there is no kubernetes.io/ingress.global-static-ip-name annotation that is widely used in google examples.

答:
Ingress - API object that manages external access to the services in a cluster, typically HTTP.

Ingress may provide load balancing, SSL termination and name-based virtual hosting.

 Kubernetes.io: Ingress

Kubernetes can have multiple Ingress controllers. This controllers are different from each other. The Ingress controllers mentioned by you in this particular question are:

Ingress-GCE - a default Ingress resource for GKE cluster:

Github.com: Kubernetes: Ingress GCE

Ingress-nginx - an alternative Ingress controller which can be deployed to your GKE cluster:

Github.com: Kubernetes: Ingress-nginx

Ingress configuration you pasted will use the Ingress-GCE controller. If you want to switch to Ingress-nginx one, you will need to deploy it and set an annotation like:

kubernetes.io/ingress.class: "nginx"

How can I configure rewrite in ingress and if it is possible with default load balancer.

There is an ongoing feature request to support rewrites with Ingress-GCE here: Github.com: Ingress-GCE: Rewrite.

You can use Ingress-nginx to have support for rewrites. There is an official documentation about deploying it: Kubernetes.github.io: Ingress-nginx: Deploy

For more resources about rewrites you can use:

Kubernetes.github.io: Ingress nginx: Examples: Rewrite

Stackoverflow.com: Ingress nginx how to serve assests to application - this is an answer which shows an example on how to configure a playground for experimenting with rewrites

What is default load balancer on GKE.

If you create an Ingress resource with a default Ingress-GCE option you will create a L7 HTTP&HTTPS LoadBalancer.

If you create a service of type LoadBalancer in GKE you will create an L4 Network Load Balancer

If you deploy an Ingress-nginx controller in GKE cluster you will create a L4 Network Loadbalancer pointing to the Ingress-nginx controller which after that will route the traffic accordingly to your Ingress definition. If you are willing to use Ingress-nginx you will need to specify:

kubernetes.io/ingress.class: "nginx"

in your Ingress definition.

Please take a look on this article: Medium.com: Google Cloud: Kubernetes Nodeport vs Loadbalancer vs Ingress

Where can I find a list of all annotations to it. I have thought that the full list is on https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/ but there is a completly different list and there is no kubernetes.io/ingress.global-static-ip-name annotation that is widely used in google examples.

The link that you provided with annotations is specifically for Ingress-nginx. This annotations will not work with Ingress-GCE.

The annotations used in GCP examples are specific to Ingress-GCE.

You can create a Feature Request for a list of available annotations for Ingress-GCE on Issuetracker.google.com.

Body:
I configure Ingress on google Kubernetes engine. I am new on ingress but as i understood ingress can serve different Loadbalancers and different LBs should be differently configured.

I have started with a simple ingress config on GKE :

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: basic-ingress

spec:
  rules:
  - http:
      paths:
      - path: /*
        backend:
          serviceName: web-np
          servicePort: 8080
      - path: /v2/keys
        backend:
          serviceName: etcd-np
          servicePort: 2379

And it works fine so I have 2 different NodePort services web-np and etcd-np . But now I need to extend this logic with some rewrite rules so that request that points to /service1 - will be redirected to the other service1-np service but before /service1/hello.html must be replaced to /hello.html. That's why I have the following questions:

How can I configure rewrite in ingress and if it is possible with default load balancer.

What is default load balancer on GKE.

Where can I find a list of all annotations to it. I have thought that the full list is on https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/ but there is a completly different list and there is no kubernetes.io/ingress.global-static-ip-name annotation that is widely used in google examples.


问:
Django: IE doesn't load localhost or loads very SLOWLY
I'm just starting to learn Django, building a project on my computer, running Windows 7 64-bit, Python 2.7, Django 1.3.

Basically whatever I write, it loads in Chrome and Firefox instantly. But for IE (version 9), it just stalls there, and does nothing. I can load up "http://127.0.0.1:8000" on IE and leave the computer on for hours and it doesn't load. Sometimes, when I refresh a couple of times or restart IE it'll work. If I change something in the code, again, Chrome and Firefox reflects changes instantly, whereas IE doesn't - if it loads the page at all.

What is going on? I'm losing my mind here....

答:
It might be related to this issue:
https://code.djangoproject.com/ticket/16099

Essentially, the dev server isn't multithreaded, and if the browser opens a connection and then tries a second connection to actually get the data, it can hang forever.

Edit:

Also, see this issue:
https://code.djangoproject.com/ticket/15178

If you can provide a way to reproduce the issue, we may be able to find a fix.

Also, if you could try the latest development version and see if that fixes it, we recently committed a new patch that adds multithreading capability to the runserver command.


问:
std::function to member function
```<code>#include <functional>

struct A
{
    int func(int x, int y)
    {
        return x+y;
    }
};

int main()
{

    typedef std::function<int(int, int) > Funcp;
    A a;
    //Funcp func = std:::bind(&A::func, &a);
    Funcp func = std::bind(&A::func, a, std::placeholders::_1);

    return 0;
}
</code>```

I am getting errors in both of the above bind functions:

```<code> error C2825: '_Fty': must be a class or namespace when followed by '::'
</code>```

Where is the syntax error? I am using visual studio 2010

答:
It took a while for me to figure out what's happening. So adding it here for the benefit of others, where an explanation would help. I've renamed some functions and variables for more clarity.

```<code>#include <functional>

struct A
{
    int MemberFunc(int x, int y)
    {
        return x+y;
    }
};

int main()
{
    typedef std::function<int(int, int)> OrdinaryFunc;

    A a;
    OrdinaryFunc ofunc = std::bind(&A::MemberFunc, a, std::placeholders::_1, std::placeholders::_2);

    int z = ofunc(10, 20); // Invoke like an ordinary function

    return 0;
}
</code>```

Class member functions have an implicit/hidden parameter which points to the object (this pointer). These member functions can be invoked only by providing an object, which makes it different from an ordinary function.

std::bind can be used to "convert" a member function into an ordinary function by passing the object (pointer or reference). It has be the first argument in the list of args  (&a or a in this case) following the member function.  In the new function, the object is bound to the implicit/hidden parameter of the member function, and need not be passed when invoked. The unbound arguments are represented by the placeholders _1, _2 and have to be passed when invoked.

Title: std::function to member function

Body:
#include <functional>

struct A
{
    int func(int x, int y)
    {
        return x+y;
    }
};

int main()
{

    typedef std::function<int(int, int) > Funcp;
    A a;
    //Funcp func = std:::bind(&A::func, &a);
    Funcp func = std::bind(&A::func, a, std::placeholders::_1);

    return 0;
}

I am getting errors in both of the above bind functions:

 error C2825: '_Fty': must be a class or namespace when followed by '::'

Where is the syntax error? I am using visual studio 2010

Body:
It took a while for me to figure out what's happening. So adding it here for the benefit of others, where an explanation would help. I've renamed some functions and variables for more clarity.

#include <functional>

struct A
{
    int MemberFunc(int x, int y)
    {
        return x+y;
    }
};

int main()
{
    typedef std::function<int(int, int)> OrdinaryFunc;

    A a;
    OrdinaryFunc ofunc = std::bind(&A::MemberFunc, a, std::placeholders::_1, std::placeholders::_2);

    int z = ofunc(10, 20); // Invoke like an ordinary function

    return 0;
}

Class member functions have an implicit/hidden parameter which points to the object (this pointer). These member functions can be invoked only by providing an object, which makes it different from an ordinary function.

std::bind can be used to "convert" a member function into an ordinary function by passing the object (pointer or reference). It has be the first argument in the list of args  (&a or a in this case) following the member function.  In the new function, the object is bound to the implicit/hidden parameter of the member function, and need not be passed when invoked. The unbound arguments are represented by the placeholders _1, _2 and have to be passed when invoked.


问:
Filtering empty partitions in RDD
Is there a way to filter empty partitions in RDD? I have some empty partitions after partitioning and I can't use them in action method.

I use Apache Spark in Scala

答:
From the little info you provide, I can think about two options. Use mapPartitions and just catching empty iterators and returning them, while working on the non-empty ones.

rdd.mapPartitions { case iter => if(iter.isEmpty) { iter } else { ??? } }
```

<p>Or you can use <code>repartition</code>, to get rid of the empty partitions.</p>

<pre class="lang-scala prettyprint-override"><code>rdd.repartition(10) // or any proper number
</code>```

Title: Filtering empty partitions in RDD

Body:
From the little info you provide, I can think about two options. Use mapPartitions and just catching empty iterators and returning them, while working on the non-empty ones.

rdd.mapPartitions { case iter => if(iter.isEmpty) { iter } else { ??? } }

Or you can use repartition, to get rid of the empty partitions.

rdd.repartition(10) // or any proper number


问:
Flutter clip without space around the clipped widget
I want to clip a widget and use this clipped image in a layout and the bounderies should be the visible part of the imgage when clipped.

Using this custom clipper

```<code>  @override
  Rect getClip(Size size) {
    Rect rect = Rect.fromLTRB(25,0,size.width - 25, size.height);
    return rect;
  }
  @override
  bool shouldReclip(CustomRect oldClipper) {
    return true;
  }
}
</code>```

results in 25 px blank space left of the clipped image and 25 px blank space right of the clipped image.

And at least we ant to copy specific areas of an image and scale/position it exactly in the app... -> more complex desired result:

答:
Okay, the solution above is not really working as if we translate the clipped image we get some free space (the amount that we translate).

Isn't there any option in Flutter to just define an area of an widget and get this area as a new Widget/Image with exactly the width and height of the defined area to be able to position it (without any paddings/white space around),to scale it, ...?

Body:
I want to clip a widget and use this clipped image in a layout and the bounderies should be the visible part of the imgage when clipped.

Using this custom clipper

  @override
  Rect getClip(Size size) {
    Rect rect = Rect.fromLTRB(25,0,size.width - 25, size.height);
    return rect;
  }
  @override
  bool shouldReclip(CustomRect oldClipper) {
    return true;
  }
}

results in 25 px blank space left of the clipped image and 25 px blank space right of the clipped image.

And at least we ant to copy specific areas of an image and scale/position it exactly in the app... -> more complex desired result:


问:
Webscraping of product prices and specs
I'm new to the VBA world and i was trying to create a Excel file to get the cheapest price and name tag on a website. I've created one file that goes through the whole search list and gathers each product URL and places on a spreadsheet. My challenge now is in making this second code work. It starts out getting the information without any issues but then, after 10 or more URLs the macro gives a bug and it starts repeating the information on all the following cells.. Is there a way i can make the code run slower so it doesn't get into this problem?

I'll list here my code and a sample of the URLs im scraping..

here's the code i've been using:

```<code>Sub test()
Dim URL As String

Set ie = CreateObject("internetexplorer.application")

For i = 2 To 300

URL = Cells(i, 1).Value

ie.navigate URL
ie.Visible = False

Do While ie.busy And ie.readystate <> "readystate_complete"
DoEvents
Loop

Cells(i, 3) = ie.document.getElementsByTagName("h1")(0).innerText
Cells(i, 4) = ie.document.getElementsByTagName("strong")(0).innerText
Next i

ie.Quit

MsgBox "acabou"

End Sub
</code>```

<https://www.zoom.com.br/notebook/notebook-vaio-vjf157f11x-b0211s-intel-core-i5-8250u-15-6-8gb-ssd-256-gb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-samsung-chromebook-plus-intel-celeron-3965y-12-2-4gb-emmc-32-gb-chrome-os-touchscreen>
<https://www.zoom.com.br/notebook/notebook-dell-xps-7390-intel-core-i7-10710u-13-3-16gb-ssd-512-gb-windows-10-touchscreen>
<https://www.zoom.com.br/notebook/notebook-dell-i15-3583-a5-intel-core-i7-8565u-15-6-8gb-hd-2-tb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-lenovo-b330-intel-core-i5-8250u-15-6-4gb-hd-1-tb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-dell-i15-7580-a20-intel-core-i7-8550u-15-6-8gb-hd-1-tb-geforce-mx150-windows-10>
<https://www.zoom.com.br/notebook/notebook-dell-i14-3480-u30-intel-core-i5-8265u-14-4gb-hd-1-tb-linux-8-geracao>
<https://www.zoom.com.br/notebook/macbook-pro-apple-muhn2bz-intel-core-i5-13-3-8gb-ssd-128-gb-tela-de-retina>
<https://www.zoom.com.br/notebook/notebook-multilaser-pc150-amd-a4-9120-14-2gb-emmc-32-gb-windows-10>
<https://www.zoom.com.br/notebook/notebook-samsung-np930qaa-kw1br-intel-core-i7-8550u-13-3-8gb-ssd-256-gb-windows-10-touchscreen>
<https://www.zoom.com.br/notebook/notebook-acer-a515-51g-58vh-intel-core-i5-7200u-15-6-8gb-hd-1-tb-geforce-940mx>
<https://www.zoom.com.br/notebook/notebook-multilaser-pc222-intel-celeron-dual-core-13-3-4gb-emmc-64-gb-windows-10>
<https://www.zoom.com.br/notebook/notebook-acer-pt515-51-788a-intel-core-i7-9750h-15-6-32gb-ssd-1-tb-geforce-rtx-2070-windows-10>
<https://www.zoom.com.br/notebook/notebook-acer-a315-53-53ak-intel-core-i5-7200u-15-6-4gb-hd-1-tb-windows-10-7-geracao>
<https://www.zoom.com.br/notebook/notebook-dell-i15-5584-m40-intel-core-i7-8565u-15-6-8gb-hd-2-tb-geforce-mx130-windows-10>
<https://www.zoom.com.br/notebook/notebook-acer-a315-41g-r21b-amd-ryzen-5-2500u-15-6-8gb-hd-1-tb-radeon-535-windows-10>
<https://www.zoom.com.br/notebook/notebook-positivo-master-n2140-intel-core-i3-7020u-14-4gb-hd-500-gb-windows-10-7-geracao>
<https://www.zoom.com.br/notebook/notebook-multilaser-pc101-intel-atom-14-1gb-ssd-32-gb-windows-10>
<https://www.zoom.com.br/notebook/notebook-lenovo-b330-intel-core-i5-8250u-15-6-8gb-hd-1-tb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-acer-an515-51-77fh-intel-core-i7-7700hq-15-6-8gb-hd-1-tb-geforce-gtx-1050-windows-10>
<https://www.zoom.com.br/notebook/notebook-dell-i15-3583-a2yp-intel-core-i5-8265u-15-6-4gb-optane-16-gb-hd-1-tb-windows-10>
<https://www.zoom.com.br/notebook/notebook-asus-g531gt-intel-core-i7-9750h-15-6-16gb-ssd-512-gb-geforce-gtx-1650-windows-10>
<https://www.zoom.com.br/notebook/notebook-vaio-fit-15s-intel-core-i3-7100u-15-6-4gb-hd-1-tb-windows-10-home>
<https://www.zoom.com.br/notebook/notebook-samsung-s50-intel-core-i7-7500u-13-3-8gb-ssd-256-gb-windows-10-style>
<https://www.zoom.com.br/notebook/notebook-lenovo-b330-intel-core-i3-7020u-15-6-4gb-ssd-120-gb-windows-10-7-geracao>```

答:
Try this</p>

```<code>Sub GetPrices()
    Dim html As MSHTML.HTMLDocument, r As Long
    For r = 1 To 4
        Set html = GetHTML(Cells(r, 1).Value)
        Cells(r, 3).Value = html.querySelector("h1.product-name").innerText
        Cells(r, 4).Value = Replace(Replace(html.querySelector(".product-price").innerText, "a partir de  ", vbNullString), ":( ", "")
        Set html = Nothing
    Next r
End Sub

Function GetHTML(ByVal sURL As String) As HTMLDocument
    Dim http As MSXML2.XMLHTTP60, html As MSHTML.HTMLDocument
    Set http = New MSXML2.XMLHTTP60
    Set html = New MSHTML.HTMLDocument
    With http
        .Open "Get", sURL, False
        .send
        html.body.innerHTML = .responseText
    End With
    Set GetHTML = html
End Function
</code>```

Title: Webscraping of product prices and specs

Body:
I'm new to the VBA world and i was trying to create a Excel file to get the cheapest price and name tag on a website. I've created one file that goes through the whole search list and gathers each product URL and places on a spreadsheet. My challenge now is in making this second code work. It starts out getting the information without any issues but then, after 10 or more URLs the macro gives a bug and it starts repeating the information on all the following cells.. Is there a way i can make the code run slower so it doesn't get into this problem?

I'll list here my code and a sample of the URLs im scraping..

here's the code i've been using:

Sub test()
Dim URL As String

Set ie = CreateObject("internetexplorer.application")

For i = 2 To 300

URL = Cells(i, 1).Value

ie.navigate URL
ie.Visible = False

Do While ie.busy And ie.readystate <> "readystate_complete"
DoEvents
Loop

Cells(i, 3) = ie.document.getElementsByTagName("h1")(0).innerText
Cells(i, 4) = ie.document.getElementsByTagName("strong")(0).innerText
Next i

ie.Quit

MsgBox "acabou"

End Sub

<https://www.zoom.com.br/notebook/notebook-vaio-vjf157f11x-b0211s-intel-core-i5-8250u-15-6-8gb-ssd-256-gb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-samsung-chromebook-plus-intel-celeron-3965y-12-2-4gb-emmc-32-gb-chrome-os-touchscreen>
<https://www.zoom.com.br/notebook/notebook-dell-xps-7390-intel-core-i7-10710u-13-3-16gb-ssd-512-gb-windows-10-touchscreen>
<https://www.zoom.com.br/notebook/notebook-dell-i15-3583-a5-intel-core-i7-8565u-15-6-8gb-hd-2-tb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-lenovo-b330-intel-core-i5-8250u-15-6-4gb-hd-1-tb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-dell-i15-7580-a20-intel-core-i7-8550u-15-6-8gb-hd-1-tb-geforce-mx150-windows-10>
<https://www.zoom.com.br/notebook/notebook-dell-i14-3480-u30-intel-core-i5-8265u-14-4gb-hd-1-tb-linux-8-geracao>
<https://www.zoom.com.br/notebook/macbook-pro-apple-muhn2bz-intel-core-i5-13-3-8gb-ssd-128-gb-tela-de-retina>
<https://www.zoom.com.br/notebook/notebook-multilaser-pc150-amd-a4-9120-14-2gb-emmc-32-gb-windows-10>
<https://www.zoom.com.br/notebook/notebook-samsung-np930qaa-kw1br-intel-core-i7-8550u-13-3-8gb-ssd-256-gb-windows-10-touchscreen>
<https://www.zoom.com.br/notebook/notebook-acer-a515-51g-58vh-intel-core-i5-7200u-15-6-8gb-hd-1-tb-geforce-940mx>
<https://www.zoom.com.br/notebook/notebook-multilaser-pc222-intel-celeron-dual-core-13-3-4gb-emmc-64-gb-windows-10>
<https://www.zoom.com.br/notebook/notebook-acer-pt515-51-788a-intel-core-i7-9750h-15-6-32gb-ssd-1-tb-geforce-rtx-2070-windows-10>
<https://www.zoom.com.br/notebook/notebook-acer-a315-53-53ak-intel-core-i5-7200u-15-6-4gb-hd-1-tb-windows-10-7-geracao>
<https://www.zoom.com.br/notebook/notebook-dell-i15-5584-m40-intel-core-i7-8565u-15-6-8gb-hd-2-tb-geforce-mx130-windows-10>
<https://www.zoom.com.br/notebook/notebook-acer-a315-41g-r21b-amd-ryzen-5-2500u-15-6-8gb-hd-1-tb-radeon-535-windows-10>
<https://www.zoom.com.br/notebook/notebook-positivo-master-n2140-intel-core-i3-7020u-14-4gb-hd-500-gb-windows-10-7-geracao>
<https://www.zoom.com.br/notebook/notebook-multilaser-pc101-intel-atom-14-1gb-ssd-32-gb-windows-10>
<https://www.zoom.com.br/notebook/notebook-lenovo-b330-intel-core-i5-8250u-15-6-8gb-hd-1-tb-windows-10-8-geracao>
<https://www.zoom.com.br/notebook/notebook-acer-an515-51-77fh-intel-core-i7-7700hq-15-6-8gb-hd-1-tb-geforce-gtx-1050-windows-10>
<https://www.zoom.com.br/notebook/notebook-dell-i15-3583-a2yp-intel-core-i5-8265u-15-6-4gb-optane-16-gb-hd-1-tb-windows-10>
<https://www.zoom.com.br/notebook/notebook-asus-g531gt-intel-core-i7-9750h-15-6-16gb-ssd-512-gb-geforce-gtx-1650-windows-10>
<https://www.zoom.com.br/notebook/notebook-vaio-fit-15s-intel-core-i3-7100u-15-6-4gb-hd-1-tb-windows-10-home>
<https://www.zoom.com.br/notebook/notebook-samsung-s50-intel-core-i7-7500u-13-3-8gb-ssd-256-gb-windows-10-style>
<https://www.zoom.com.br/notebook/notebook-lenovo-b330-intel-core-i3-7020u-15-6-4gb-ssd-120-gb-windows-10-7-geracao>

Body:
Try this

Sub GetPrices()
    Dim html As MSHTML.HTMLDocument, r As Long
    For r = 1 To 4
        Set html = GetHTML(Cells(r, 1).Value)
        Cells(r, 3).Value = html.querySelector("h1.product-name").innerText
        Cells(r, 4).Value = Replace(Replace(html.querySelector(".product-price").innerText, "a partir de  ", vbNullString), ":( ", "")
        Set html = Nothing
    Next r
End Sub

Function GetHTML(ByVal sURL As String) As HTMLDocument
    Dim http As MSXML2.XMLHTTP60, html As MSHTML.HTMLDocument
    Set http = New MSXML2.XMLHTTP60
    Set html = New MSHTML.HTMLDocument
    With http
        .Open "Get", sURL, False
        .send
        html.body.innerHTML = .responseText
    End With
    Set GetHTML = html
End Function


问:
Translate ">" in XML RDF Triple
I have JSON String value > which is a special character in XML.

After the data ingestion, the XML String becomes \u003e.

How can I preserve > in the XML String?

答:
In almost all cases, > is fine as itself in XML.  See Simplified XML Escaping for details.

After the data ingestion, the XML String becomes \u003e.

How can I preserve > in the XML String?

How to preserve a character through a translation depends entirely on the translation.  You've said specified nothing more than "data ingestion".  It can be a challenge to identify and remedy a poor translation of a known program; doing so for an unknown program is impossible.

Your question is unanswerable as it currently stands.

Title: Translate ">" in XML RDF Triple


问:
Flutter Undraw Widget - PictureStream Error after update
I encountered an error after i updated to Flutter 1.17 in the Undraw widget. It was working fine previously.

The code -

```<code>Container(
          height: height * 0.3,
          width: width,
          child: UnDraw(
              width: width,
              color: accentColor,
              illustration: UnDrawIllustration.medicine,
              placeholder: CircularProgressIndicator(),
              errorWidget:
                  Icon(Icons.error_outline, color: Colors.red, size: 50),
            ),
       ),
</code>```

Dependency -   undraw: ^1.0.2

The Error I encountered -

```<code>abstract class PictureStreamCompleter extends Diagnosticable {

           ^
</code>```

Compiler message:

```<code>/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_svg-0.13.1/lib/src/picture_stream.dart:92:3: Error: The superclass, 'Diagnosticable', has no unnamed constructor that takes no arguments.
  PictureStream();
  ^^^^^^^^^^^^^
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_svg-0.13.1/lib/src/picture_stream.dart:192:16: Error: The superclass, 'Diagnosticable', has no unnamed constructor that takes no arguments.
abstract class PictureStreamCompleter extends Diagnosticable {
           ^
</code>```

Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
build failed.

FAILURE: Build failed with an exception.

Where:
Script 'C:\src\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 882

What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.

Process 'command 'C:\src\flutter\bin\flutter.bat'' finished with non-zero exit value 1

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

Here is the result of flutter doctor -

```<code>Doctor summary (to see all details, run flutter doctor -v):
</code>```

* [√] Flutter (Channel stable, v1.17.0, on Microsoft Windows [Version 10.0.18363.778], locale en-US)

[√] Android toolchain - develop for Android devices (Android SDK version 29.0.2)

[√] Android Studio (version 3.5)

[√] VS Code (version 1.44.2)

[√] Connected device (1 available)

• No issues found!

答: Downgrade undraw to ^1.0.1 instead of ^1.0.2 and you can add flutter_svg: ^0.17.4, if you have upgraded your flutter to  Flutter (Channel stable, v1.17.1, on Mac OS X 10.14.6 18G2022, locale en-ZA). Hope this help</p>

Body:
I encountered an error after i updated to Flutter 1.17 in the Undraw widget. It was working fine previously.

The code -

Container(
          height: height * 0.3,
          width: width,
          child: UnDraw(
              width: width,
              color: accentColor,
              illustration: UnDrawIllustration.medicine,
              placeholder: CircularProgressIndicator(),
              errorWidget:
                  Icon(Icons.error_outline, color: Colors.red, size: 50),
            ),
       ),

Dependency -   undraw: ^1.0.2

The Error I encountered -

abstract class PictureStreamCompleter extends Diagnosticable {

           ^

Compiler message:

/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_svg-0.13.1/lib/src/picture_stream.dart:92:3: Error: The superclass, 'Diagnosticable', has no unnamed constructor that takes no arguments.
  PictureStream();
  ^^^^^^^^^^^^^
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_svg-0.13.1/lib/src/picture_stream.dart:192:16: Error: The superclass, 'Diagnosticable', has no unnamed constructor that takes no arguments.
abstract class PictureStreamCompleter extends Diagnosticable {
           ^

Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
build failed.

FAILURE: Build failed with an exception.

Where:
Script 'C:\src\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 882

What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.

Process 'command 'C:\src\flutter\bin\flutter.bat'' finished with non-zero exit value 1

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

Here is the result of flutter doctor -

Doctor summary (to see all details, run flutter doctor -v):

* [√] Flutter (Channel stable, v1.17.0, on Microsoft Windows [Version 10.0.18363.778], locale en-US)

[√] Android toolchain - develop for Android devices (Android SDK version 29.0.2)

[√] Android Studio (version 3.5)

[√] VS Code (version 1.44.2)

[√] Connected device (1 available)

• No issues found!


问:
Is there a way to check nested option values in one pattern in F#?
Let's pretend we have the following types:

```<code>type Message {
    text : Option<string>
}

type Update {
    msg : Option<Message>
}
</code>```

How do I match it in one line, like in C# using null-conditional operator i.e update?.msg?.text ?

Is there a way to do it like this?:

```<code>match msg, msg.text with
| Some msg, Some txt -> ...
| None -> ...
</code>```

because I don't want to be writing 2 nested match expressions.

答:
You have two Record types (missing the "=" in your example). To match some variable of Update type, you could do as follows:</p>

```<code>type Message = { text : Option<string> }

type Update = { msg : Option<Message> }

let u = {msg = Some({text = Some "text"})}

//all 3 possible cases
match u with
| {msg = Some({text = Some t})} -> t
| {msg = Some({text = None})} -> ""
| {msg = None} -> ""
</code>```

Body:
Let's pretend we have the following types:

type Message {
    text : Option<string>
}

type Update {
    msg : Option<Message>
}

How do I match it in one line, like in C# using null-conditional operator i.e update?.msg?.text ?

Is there a way to do it like this?:

match msg, msg.text with
| Some msg, Some txt -> ...
| None -> ...

because I don't want to be writing 2 nested match expressions.

Body:
You have two Record types (missing the "=" in your example). To match some variable of Update type, you could do as follows:

type Message = { text : Option<string> }

type Update = { msg : Option<Message> }

let u = {msg = Some({text = Some "text"})}

//all 3 possible cases
match u with
| {msg = Some({text = Some t})} -> t
| {msg = Some({text = None})} -> ""
| {msg = None} -> ""