问:
QuickFIX C++ library - general question regarding ThreadedSocketInitiator
I am new to QuickFIX and I have some basic question regarding QuickFix:

1)
Considering that at one time, there will be only one fix session between an acceptor and an initiator. I do not quite understand the purpose of ThreadedSocketInitiator and ThreadedSocketAcceptor classes.

Or do these classes exist to facilitate multiple sessions, in which multiple "initiators" can talk to different acceptors and vice versa?

2) Does QuickFIX has some kinds of message persistence, for example, what happens if the message is lost in transit? Does the engine takes care of resending the message?

答:
1) Quickfix uses 1 thread per session. Engine you can assume is the whole process.

ThreadedSocketInitiator is used when you want to use the engine as a client. You connect to another server and transmit messages. You initiate connections, hence the name initiator. You spawn a new thread for each session you set up with a server.

ThreadedSocketAcceptor is used when you want to use the engine as a server. You accept connections hence acceptor. When you set up a new session with a client a new thread is spawned for that specific session only.

Remember all sessions have a unique id to differentiate between multiple sessions. A server can have multiple sessions with the same client and vice versa.

2) Yes. But the receiver has to initiate a ResendRequest message to make the sender to send again. It will do it automatically by checking the latency flag in the config file, if it hasn't received a reply to an already sent message.


来源: stackexchange

问:
Python - How to filter out files that contain char at specific index?
I would like to filter out all files that doesn't contain "-" at index 82.

Sorry, real new to programming in general, any help is appreciated.

答:
```<code>[fname for fname in list_of_filenames if fname[82:83] == '-']
</code>```

will filter out any filenames in a list that dont contain '-' at index 82 ...

(but i think you want fname[83:84] since arrays are zero based... and presumably your text editor columns start at 1)

ContentLicense: CC BY-SA 4.0

Body:
[fname for fname in list_of_filenames if fname[82:83] == '-']

will filter out any filenames in a list that dont contain '-' at index 82 ...

(but i think you want fname[83:84] since arrays are zero based... and presumably your text editor columns start at 1)


问:
Kotlin Multiplatform Compose + Desktop + Web + Mobile
Is it possible at the moment to have a kotlin multiplatform project using compose for sharing the ui code for desktop, web, and mobile at the same time? All the examples i found only cover multiplatform with JS Front + Jvm Backend, or JVM Android + Desktop + Common Module, and I'm having trouble setting a project with all those at the same time.

I tried doing:

plugins {
    kotlin("multiplatform")
    id("org.jetbrains.compose") version "1.0.1-rc2"
    id("com.android.library")
}
kotlin {
    android()
    jvm("desktop") {
       ...
    }
    js{
       ...
    }
    sourceSets {
        val commonMain by getting {
            dependencies {
               ...
            }
        }
        val commonTest by getting {
            dependencies {
               ...
            }
        }
        val androidMain by getting {
            dependencies {
                ...
            }
        }
        val androidTest by getting {
            dependencies {
                ...
            }
        }
        val desktopMain by getting {
            dependencies {
                ...
            }
        }
        val desktopTest by getting
        val jsMain by getting{
            dependencies{
                ...
            }
        }
        val jsTest by getting {
            dependencies {
                ...
            }
        }
    }
}
```
<p>But it produces the error:</p>
```:common:jsMain: Could not resolve org.jetbrains.compose.runtime:runtime:1.0.1-rc2.
Required by:
    project :common
```

If i comment the JS related sections it works, or if i comment all the non-js related stuff it also works

Commenting everything compose-related also works

The problem is only when combining everything

答:
The short answer is: No, this is not possible at this time.

The JB team is working on such support, which can be tested in these examples, but for now it is experimental and there is no guarantee that it will be released any time soon. Compose JB version is now synced with Android Compose, so I expect that 1.2.0 will be released around the same time by both of them, even if Web support is not yet complete.

I have not been able to reproduce your error, but I assume that you have not removed compose.foundation and compose.material from the common dependencies.

At the moment, only compose.runtime is available for the common module, and this makes it almost impossible to do any layout at this point: even Button and Text are not available.

As you can see in the JS application example, Text is not imported from androidx.compose.material.Text, but from org.jetbrains.compose.web.dom.Text, which is a completely different element, so it cannot be used in a common module.

At this point, I would say that Compose JS is another framework that allows you to write UI in Compose style.

Body:
Is it possible at the moment to have a kotlin multiplatform project using compose for sharing the ui code for desktop, web, and mobile at the same time? All the examples i found only cover multiplatform with JS Front + Jvm Backend, or JVM Android + Desktop + Common Module, and I'm having trouble setting a project with all those at the same time.

I tried doing:

plugins {
    kotlin("multiplatform")
    id("org.jetbrains.compose") version "1.0.1-rc2"
    id("com.android.library")
}
kotlin {
    android()
    jvm("desktop") {
       ...
    }
    js{
       ...
    }
    sourceSets {
        val commonMain by getting {
            dependencies {
               ...
            }
        }
        val commonTest by getting {
            dependencies {
               ...
            }
        }
        val androidMain by getting {
            dependencies {
                ...
            }
        }
        val androidTest by getting {
            dependencies {
                ...
            }
        }
        val desktopMain by getting {
            dependencies {
                ...
            }
        }
        val desktopTest by getting
        val jsMain by getting{
            dependencies{
                ...
            }
        }
        val jsTest by getting {
            dependencies {
                ...
            }
        }
    }
}

But it produces the error:

:common:jsMain: Could not resolve org.jetbrains.compose.runtime:runtime:1.0.1-rc2.
Required by:
    project :common

If i comment the JS related sections it works, or if i comment all the non-js related stuff it also works

Commenting everything compose-related also works

The problem is only when combining everything


问:
Coarse and fine grid
Please see below the code and guide me.

I want to create coarse and fine mesh. For 1st set of loop and given limits, result is 5*3 matrix (coarse mesh).  For the 2nd set of loop and given limits, result is 5*3 matrix.  However, I want to convert the 2nd result in 10*6 matrix without changing the limit (if (i >= 0 && i < 5  && j >= 2 && j <5)).

Code is as follows:

```<code>#define NX 5
#define NY 5

using namespace std;

int main()
{
    for (int i = 0; i < NX; i++)
    {
        for (int j = 0; j < NY; j++)
        {
        if (i >= 0 && i < 5  && j >= 0 && j <3)
            {
            int count =i* NY+ j;
            cout << count << " ";
            }
        }
    }

    for (int i = 0; i < NX; i++)
    {
        for (int j = 0; j < NY; j++)
        {
        if (i >= 0 && i < 5  && j >= 2 && j <5)
            {
            int count =i* NY+ j;
            cout << count << " ";
            }
        }
    }
}
</code>```

first set of loop,  result is

```
0 1 2
5 6 7
10 11 12
15 16 17
20 21 22
```

2nd set of loop, result is

```
2 3 4
7 8 9
12 13 14
17 18 19
22 23 24
```

I want the 2nd loop result to be 10*6 matrix to generate fine mesh.

答: I solved this problem by creating seperate variables for both loops. then I communicated between these variables to create coarse and fine mesh.</p>

Title: Coarse and fine grid

Body:
Please see below the code and guide me.

I want to create coarse and fine mesh. For 1st set of loop and given limits, result is 5*3 matrix (coarse mesh).  For the 2nd set of loop and given limits, result is 5*3 matrix.  However, I want to convert the 2nd result in 10*6 matrix without changing the limit (if (i >= 0 && i < 5  && j >= 2 && j <5)).

Code is as follows:

#define NX 5
#define NY 5

using namespace std;

int main()
{
    for (int i = 0; i < NX; i++)
    {
        for (int j = 0; j < NY; j++)
        {
        if (i >= 0 && i < 5  && j >= 0 && j <3)
            {
            int count =i* NY+ j;
            cout << count << " ";
            }
        }
    }

    for (int i = 0; i < NX; i++)
    {
        for (int j = 0; j < NY; j++)
        {
        if (i >= 0 && i < 5  && j >= 2 && j <5)
            {
            int count =i* NY+ j;
            cout << count << " ";
            }
        }
    }
}

first set of loop,  result is

0 1 2
5 6 7
10 11 12
15 16 17
20 21 22

2nd set of loop, result is

2 3 4
7 8 9
12 13 14
17 18 19
22 23 24

I want the 2nd loop result to be 10*6 matrix to generate fine mesh.


问:
preloading font with rel preload
I am preloading a font using the <link> HTML tag with the rel attribute set to preload as captured in the snippet below;

```<code><link rel="preload" href="fonts/32ADEO.woff2" as="font" type="font/woff2">
</code>```

While this works as expected by loading the typeface, it gets loaded again.

The screenshot of the network tab in Google Chrome browser shows the typeface loading twice - see below;

Also, I get the following warning in the Google Chrome browser console tab;

The resource https://example.com/new-v8/fonts/32A0E0.woff2 was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it Please make sure it has an appropriate 'as' value and it is preloaded intentionally.

What am I doing wrong and how can I fix it?

答:
I ran into this issue with a self hosted font. I was preloading it like this:

<link rel="preload" href="/fonts/SomeFont.woff2" as="font" type="font/woff2" crossorigin>
```
<p>The problem was that webpack was adding a hash to the compiled css font path.</p>
<pre class="lang-css prettyprint-override"><code>/* Before */
@font-face {
    font-family: "SomeFont";
    src: url("../fonts/SomeFont.woff2") format("woff2");
}

/* After (Webpack Output) */
@font-face {
    font-family: "SomeFont";
    src: url("../fonts/SomeFont.woff2?7d18a001dd0b6e04c2393") format("woff2");
}
</code>```

So I added the same hash to the preload tag and problem solved!

<link rel="preload" href="/fonts/SomeFont.woff2?7d18a001dd0b6e04c2393" as="font" type="font/woff2" crossorigin>
```

Title: preloading font with rel preload

Body:
I am preloading a font using the <link> HTML tag with the rel attribute set to preload as captured in the snippet below;

<link rel="preload" href="fonts/32ADEO.woff2" as="font" type="font/woff2">

While this works as expected by loading the typeface, it gets loaded again.

The screenshot of the network tab in Google Chrome browser shows the typeface loading twice - see below;

Also, I get the following warning in the Google Chrome browser console tab;

The resource https://example.com/new-v8/fonts/32A0E0.woff2 was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it Please make sure it has an appropriate 'as' value and it is preloaded intentionally.

What am I doing wrong and how can I fix it?

Body:
I ran into this issue with a self hosted font. I was preloading it like this:

<link rel="preload" href="/fonts/SomeFont.woff2" as="font" type="font/woff2" crossorigin>

The problem was that webpack was adding a hash to the compiled css font path.

/* Before */
@font-face {
    font-family: "SomeFont";
    src: url("../fonts/SomeFont.woff2") format("woff2");
}

/* After (Webpack Output) */
@font-face {
    font-family: "SomeFont";
    src: url("../fonts/SomeFont.woff2?7d18a001dd0b6e04c2393") format("woff2");
}

So I added the same hash to the preload tag and problem solved!

<link rel="preload" href="/fonts/SomeFont.woff2?7d18a001dd0b6e04c2393" as="font" type="font/woff2" crossorigin>


问:
how to just access the count of products through another model which are connected by foreign key
```<code>class Category(models.Model):
    category_name = models.CharField(max_length=50, unique=True)

class Product(models.Model):
    category        = models.ForeignKey(Category, on_delete=models.CASCADE)
    product_name    = models.CharField(max_length=200, unique=True)
    slug            = models.SlugField(max_length=200, unique=True)
</code>```

Here what i want is just the number of the product present in each category just the number of product i know i have can fire somequery

```<code>cat = Category.objects.all()
</code>```

run loop for cat

```<code>prod_cat = Product.object.filter(category=cat)
</code>```

But i belive its not the efficient way to achive this

答:
Full examples and understanding here:
https://able.bio/dfernsby/django-queryset-annotations-with-conditions--19d4cb4b</p>

Body:
class Category(models.Model):
    category_name = models.CharField(max_length=50, unique=True)

class Product(models.Model):
    category        = models.ForeignKey(Category, on_delete=models.CASCADE)
    product_name    = models.CharField(max_length=200, unique=True)
    slug            = models.SlugField(max_length=200, unique=True)

Here what i want is just the number of the product present in each category just the number of product i know i have can fire somequery

cat = Category.objects.all()

run loop for cat

prod_cat = Product.object.filter(category=cat)

But i belive its not the efficient way to achive this


问:
Obtaining the Index Number of a Drop-Down List
In short, I am trying to get the index number of a drop-down list through VBA. In this case, the drop-down list is created via data validation.

Long story, I have created a simple worksheet that contains a few drop-down lists that were made through data validation, which contains strings only.

Depending on the user selection, I would like to then perform some tasks depending on the selected option. Instead of inputting the entire string into a select case or an if-else then statement, getting the index number of the selected option of that particular drop-down list would be a much more efficient way of doing it.

I am aware of the ListIndex property which function fits my exact requirement, but as far as I'm aware, it is only applicable to listbox and combobox.

I am also aware of another similar question raised:
Get position (in number) of selected item in dropdown list.
This solution however does not work for me and results in a returned value of "0" in most cases when selecting options other than the first item in the drop down list. From my shallow understanding in VBA, it seems to only function as expected when there are no repeating words between the various drop-down options.

I would also greatly appreciate it if anyone could elaborate on the solution code as I would like to understand what exactly is going on and grow my knowledge on VBA programming.

答:
This works fine for me - similar to Doug's answer at your linked post.

Sub tester()

    Debug.Print SelectedListIndex([F1])

End Sub

'If `c` has a list-based validation (from direct entry, not a range reference)
'  and a value has been selected, return the index of the value in the list
Function SelectedListIndex(c As Range)
    Dim arr, m, v
    m = -1
    v = c.Value
    If Len(v) > 0 Then
        If Not c.Validation Is Nothing Then
            If c.Validation.Type = xlValidateList Then
                arr = Split(c.Validation.Formula1, _
                            Application.International(xlListSeparator))
                m = Application.Match(c.Value, arr, 0)
            End If
        End If
    End If
    SelectedListIndex = IIf(IsError(m), -1, m)
End Function
```


问:
How to know mysql Error in zend
I have following query in my project,

```<code>$values = array("test"=>"value")
$this->_db->update("tablename",$values,array('id = ?'=> $data['id'],'wid = ?'=> $data['WId']));
</code>```

If i execute first time i got updated with values, if i did second time, Sql error will be something like "0 rows affected" . So here I need to know that exception in zend framwork. Kindly help me

答:
```<code>Zend_Db_Adapter_Abstract.update(mixed $table, array $bind, mixed $where)
Updates table rows with specified data based on a WHERE clause.

Parameters:
mixed $table The table to update.
array $bind Column-value pairs.
mixed $where UPDATE WHERE clause(s).

Returns:
int The number of affected rows.

Throws:
Zend_Db_Adapter_Exception
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to know mysql Error in zend

Body:
I have following query in my project,

$values = array("test"=>"value")
$this->_db->update("tablename",$values,array('id = ?'=> $data['id'],'wid = ?'=> $data['WId']));

If i execute first time i got updated with values, if i did second time, Sql error will be something like "0 rows affected" . So here I need to know that exception in zend framwork. Kindly help me


问:
RDS Accessible but fails password auth when not in VPC
I'm unable to connect to my RDS instance from my local computer despite following the documentation. The problem is, I can connect from an ec2 instance in the VPC, but when using the same credentials on my local machine I get "incorrect password".

What I've tried:

I've configured RDS for public access, followed the troubleshooting documentation here: RDS Troubleshooting
Additionally:

Confirm RDS is publicly accessible √

Confirm Subnet ACL allows postgres traffic √

Connect internet gateway to VPC √

Associate public subnets with public route tables √

Enable VPC dns resolution √

Enable incoming postgres traffic from 0.0.0.0/0 in security group √

I was even able to test connectivity locally and confirm that I am in fact able to connect to the RDS instance using the below command on my local computer:

nc -zv <rds.dns> <port>

which returns:

xxx.xxx.us-east-2.rds.amazonaws.com [ip.address] 5432 (postgresql) open

This signals to me that my computer has network access to the RDS instance, and yet, when I try to login using the PSQL command:

```<code>sudo psql \
   --host=xxx.xxx.us-east-2.rds.amazonaws.com \
   --port=5432 \
   --username=<dbuser> \
   --password \
   --dbname=<dbname>
</code>```

I am then prompted for my password, which I get:

```<code>...
Password:
sudo: 3 incorrect password attempts
</code>```

The weird part is this password works fine from within an ec2 instance inside the VPC, so I'm completely at a loss as to why the password auth is failing from my psql client on my local computer.

Any help, documentation or references would be appreciated, thanks in advance.

答:
Turns out the issue was in the command

```<code>sudo psql \
   --host=xxx.xxx.us-east-2.rds.amazonaws.com \
   --port=5432 \
   --username=<dbuser> \
   --password \
   --dbname=<dbname>
</code>```

As @jjanes pointed out, the error was using 'sudo' for this command.

```<code>psql \
   --host=xxx.xxx.us-east-2.rds.amazonaws.com \
   --port=5432 \
   --username=<dbuser> \
   --password \
   --dbname=<dbname>
</code>```

With the above configuration in the VPC worked as expected.

Body:
I'm unable to connect to my RDS instance from my local computer despite following the documentation. The problem is, I can connect from an ec2 instance in the VPC, but when using the same credentials on my local machine I get "incorrect password".

What I've tried:

I've configured RDS for public access, followed the troubleshooting documentation here: RDS Troubleshooting
Additionally:

Confirm RDS is publicly accessible √

Confirm Subnet ACL allows postgres traffic √

Connect internet gateway to VPC √

Associate public subnets with public route tables √

Enable VPC dns resolution √

Enable incoming postgres traffic from 0.0.0.0/0 in security group √

I was even able to test connectivity locally and confirm that I am in fact able to connect to the RDS instance using the below command on my local computer:

nc -zv <rds.dns> <port>

which returns:

xxx.xxx.us-east-2.rds.amazonaws.com [ip.address] 5432 (postgresql) open

This signals to me that my computer has network access to the RDS instance, and yet, when I try to login using the PSQL command:

sudo psql \
   --host=xxx.xxx.us-east-2.rds.amazonaws.com \
   --port=5432 \
   --username=<dbuser> \
   --password \
   --dbname=<dbname>

I am then prompted for my password, which I get:

...
Password:
sudo: 3 incorrect password attempts

The weird part is this password works fine from within an ec2 instance inside the VPC, so I'm completely at a loss as to why the password auth is failing from my psql client on my local computer.

Any help, documentation or references would be appreciated, thanks in advance.

Body:
Turns out the issue was in the command

sudo psql \
   --host=xxx.xxx.us-east-2.rds.amazonaws.com \
   --port=5432 \
   --username=<dbuser> \
   --password \
   --dbname=<dbname>

As @jjanes pointed out, the error was using 'sudo' for this command.

psql \
   --host=xxx.xxx.us-east-2.rds.amazonaws.com \
   --port=5432 \
   --username=<dbuser> \
   --password \
   --dbname=<dbname>

With the above configuration in the VPC worked as expected.


问:
How do you use fetch api to an ec2 instance?
I've been trying to find a good free server for our school project so I've decided to try ec2 and just make my pc the server that I will use. I've managed to install my node server onto the ec2. I can post requests using postman but when I'm trying to fetch data from my html file to the ec2 instance, it says:

Fetch API cannot load ec2xxxxxx.amazonaws.com:3000/login. URL scheme "ecxxxxxxx.compute-1.amazonaws.com" is not supported.

Is there any workaround for this? Thanks in advance!!!

答:
Follow these steps:

Make sure your application is listening on port 3000: netstat -anp |
grep 3000 also telnet 127.0.0.1 3000

Then make sure that local firewall is configured to allow incoming access to port 3000 OR  disable local firewall to do a quick test (service iptables stop). for linux, its usually iptables

Allow incoming access to port 3000 in your AWS security group.


问:
Non nullable instance field must be initalised
im new to Dart-flutter.

i have watching a tutorial video from udemy course writing in dart pad

so i also wrote in dartpad. but it showing error in it.

this is the code wrote in udemy..

```<code>import 'dart:convert';

 void main(){
  var rawJson = '{"url": "https://helo.com","id": 2}';
  var parsedJson = json.decode(rawJson);
  var imageModel = new ImageModel.fromJson(parsedJson);

  print(imageModel.url);
 }

class ImageModel{
  int id;
  String url;

  ImageModel.fromJson(parsedJson) {
    id = parsedJson['id'];
    url = parsedJson['url'];
  }

   ImageModel(this.id, this.url);
}
</code>```

in that video it runs, but for me it shows error as

```<code>Error compiling to JavaScript:
Info: Compiling with sound null safety
Warning: Interpreting this as package URI, 'package:dartpad_sample/main.dart'.
lib/main.dart:15:3:
Error: This constructor should initialize field 'id' because its type 'int' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:12:7:
Info: 'id' is defined here.
  int id;
      ^^
lib/main.dart:15:3:
Error: This constructor should initialize field 'url' because its type 'String' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:13:10:
Info: 'url' is defined here.
  String url;
         ^^^
Error: Compilation failed.
</code>```

i have no idea what the problem is..
can you guys help me to troubleshoot the error

答:
You will try like this

```<code>import 'dart:convert';
 class ImageModel{
  final int id;
  final String url;

  ImageModel({required this.id, required this.url});

 factory ImageModel.fromJson(Map<String, dynamic> parsedJson) {
  return ImageModel(
    id: parsedJson['id'] as int,
     url: parsedJson['url'] as String,
    );
   }
  }

 void main() {
   var rawJson = '{"url": "https://helo.com","id": 2}';
   var parsedJson = json.decode(rawJson);

   print(parsedJson['url']);
   print(parsedJson['id']);
 }
</code>```

Body:
im new to Dart-flutter.

i have watching a tutorial video from udemy course writing in dart pad

so i also wrote in dartpad. but it showing error in it.

this is the code wrote in udemy..

import 'dart:convert';

 void main(){
  var rawJson = '{"url": "https://helo.com","id": 2}';
  var parsedJson = json.decode(rawJson);
  var imageModel = new ImageModel.fromJson(parsedJson);

  print(imageModel.url);
 }

class ImageModel{
  int id;
  String url;

  ImageModel.fromJson(parsedJson) {
    id = parsedJson['id'];
    url = parsedJson['url'];
  }

   ImageModel(this.id, this.url);
}

in that video it runs, but for me it shows error as

Error compiling to JavaScript:
Info: Compiling with sound null safety
Warning: Interpreting this as package URI, 'package:dartpad_sample/main.dart'.
lib/main.dart:15:3:
Error: This constructor should initialize field 'id' because its type 'int' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:12:7:
Info: 'id' is defined here.
  int id;
      ^^
lib/main.dart:15:3:
Error: This constructor should initialize field 'url' because its type 'String' doesn't allow null.
  ImageModel.fromJson(parsedJson) {
  ^
lib/main.dart:13:10:
Info: 'url' is defined here.
  String url;
         ^^^
Error: Compilation failed.

i have no idea what the problem is..
can you guys help me to troubleshoot the error

Body:
You will try like this

import 'dart:convert';
 class ImageModel{
  final int id;
  final String url;

  ImageModel({required this.id, required this.url});

 factory ImageModel.fromJson(Map<String, dynamic> parsedJson) {
  return ImageModel(
    id: parsedJson['id'] as int,
     url: parsedJson['url'] as String,
    );
   }
  }

 void main() {
   var rawJson = '{"url": "https://helo.com","id": 2}';
   var parsedJson = json.decode(rawJson);

   print(parsedJson['url']);
   print(parsedJson['id']);
 }


问:
Eclipse Debugger Problem: com.sun.jdi.ObjectCollectedException occurred while retrieving value
I am using the following Eclipse, 2019-03 (March):

```<code>Version: 2019-03 (4.11.0)
Build id: 20190314-1200
</code>```

I'm unable to debug properly because randomly, out of the blue, when click on Variables or Expressions, the window suddenly becomes this:

Please note that I tried playing with this setting, both On and Off, as suggested in some threads, but it didn't help:

Show Method Result After a Step Operation

Any other ideas?

答:
Solved this issue with possible work-around.

Right click on the variable and go to the "Show Logical Structure" field.

Uncheck the "Array" field.

Validate the variable now. Hope this will show the your corresponding results.

Body:
I am using the following Eclipse, 2019-03 (March):

Version: 2019-03 (4.11.0)
Build id: 20190314-1200

I'm unable to debug properly because randomly, out of the blue, when click on Variables or Expressions, the window suddenly becomes this:

Please note that I tried playing with this setting, both On and Off, as suggested in some threads, but it didn't help:

Show Method Result After a Step Operation

Any other ideas?


问:
How to draw with CSS canvas a slideshow frame?
I have 2 slideshows which should look like this. The user will upload the photos via a Wordpress gallery so I can't cut them up to make them transparent (plus I don't really know how). I've already posted a question here on how I may achieve this and one user was kind enough to tell me that I have 2 options: webkit mask and canvas; canvas being the recommended option because of better browser support.

For the past hour I've been searching on the Internet on how to draw with canvas but I've had no luck...

Could you please direct me to a tutorial that's easy to follow or give me some pointers?

Thank you!!

答:
I would recommend MDN's docs on the subject.

There are also some good resources in a similar question.


问:
Wso2: cannot save parameters of DBReport or properties of the Log mediator
Please tell what am I doing wrong?
I add parameters to the sql statement in DB Report Mediator and then click on Update, so that my parameters would've been saved, but when I reopen my DBReport, there is nothing...

After reopening:

Actually I'm creating REST API for the first time, does anyone have examples?
Is it even possible to do that without Integration Studio?
Thanks in advance.

答:
The correct expression should be get-property() [1]. Can you try that.

[1]-https://ei.docs.wso2.com/en/7.0.0/micro-integrator/references/mediators/property-reference/accessing-properties-with-xpath/#get-property-function


问:
How to access a variable from another dart file . Flutter
I am new to Flutter and I need to access a variable from another dart file.I am using showDatePicker to select a date.I need to get that date in another file in which where dob.dart is calling to insert in database.

dob.dart

```<code>class _DateOfBirthState extends State<DateOfBirth> {
  DateTime? dateTime;
  String _text = '';
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(),
        borderRadius: BorderRadius.circular(5),
      ),
      width: double.infinity,
      child: Padding(
        padding: const EdgeInsets.only(left: 8, right: 8),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text('Date Of Birth'),
            Text(_text),
            ElevatedButton(
              onPressed: () async {
                dateTime = await showDatePicker(
                  context: context,
                  initialDate: dateTime ?? DateTime.now(),
                  firstDate: DateTime(1900),
                  lastDate: DateTime.now(),
                );
                setState(() {
                  _text =
                      '${dateTime?.day}/${dateTime?.month}/${dateTime?.year}';
                });
              },
              child: const Text('Date Of Birth'),
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

I need to use value of dateTime in another file addStudents.dart

addstudents.dart

```<code>class _AddStudentsState extends State<AddStudents> {
  final _nameController = TextEditingController();
  final _addressController = TextEditingController();
  final _mobileController = TextEditingController();
  final _emailController = TextEditingController();
  final GlobalKey<FormState> _formkey = GlobalKey<FormState>(); @override
  Widget build(BuildContext context) {
    return Center(
      child: SingleChildScrollView(
        child: Form(
          key: _formkey,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              children: [
                TextFormField(
                  validator: (value) {
                    if (value!.isEmpty) {
                      return 'Enter your name';
                    }
                  },
                  controller: _nameController,
                  decoration: const InputDecoration(
                      labelText: 'Name',
                      hintText: 'Alex',
                      border: OutlineInputBorder()),
                ),
                DateOfBirth(),
                TextFormField(
                  maxLines: 5,
                  keyboardType: TextInputType.multiline,
                  controller: _addressController,
                  decoration: const InputDecoration(
                      labelText: 'Address',
                      hintText:
                          'House 21\nKolachery mukk\nP.O.Kolachery\nKannur\n670601',
                      border: OutlineInputBorder()),
                ),
                TextFormField(
                  maxLength: 10,
                  keyboardType: TextInputType.number,
                  controller: _mobileController,
                  decoration: const InputDecoration(
                    labelText: 'Mobile Number',
                    prefixText: '+91',
                    hintText: '0000000000',
                    border: OutlineInputBorder(),
                  ),
                ),
                TextFormField(
                  keyboardType: TextInputType.emailAddress,
                  controller: _emailController,
                  decoration: const InputDecoration(
                      labelText: 'Email',
                      hintText: 'name@example.com',
                      border: OutlineInputBorder()),
                ),
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    child: const Text('Submit'),
                    onPressed: () async {
                      if (!_formkey.currentState!.validate()) {
                        return;
                      }

                      await DataBaseHelper.instance.addStudent(
                        StudentDetails(
                          name: _nameController.text,
                          dob:
                              // '${dateTime!.day}/${dateTime!.month}/${dateTime!.year}',
                          address: _addressController.text,
                          phone: _mobileController.text,
                          email: _emailController.text,
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

</code>```

答:
Create a constructor onDateSelected so you can get a datetime when you select a date from date-picker.

```<code>class DateOfBirth extends StatefulWidget {
  final Function onDateSelected;

  DateOfBirth({this.onDateSelected});

  @override
  _DateOfBirthState createState() => _DateOfBirthState();
}

class _DateOfBirthState extends State<DateOfBirth> {
  DateTime? dateTime;
  String _text = '';

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
          border: Border.all(), borderRadius: BorderRadius.circular(5)),
      width: double.infinity,
      child: Padding(
        padding: const EdgeInsets.only(left: 8, right: 8),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text('Date Of Birth'),
            Text(_text),
            ElevatedButton(
              onPressed: () async {
                dateTime = await showDatePicker(
                  context: context,
                  initialDate: dateTime ?? DateTime.now(),
                  firstDate: DateTime(1900),
                  lastDate: DateTime.now(),
                );
                widget.onDateSelected(dateTime);
                setState(() {
                  _text =
                      '${dateTime?.day}/${dateTime?.month}/${dateTime?.year}';
                });
              },
              child: const Text('Date Of Birth'),
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

// You can get date like this.

```<code>DateOfBirth(
      onDateSelected: (date) {
        //
      },
    )
</code>```

Body:
I am new to Flutter and I need to access a variable from another dart file.I am using showDatePicker to select a date.I need to get that date in another file in which where dob.dart is calling to insert in database.

dob.dart

class _DateOfBirthState extends State<DateOfBirth> {
  DateTime? dateTime;
  String _text = '';
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(),
        borderRadius: BorderRadius.circular(5),
      ),
      width: double.infinity,
      child: Padding(
        padding: const EdgeInsets.only(left: 8, right: 8),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text('Date Of Birth'),
            Text(_text),
            ElevatedButton(
              onPressed: () async {
                dateTime = await showDatePicker(
                  context: context,
                  initialDate: dateTime ?? DateTime.now(),
                  firstDate: DateTime(1900),
                  lastDate: DateTime.now(),
                );
                setState(() {
                  _text =
                      '${dateTime?.day}/${dateTime?.month}/${dateTime?.year}';
                });
              },
              child: const Text('Date Of Birth'),
            ),
          ],
        ),
      ),
    );
  }
}

I need to use value of dateTime in another file addStudents.dart

addstudents.dart

class _AddStudentsState extends State<AddStudents> {
  final _nameController = TextEditingController();
  final _addressController = TextEditingController();
  final _mobileController = TextEditingController();
  final _emailController = TextEditingController();
  final GlobalKey<FormState> _formkey = GlobalKey<FormState>(); @override
  Widget build(BuildContext context) {
    return Center(
      child: SingleChildScrollView(
        child: Form(
          key: _formkey,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              children: [
                TextFormField(
                  validator: (value) {
                    if (value!.isEmpty) {
                      return 'Enter your name';
                    }
                  },
                  controller: _nameController,
                  decoration: const InputDecoration(
                      labelText: 'Name',
                      hintText: 'Alex',
                      border: OutlineInputBorder()),
                ),
                DateOfBirth(),
                TextFormField(
                  maxLines: 5,
                  keyboardType: TextInputType.multiline,
                  controller: _addressController,
                  decoration: const InputDecoration(
                      labelText: 'Address',
                      hintText:
                          'House 21\nKolachery mukk\nP.O.Kolachery\nKannur\n670601',
                      border: OutlineInputBorder()),
                ),
                TextFormField(
                  maxLength: 10,
                  keyboardType: TextInputType.number,
                  controller: _mobileController,
                  decoration: const InputDecoration(
                    labelText: 'Mobile Number',
                    prefixText: '+91',
                    hintText: '0000000000',
                    border: OutlineInputBorder(),
                  ),
                ),
                TextFormField(
                  keyboardType: TextInputType.emailAddress,
                  controller: _emailController,
                  decoration: const InputDecoration(
                      labelText: 'Email',
                      hintText: 'name@example.com',
                      border: OutlineInputBorder()),
                ),
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    child: const Text('Submit'),
                    onPressed: () async {
                      if (!_formkey.currentState!.validate()) {
                        return;
                      }

                      await DataBaseHelper.instance.addStudent(
                        StudentDetails(
                          name: _nameController.text,
                          dob:
                              // '${dateTime!.day}/${dateTime!.month}/${dateTime!.year}',
                          address: _addressController.text,
                          phone: _mobileController.text,
                          email: _emailController.text,
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Body:
Create a constructor onDateSelected so you can get a datetime when you select a date from date-picker.

class DateOfBirth extends StatefulWidget {
  final Function onDateSelected;

  DateOfBirth({this.onDateSelected});

  @override
  _DateOfBirthState createState() => _DateOfBirthState();
}

class _DateOfBirthState extends State<DateOfBirth> {
  DateTime? dateTime;
  String _text = '';

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
          border: Border.all(), borderRadius: BorderRadius.circular(5)),
      width: double.infinity,
      child: Padding(
        padding: const EdgeInsets.only(left: 8, right: 8),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text('Date Of Birth'),
            Text(_text),
            ElevatedButton(
              onPressed: () async {
                dateTime = await showDatePicker(
                  context: context,
                  initialDate: dateTime ?? DateTime.now(),
                  firstDate: DateTime(1900),
                  lastDate: DateTime.now(),
                );
                widget.onDateSelected(dateTime);
                setState(() {
                  _text =
                      '${dateTime?.day}/${dateTime?.month}/${dateTime?.year}';
                });
              },
              child: const Text('Date Of Birth'),
            ),
          ],
        ),
      ),
    );
  }
}

// You can get date like this.

DateOfBirth(
      onDateSelected: (date) {
        //
      },
    )


问:
Remove newline from string output

try:
    with cx_oracle.connect(user,password,dsn,encoding ="UTF-8") as connection:
        cursor = connection.cursor()
        cursor.execute("select * from customer")
        results =cursor.fetchall()
        return json.dumps(results,indent=4,sort_keys = True,default=str)
except Exception as error:
    print ("error occurred",error)
```
<p>output</p>
```'[\n [\n 1456,\n   "ice kle",\n  "2022:02:08 8:06:01",\n  "2022-02-08 8:07:01",\n "fund"\n]'
```

答:
Better replace the '\n' with ''

result = result.replace('\n','')

Title: Remove newline from string output

Body:
try:
    with cx_oracle.connect(user,password,dsn,encoding ="UTF-8") as connection:
        cursor = connection.cursor()
        cursor.execute("select * from customer")
        results =cursor.fetchall()
        return json.dumps(results,indent=4,sort_keys = True,default=str)
except Exception as error:
    print ("error occurred",error)

output

'[\n [\n 1456,\n   "ice kle",\n  "2022:02:08 8:06:01",\n  "2022-02-08 8:07:01",\n "fund"\n]'


问:
How to count total receipts by date
Would like to know why do I keep getting the error message?

Created query with SQL Server Management Studio, my output to display correctly has parameters, and I have tried the following with my query.

What I really would like is to have a specific start and end dates and change selected dates with any other combination of MinDate, MaxDate as follows:

```<code>@MinDate DATE = '2020-01-01',
@MaxDate DATE = '2020-02-01';
</code>```

Totals:

```<code>COUNT(Receipt_ID) AS 'Total_Number_Of_Receipts',
SUM(Receipt_Amount) AS 'Total_Amount'
</code>```

This is the error I get:

Msg 102, Level 15, State 1, Line 5

Incorrect syntax near '.'.

Msg 8158, Level 16, State 1, Line 5

'Receipt_Date' has more columns than were specified in the column list.

Query:

```<code>DECLARE
    @MinDate DATE = '2020-01-01',
    @MaxDate DATE = '2020-02-01';

WITH Receipt_Date(day) AS
(
    SELECT,
        DATEADD(d, -1, GETDATE()) AS 'Yesterday',
        COUNT(Receipt_ID) AS 'Total_Number_Of_Receipts',
        SUM(Receipt_Amount) AS 'Total_Amount'
    FROM
        receipts AS r
    WHERE
        CAST(DATEADD(day, 1, day) AS Date) < @MaxDate
)
SELECT *
FROM receipts AS r
</code>```

答:
A few things:

1: You've got a comma after the select inside your CTE

```<code>SELECT, --<< here
        DATEADD(d, -1, GETDATE()) AS 'Yesterday',
</code>```

2: You need to match the definition of the CTE with the columns being returned, so you can't just have 'day' if you're returning 4 columns in the CTE

3: In your select statement you need to reference the CTE.

This returns, but I've no example data:

```<code>DROP TABLE IF EXISTS #receipts;

CREATE TABLE #receipts
(
Receipt_ID INTEGER IDENTITY(1,1),
d DATE,
Receipt_Amount MONEY
);

DECLARE
    @MinDate DATE = '2020-01-01',
    @MaxDate DATE = '2020-02-01';

WITH Receipt_Date(Yesterday, Total_Number_Of_Receipts, Total_Amount) AS
(
    SELECT
        DATEADD([day], -1, GETDATE()) AS 'Yesterday',
        COUNT(Receipt_ID) AS 'Total_Number_Of_Receipts',
        SUM(Receipt_Amount) AS 'Total_Amount'
    FROM
        #receipts AS r
    WHERE
        CAST(DATEADD(day, 1, d) AS Date) < @MaxDate
    GROUP BY DATEADD([day], -1, GETDATE())
)

SELECT *
FROM Receipt_Date;
</code>```

Title: How to count total receipts by date

Body:
Would like to know why do I keep getting the error message?

Created query with SQL Server Management Studio, my output to display correctly has parameters, and I have tried the following with my query.

What I really would like is to have a specific start and end dates and change selected dates with any other combination of MinDate, MaxDate as follows:

@MinDate DATE = '2020-01-01',
@MaxDate DATE = '2020-02-01';

Totals:

COUNT(Receipt_ID) AS 'Total_Number_Of_Receipts',
SUM(Receipt_Amount) AS 'Total_Amount'

This is the error I get:

Msg 102, Level 15, State 1, Line 5

Incorrect syntax near '.'.

Msg 8158, Level 16, State 1, Line 5

'Receipt_Date' has more columns than were specified in the column list.

Query:

DECLARE
    @MinDate DATE = '2020-01-01',
    @MaxDate DATE = '2020-02-01';

WITH Receipt_Date(day) AS
(
    SELECT,
        DATEADD(d, -1, GETDATE()) AS 'Yesterday',
        COUNT(Receipt_ID) AS 'Total_Number_Of_Receipts',
        SUM(Receipt_Amount) AS 'Total_Amount'
    FROM
        receipts AS r
    WHERE
        CAST(DATEADD(day, 1, day) AS Date) < @MaxDate
)
SELECT *
FROM receipts AS r

Body:
A few things:

1: You've got a comma after the select inside your CTE

SELECT, --<< here
        DATEADD(d, -1, GETDATE()) AS 'Yesterday',

2: You need to match the definition of the CTE with the columns being returned, so you can't just have 'day' if you're returning 4 columns in the CTE

3: In your select statement you need to reference the CTE.

This returns, but I've no example data:

DROP TABLE IF EXISTS #receipts;

CREATE TABLE #receipts
(
Receipt_ID INTEGER IDENTITY(1,1),
d DATE,
Receipt_Amount MONEY
);

DECLARE
    @MinDate DATE = '2020-01-01',
    @MaxDate DATE = '2020-02-01';

WITH Receipt_Date(Yesterday, Total_Number_Of_Receipts, Total_Amount) AS
(
    SELECT
        DATEADD([day], -1, GETDATE()) AS 'Yesterday',
        COUNT(Receipt_ID) AS 'Total_Number_Of_Receipts',
        SUM(Receipt_Amount) AS 'Total_Amount'
    FROM
        #receipts AS r
    WHERE
        CAST(DATEADD(day, 1, d) AS Date) < @MaxDate
    GROUP BY DATEADD([day], -1, GETDATE())
)

SELECT *
FROM Receipt_Date;


问:
How to create an array or list column in SQLAlchemy model?
I know it's possible to create array of string in postgres but I want to create a model in sqlalchemy that contains a list or array column but I don't know how

Please view the code below

```<code>class Question(Base):
    __tablename__= 'questions'
    id = Column(Integer, nullable=False, primary_key=True)
    question = Column(String,nullable=False)
    options = Column([String],nullable=False)
    answer = Column(String,nullable=False)
    created_at = Column(TIMESTAMP(timezone=true),server_default=text('now()')

</code>```

答:
You need to use:

```<code>from sqlalchemy.dialects.postgresql import ARRAY
</code>```

Here:

```<code>from datetime import datetime
from sqlalchemy import *
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Question1(Base):
    __tablename__= 'questions'
    id = Column(Integer, nullable=False, primary_key=True)
    question = Column(String,nullable=False)
    options = Column(ARRAY(String),nullable=False)
    answer = Column(String,nullable=False)
</code>```

Example:

```<code>Python 3.8.2 (default, Dec 21 2020, 15:06:04)
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> from sqlalchemy import *
>>> from sqlalchemy.dialects.postgresql import ARRAY
>>> from sqlalchemy.ext.declarative import declarative_base
>>> Base = declarative_base()
>>> class Question1(Base):
...     __tablename__= 'questions'
...     id = Column(Integer, nullable=False, primary_key=True)
...     question = Column(String,nullable=False)
...     options = Column(ARRAY(String),nullable=False)
...     answer = Column(String,nullable=False)
...
>>>

</code>```

Body:
I know it's possible to create array of string in postgres but I want to create a model in sqlalchemy that contains a list or array column but I don't know how

Please view the code below

class Question(Base):
    __tablename__= 'questions'
    id = Column(Integer, nullable=False, primary_key=True)
    question = Column(String,nullable=False)
    options = Column([String],nullable=False)
    answer = Column(String,nullable=False)
    created_at = Column(TIMESTAMP(timezone=true),server_default=text('now()')

Body:
You need to use:

from sqlalchemy.dialects.postgresql import ARRAY

Here:

from datetime import datetime
from sqlalchemy import *
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Question1(Base):
    __tablename__= 'questions'
    id = Column(Integer, nullable=False, primary_key=True)
    question = Column(String,nullable=False)
    options = Column(ARRAY(String),nullable=False)
    answer = Column(String,nullable=False)

Example:

Python 3.8.2 (default, Dec 21 2020, 15:06:04)
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> from sqlalchemy import *
>>> from sqlalchemy.dialects.postgresql import ARRAY
>>> from sqlalchemy.ext.declarative import declarative_base
>>> Base = declarative_base()
>>> class Question1(Base):
...     __tablename__= 'questions'
...     id = Column(Integer, nullable=False, primary_key=True)
...     question = Column(String,nullable=False)
...     options = Column(ARRAY(String),nullable=False)
...     answer = Column(String,nullable=False)
...
>>>


问:
I am struggling to figure out how to compare the two instances in Java
My task is as follows:

Create a Java class called SalesPerson with following properties:

sales id - data type int

sales amount - data type double

Write a default constructor to initialize each of the properties.

Code getters and setters for each property.

In the main method, instantiate two instances of SalesPerson type.

Using setters, set the id and sales amount for each sales person. Then compare each sales person's sales amount and display the id of the sales person with higher sales amount.

I believe I have correctly written everything so far but I am at a loss for how to compare "amount1" and "amount2". The instructions I was given are pasted above if that helps at all. My current code is this:

```<code>public class SalesPerson {
    public int salesId;
    public double salesAmount;

    public SalesPerson() {
        salesId = 101;
        salesAmount = 1002.36;
    }

    public void setSalesId(int i) {
        salesId = i;
    }

    public void setSalesAmount(double a) {
        salesAmount = a;
    }

    public int getSalesId() {
        return salesId;
    }

    public double getSalesAmount() {
        return salesAmount;
    }

    public static void main(String[] args) {
        SalesPerson amount1 = new SalesPerson();
        SalesPerson amount2 = new SalesPerson();
        System.out.println("ID is: " + amount1.getSalesId());
        System.out.println("Sale amount is: " + amount1.getSalesAmount());
        amount2.setSalesId(254);
        amount2.setSalesAmount(1563.58);
        System.out.println("ID is: " + amount2.getSalesId());
        System.out.println("Sale amount is: " + amount2.getSalesAmount());
        if(amount2 > amount1) {

        }
    }
}
</code>```

答:
You have to campare getter getSalesAmount() of amount1 and amount2 but you compare whole object.

```<code>if(amount2.getSalesAmount() > amount1.getSalesAmount()) {
     System.out.println("Id: " + amount2.getSalesId());
}
else {
     System.out.println("Id: " + amount1.getSalesId());
}
</code>```

Body:
My task is as follows:

Create a Java class called SalesPerson with following properties:

sales id - data type int

sales amount - data type double

Write a default constructor to initialize each of the properties.

Code getters and setters for each property.

In the main method, instantiate two instances of SalesPerson type.

Using setters, set the id and sales amount for each sales person. Then compare each sales person's sales amount and display the id of the sales person with higher sales amount.

I believe I have correctly written everything so far but I am at a loss for how to compare "amount1" and "amount2". The instructions I was given are pasted above if that helps at all. My current code is this:

public class SalesPerson {
    public int salesId;
    public double salesAmount;

    public SalesPerson() {
        salesId = 101;
        salesAmount = 1002.36;
    }

    public void setSalesId(int i) {
        salesId = i;
    }

    public void setSalesAmount(double a) {
        salesAmount = a;
    }

    public int getSalesId() {
        return salesId;
    }

    public double getSalesAmount() {
        return salesAmount;
    }

    public static void main(String[] args) {
        SalesPerson amount1 = new SalesPerson();
        SalesPerson amount2 = new SalesPerson();
        System.out.println("ID is: " + amount1.getSalesId());
        System.out.println("Sale amount is: " + amount1.getSalesAmount());
        amount2.setSalesId(254);
        amount2.setSalesAmount(1563.58);
        System.out.println("ID is: " + amount2.getSalesId());
        System.out.println("Sale amount is: " + amount2.getSalesAmount());
        if(amount2 > amount1) {

        }
    }
}

Body:
You have to campare getter getSalesAmount() of amount1 and amount2 but you compare whole object.

if(amount2.getSalesAmount() > amount1.getSalesAmount()) {
     System.out.println("Id: " + amount2.getSalesId());
}
else {
     System.out.println("Id: " + amount1.getSalesId());
}


问:
How should I document my C# code?
I am building the documentation for our C# API containing:

A general overview and description of the current state as a doc/pdf file.

A class library API in a .chm file using Sandcastle.

Questions:

Should I merge these two into the same .chm file? What is a good way to merge them?

I need to exclude certain classes/packages. How can I specify that in SandCastle?

It generates documentation for the VB code and the Visual C++ code. How can I change this? Or should I leave it, knowing that I am only using safe code?

Where can I find HTML Help 2.x Viewer Path on my system?

Edit:

The comments I make above methods, fields and classes are not generated in the documentation.

What should I do?

答: In addition to Sand Castle as mentioned above, I would also recommend looking at FxCop and StyleCop to help make sure your code and documentation is up to CLS Compliance standards.</p>

OwnerDisplayName: Sasha

LastEditorDisplayName: Rich B

ContentLicense: CC BY-SA 2.5

Title: How should I document my C# code?

OwnerDisplayName: John Gietzen


问:
Seeing escape characters when pressing the arrow keys in python shell
In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.

But after I ssh into another machine and start python there, I get sessions like:

```<code>>>> import os
>>> ^[[A
</code>```

where the last character comes from arrow-up. Or, using arrow-left:

```<code>>>> impor^[[D
</code>```

How can I fix this?

In the regular bash, arrow keys work fine. The weird behavior is just in the interactive python (or perl etc.) shell.

答:
you can switch from 'sh" to "bash" by</p>
```<code>$ /sh/bash
</code>```

Body:
In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.

But after I ssh into another machine and start python there, I get sessions like:

>>> import os
>>> ^[[A

where the last character comes from arrow-up. Or, using arrow-left:

>>> impor^[[D

How can I fix this?

In the regular bash, arrow keys work fine. The weird behavior is just in the interactive python (or perl etc.) shell.

Body:
you can switch from 'sh" to "bash" by

$ /sh/bash


问:
Get local IP address in Node.js
I have a simple Node.js program running on my machine and I want to get the local IP address of a PC on which my program is running. How do I get it with Node.js?</p>

答:
Some answers here seemed unnecessarily over-complicated to me.
Here's a better approach to it using plain Nodejs.

```<code>import os from "os";

const machine = os.networkInterfaces()["Ethernet"].map(item => item.family==="IPv4")

console.log(machine.address) //gives 192.168.x.x or whatever your local address is
</code>```

See documentation: NodeJS - os module: networkInterfaces

Title: Get local IP address in Node.js

Body:
Some answers here seemed unnecessarily over-complicated to me.
Here's a better approach to it using plain Nodejs.

import os from "os";

const machine = os.networkInterfaces()["Ethernet"].map(item => item.family==="IPv4")

console.log(machine.address) //gives 192.168.x.x or whatever your local address is

See documentation: NodeJS - os module: networkInterfaces


问:
How to delete multiple elements if checkbox is checked using javascript?
So I got this code, I figured out how to delete one element with the checkbox checked but if I try to delete the second div it won't let me?
Does anyone have a solution to it?

HTML

```<code><div id="product-space">
            <div id="product"> <input type="checkbox" id="delete-checkbox">
                <p> JVC200123 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
            </div>
            <div id="product"> <input type="checkbox" id="delete-checkbox">
                <p> KRK201929 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
            </div>
        </div>
<button type="submit" name="button" value="enter" id="button" onclick="removeCheckedCheckboxes()">MASS DELETE</button>
</code>```

JavaScript

```<code>function removeCheckedCheckboxes() {
    var checkBox = document.getElementById("delete-checkbox");
    var box = document.getElementById("product");
    if (checkBox.checked == true) {
        box.style.display = "none";
    }
}
</code>```

答:
see the ref:

getElementById will return the first element with the given ID

You could name them as different ids if just want to handle this issue quickly.

Body:
So I got this code, I figured out how to delete one element with the checkbox checked but if I try to delete the second div it won't let me?
Does anyone have a solution to it?

HTML

 <input type="checkbox" id="delete-checkbox">

 JVC200123
 Acme DISC
 1.00 $
 Size: 700 MB

 <input type="checkbox" id="delete-checkbox">

 KRK201929
 Acme DISC
 1.00 $
 Size: 700 MB

<button type="submit" name="button" value="enter" id="button" onclick="removeCheckedCheckboxes()">MASS DELETE</button>

JavaScript

function removeCheckedCheckboxes() {
    var checkBox = document.getElementById("delete-checkbox");
    var box = document.getElementById("product");
    if (checkBox.checked == true) {
        box.style.display = "none";
    }
}


问:
How to disable groups of frames based on button click?
So I'm trying to make a light/dark mode configuration for my app. My idea is to make two groups of frames: one light, another dark. Upon the user clicking a small button, light would turn to dark. So the light group of frames gets disabled, and the user is taken to the first frame in the dark group. And if the button is clicked again, the dark group gets disabled, and the user is taken to the first frame in the light group.

Is there a way I can make something like this happen? I know it seems a bit complex, if so, is there an easier way to do this? Thank you.

答:
For example:
button to change background
you can change the function however you want</p>
```<code>from tkinter import *

root = Tk()
root.geometry("600x480")
root.title("Dark Theme")
btn = Button(text="On", command=lambda: on(True))
btn.pack()
btn = Button(text="Off", command=lambda: off(True))
btn.pack()
def on(which):
    if which:
        root.configure(bg='black')
    else:
        print("")

def off(which):
    if which:
       root.configure(bg='white')
    else:
        print("")

root.mainloop()
</code>```

Body:
For example:
button to change background
you can change the function however you want

from tkinter import *

root = Tk()
root.geometry("600x480")
root.title("Dark Theme")
btn = Button(text="On", command=lambda: on(True))
btn.pack()
btn = Button(text="Off", command=lambda: off(True))
btn.pack()
def on(which):
    if which:
        root.configure(bg='black')
    else:
        print("")

def off(which):
    if which:
       root.configure(bg='white')
    else:
        print("")

root.mainloop()


问:
Getting "405: method not allowed" error while pinging to Jfrog Artifactory in Jfrog CLI
I have Installed Jfrog CLI (2.12.0) and configured it by using jf config addcommand.

After passing the platform URL, username and password I executed  jf rt ping to check the connection.

But am getting the below error as a response

```<code>[root@osc-in-bldslave-1 opt]# jf rt ping
19:13:51 [Error] Server response: 405 Method Not Allowed
{
  "errors": [
    {
      "status": 405,
      "message": "Method Not Allowed"
    }
  ]
}
</code>```

Please let me know if you need any other details.

Below are the Steps I followed while Jfrog CLI configuration. Correct me if there is any issues with configuration.

```<code>[root@osc-in-bldslave-1 ~]# jf -version
jf version 2.12.0
[root@osc-in-bldslave-1 ~]#
[root@osc-in-bldslave-1 ~]# jf config add
Choose a server ID : <server id>
JFrog platform URL [http://xxx.xx.xxx.xx:8081/]: http://xxx.xx.xxx.xx:8081/
JFrog access token (Leave blank for username and password/API key):
JFrog username [username]: <username>
JFrog password or API key:<passing password here>
Is the Artifactory reverse proxy configured to accept a client certificate? (y/n) [n]? n
[root@osc-in-bldslave-1 ~]#
[root@osc-in-bldslave-1 ~]# jf rt ping
09:55:13 [Error] Server response: 405 Method Not Allowed
{
  "errors": [
    {
      "status": 405,
      "message": "Method Not Allowed"
    }
  ]
}
[root@osc-in-bldslave-1 ~]#
</code>```

But if it try pinging to my URL directly using below command it is working fine.

```<code>[root@osc-in-bldslave-1 ~]# jf rt ping --url=http://172.xx.xxx.xx:8081/artifactory/
OK
</code>```

I deleted and installed Jfrog CLI freshly, still am facing the same 405: method not allowed issue.

Can anyone please let me know what am missing?

答: you can find using command which jf & whereis jf

Body:
I have Installed Jfrog CLI (2.12.0) and configured it by using jf config addcommand.

After passing the platform URL, username and password I executed  jf rt ping to check the connection.

But am getting the below error as a response

[root@osc-in-bldslave-1 opt]# jf rt ping
19:13:51 [Error] Server response: 405 Method Not Allowed
{
  "errors": [
    {
      "status": 405,
      "message": "Method Not Allowed"
    }
  ]
}

Please let me know if you need any other details.

Below are the Steps I followed while Jfrog CLI configuration. Correct me if there is any issues with configuration.

[root@osc-in-bldslave-1 ~]# jf -version
jf version 2.12.0
[root@osc-in-bldslave-1 ~]#
[root@osc-in-bldslave-1 ~]# jf config add
Choose a server ID : <server id>
JFrog platform URL [http://xxx.xx.xxx.xx:8081/]: http://xxx.xx.xxx.xx:8081/
JFrog access token (Leave blank for username and password/API key):
JFrog username [username]: <username>
JFrog password or API key:<passing password here>
Is the Artifactory reverse proxy configured to accept a client certificate? (y/n) [n]? n
[root@osc-in-bldslave-1 ~]#
[root@osc-in-bldslave-1 ~]# jf rt ping
09:55:13 [Error] Server response: 405 Method Not Allowed
{
  "errors": [
    {
      "status": 405,
      "message": "Method Not Allowed"
    }
  ]
}
[root@osc-in-bldslave-1 ~]#

But if it try pinging to my URL directly using below command it is working fine.

[root@osc-in-bldslave-1 ~]# jf rt ping --url=http://172.xx.xxx.xx:8081/artifactory/
OK

I deleted and installed Jfrog CLI freshly, still am facing the same 405: method not allowed issue.

Can anyone please let me know what am missing?


问:
I want to add a 9.7 GB project to GitHUB
I am trying to push my local git into my remote but the project is too big:

```<code>MINGW64 ~/source/repos/DBO (master)
$ git config http.postBuffer 9370000000

MINGW64 ~/source/repos/DBO (master)
$ git push --set-upstream origin master
Enumerating objects: 149849, done.
Counting objects: 100% (149849/149849), done.
Delta compression using up to 16 threads
Compressing objects: 100% (94939/94939), done.
fatal: protocol error: bad line length 81925 MiB | 342.52 MiB/s
send-pack: unexpected disconnect while reading sideband packet
error: failed to push some refs to 'https://github.com/Alejandro-HUB/DBO.git'

MINGW64 ~/source/repos/DBO (master)
</code>```

I tried using this to increase GitHUB's file size limit but I think they may have a limit for how big the project can be:

```<code>$ git config http.postBuffer 9370000000
</code>```

Is there any way for me to get my project into GitHUB?

答: Thank you for all your help and suggestions! I decided to use Azure Dev Ops and gradually push my project there since they are limited to 5GB at a time which makes the process faster than 2GB at a time.</p>

Body:
I am trying to push my local git into my remote but the project is too big:

MINGW64 ~/source/repos/DBO (master)
$ git config http.postBuffer 9370000000

MINGW64 ~/source/repos/DBO (master)
$ git push --set-upstream origin master
Enumerating objects: 149849, done.
Counting objects: 100% (149849/149849), done.
Delta compression using up to 16 threads
Compressing objects: 100% (94939/94939), done.
fatal: protocol error: bad line length 81925 MiB | 342.52 MiB/s
send-pack: unexpected disconnect while reading sideband packet
error: failed to push some refs to 'https://github.com/Alejandro-HUB/DBO.git'

MINGW64 ~/source/repos/DBO (master)

I tried using this to increase GitHUB's file size limit but I think they may have a limit for how big the project can be:

$ git config http.postBuffer 9370000000

Is there any way for me to get my project into GitHUB?


问:
Androidx Naviagtion - Pass custom object to destination fragment
I need to pass a custom object from one fragment to another fragment. I use androidx navigation for navigation between fragments. I had to use deepLink for navigation for my use case.

The navigation graph with the destination fragment has,

```<code>    <fragment
       android:id="@+id/ListFragment"
       android:name="com.joseph.learning.ListFragment"
       android:label="ListFragment">

       <argument android:name="todoItem"
        app:argType="com.joseph.learning.models.todoItem" />

      <deepLink app:uri="android-app://androidx.navigation/todoList/{todoItem}" />
  </fragment>
</code>```

And from the source fragment, the navigation is initiated like

```<code>findNavController().navigate(
  Uri.parse("android-app://androidx.navigation/todoList/$item"),
  NavOptions.Builder()
      .setEnterAnim(R.anim.transition_slide_in_right)
      .setExitAnim(R.anim.transition_slide_out_left)
      .setPopExitAnim(R.anim.transition_slide_out_right)
      .setPopEnterAnim(R.anim.transition_slide_in_left)
      .build()
 )
</code>```

But this fails as soon as it executes with below error

```<code>java.lang.UnsupportedOperationException: Parcelables don't support default values.
        at androidx.navigation.NavType$ParcelableType.parseValue(NavType.java:679)
        at androidx.navigation.NavType.parseAndPut(NavType.java:96)
        at androidx.navigation.NavDeepLink.parseArgument(NavDeepLink.java:306)
        ...
</code>```

If incase, the custom object as argument is replaced with string or integer, then the navigation works without any issues. Also the passed data can be extracted in the destination fragment using navArgs()

What should be done to pass custom object across fragments ?

答:
Android Documentation

Routes, deep links, and URIs with their arguments can be parsed from strings. This is not possible using custom data types such as Parcelables and Serializables as seen in the above table.

Solution: To pass around custom complex data, store the data elsewhere such as a ViewModel or database and only pass an identifier while navigating; then retrieve the data in the new location after navigation has concluded.

Body:
I need to pass a custom object from one fragment to another fragment. I use androidx navigation for navigation between fragments. I had to use deepLink for navigation for my use case.

The navigation graph with the destination fragment has,

    <fragment
       android:id="@+id/ListFragment"
       android:name="com.joseph.learning.ListFragment"
       android:label="ListFragment">

       <argument android:name="todoItem"
        app:argType="com.joseph.learning.models.todoItem" />

      <deepLink app:uri="android-app://androidx.navigation/todoList/{todoItem}" />
  </fragment>

And from the source fragment, the navigation is initiated like

findNavController().navigate(
  Uri.parse("android-app://androidx.navigation/todoList/$item"),
  NavOptions.Builder()
      .setEnterAnim(R.anim.transition_slide_in_right)
      .setExitAnim(R.anim.transition_slide_out_left)
      .setPopExitAnim(R.anim.transition_slide_out_right)
      .setPopEnterAnim(R.anim.transition_slide_in_left)
      .build()
 )

But this fails as soon as it executes with below error

java.lang.UnsupportedOperationException: Parcelables don't support default values.
        at androidx.navigation.NavType$ParcelableType.parseValue(NavType.java:679)
        at androidx.navigation.NavType.parseAndPut(NavType.java:96)
        at androidx.navigation.NavDeepLink.parseArgument(NavDeepLink.java:306)
        ...

If incase, the custom object as argument is replaced with string or integer, then the navigation works without any issues. Also the passed data can be extracted in the destination fragment using navArgs()

What should be done to pass custom object across fragments ?


问:
Huawei mobile services push kit 907122036: no right API call
I want to use the Push Kit.. is there something wrong with my configuration or setup?

Environment :

Phone model (Settings > About phone): ANA-NX9 Huawei P40.

EMUI version (Settings > About phone): 11.0.0

HMS Core version number(Settings > Apps > Apps > HMS Core): 6.1.0.314 SDK version number

(app-level build.gradle document): 24

LOGS:
**Error/Exception: {"framesToPop":1,"nativeStackAndroid":[],"userInfo":null,"message":"907122036: no right","code":"907122045"}

Above error whenever I try to getToken via HmsPushInstanceId.getToken('')**

答:
Basically this error(907122036 ) will come if HUAWEI Push Kit is not enabled.  For details, refer to Getting Started to check whether the related service is enabled for the app.

Result Code reference

check whether you have enable permission from Manage APIs: Go to Project settings > Manage APIs and enable Push Kit.

How can I check whether HUAWEI Push Kit is enabled for an app?
Sign in to AppGallery Connect, select the app to be checked, click Manage APIs, and check whether HUAWEI Push Kit is enabled.

Check the Service status parameter. If its value is Enabled, HUAWEI Push Kit is enabled for the app.

React native push kit reference sample code

make sure you are using React Native Push Plugin, download the HMS Core SDK package and integrate it locally.

For the integration process, refer to React Native Development Guide. latest plugin.

Happy coding!!


问:
How to exit loop using BGT?
I've only seen BLT Loop which is a comparison between the index of a for loop and the loop upper bound. So if the index is less than the bound, then branch to Loop. But how would I manage to achieve the same functionality using BGT? Would I instead say BGT Exit? So if the index is greater than the bound, then exit the loop? Would that ensure the loop keeps looping as long as the index is NOT greater than the bound? Also, for Exit, do I need to write anything after it? Or is just "Exit: " fine?</p>

答:
The inverse of BLT is BGE, not BGT. Note the equality. BGE or BGT would make sense if the index was decreasing, as in for (int i = 7; i >=0; --i).

In incremented loop one can skip out of the loop with BGE/BGT, but then one would need an additional jump back to the loop beginning.

```<code>loop_begin:
     add r0, r0, #1
     cmp r0, r1
     b.ge out
     b loop_begin
out:
</code>```

It's anyway typical that a regular loop for (int i = 0; i < N; i++) is converted by a compiler to the decremented version (when the iteration count can be computed), producing

```<code> cmp r0, 0  // assume r0 == N
 b.le  out  // need to skip the branch if N<=0
 loop_begin:
    subs r0, r0, #1  // decrement and compare to zero
    b.gt loop_begin
 out:
</code>```

If possible, one should try to formulate the loops to the form do { } while (--i), executing at least one iteration.

```<code>loop_begin:
  subs r0, r0, #1  // decrement and compare to zero
  b.gt loop_begin
</code>```

Title: How to exit loop using BGT?

Body:
The inverse of BLT is BGE, not BGT. Note the equality. BGE or BGT would make sense if the index was decreasing, as in for (int i = 7; i >=0; --i).

In incremented loop one can skip out of the loop with BGE/BGT, but then one would need an additional jump back to the loop beginning.

loop_begin:
     add r0, r0, #1
     cmp r0, r1
     b.ge out
     b loop_begin
out:

It's anyway typical that a regular loop for (int i = 0; i < N; i++) is converted by a compiler to the decremented version (when the iteration count can be computed), producing

 cmp r0, 0  // assume r0 == N
 b.le  out  // need to skip the branch if N<=0
 loop_begin:
    subs r0, r0, #1  // decrement and compare to zero
    b.gt loop_begin
 out:

If possible, one should try to formulate the loops to the form do { } while (--i), executing at least one iteration.

loop_begin:
  subs r0, r0, #1  // decrement and compare to zero
  b.gt loop_begin


问:
How to generate custom Docker Content Trust root key
I have little idea in security aspects in and outside docker world.
As the document states, I tried the below command

```<code>docker trust key generate jeff
</code>```

Whenever I run this command first time it will automatically generate a root key. Isn't it possible to generate a root key based on my own existing pem file? I have checked docker and notary client/ server etc there is no information regarding this. I hope this is a valid question.

答:
Yes we can do that

Reference Link:https://docs.docker.com/engine/reference/commandline/trust_key_load/#:~:text=docker%20trust%20key%20load%20adds%20private%20keys%20to,this%20command%2C%20refer%20to%20the%20examples%20section%20below.

Below are the steps to load existing pem file (ie private key) .It works only in windows VM Image.(Not Ubuntu Image)

set DOCKER_CONTENT_TRUST=1

docker trust key load privatekey.pem --name username

Enter passphrase :

docker trust signer add --key publickey.pem username dockerimageregistry.azurecr.io/hello-world:signed

Body:
I have little idea in security aspects in and outside docker world.
As the document states, I tried the below command

docker trust key generate jeff

Whenever I run this command first time it will automatically generate a root key. Isn't it possible to generate a root key based on my own existing pem file? I have checked docker and notary client/ server etc there is no information regarding this. I hope this is a valid question.


问:
How can i use % with RestTemplate
I am trying to make a HTTP request to a API with a route like this:

https://example.test/{ID}/get

The problem is, the ID starts with %, something like "%123123123", after the "excute" method, locate in RestTemplate class, this ID's becomes %25123123123, % changes into %25.
More specific, in this line of the method:

```<code>URI expanded = getUriTemplateHandler().expand(url, uriVariables);
</code>```

Here my uriVariables is just a empty Object, and when i manually change the value of expanded variable removing "25", the request works just fine.

Anyone knows how to fix it ?

答:
After Spring 5, the DefaultUriBuilderFactory, used by RestTemplate, defaults is EncodingMode.URI_COMPONENT, as described below:

Expand URI variables first, and then encode the resulting URI component values, replacing only non-ASCII and illegal (within a given URI component type) characters, but not characters with reserved meaning.

If you want your URI to be unencoded like I do, just create a new DefaultUriBuilderFactory with EncodingMode.NONE and add it to your RestTemplate:

```<code>DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory();
uriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setUriTemplateHandler(uriBuilderFactory);
</code>```

You can check here for other EncondingModes.

Title: How can i use % with RestTemplate

Body:
I am trying to make a HTTP request to a API with a route like this:

https://example.test/{ID}/get

The problem is, the ID starts with %, something like "%123123123", after the "excute" method, locate in RestTemplate class, this ID's becomes %25123123123, % changes into %25.
More specific, in this line of the method:

URI expanded = getUriTemplateHandler().expand(url, uriVariables);

Here my uriVariables is just a empty Object, and when i manually change the value of expanded variable removing "25", the request works just fine.

Anyone knows how to fix it ?

Body:
After Spring 5, the DefaultUriBuilderFactory, used by RestTemplate, defaults is EncodingMode.URI_COMPONENT, as described below:

Expand URI variables first, and then encode the resulting URI component values, replacing only non-ASCII and illegal (within a given URI component type) characters, but not characters with reserved meaning.

If you want your URI to be unencoded like I do, just create a new DefaultUriBuilderFactory with EncodingMode.NONE and add it to your RestTemplate:

DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory();
uriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setUriTemplateHandler(uriBuilderFactory);

You can check here for other EncondingModes.


问:
Adding a react component to a array in forEach does not render
EDIT: I have done some debugging and found that the elements I am adding to the display array are not being recognized. If I display the array in the console I can see that the size would be 2 for example, however If I display the length of array (display.length) it shows a length of 0.

I am trying to use firebase and react to create a little personal project. In this I am trying to get information from firebase and then display it. I am getting the data using a async function (basically copied the code from the firebase website to do it) so I guess that could possibly cause some issues but I am not smart enough to find a way to get information without it being async.

```<code>renderFavoriteGyms(){
    let display = []

    getGymsFromLocation("Rochester").then(ref =>{

        ref.map(gym => {
            display.push(<GymDisplay key ={gym} reference = {gym}/>)
        })
    })

    display.push(<GymDisplay  key = {"CRG Rochester"}
    reference = {"Gyms/Rochester/CRG Rochester/Atributes"}/>)
    return display
}
</code>```

When adding a react component inside of the forEach/map it does not render however manually pushing it worked perfectly. I manually checked in the dev console that the display array contains the correct information and it does. I am rendering below

```<code>render() {
    return(
        <div>

            <Row className='gymFavorites' sm = {4}>
                    <this.renderFavoriteGyms/>
            </Row>

        </div>
    )
}
</code>```

Any help would be great!

答:
If you want to use a function to render you can not call it as a component but as a function:

instead of:

```<code><this.renderFavoriteGyms/>
</code>```

do this:

```<code>{this.renderFavoriteGyms()}
</code>```

Body:
EDIT: I have done some debugging and found that the elements I am adding to the display array are not being recognized. If I display the array in the console I can see that the size would be 2 for example, however If I display the length of array (display.length) it shows a length of 0.

I am trying to use firebase and react to create a little personal project. In this I am trying to get information from firebase and then display it. I am getting the data using a async function (basically copied the code from the firebase website to do it) so I guess that could possibly cause some issues but I am not smart enough to find a way to get information without it being async.

renderFavoriteGyms(){
    let display = []

    getGymsFromLocation("Rochester").then(ref =>{

        ref.map(gym => {
            display.push(<GymDisplay key ={gym} reference = {gym}/>)
        })
    })

    display.push(<GymDisplay  key = {"CRG Rochester"}
    reference = {"Gyms/Rochester/CRG Rochester/Atributes"}/>)
    return display
}

When adding a react component inside of the forEach/map it does not render however manually pushing it worked perfectly. I manually checked in the dev console that the display array contains the correct information and it does. I am rendering below

render() {
    return(

            <Row className='gymFavorites' sm = {4}>
                    <this.renderFavoriteGyms/>
            </Row>

    )
}

Any help would be great!

Body:
If you want to use a function to render you can not call it as a component but as a function:

instead of:

<this.renderFavoriteGyms/>

do this:

{this.renderFavoriteGyms()}


问:
Correct way to terminate a postgres replication mode connection
I have the following code that enables logical decoding in PostgreSQL 9.4:

```<code>pg_recvlogical -h localhost --slot test_slot --create-slot
pg_recvlogical -h localhost --slot test_slot --start -f -
</code>```

I spawn a node.js subprocess to run this code and listen for changes however I'm unsure of what the correct procedure is to terminate the connection. I usually just CNTRL+C from the command line or kill the subprocess in code but I always get a pg_recvlogical: unexpected termination of replication stream: error. What is the correct way to terminate this connection?

答:
I did the following to kill a zombie active replication slot.

connect to the server where postgres is installed using CLI with ssh.

```<code>ssh -i <generated_security_key_name/path>.pem <username>@<hostIp>
</code>```

once connected with the VM in your server. type following command to connect to postgres sql.

```<code>sudo -i -u <postgres-username>
</code>```

you can go with psql which is a terminal-based front-end to PostgreSQL

```<code>psql
</code>```

check the pid against your replication slot.

```<code>select * from pg_replication_slots;
</code>```

Enter the following to kill it.

```<code>sudo kill <pid>
</code>```

Body:
I have the following code that enables logical decoding in PostgreSQL 9.4:

pg_recvlogical -h localhost --slot test_slot --create-slot
pg_recvlogical -h localhost --slot test_slot --start -f -

I spawn a node.js subprocess to run this code and listen for changes however I'm unsure of what the correct procedure is to terminate the connection. I usually just CNTRL+C from the command line or kill the subprocess in code but I always get a pg_recvlogical: unexpected termination of replication stream: error. What is the correct way to terminate this connection?

Body:
I did the following to kill a zombie active replication slot.

connect to the server where postgres is installed using CLI with ssh.

ssh -i <generated_security_key_name/path>.pem <username>@<hostIp>

once connected with the VM in your server. type following command to connect to postgres sql.

sudo -i -u <postgres-username>

you can go with psql which is a terminal-based front-end to PostgreSQL

psql

check the pid against your replication slot.

select * from pg_replication_slots;

Enter the following to kill it.

sudo kill <pid>


问:
What does '&' do in C/C++ and what is its equivalent operator in perl?
I'm writing a perl implementation of a protocol whose specification is given for C/C++ but I don't know much C.

What does the condition if ((flags & 0x400) != 0) mean? How do I do that in perl?

Is if ($flags == "\x400") correct?

答: The & operator performs a bitwise AND. In your case, if ((flags & 0x400) != 0) checks whether the eleventh bit of the flags variable is not set to 0. You can do bitwise operations in Perl, too.


答:
The reason your code does not work is because you use the id attribute multiple times with the same value. This is against HTML standards. Also you use getElementById which can only return a single element.

I would suggest using css classes for marking all relevant elements, and using a simple CSS selector for matching all checked boxes.

function removeCheckedCheckboxes() {
  var checked = document.querySelectorAll(".delete-checkbox:checked");
  checked.forEach((elem) => {
    elem.parentElement.style.display = "none";
  })
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="product-space">
  <div class="product"> <input type="checkbox" class="delete-checkbox">
    <p> JVC200123 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
  </div>
  <div class="product"> <input type="checkbox" class="delete-checkbox">
    <p> KRK201929 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
  </div>
</div>
<button type="submit" name="button" value="enter" id="deleteButton" onclick="removeCheckedCheckboxes()">MASS DELETE</button></code>```

Title: How to delete multiple elements if checkbox is checked using javascript?

Body:
The reason your code does not work is because you use the id attribute multiple times with the same value. This is against HTML standards. Also you use getElementById which can only return a single element.

I would suggest using css classes for marking all relevant elements, and using a simple CSS selector for matching all checked boxes.

function removeCheckedCheckboxes() {
  var checked = document.querySelectorAll(".delete-checkbox:checked");
  checked.forEach((elem) => {
    elem.parentElement.style.display = "none";
  })
}

<div id="product-space">
  <div class="product"> <input type="checkbox" class="delete-checkbox">
    <p> JVC200123 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
  </div>
  <div class="product"> <input type="checkbox" class="delete-checkbox">
    <p> KRK201929 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
  </div>
</div>
<button type="submit" name="button" value="enter" id="deleteButton" onclick="removeCheckedCheckboxes()">MASS DELETE</button>


答:
Document.getElementById() is used to find elements from DOM with matching ID. It returns a single Element object representing the element whose id property matches the specified string. In your case you have multiple elements with same id. So it will always returns the first element while running this script. So your second element remains in visible state always.

So a better approach is to pick the element using class name rather than id, because id is supposed to be unique and class names need not be unique.

Logic

Pick the target elements using the class names. I used same class names product for the container div and delete-checkbox for the check boxes.

On clicking delete button, loop through the elements with class name product.

Find checkbox inside each product element by checking an element with classname delete-checkbox inside each node.

Check the checked status of each checkbox, if checked, hide the box.

Working Fiddle

var boxes = document.querySelectorAll(".product");
function removeCheckedCheckboxes() {
    boxes.forEach((box) => {
        const checkBox = box.querySelector('.delete-checkbox');
        if (checkBox.checked == true) {
            box.style.display = "none";
        }
    })
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="product-space">
    <div class="product">
        <input type="checkbox" class="delete-checkbox">
        <p> JVC200123 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
    </div>
    <div class="product">
        <input type="checkbox" class="delete-checkbox">
        <p> KRK201929 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
    </div>
</div>
<button type="submit"
    name="button" value="enter" id="button"
    onclick="removeCheckedCheckboxes()">MASS
    DELETE
</button></code>```

Body:
Document.getElementById() is used to find elements from DOM with matching ID. It returns a single Element object representing the element whose id property matches the specified string. In your case you have multiple elements with same id. So it will always returns the first element while running this script. So your second element remains in visible state always.

So a better approach is to pick the element using class name rather than id, because id is supposed to be unique and class names need not be unique.

Logic

Pick the target elements using the class names. I used same class names product for the container div and delete-checkbox for the check boxes.

On clicking delete button, loop through the elements with class name product.

Find checkbox inside each product element by checking an element with classname delete-checkbox inside each node.

Check the checked status of each checkbox, if checked, hide the box.

Working Fiddle

var boxes = document.querySelectorAll(".product");
function removeCheckedCheckboxes() {
    boxes.forEach((box) => {
        const checkBox = box.querySelector('.delete-checkbox');
        if (checkBox.checked == true) {
            box.style.display = "none";
        }
    })
}

<div id="product-space">
    <div class="product">
        <input type="checkbox" class="delete-checkbox">
        <p> JVC200123 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
    </div>
    <div class="product">
        <input type="checkbox" class="delete-checkbox">
        <p> KRK201929 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
    </div>
</div>
<button type="submit"
    name="button" value="enter" id="button"
    onclick="removeCheckedCheckboxes()">MASS
    DELETE
</button>


问:
Facebook Graph API gem
I wanted to use the Facebook graph API in my rails app.

What is the recommended gem to work with the FB graph APIs?

Thanks

答: You can use the Koala gem from https://github.com/arsduo/koala</p>

Title: Facebook Graph API gem


问:
double quote coin flip
```<code>import random
input("You tossed a coin. Select 0 or 1\n" )
random_side = random.randint(0, 1)
if random_side == 1:
  print("Heads")
else:
  print("Tails")
</code>```

when I use double quote in 1(if random_side == "1":). It gives me same output not random outcome.

答:
If you wanted your input to determine which side the coin flips, then you have to first:

store the input in a variable

since you want it to be an integer, ensure it is an integer

add it to the conditional

coinFlip = int(input("You tossed a coin. Select 0 or 1\n"))

if coinFlip == 1:
print("Heads")
else:
print("Tails")

Title: double quote coin flip

Body:
import random
input("You tossed a coin. Select 0 or 1\n" )
random_side = random.randint(0, 1)
if random_side == 1:
  print("Heads")
else:
  print("Tails")

when I use double quote in 1(if random_side == "1":). It gives me same output not random outcome.


答:
Quoting the result of random.randint won't work because randint produces an integer value. You can tell the type of a value by calling the type function:

```<code>>>> type(random.randint(0, 1))
<class 'int'>
</code>```

So, when comparing, you should do if if random_side == 1:. Alternatively, you could do if random_side: as Python will interpret a 0 as False and a 1 as  True.

As an aside, before using Python's random library, you should seed the random generator to ensure that you get reasonably random results. Failing to do so might result in the random number generator using the same values for each run. You can find relevant documentation here.

Title: double quote coin flip

Body:
Quoting the result of random.randint won't work because randint produces an integer value. You can tell the type of a value by calling the type function:

>>> type(random.randint(0, 1))
<class 'int'>

So, when comparing, you should do if if random_side == 1:. Alternatively, you could do if random_side: as Python will interpret a 0 as False and a 1 as  True.

As an aside, before using Python's random library, you should seed the random generator to ensure that you get reasonably random results. Failing to do so might result in the random number generator using the same values for each run. You can find relevant documentation here.


问:
Is it mandatory to add security group to catalog in Azure? are there any other ways?
I'm creating access packages. I would like to know, Is it mandatory to add security group to catalog 1st then add those security groups to access package?

I'm bit unclear about "resource roles" Here

However,lets say, If I add them directly to the access package ( during access package creation) like below:

" Add resource roles" -> "group and teams" -> select check box which
says (See all groups and teams not in the "catalog-name" catalog. You
must have correct permissions to add them in this access package) ->
then search the security group -> Select the security group to add.

What could be the problem? Will it have some problematic consequences? If yes, what would be the consequences? Please suggest. Thanks.

答:
Is it mandatory to add security group to catalog 1st then add those
security groups to access package

It is not mandatory to add security group to catalog first and then add those security groups to access package

As you are selecting check box which says See all groups and teams not in the "catalog-name" catalog, these groups will be added to the catalog for the other catalog administrators to build access packages with