问:
Nice looking tables in both base R and RStudio notebooks
I want my function to print nice-looking tables, whether it's called from base R or from an RStudio Notebook (.Rmd file). The function should figure out where it's being called from, and adjust the table accordingly. I want the function to be easy to use, and don't want the user to have to specify anything about where the function is being called from.

I can achieve some of this with huxtable, but the user still has to modify the code a little. (I think this would work similarly with kable.)

Here is the function definition:

library(huxtable)

func = function() {
    table = hux(head(iris))
    # Color of table border: white on screen / base R, black in HTML
    color = if(isTRUE(all.equal(getOption('huxtable.print') , huxtable::print_screen))) "white" else "black"
    table = set_all_borders(table, brdr(color = color))
    print(table)
}

```
<p>In base R, I can just call the function:</p>
<pre class="lang-r prettyprint-override"><code># Base R
func()
</code>```

But in an RStudio Notebook, I need to make a couple of changes when calling the function, namely:

{r, results="asis"}

options("huxtable.print" = huxtable::print_html)

The call looks like this:

    ```{r, results="asis"}
    # RStudio
    options("huxtable.print" = huxtable::print_html)
    func()
    ```

```

Is there a better solution where the user can call the function the same way in base R and RStudio?

答:
Maybe something like this?

library(huxtable)

func = function(table) {
    html_output = isTRUE(all.equal(getOption('huxtable.print') ,
                         huxtable::print_html) ||
                  guess_knitr_output_format() == "html"
    color = if(html_output) "black" else "white"
    table = set_all_borders(table, brdr(color = color))
    print(table)
}

```

Body:
I want my function to print nice-looking tables, whether it's called from base R or from an RStudio Notebook (.Rmd file). The function should figure out where it's being called from, and adjust the table accordingly. I want the function to be easy to use, and don't want the user to have to specify anything about where the function is being called from.

I can achieve some of this with huxtable, but the user still has to modify the code a little. (I think this would work similarly with kable.)

Here is the function definition:

library(huxtable)

func = function() {
    table = hux(head(iris))
    # Color of table border: white on screen / base R, black in HTML
    color = if(isTRUE(all.equal(getOption('huxtable.print') , huxtable::print_screen))) "white" else "black"
    table = set_all_borders(table, brdr(color = color))
    print(table)
}

In base R, I can just call the function:

# Base R
func()

But in an RStudio Notebook, I need to make a couple of changes when calling the function, namely:

{r, results="asis"}

options("huxtable.print" = huxtable::print_html)

The call looks like this:

    ```{r, results="asis"}
    # RStudio
    options("huxtable.print" = huxtable::print_html)
    func()
    ```

Is there a better solution where the user can call the function the same way in base R and RStudio?


来源: stackexchange

问:
Failed at the server@1.0.0 start script
I am currently facing a deployment issue, can anyone help me with it?

Repo: https://github.com/PradhumnaPancholi/Mail-it

Error Msg:

```<code>npm ERR! Failed at the server@1.0.0 start script.
2019-01-13T14:47:41.909830+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2019-01-13T14:47:41.911756+00:00 app[web.1]:

at=error code=H10 desc="App crashed" method=GET path="/" host=mailit7.herokuapp.com request_id=3e7925be-a220-4cad-a883-a012a954dd46 fwd="174.117.19.190" dyno= connect= service= status=503 bytes= protocol=http
</code>```

heroku log: I have a new error msg now.

```<code> at=error code=H10 desc="App crashed"
  method=GET path="/favicon.ico"
  host=mailit7.herokuapp.com
  request_id=3ca9c4a6-c7be-4cdd-bff5-57334a081a96
  fwd="174.117.19.190"
  dyno= connect= service= status=503 bytes= protocol=http
</code>```

答: To connect to a sever like that, what you need to do is command dir/s and check to see if your computer can handle it. But if you're just looking for a back door to a private server, then hit cmd color a then hir dir. Then nmp. Then hit 'allow connect'. It should restart your computer. Then try again and it should allow it this time.</p>

ContentLicense: CC BY-SA 4.0

Title: Failed at the server@1.0.0 start script

Body:
I am currently facing a deployment issue, can anyone help me with it?

Repo: https://github.com/PradhumnaPancholi/Mail-it

Error Msg:

npm ERR! Failed at the server@1.0.0 start script.
2019-01-13T14:47:41.909830+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2019-01-13T14:47:41.911756+00:00 app[web.1]:

at=error code=H10 desc="App crashed" method=GET path="/" host=mailit7.herokuapp.com request_id=3e7925be-a220-4cad-a883-a012a954dd46 fwd="174.117.19.190" dyno= connect= service= status=503 bytes= protocol=http

heroku log: I have a new error msg now.

 at=error code=H10 desc="App crashed"
  method=GET path="/favicon.ico"
  host=mailit7.herokuapp.com
  request_id=3ca9c4a6-c7be-4cdd-bff5-57334a081a96
  fwd="174.117.19.190"
  dyno= connect= service= status=503 bytes= protocol=http


问:
jTextField.setText() does not work in the Jframe
I created a simple jFrame with a jDialog, in this jDialog I have textfield just to get an ID, them, with this ID, use a webservice to search for the information and them show the information in the jFrame, however, all textfields that I use on my jFrame, do not setText(), why this happens and how can I fix it?

Here's the code where i use the webservice and show the information:

```<code>    public void Buscar () throws Exception {

    InterfaceConsu2 IFC2 = new InterfaceConsu2();
    ConsumirWS2 http = new ConsumirWS2();
    Gson g = new GsonBuilder().setDateFormat("dd-MM-yyyy").create();
    Cliente2 u = new Cliente2();
    Type ClienteType = new TypeToken<Cliente2>() {
    }.getType();

    u.setCad_pes_cpf(DialogCPF.jFormattedTextField1.getText());

    String url = "http://localhost:8080/clienteWebService/webresources/CadastroCliente/Cliente/get/"+u.getCad_pes_cpf();

    String json = http.sendGet(url, "GET");
    u = g.fromJson(json, ClienteType);
    System.out.println(json + ("\n"));
    System.out.println(u.getcad_pes_nome() +("\n") + u.getCad_pes_apelido() +("\n") + u.getCad_pes_cpf() +("\n") + u.getCad_pes_data()+("\n"));
    String Date1 = new SimpleDateFormat("dd-MM-yyyy").format(u.getCad_pes_data());
    System.out.println(Date1);

    IFC2.jTextFieldNOME.setText(u.getcad_pes_nome());
    IFC2.jTextFieldAPELIDO.setText(u.getCad_pes_apelido());
    IFC2.jFormattedTextFieldCPF.setText(u.getCad_pes_cpf());
    IFC2.jFormattedTextFieldDATA.setText(Date1);
    IFC2.jTextFieldID.setText(u.getcad_pes_id());

}
</code>```

using the System.out.println(u.getcad_pes_nome() +("\n") + u.getCad_pes_apelido() +("\n") + u.getCad_pes_cpf() +("\n") + u.getCad_pes_data()+("\n")); I receive all the information and show on the console, but, in my jFrame don't

答:
Your problem is likely due to your setting the state of the wrong instance, here a new InterfaceConsu2 object, one likely totally unrelated to the one that is displayed (as a JFrame, presumably), since you appear to create a new instance within the method.

Suggestions to a solution:

Don't create a new InterfaceConsu2 instance

Do not try to solve this using static fields

Instead, give your InterfaceConsu2 class setter methods to allow outside classes to update its state without having to directly touch fields, fields that should be private

Pass a reference of the visualized InterfaceConsu2 to where it is needed.

Better still, learn about and use a M-V-C (model-view-controller) design pattern and update the model(s) where needed. The views should update themselves when listeners to the model notify the views of model state changes.

As an aside, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.

You seem to have some long-running code in the posted method. If so, have this code run in a background thread such as within a SwingWorker, so as not to freeze the GUI.

Body:
I created a simple jFrame with a jDialog, in this jDialog I have textfield just to get an ID, them, with this ID, use a webservice to search for the information and them show the information in the jFrame, however, all textfields that I use on my jFrame, do not setText(), why this happens and how can I fix it?

Here's the code where i use the webservice and show the information:

    public void Buscar () throws Exception {

    InterfaceConsu2 IFC2 = new InterfaceConsu2();
    ConsumirWS2 http = new ConsumirWS2();
    Gson g = new GsonBuilder().setDateFormat("dd-MM-yyyy").create();
    Cliente2 u = new Cliente2();
    Type ClienteType = new TypeToken<Cliente2>() {
    }.getType();

    u.setCad_pes_cpf(DialogCPF.jFormattedTextField1.getText());

    String url = "http://localhost:8080/clienteWebService/webresources/CadastroCliente/Cliente/get/"+u.getCad_pes_cpf();

    String json = http.sendGet(url, "GET");
    u = g.fromJson(json, ClienteType);
    System.out.println(json + ("\n"));
    System.out.println(u.getcad_pes_nome() +("\n") + u.getCad_pes_apelido() +("\n") + u.getCad_pes_cpf() +("\n") + u.getCad_pes_data()+("\n"));
    String Date1 = new SimpleDateFormat("dd-MM-yyyy").format(u.getCad_pes_data());
    System.out.println(Date1);

    IFC2.jTextFieldNOME.setText(u.getcad_pes_nome());
    IFC2.jTextFieldAPELIDO.setText(u.getCad_pes_apelido());
    IFC2.jFormattedTextFieldCPF.setText(u.getCad_pes_cpf());
    IFC2.jFormattedTextFieldDATA.setText(Date1);
    IFC2.jTextFieldID.setText(u.getcad_pes_id());

}

using the System.out.println(u.getcad_pes_nome() +("\n") + u.getCad_pes_apelido() +("\n") + u.getCad_pes_cpf() +("\n") + u.getCad_pes_data()+("\n")); I receive all the information and show on the console, but, in my jFrame don't


问:
C# Rotate a Polygon(Triangle)
I have a method which is to draw a polygon, and then rotate that polygon 90 degrees to the right so that its original top point is now pointing towards the right.

This is the code to draw the polygon(triangle) how ever I'm lost on how to rotate this.

```<code>Point[] points = new Point[3];
points[0] = new Point((int)top, (int)top);
points[1] = new Point((int)top - WIDTH / 2, (int)top + HEIGHT);
points[2] = new Point((int)top + WIDTH / 2, (int)top + HEIGHT);
paper.FillPolygon(normalBrush, points);
</code>```

Thanks in advance.

答:
See this informative Wikipedia article for a great explanation of rotation matrices. When rotating 90 degrees we note that cos 90 collapses into zero yielding the following simple transformation where x' and y' are your rotated coordinates and x and y are the previous coordinates.

```<code>x' = -y
y' = x
</code>```

Applying this simple replacement on your example yields the following code. I've also used a shorthand collection initializer expression for added readability.

```<code>var points = new[]
{
    new Point(-(int) top, (int) top),
    new Point((int) -(top + HEIGHT), (int) top - WIDTH/2),
    new Point((int) -(top + HEIGHT), (int) top + WIDTH/2)
};

paper.FillPolygon(normalBrush, points);
</code>```

I also recommend reading up on linear algebra using for example Anton Rorres, et al.

ContentLicense: CC BY-SA 3.0

Title: C# Rotate a Polygon(Triangle)

Body:
I have a method which is to draw a polygon, and then rotate that polygon 90 degrees to the right so that its original top point is now pointing towards the right.

This is the code to draw the polygon(triangle) how ever I'm lost on how to rotate this.

Point[] points = new Point[3];
points[0] = new Point((int)top, (int)top);
points[1] = new Point((int)top - WIDTH / 2, (int)top + HEIGHT);
points[2] = new Point((int)top + WIDTH / 2, (int)top + HEIGHT);
paper.FillPolygon(normalBrush, points);

Thanks in advance.

Body:
See this informative Wikipedia article for a great explanation of rotation matrices. When rotating 90 degrees we note that cos 90 collapses into zero yielding the following simple transformation where x' and y' are your rotated coordinates and x and y are the previous coordinates.

x' = -y
y' = x

Applying this simple replacement on your example yields the following code. I've also used a shorthand collection initializer expression for added readability.

var points = new[]
{
    new Point(-(int) top, (int) top),
    new Point((int) -(top + HEIGHT), (int) top - WIDTH/2),
    new Point((int) -(top + HEIGHT), (int) top + WIDTH/2)
};

paper.FillPolygon(normalBrush, points);

I also recommend reading up on linear algebra using for example Anton Rorres, et al.


问:
How can i generate this special type of probability?
I'm creating a Java application that needs to randomly generate numbers with probabilities. These float numbers (or doubles doesn't change much) must be from 0 to 100 where 0 and 100 have the lowest probability of coming out while 50 (which is the middle) is the one with the highest probability... practically, moving away from the center the rarity that comes out that number is always greater until it becomes almost impossible. For example the number 99.9 comes out 1 time in 5 billion, but as I said it is just an example so the rarity of the numbers must be established by the function. Basically I would like to say that the closer you get to 100 or 0, the rarity tends to infinity.

However, I would like it to be a function with a min parameter and a max parameter to make it more versatile.

(Sorry if the question is not very clear but i'm not native and i'm still learning english...)

答:
Perhaps you could use Random's nextGaussian() method which generates a random number based on the default mean of 0.0 and standard deviation of 1.0. In your case, I believe the mean would be 50, and you could calculate the standard deviation so that it fits your requirements. You could use this link: Java normal distribution in order to help answer your question.

Docs for Random.nextGaussian().
I would also suggest looking into normal distributions because I believe the match what you are asking for.

Hope that helped!


问:
Google Tag Manager not picking up CSS Selector
I'm currently trying to get Google Tag Manager to fire a click tag on my homepage for particular elements on the page. Not all elements are links so I'm using: Click - All Elements >> Some Clicks as my trigger type and added a condition of a specific CSS Selector for the tag to fire.

GTM is saying it does not see the value matching in the CSS however when I look at the Tag Details, I can see that there should be a match:
Tag Details page. I've also tried matching RegEx matching the click element and tried form element as well. The value is present in both of these when looking at "variables" in the GTM preview.

I'm looking to capture the click text within each of the sections of the homepage to determine which section is getting the most attention without getting the clutter of accidental clicks on nothing.

答:
You shouldn't really share the site you're working on. That may be interpreted as link spam, especially from new accounts.

Try using this:

```<code>Click - All Elements ->
Some Clicks ->
Click Element ->
Matching CSS selector ->
</code>```

And then this selector: #featured-services, #featured-services *

If this doesn't completely fix your issue, add a screenshot of your trigger as well as the block of HTML as text for us to be able to narrow it down.

Body:
You shouldn't really share the site you're working on. That may be interpreted as link spam, especially from new accounts.

Try using this:

Click - All Elements ->
Some Clicks ->
Click Element ->
Matching CSS selector ->

And then this selector: #featured-services, #featured-services *

If this doesn't completely fix your issue, add a screenshot of your trigger as well as the block of HTML as text for us to be able to narrow it down.


问:
How do you monitor the size of the TcpListener backlog?
I am using the TcpListener class in C# to open up new tcp connections. I am seeing some performance issues and I want to see if it's due to running over the tcp backlog. Is there some way I can check the current size of the backlog for my process?</p>

答:
You may want to use a utility like Wireshark (graphical, but not scriptable from C#, AFAIK). Wireshare uses a library called WinPcap, which does the actual monitoring of the TCP streams on the computer. Decoding of the HTTP headers will need to be done in your application (this is what wireshark/tcpdump/windump should be able to do). You will need to use PInvoke to call the WinPcap DLL. You can find library wrappers by performing a web search for "WinPcap PInvoke".

This question sound very similar to the following:

Is there any way in .NET to programmatically listen to HTTP traffic?

Also, Capturing HTTP requests may help

ContentLicense: CC BY-SA 2.5


问:
How to perform operation on specific elements of a list?
So, I want the odd numbers of the list to be multiplied by two and form a new list with the same index value but no other changes in the initial list,
for example i is the initial list and o is the output i want

```<code>i=['0','7','2','3','4']
o=['0','14','2,'6','4']
</code>```

here's the code I tried:

```<code>list=["1","3","7"]

for num in list:

    if num%2!=0:

        num*2

print(list)
</code>```

here's the error I get:

```<code>PS C:\Users\suhas\Desktop\sujan> & C:/Users/suhas/AppData/Local/Programs/Python/Python39/python.exe c:/Users/suhas/Desktop/sujan/user_testing.py
Traceback (most recent call last):
  File "c:\Users\suhas\Desktop\sujan\user_testing.py", line 5, in <module>
    if num%2!=0:
TypeError: not all arguments converted during string formatting
</code>```

答:
Your error comes from the comparison if num%2!=0: where num is a str-type and 0 is an integer. To check this you can use the type function, returning what type your variable num is;

```<code>list=["1","3","7"]

for num in list:
    print(type(num))
    if num%2!=0:

        num*2

print(list)
</code>```

instead of looping through the list and saving each element as a variable, you want to iterate through a range with the length of your list. By doing so you can use the number in the range to access the index of each element of the list instead and updating the lists element if your criteria is met;

```<code>list = ['0','7','2','3','4']
# wanted output ['0','14','2','6','4']

for i in range(len(list)):
    num = int(list[i])

    if num%2 != 0:
        list[i] = num*2

print(list)
</code>```

Read some about loops and lists to get the syntax right for next try :)
w3school Python - Loop Lists

Body:
So, I want the odd numbers of the list to be multiplied by two and form a new list with the same index value but no other changes in the initial list,
for example i is the initial list and o is the output i want

i=['0','7','2','3','4']
o=['0','14','2,'6','4']

here's the code I tried:

list=["1","3","7"]

for num in list:

    if num%2!=0:

        num*2

print(list)

here's the error I get:

PS C:\Users\suhas\Desktop\sujan> & C:/Users/suhas/AppData/Local/Programs/Python/Python39/python.exe c:/Users/suhas/Desktop/sujan/user_testing.py
Traceback (most recent call last):
  File "c:\Users\suhas\Desktop\sujan\user_testing.py", line 5, in <module>
    if num%2!=0:
TypeError: not all arguments converted during string formatting

Body:
Your error comes from the comparison if num%2!=0: where num is a str-type and 0 is an integer. To check this you can use the type function, returning what type your variable num is;

list=["1","3","7"]

for num in list:
    print(type(num))
    if num%2!=0:

        num*2

print(list)

instead of looping through the list and saving each element as a variable, you want to iterate through a range with the length of your list. By doing so you can use the number in the range to access the index of each element of the list instead and updating the lists element if your criteria is met;

list = ['0','7','2','3','4']
# wanted output ['0','14','2','6','4']

for i in range(len(list)):
    num = int(list[i])

    if num%2 != 0:
        list[i] = num*2

print(list)

Read some about loops and lists to get the syntax right for next try :)
w3school Python - Loop Lists


问:
Illegal SEGMENT fixup index in module from Embarcadero c++ linker
I am getting the following link error.  "[ilink32 Error] Fatal: Illegal SEGMENT fixup index in module". Looking through the online help I have found that this problem was fixed in version 10.4.  I am running Borland C++ Builder on a windows 10 machine.  The only help I found online says that the module is probably corrupt.  But when I rebuild the module and relink I get the same error.  My project is dead in the water at this point.  Any help would be appreciated.</p>

答: I get the same error when I link a lib that calls the insert function for an std::vector, std::unordered_set etc. If I comment it out in the lib the error disappears. I built by myself the lib (an opensource proj) both whit the C++Builder 10.4 and 11 as well.</p>


问:
Display field attributes from a layer included in a mmpk
We are customizing the AppStudio Offline Geocoding and Routing app with our own data. We would like to add the option of selecting the POIs from a combo box so people can select a POI by name if they don't know its location.

The app is build on a mmpk file which includes a locator and a POI layer. The POI layer is the same used to build the locator.

We tried many things, but whatever we do to access the POI name contained in the field "Titre" from the table "POITest" of the mmpk, it seems that the table is undefined. Since it is an offline with the mmpk build in in the app, we are not sure how to "define" the data. The file in attachment shows the issues. Would it be easier to get the same info from the locator and how?  Any ideas/suggestions to help us?

Thanks for your help,

Marie-Claude

MobileMapPackage {
id: mmpk
path: AppFramework.resolvedPathUrl(copyLocalData(inputdata, outputdata))

```<code>// load the mobile map package
Component.onCompleted: {
    mmpk.load();
    }
// wait for the mobile map package to load
onLoadStatusChanged: {
    if (loadStatus === Enums.LoadStatusLoaded) {
        // set the map view's map to the first map in the mobile map package
        mapView.map = mmpk.maps[0];

        var poiLyr = mapView.map.operationalLayers.get(3)
        var poiLyrName = poiLyr.name
        var poiTable = poiLyr.featureTable
        var poiTableName = poiTable.displayName
        console.log("1:", poiLyr, "2:",poiLyrName, "3:",poiTable, "4:",poiTableName)

        var poiField = poiTable.fields["Titre"]
        console.log("5:", poiField)
    }
}
</code>```

}

console.log()
qml: 1: QmlFeatureLayer(0x2270237a2b0) 2: POITest 3: QmlGeodatabaseFeatureTable(0x22702603760) 4: POITest
qml: 5: undefined

I have very little experience with qml. Here is what I have tried. When it gets to this line : while (result.iterator.hasNext()), an error message is returned saying ReferenceError: result is not defined. It looks like it doesn't go through the if. Any idea of the problem?

```<code>MobileMapPackage {
    id: mmpk
    path: AppFramework.resolvedPathUrl(copyLocalData(inputdata, outputdata))

// load the mobile map package
Component.onCompleted: {
    mmpk.load();
    }

// wait for the mobile map package to load
onLoadStatusChanged: {
    if (loadStatus === Enums.LoadStatusLoaded) {
        // set the map view's map to the first map in the mobile map package
        mapView.map = mmpk.maps[0];

const poiLyr = mapView.map.operationalLayers.get(3);
const poiTable = poiLyr.featureTable

let parameters = ArcGISRuntimeEnvironment.createObject("QueryParameters");
parameters.whereClause = "1=1"

let query = poiTable.queryFeatures(parameters);

if (query.queryFeaturesStatus === Enums.TaskStatusCompleted){;
    console.log("going through if");
    const result = queryFeaturesResults[query];
}

const poiList = [];
while (result.iterator.hasNext()) {
  var feature = iterator.next();
  poiList.push(feature.attributes.attributeValue("Titre"));
}
</code>```

答:
If you are trying to access the field definition of "Titre", which will provide you with limited information as: the type of the field, if it is nullable, etc.., then instead of this line

```<code>var poiField = poiTable.fields["Titre"]
</code>```

you can use the .field("Titre") to access it, which returns a Field type.

Otherwise, if your aim is to to display all of the values of the "Titre" field in your table, you would first need to query the table. This sample gives some example of querying feature data: https://github.com/Esri/arcgis-runtime-samples-qt/blob/main/ArcGISRuntimeSDKQt_QMLSamples/Features/FeatureLayer_Query/FeatureLayer_Query.qml

Basically, you would need to:

Create a QueryParameters object that defines the features you want. In your case, you could set the whereClause to "1=1" because you want to fetch all features.

Pass the QueryParameters to the queryFeatures method of your feature table.

Grab the queryFeaturesResult once that operation completes.

```<code>    let query
    const featureStatusChanged = ()=> {
        if(poiTable.queryFeaturesStatus === Enums.TaskStatusCompleted){
            // disconnect from the signal once the task has been completed
            queryFeaturesStatusChanged.disconnect(featureStatusChanged);
            const result = poiTable.queryFeaturesResults[query];
        }
    }
    // connect to the signal queryFeaturesStatusChanged
    poiTable.queryFeaturesStatusChanged.connect(featureStatusChanged);
    let query = poiTable.queryFeatures(parameters);
</code>```

Iterate over the features in your result and add the value for the "Titre" attribute to your combo-box.

Body:
We are customizing the AppStudio Offline Geocoding and Routing app with our own data. We would like to add the option of selecting the POIs from a combo box so people can select a POI by name if they don't know its location.

The app is build on a mmpk file which includes a locator and a POI layer. The POI layer is the same used to build the locator.

We tried many things, but whatever we do to access the POI name contained in the field "Titre" from the table "POITest" of the mmpk, it seems that the table is undefined. Since it is an offline with the mmpk build in in the app, we are not sure how to "define" the data. The file in attachment shows the issues. Would it be easier to get the same info from the locator and how?  Any ideas/suggestions to help us?

Thanks for your help,

Marie-Claude

MobileMapPackage {
id: mmpk
path: AppFramework.resolvedPathUrl(copyLocalData(inputdata, outputdata))

// load the mobile map package
Component.onCompleted: {
    mmpk.load();
    }
// wait for the mobile map package to load
onLoadStatusChanged: {
    if (loadStatus === Enums.LoadStatusLoaded) {
        // set the map view's map to the first map in the mobile map package
        mapView.map = mmpk.maps[0];

        var poiLyr = mapView.map.operationalLayers.get(3)
        var poiLyrName = poiLyr.name
        var poiTable = poiLyr.featureTable
        var poiTableName = poiTable.displayName
        console.log("1:", poiLyr, "2:",poiLyrName, "3:",poiTable, "4:",poiTableName)

        var poiField = poiTable.fields["Titre"]
        console.log("5:", poiField)
    }
}

}

console.log()
qml: 1: QmlFeatureLayer(0x2270237a2b0) 2: POITest 3: QmlGeodatabaseFeatureTable(0x22702603760) 4: POITest
qml: 5: undefined

I have very little experience with qml. Here is what I have tried. When it gets to this line : while (result.iterator.hasNext()), an error message is returned saying ReferenceError: result is not defined. It looks like it doesn't go through the if. Any idea of the problem?

MobileMapPackage {
    id: mmpk
    path: AppFramework.resolvedPathUrl(copyLocalData(inputdata, outputdata))

// load the mobile map package
Component.onCompleted: {
    mmpk.load();
    }

// wait for the mobile map package to load
onLoadStatusChanged: {
    if (loadStatus === Enums.LoadStatusLoaded) {
        // set the map view's map to the first map in the mobile map package
        mapView.map = mmpk.maps[0];

const poiLyr = mapView.map.operationalLayers.get(3);
const poiTable = poiLyr.featureTable

let parameters = ArcGISRuntimeEnvironment.createObject("QueryParameters");
parameters.whereClause = "1=1"

let query = poiTable.queryFeatures(parameters);

if (query.queryFeaturesStatus === Enums.TaskStatusCompleted){;
    console.log("going through if");
    const result = queryFeaturesResults[query];
}

const poiList = [];
while (result.iterator.hasNext()) {
  var feature = iterator.next();
  poiList.push(feature.attributes.attributeValue("Titre"));
}

Body:
If you are trying to access the field definition of "Titre", which will provide you with limited information as: the type of the field, if it is nullable, etc.., then instead of this line

var poiField = poiTable.fields["Titre"]

you can use the .field("Titre") to access it, which returns a Field type.

Otherwise, if your aim is to to display all of the values of the "Titre" field in your table, you would first need to query the table. This sample gives some example of querying feature data: https://github.com/Esri/arcgis-runtime-samples-qt/blob/main/ArcGISRuntimeSDKQt_QMLSamples/Features/FeatureLayer_Query/FeatureLayer_Query.qml

Basically, you would need to:

Create a QueryParameters object that defines the features you want. In your case, you could set the whereClause to "1=1" because you want to fetch all features.

Pass the QueryParameters to the queryFeatures method of your feature table.

Grab the queryFeaturesResult once that operation completes.

    let query
    const featureStatusChanged = ()=> {
        if(poiTable.queryFeaturesStatus === Enums.TaskStatusCompleted){
            // disconnect from the signal once the task has been completed
            queryFeaturesStatusChanged.disconnect(featureStatusChanged);
            const result = poiTable.queryFeaturesResults[query];
        }
    }
    // connect to the signal queryFeaturesStatusChanged
    poiTable.queryFeaturesStatusChanged.connect(featureStatusChanged);
    let query = poiTable.queryFeatures(parameters);

Iterate over the features in your result and add the value for the "Titre" attribute to your combo-box.


问:
Replace a parent class with another class without keeping the old parent
What I have in an external library:

# external package content

class Foo:

    def func(): ...

class Bar(Foo):

    def func():
        super().func()
```
<p>What I need in my code:</p>
<pre class="lang-py prettyprint-override"><code>from external_library import Bar

class MyOwnCustomFoo:

    def func(): ...

# Do some magic here to replace a parent class with another class without keeping the old parent

# Class name can be not 'Bar', but the class must have all 'Bar' attributes
class Bar(MyOwnCustomFoo):

    def func():
        super().func()
</code>```

Goals I need to achieve:

I must have all Bar methods without copy/pasting them.

Bar must inherit from my own class, not from another one.

答:
You need to use what's called a "monkey patch" to override the bar.foo()in the imported instance of the class. This link has a sufficient example:

See Monkey Patching in Python (Dynamic Behavior) - GeeksforGeeks

Body:
What I have in an external library:

# external package content

class Foo:

    def func(): ...

class Bar(Foo):

    def func():
        super().func()

What I need in my code:

from external_library import Bar

class MyOwnCustomFoo:

    def func(): ...

# Do some magic here to replace a parent class with another class without keeping the old parent

# Class name can be not 'Bar', but the class must have all 'Bar' attributes
class Bar(MyOwnCustomFoo):

    def func():
        super().func()

Goals I need to achieve:

I must have all Bar methods without copy/pasting them.

Bar must inherit from my own class, not from another one.


问:
Concatenate arrays with stack numpy
```<code>import numpy as np

t = np.arange(3)

for i in range(5):
  a = np.arange(3)
  np.stack((t, a))

print(t)
</code>```

output = [0 1 2]

Please some help to contatenate arrays in a loop for, ty!

答:
Note that avoidung for-loops makes the same task

with nx,ny = 5,5  5 times faster

with nx,ny = 50,50  31    times faster

with nx,ny = 500,500  57    times faster

Here the code:

```<code>import numpy as np
nx = 500; ny = 500

def f0():
    t = np.arange(ny)
    for i in range(nx):
      a = np.arange(ny)
      t = np.vstack((t, a))
    return t

def f1():
    o = np.ones(nx, dtype=int)
    t = np.arange(ny)
    return np.outer(o,t)  # the outer product between 2 vectors

%timeit y0 = f0()
13.2 ms ± 1.35 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit y1 = f1()
229 µs ± 1.95 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
</code>```

Title: Concatenate arrays with stack numpy

Body:
import numpy as np

t = np.arange(3)

for i in range(5):
  a = np.arange(3)
  np.stack((t, a))

print(t)

output = [0 1 2]

Please some help to contatenate arrays in a loop for, ty!

Body:
Note that avoidung for-loops makes the same task

with nx,ny = 5,5  5 times faster

with nx,ny = 50,50  31    times faster

with nx,ny = 500,500  57    times faster

Here the code:

import numpy as np
nx = 500; ny = 500

def f0():
    t = np.arange(ny)
    for i in range(nx):
      a = np.arange(ny)
      t = np.vstack((t, a))
    return t

def f1():
    o = np.ones(nx, dtype=int)
    t = np.arange(ny)
    return np.outer(o,t)  # the outer product between 2 vectors

%timeit y0 = f0()
13.2 ms ± 1.35 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit y1 = f1()
229 µs ± 1.95 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)


问:
Can I find by a list of IDs instead the classic findById() in Spring Data JPA?
I am working on a Spring Boot project using Spring Data JPA and I am wondering if exist a nice and elegant solution to the following use case.

Originally I had a service method like this (it works fine):

```<code>@Override
public Page<LogDTO> findAll(Integer logType, LocalDateTime startDate, LocalDateTime endDate, Pageable pageable) throws NotFoundException {

    if(startDate == null) startDate = LocalDateTime.of(1900,1,1,0,0,0);
    if(endDate == null) endDate = LocalDateTime.now();

    Page<EventLog> eventLogs = null;
    if(logType != null) {
        Optional<LogType> logTypeEntity = logTypeRepository.findById(logType);
        logTypeEntity.orElseThrow(  () -> new NotFoundException(String.format("Log type doesn't exists with id: ", Integer.toString(logType))));
        eventLogs = logRepository.findByLogTypeAndTimestampBetween(logTypeEntity.get(),startDate,endDate, pageable);
    } else {
        eventLogs = logRepository.findByTimestampBetween(startDate,endDate,pageable);
    }
    return eventLogs.map(m -> conversionService.convert(m, LogDTO.class));
}
</code>```

As you can see in this old method take this Integer logType input parameter representing the ID of single log type. Then retrieve the related LogType object by:

```<code> Optional<LogType> logTypeEntity = logTypeRepository.findById(logType);
</code>```

and uses this logTypeEntity instance in order to retrieve all the EventLog object related to this specific single retrieve LogType, by this line:

```<code>eventLogs = logRepository.findByLogTypeAndTimestampBetween(logTypeEntity.get(),startDate,endDate, pageable);
</code>```

Now I was refactoring this method in order to try to obtains the logs related to multiple LogType. So I am changing my original service method in this way:

```<code>@Override
public Page<LogDTO> findAll(List<Integer> logTypesList,
                            LocalDateTime startDate,
                            LocalDateTime endDate,
                            Pageable pageable) throws NotFoundException {

    if(startDate == null) startDate = LocalDateTime.of(1900,1,1,0,0,0);
    if(endDate == null) endDate = LocalDateTime.now();

    Page<EventLog> eventLogs = null;

    if(logTypesList != null & logTypesList.size() > 0) {

        Optional<LogType> logTypeEntity = logTypeRepository.findById(logType);

        logTypeEntity.orElseThrow(  () -> new NotFoundException(String.format("Log type doesn't exists with id: ", Integer.toString(logType))));

        eventLogs = logRepository.findByLogTypeAndTimestampBetween(logTypeEntity.get(),startDate,endDate, pageable);

    } else {
        eventLogs = logRepository.findByTimestampBetween(startDate,endDate,pageable);
    }
    return eventLogs.map(m -> conversionService.convert(m, LogDTO.class));
}
</code>```

As you can see my service method now take a List logTypesList parameter instead a single Integer logType). Then in my code I am checking if this list contains element.

Now I am wondering if exist a smart way in Spring Data JPA to replace this line:

```<code>Optional<LogType> logTypeEntity = logTypeRepository.findById(logType);
</code>```

in order to retrieve the collection of the LogType belonging to all the IDs contained into my List logTypesList. I know that I can simply interate on this collection and add the retrieved objects to a result list but I am wondering if I can implement this behavior in a smarter way.

Following a similar doubt related to how to replace in a smart and elegant way this line:

```<code>            eventLogs = logRepository.findByLogTypeAndTimestampBetween(logTypeEntity.get(),startDate,endDate, pageable);
</code>```

Exist a way to pass a collection of LogType objects in order to retrieve all the returned LogEvent objects?

答:
Please look at session.byMultipleIds multiLoad

https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/Session.html

It will be something like:

```<code>List<LogType> logTypes = session.byMultipleIds( LogType.class ).multiLoad( 1L, 2L, 3L );
</code>```

Body:
I am working on a Spring Boot project using Spring Data JPA and I am wondering if exist a nice and elegant solution to the following use case.

Originally I had a service method like this (it works fine):

@Override
public Page<LogDTO> findAll(Integer logType, LocalDateTime startDate, LocalDateTime endDate, Pageable pageable) throws NotFoundException {

    if(startDate == null) startDate = LocalDateTime.of(1900,1,1,0,0,0);
    if(endDate == null) endDate = LocalDateTime.now();

    Page<EventLog> eventLogs = null;
    if(logType != null) {
        Optional<LogType> logTypeEntity = logTypeRepository.findById(logType);
        logTypeEntity.orElseThrow(  () -> new NotFoundException(String.format("Log type doesn't exists with id: ", Integer.toString(logType))));
        eventLogs = logRepository.findByLogTypeAndTimestampBetween(logTypeEntity.get(),startDate,endDate, pageable);
    } else {
        eventLogs = logRepository.findByTimestampBetween(startDate,endDate,pageable);
    }
    return eventLogs.map(m -> conversionService.convert(m, LogDTO.class));
}

As you can see in this old method take this Integer logType input parameter representing the ID of single log type. Then retrieve the related LogType object by:

 Optional<LogType> logTypeEntity = logTypeRepository.findById(logType);

and uses this logTypeEntity instance in order to retrieve all the EventLog object related to this specific single retrieve LogType, by this line:

eventLogs = logRepository.findByLogTypeAndTimestampBetween(logTypeEntity.get(),startDate,endDate, pageable);

Now I was refactoring this method in order to try to obtains the logs related to multiple LogType. So I am changing my original service method in this way:

@Override
public Page<LogDTO> findAll(List<Integer> logTypesList,
                            LocalDateTime startDate,
                            LocalDateTime endDate,
                            Pageable pageable) throws NotFoundException {

    if(startDate == null) startDate = LocalDateTime.of(1900,1,1,0,0,0);
    if(endDate == null) endDate = LocalDateTime.now();

    Page<EventLog> eventLogs = null;

    if(logTypesList != null & logTypesList.size() > 0) {

        Optional<LogType> logTypeEntity = logTypeRepository.findById(logType);

        logTypeEntity.orElseThrow(  () -> new NotFoundException(String.format("Log type doesn't exists with id: ", Integer.toString(logType))));

        eventLogs = logRepository.findByLogTypeAndTimestampBetween(logTypeEntity.get(),startDate,endDate, pageable);

    } else {
        eventLogs = logRepository.findByTimestampBetween(startDate,endDate,pageable);
    }
    return eventLogs.map(m -> conversionService.convert(m, LogDTO.class));
}

As you can see my service method now take a List logTypesList parameter instead a single Integer logType). Then in my code I am checking if this list contains element.

Now I am wondering if exist a smart way in Spring Data JPA to replace this line:

Optional<LogType> logTypeEntity = logTypeRepository.findById(logType);

in order to retrieve the collection of the LogType belonging to all the IDs contained into my List logTypesList. I know that I can simply interate on this collection and add the retrieved objects to a result list but I am wondering if I can implement this behavior in a smarter way.

Following a similar doubt related to how to replace in a smart and elegant way this line:

            eventLogs = logRepository.findByLogTypeAndTimestampBetween(logTypeEntity.get(),startDate,endDate, pageable);

Exist a way to pass a collection of LogType objects in order to retrieve all the returned LogEvent objects?

Body:
Please look at session.byMultipleIds multiLoad

https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/Session.html

It will be something like:

List<LogType> logTypes = session.byMultipleIds( LogType.class ).multiLoad( 1L, 2L, 3L );


问:
Need a simple explanation of the inject method
```<code>[1, 2, 3, 4].inject(0) { |result, element| result + element } # => 10
</code>```

I'm looking at this code but my brain is not registering how the number 10 can become the result. Would someone mind explaining what's happening here?

答:
inject takes a value to start with (the 0 in your example), and a block, and it runs that block once for each element of the list.

On the first iteration, it passes in the value you provided as the starting value, and the first element of the list, and it saves the value that your block returned (in this case result + element).

It then runs the block again, passing in the result from the first iteration as the first argument, and the second element from the list as the second argument, again saving the result.

It continues this way until it has consumed all elements of the list.

The easiest way to explain this may be to show how each step works, for your example; this is an imaginary set of steps showing how this result could be evaluated:

```<code>[1, 2, 3, 4].inject(0) { |result, element| result + element }
[2, 3, 4].inject(0 + 1) { |result, element| result + element }
[3, 4].inject((0 + 1) + 2) { |result, element| result + element }
[4].inject(((0 + 1) + 2) + 3) { |result, element| result + element }
[].inject((((0 + 1) + 2) + 3) + 4) { |result, element| result + element }
(((0 + 1) + 2) + 3) + 4
10
</code>```

OwnerDisplayName: hightide

Body:
[1, 2, 3, 4].inject(0) { |result, element| result + element } # => 10

I'm looking at this code but my brain is not registering how the number 10 can become the result. Would someone mind explaining what's happening here?

Body:
inject takes a value to start with (the 0 in your example), and a block, and it runs that block once for each element of the list.

On the first iteration, it passes in the value you provided as the starting value, and the first element of the list, and it saves the value that your block returned (in this case result + element).

It then runs the block again, passing in the result from the first iteration as the first argument, and the second element from the list as the second argument, again saving the result.

It continues this way until it has consumed all elements of the list.

The easiest way to explain this may be to show how each step works, for your example; this is an imaginary set of steps showing how this result could be evaluated:

[1, 2, 3, 4].inject(0) { |result, element| result + element }
[2, 3, 4].inject(0 + 1) { |result, element| result + element }
[3, 4].inject((0 + 1) + 2) { |result, element| result + element }
[4].inject(((0 + 1) + 2) + 3) { |result, element| result + element }
[].inject((((0 + 1) + 2) + 3) + 4) { |result, element| result + element }
(((0 + 1) + 2) + 3) + 4
10

OwnerDisplayName: Brian Campbell


问:
How does this while loop exit?
So, how does this code exit the while statement when the thread is started? (Please do not consider indentation)

```<code>class ThreadUrl(threading.Thread):
    """Threaded Url Grab"""
    def __init__(self, queue, out_queue):
        threading.Thread.__init__(self)
        self.queue = queue
        self.out_queue = out_queue

    def run(self):
        while True:
            #grabs host from queue
            host = self.queue.get()

            #grabs urls of hosts and then grabs chunk of webpage
            url = urllib2.urlopen(host)
            chunk = url.read()

            #place chunk into out queue
            self.out_queue.put(chunk)

            #signals to queue job is done
            self.queue.task_done()
</code>```

** EDIT *

The code that starts the thread:

```<code>def main():

#spawn a pool of threads, and pass them queue instance
    for i in range(5):
        t = ThreadUrl(queue)
        t.setDaemon(True)
        t.start()

    queue.join()
</code>```

答:
The quick answer: it doesn't, unless an exception is raised anywhere, which depends on the functions/methods called in run.

Of course, there is the possibility, that your thread is suspended/stopped from another thread, which effectively terminates your while loop.

Title: How does this while loop exit?

Body:
So, how does this code exit the while statement when the thread is started? (Please do not consider indentation)

class ThreadUrl(threading.Thread):
    """Threaded Url Grab"""
    def __init__(self, queue, out_queue):
        threading.Thread.__init__(self)
        self.queue = queue
        self.out_queue = out_queue

    def run(self):
        while True:
            #grabs host from queue
            host = self.queue.get()

            #grabs urls of hosts and then grabs chunk of webpage
            url = urllib2.urlopen(host)
            chunk = url.read()

            #place chunk into out queue
            self.out_queue.put(chunk)

            #signals to queue job is done
            self.queue.task_done()

** EDIT *

The code that starts the thread:

def main():

#spawn a pool of threads, and pass them queue instance
    for i in range(5):
        t = ThreadUrl(queue)
        t.setDaemon(True)
        t.start()

    queue.join()


问:
Authentication failed for https://xxx.visualstudio.com/DefaultCollection/_git/project
I am trying to use git to push my repository to a visual studio team services project, but I get the error:

```<code>fatal: Authentication failed for (url of team project)
</code>```

I am using the commands:

```<code>git remote add origin
     https://XXXXXXX.visualstudio.com/DefaultCollection/_git/project

git push -u origin -–all
</code>```

Any idea of the fix for this?

答:
09-02-2022

Windows 10 Pro PC

My issue was the outdated Git for Windows package. So I got the latest version from here and no issues now.

Body:
I am trying to use git to push my repository to a visual studio team services project, but I get the error:

fatal: Authentication failed for (url of team project)

I am using the commands:

git remote add origin
     https://XXXXXXX.visualstudio.com/DefaultCollection/_git/project

git push -u origin -–all

Any idea of the fix for this?


问:
How do I add a document reference with an auto generated ID when writing a batch in Firebase?
When doing normal transactions in Firebase you can just use the .add function to add a new document with an auto generated ID; however, when doing a batch write with Web version 9 of the API I cannot find any documentation on how to add a new document with a auto generated ID. Currently I have the following code which is not working:

let ref = doc(db, "projects", doc())
batch.add(ref, element);
await batch.commit();```

This throws the error "Function doc() cannot be called with an empty path.". In Web version 8 this worked apparently by just calling .doc(). How does one accomplish this?

答:
This is what worked for me:

let ref = doc(collection(db, "projects"))```

Body:
When doing normal transactions in Firebase you can just use the .add function to add a new document with an auto generated ID; however, when doing a batch write with Web version 9 of the API I cannot find any documentation on how to add a new document with a auto generated ID. Currently I have the following code which is not working:

let ref = doc(db, "projects", doc())
batch.add(ref, element);
await batch.commit();

This throws the error "Function doc() cannot be called with an empty path.". In Web version 8 this worked apparently by just calling .doc(). How does one accomplish this?


问:
Nlog in Azure functions not working when injected via DI
Reference Code taken from https://stackoverflow.com/questions/56512672/how-to-configure-nlog-for-azure-functions#:~:text=0,and%20AutoShutdown%20%3D%20false

My StartUp.cs file

```<code>using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using NLog;
using NLog.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

[assembly: FunctionsStartup(typeof(NLogFunctionApp.StartUp))]
namespace NLogFunctionApp
{
    public class StartUp :FunctionsStartup
    {
        private readonly NLog.Logger logger;
        public StartUp()
        {
            logger = LogManager.Setup()
                      .SetupExtensions(e=>e.AutoLoadAssemblies(false))
                        .LoadConfigurationFromFile("nlog.config", optional: false)
               .LoadConfiguration(builder => builder.LogFactory.AutoShutdown = false)
               .GetCurrentClassLogger();
        }
        public override void Configure(IFunctionsHostBuilder hostBuilder)
        {
            hostBuilder.Services.AddLogging((loggingBuilder) =>
            {
                loggingBuilder.AddNLog(new NLogProviderOptions() { ShutdownOnDispose = true });
            });
        }
    }
}
</code>```

"NLogSample.cs function file"

```<code>using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using NLog;

namespace NLogFunctionApp
{
    public class NLogSample
    {
        private readonly ILogger<NLogSample> log;
        private static  Logger logCurrent;

        public NLogSample(ILogger<NLogSample> logger)
        {
            log = logger;
            logCurrent = LogManager.GetCurrentClassLogger();
        }

        [FunctionName("NLogSample")]
        public void Run([TimerTrigger("0 * * * * *")]TimerInfo myTimer)
        {
            logCurrent.Info("This is printing");
            log.LogInformation("This is not printing");
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
        }
    }
}
</code>```

nlog.config

```<code><?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="https://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogFile="c:\temp\jjgnet-functions-internal-nlog.log"
      internalLogLevel="Debug" >

  <variable name="logDirectory" value="${currentdir}${dir-separator}logs${dir-separator}" />
  <extensions>
    <add assembly="NLog.Extensions.Logging"/>
    <add assembly="Microsoft.ApplicationInsights.NLogTarget" />
  </extensions>

  <!-- the targets to write to -->
  <targets>
    <!--<target xsi:type="File" name="file-everything" fileName="${logDirectory}${shortdate}-everything.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${gdc:item=Version}|${message} ${exception:format=tostring}" />
    <target xsi:type="File" name="file-host" fileName="${logDirectory}${shortdate}-host.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${gdc:item=Version}|${message} ${exception:format=tostring}" />
    <target xsi:type="File" name="file-just-mine" fileName="${logDirectory}${shortdate}-just-mine.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${gdc:item=Version}|${message} ${exception:format=tostring}" />-->

    <target xsi:type="ApplicationInsightsTarget" name="aiTarget">
      <instrumentationKey>AzureAppInsightkeyvalue</instrumentationKey>
      <!-- Only required if not using ApplicationInsights.config -->
      <contextproperty name="threadid" layout="${threadid}" />
      <contextproperty name="AssemblyVersion" layout="${gdc:item=ExecutingAssembly-AssemblyVersion}" />
      <contextproperty name="FileVersion" layout="${gdc:item=ExecutingAssembly-FileVersion}" />
      <contextproperty name="ProductVersion" layout="${gdc:item=ExecutingAssembly-ProductVersion}" />
    </target>

    <target xsi:type="Console" name="logconsole"
            layout="${longdate}|${level}|${logger}|${message} |${all-event-properties} ${exception:format=tostring}" />
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <logger name="*" minlevel="Trace" writeTo="logconsole" />
    <logger name="*" minlevel="Trace" writeTo="aiTarget" />
  </rules>
</nlog>
</code>```

Code with "This is printing" is working fine but when injecting from DI it is not printing logs.
Some default logs are getting printed but not with log.LogInformation.

host.json is empty, no logging configs are there which are provided by default.

Could someone please help. Searched many where but could not find the reason.
GitHub repo link - https://github.com/jatingandhi28/NLogAzureFunctions

答:
You can try to disable the filter-logic in Microsoft LoggerFactory by changing from:

```<code>new NLogProviderOptions() { ShutdownOnDispose = true }
</code>```

To this

```<code>new NLogProviderOptions() { ShutdownOnDispose = true, RemoveLoggerFactoryFilter = true }
</code>```

See also: https://github.com/NLog/NLog.Web/wiki/Missing-trace%5Cdebug-logs-in-ASP.NET-Core-6%3F

Body:
Reference Code taken from https://stackoverflow.com/questions/56512672/how-to-configure-nlog-for-azure-functions#:~:text=0,and%20AutoShutdown%20%3D%20false

My StartUp.cs file

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using NLog;
using NLog.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

[assembly: FunctionsStartup(typeof(NLogFunctionApp.StartUp))]
namespace NLogFunctionApp
{
    public class StartUp :FunctionsStartup
    {
        private readonly NLog.Logger logger;
        public StartUp()
        {
            logger = LogManager.Setup()
                      .SetupExtensions(e=>e.AutoLoadAssemblies(false))
                        .LoadConfigurationFromFile("nlog.config", optional: false)
               .LoadConfiguration(builder => builder.LogFactory.AutoShutdown = false)
               .GetCurrentClassLogger();
        }
        public override void Configure(IFunctionsHostBuilder hostBuilder)
        {
            hostBuilder.Services.AddLogging((loggingBuilder) =>
            {
                loggingBuilder.AddNLog(new NLogProviderOptions() { ShutdownOnDispose = true });
            });
        }
    }
}

"NLogSample.cs function file"

using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using NLog;

namespace NLogFunctionApp
{
    public class NLogSample
    {
        private readonly ILogger<NLogSample> log;
        private static  Logger logCurrent;

        public NLogSample(ILogger<NLogSample> logger)
        {
            log = logger;
            logCurrent = LogManager.GetCurrentClassLogger();
        }

        [FunctionName("NLogSample")]
        public void Run([TimerTrigger("0 * * * * *")]TimerInfo myTimer)
        {
            logCurrent.Info("This is printing");
            log.LogInformation("This is not printing");
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
        }
    }
}

nlog.config

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="https://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogFile="c:\temp\jjgnet-functions-internal-nlog.log"
      internalLogLevel="Debug" >

  <variable name="logDirectory" value="${currentdir}${dir-separator}logs${dir-separator}" />
  <extensions>
    <add assembly="NLog.Extensions.Logging"/>
    <add assembly="Microsoft.ApplicationInsights.NLogTarget" />
  </extensions>

  <targets>

    <target xsi:type="ApplicationInsightsTarget" name="aiTarget">
      <instrumentationKey>AzureAppInsightkeyvalue</instrumentationKey>

      <contextproperty name="threadid" layout="${threadid}" />
      <contextproperty name="AssemblyVersion" layout="${gdc:item=ExecutingAssembly-AssemblyVersion}" />
      <contextproperty name="FileVersion" layout="${gdc:item=ExecutingAssembly-FileVersion}" />
      <contextproperty name="ProductVersion" layout="${gdc:item=ExecutingAssembly-ProductVersion}" />
    </target>

    <target xsi:type="Console" name="logconsole"
            layout="${longdate}|${level}|${logger}|${message} |${all-event-properties} ${exception:format=tostring}" />
  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="logconsole" />
    <logger name="*" minlevel="Trace" writeTo="aiTarget" />
  </rules>
</nlog>

Code with "This is printing" is working fine but when injecting from DI it is not printing logs.
Some default logs are getting printed but not with log.LogInformation.

host.json is empty, no logging configs are there which are provided by default.

Could someone please help. Searched many where but could not find the reason.
GitHub repo link - https://github.com/jatingandhi28/NLogAzureFunctions

Body:
You can try to disable the filter-logic in Microsoft LoggerFactory by changing from:

new NLogProviderOptions() { ShutdownOnDispose = true }

To this

new NLogProviderOptions() { ShutdownOnDispose = true, RemoveLoggerFactoryFilter = true }

See also: https://github.com/NLog/NLog.Web/wiki/Missing-trace%5Cdebug-logs-in-ASP.NET-Core-6%3F


问:
Informatica how to POST JSON data with Bearer Token in Header
Having issue with http transformation simple post with bearer token.
So, we have a mapping that uses http transformation to SIMPLE POST JSON data into an api. The api uses bearer token authorization. So you send a user/pass and get a token back and then POST your json data with the token in the header.

But when we are trying to POST along with token, we are facing issues. Basically i am not sure how to post json data with token in the header info.

Anyone have any ideas ?

答:
It worked with below approach for Barer token.

Flow:
SQ->exp->HTTP->exp->HTTP->TGT

HTTP connection:
Base URL : Provide the login URL for the API
Authentication : Basic

First HTTP transformation:
Give the login URL in Base URl. Pass a single row as an input for trigger of URL. This should give the generated token as an output (JSON/XML).
Pass the output to expression transf. Add a new output port and extract the token value only.
output port value : 'Bearer '||substr(ouput,2,30)
Methods - POST

Second HTTP transformation:
Add new input port and connect the above expression output as input.
Add new Header port as "Authorization".
Provide the API URL in the base url.
Methods - POST
Connect the output port to Flat file to check the received response.
Note: Do not give/select any connection details to this transformation.


问:
Using union and order by clause in mysql
I want to use order by with union in mysql query.
I am fetching different types of record based on different criteria from a table based on distance for a search on my site.
The first select query returns data related to the exact place search .
The 2nd select query returns data related to distance within 5 kms from the place searched.
The 3rd select query returns data related to distance within 5-15 kms from the place searched.

Then i m using union to merge all results and show on a page with paging. Under appropriate heading as 'Exact search results', 'Results within 5 kms' etc

Now i want to sort results based on id or add_date. But when i add order by clause at the end of my query ( query1 union query 2 union query 3 order by add_date). It sorts all results. But what i want is it should sort under each heading.

答:
My favorite solution is to create a CTE</p>
```<code>WITH cte as (
(SELECT * FROM table1)

UNION ALL

(SELECT * FROM table2)
)
SELECT *
FROM cte
ORDER BY col1
</code>```

Body:
My favorite solution is to create a CTE

WITH cte as (
(SELECT * FROM table1)

UNION ALL

(SELECT * FROM table2)
)
SELECT *
FROM cte
ORDER BY col1


问:
import function from another file without running automatically
To make simple I have two file, a.py and b.py

code inside a.py:

from b import fun1

class sample:
    # sample Code related to kivy
```
<p>code inside <code>b.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>def fun1():
    # same code
def fun2():
    # same code
</code>```

when I run file a.py immediately b.py run automatically
I search about this problem ,I know to solve this problem I have to use
if __name__=="__main__":, but I don't understand how to use .

how I can call fun1 or fun2  inside a.py file

答:
The problem is that you are calling the functions inside of b.py without using the if name=="main". You can solve this issue by putting the functions calls inside this if statement:

b.py

def fun1():
    print("Hello")

def fun2():
    print("World")

if __name__ == "main":
    fun1()
```
<p>That way, the function will only be called if you run <code>b.py</code> directly (that's what <code>__name__ = "main"</code> means)</p>
<p>For your other issue: to use the functions inside of <code>a.py</code> you have two main ways:</p>
<ul>
<li>you can import them directly (like you did) with either <code>from b import fun1, fun2</code> or <code>from b import *</code> (this will import all functions defined inside of <code>b.py</code>. By doing this you will be be able to use these functions directly by calling them like this:</li>
</ul>
<p><code>a.py</code></p>
<pre class="lang-py prettyprint-override"><code>from b import fun1

fun1()
</code>```

or you can import b.py by using import b. Then you'd have to first name import and then the function when calling it:

import b

b.fun2()
```

More on imports on the official Python documentation here.

Body:
To make simple I have two file, a.py and b.py

code inside a.py:

from b import fun1

class sample:
    # sample Code related to kivy

code inside b.py:

def fun1():
    # same code
def fun2():
    # same code

when I run file a.py immediately b.py run automatically
I search about this problem ,I know to solve this problem I have to use
if __name__=="__main__":, but I don't understand how to use .

how I can call fun1 or fun2  inside a.py file

Body:
The problem is that you are calling the functions inside of b.py without using the if name=="main". You can solve this issue by putting the functions calls inside this if statement:

b.py

def fun1():
    print("Hello")

def fun2():
    print("World")

if __name__ == "main":
    fun1()

That way, the function will only be called if you run b.py directly (that's what __name__ = "main" means)

For your other issue: to use the functions inside of a.py you have two main ways:

you can import them directly (like you did) with either from b import fun1, fun2 or from b import * (this will import all functions defined inside of b.py. By doing this you will be be able to use these functions directly by calling them like this:

a.py

from b import fun1

fun1()

or you can import b.py by using import b. Then you'd have to first name import and then the function when calling it:

import b

b.fun2()

More on imports on the official Python documentation here.


问:
Add data in listbox in multiple columns
recently i came across a userfrom which have list box which shows the sheets name in first column and there property like are they visible or hidden in second columns. but when i tried to access the codes its lock i googled and did every thing to understand how it is done but i didnt found it hope i get my answer here below is mycode which i did i am noob please help me

my code:-

```<code>Private Sub UserForm_Initialize()

Dim ws As Worksheet

ListBox1.ColumnCount = 2
For Each ws In ThisWorkbook.Worksheets

    Me.ListBox1.AddItem ws.Name

Next ws

End Sub
</code>```

答:
Private Sub UserForm_Initialize()

    Dim ws As Worksheet, n As Long, arText
    arText = Array("xlSheetVisible", "xlSheetHidden", "", "xlSheetVeryHidden")

    ListBox1.ColumnCount = 2
    For Each ws In ThisWorkbook.Worksheets
        Me.ListBox1.AddItem ws.Name
        Me.ListBox1.List(n, 1) = arText(ws.Visible + 1)
        n = n + 1
    Next ws

End Sub
```

Title: Add data in listbox in multiple columns

Body:
recently i came across a userfrom which have list box which shows the sheets name in first column and there property like are they visible or hidden in second columns. but when i tried to access the codes its lock i googled and did every thing to understand how it is done but i didnt found it hope i get my answer here below is mycode which i did i am noob please help me

my code:-

Private Sub UserForm_Initialize()

Dim ws As Worksheet

ListBox1.ColumnCount = 2
For Each ws In ThisWorkbook.Worksheets

    Me.ListBox1.AddItem ws.Name

Next ws

End Sub


问:
Exception has occurred: ModuleNotFoundError No module named 'pygame'
I am trying to make a python game. In its first line I have imported pygame. I installed and did all the essential stuff for it but when I import it, it shows an error telling that:

```<code>Exception has occurred: ModuleNotFoundError
No module named 'pygame
</code>```

Hope you understand the problem.

答:
Easiest way to install pygame is with pip tool, which Python uses to install packages.

Run this in your terminal to install:

```<code>python3 -m pip install -U pygame --user
</code>```

To test it, run this in your terminal:

```<code>python3 -m pygame.examples.aliens
</code>```

It works for me!

Body:
I am trying to make a python game. In its first line I have imported pygame. I installed and did all the essential stuff for it but when I import it, it shows an error telling that:

Exception has occurred: ModuleNotFoundError
No module named 'pygame

Hope you understand the problem.

Body:
Easiest way to install pygame is with pip tool, which Python uses to install packages.

Run this in your terminal to install:

python3 -m pip install -U pygame --user

To test it, run this in your terminal:

python3 -m pygame.examples.aliens

It works for me!


问:
Is there a way to get the perfect (proper format) values from web page using encoding in python?
Problem : Things on webpage like AMD Ryzen™ 9 5950X, when i am getting it into csv file it shows up as : AMD Ryzenâ„¢ 9 5950X, 90°C shows up as 90Â°C. i have to write a function to get the exact(proper) values from the web page. i tried to capture and store these in .txt file. It shows up as perfectly normal values. Is excel/csv creating this problem? How can i solve this issue?

config.ini

```<code>[configData]
baseurl = https://www.amd.com/en/processors/ryzen
sub_url = https://www.amd.com
all_keys = Model,Platform,Product Family,Product Line,# of CPU Cores,# of Threads, Max. Boost Clock, Base Clock, Total L2 Cache, Total L3 Cache,Default TDP, Processor Technology for CPU Cores, Unlocked for Overclocking, CPU Socket,Thermal Solution (PIB), Max. Operating Temperature (Tjmax), Launch Date, *OS Support

</code>```

Main.py file code

```<code>import logging
from data_extraction import data_extraction
from data_processing import data_processing
from configparser import ConfigParser

class Main:

    def __init__(self):
        self.config = ConfigParser()
        self.config.read('config.ini')
        logging.basicConfig(filename='logfile.log', level=logging.DEBUG,
                            format='%(asctime)s:%(lineno)d:%(name)s:%(levelname)s:%(message)s')

        self.baseurl = self.config['configData']['baseurl']
        self.sub_url = self.config['configData']['sub_url']
        self.all_keys = self.config['configData']['all_keys']
        # print(all_keys)
        self.all_keys = [key.strip() for key in self.all_keys.split(',')]

    def __Processing__(self):
        de = data_extraction(self.baseurl)
        dp = data_processing()
        self.model_links = de.get_links_in_list(self.sub_url)
        logging.debug(self.model_links)
        each_link_data = de.data_extraction(self.baseurl, self.all_keys, self.model_links)
        logging.info('data extraction is called from main')
        all_link_data = dp.data_processing(each_link_data)

        # calling function write_to_csv
        dp.write_to_csv(all_link_data,self.all_keys)
        logging.info('data copied to csv')
        dp.rectify_csv(str(all_link_data))

Main().__Processing__()

</code>```

DataExtraction.py

```<code>import logging
import requests
from bs4 import BeautifulSoup

class data_extraction:
    def __init__(self, baseurl):
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36',
            "Upgrade-Insecure-Requests": "1", "DNT": "1",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language": "en-US,en;q=0.5",
            "Accept-Encoding": "gzip, deflate"}

        r = requests.get(baseurl, headers=self.headers)
        status = r.status_code
        self.soup = BeautifulSoup(r.content, 'html.parser')
        self.model_links = []

    # function to get the model links in one list from soup object(1st page extraction)
    def get_links_in_list(self, sub_url):
        for model_list in self.soup.find_all('td', headers='view-name-table-column'):
            # model_list = model_list.a.text - to get the model names
            model_list = model_list.a.get('href')
            # print(model_list)
            model_list = sub_url + model_list
            # print(model_list)
            one_link = model_list.split(" ")[0]
            self.model_links.append(one_link)
        return self.model_links

    # function to get data for each link from the website(2nd page extraction)
    def data_extraction(self, baseurl, all_keys, model_links):
        r = requests.get(baseurl, headers=self.headers)
        status = r.status_code
        soup = BeautifulSoup(r.content, 'html.parser')
        each_link_data = []
        try:
            for link in model_links:
                r = requests.get(link, headers=self.headers)
                soup = BeautifulSoup(r.content, 'html.parser')
                specification = {}
                for key in all_keys:
                    spec = soup.select_one(
                        f'.field__label:-soup-contains("{key}") + .field__item, .field__label:-soup-contains("{key}") + .field__items .field__item')

                    # print(spec)
                    if spec is None:
                        specification[key] = ''
                        if key == 'Model':
                            specification[key] = [i.text for i in soup.select_one('.page-title')]
                            specification[key] = specification[key][0:1:1]
                            # print(specification[key])

                    else:

                        if key == '*OS Support':
                            specification[key] = [i.text for i in spec.parent.select('.field__item')]
                        else:
                            specification[key] = spec.text
                    specification['link'] = link
                    each_link_data.append(specification)
        except Exception as e:
            print('Error occurred')
            logging.info('data not extracted')

        return each_link_data
        # print(each_link_data)

</code>```

Data processing.py

```<code>import pandas as pd

class data_processing:
    # function for data processing : converting the each link object into dataframe

    def data_processing(self, each_link_data):
        all_link_data = []
        for each_linkdata_obj in each_link_data:
            # make the nested dictionary to normal dict
            norm_dict = dict()
            for key in each_linkdata_obj:
                if isinstance(each_linkdata_obj[key], list):
                    norm_dict[key] = ','.join(each_linkdata_obj[key])
                else:
                    norm_dict[key] = each_linkdata_obj[key]

            all_link_data.append(norm_dict)
        return all_link_data

    # function to write dataframe data into csv
    def write_to_csv(self, all_link_data, all_keys):
        all_link_df = pd.DataFrame.from_dict(all_link_data)
        all_link_df2 = all_link_df.drop_duplicates()
        all_link_df3 = all_link_df2.reset_index()
        # print(all_link_df3)
        all_keys = all_keys + ['link']
        all_link_df4 = all_link_df3[all_keys]
        # print(all_link_df4)
        all_link_df4.to_csv('final_data.csv', index=False)
        # all_link_df4.to_csv('final_data.xlsx',index=False)

    # function to remove unwanted characters from the csv file.
    def rectify_csv(self, all_link_df4):
        all_link_data_str = str(all_link_df4)
        with open('readme.txt', 'w') as f:
            f.writelines(all_link_data_str)

</code>```

readme.txt:

```<code> 'link': 'https://www.amd.com/en/products/cpu/amd-ryzen-9-5950x',
 'Platform': 'Boxed Processor',
 'Product Family': 'AMD Ryzen™ Processors',
 'Product Line': 'AMD Ryzen™ 9 Desktop Processors',
 '# of CPU Cores': '16',
 '# of Threads': '32',
 'Max. Boost Clock': 'Up to 4.9GHz',
 'Base Clock': '3.4GHz',
 'Total L2 Cache': '8MB',
 'Total L3 Cache': '64MB',
 'Default TDP': '105W',
 'Processor Technology for CPU Cores': 'TSMC 7nm FinFET',
 'Unlocked for Overclocking': 'Yes',
 'CPU Socket': 'AM4',
 'Thermal Solution (PIB)': 'Not included',
 'Max. Operating Temperature (Tjmax)': '90°C',
 'Launch Date': '11/5/2020',
 '*OS Support': 'Windows 10 - 64-Bit Edition,RHEL x86 64-Bit,Ubuntu x86 64-Bit,*Operating System (OS) support will vary by manufacturer.'},
</code>```

final_data.csv

```<code>AMD Ryzenâ„¢ 9 5950X Desktop Processors
AMD Ryzenâ„¢ Processors
AMD Ryzenâ„¢ 9 Desktop Processors
90Â°C
</code>```

答:
Microsoft software is infamous for assuming the contents of a file are encoded in the native Windows character encoding.  If your file is written in something reasonable like UTF-8 it is likely to be misinterpreted.

The way to get Microsoft applications like Excel to recognize UTF-8 properly is to put a byte order mark at the front of the file.  Python can add this automatically if you open the file with encoding='utf_8_sig'.

Body:
Problem : Things on webpage like AMD Ryzen™ 9 5950X, when i am getting it into csv file it shows up as : AMD Ryzenâ„¢ 9 5950X, 90°C shows up as 90Â°C. i have to write a function to get the exact(proper) values from the web page. i tried to capture and store these in .txt file. It shows up as perfectly normal values. Is excel/csv creating this problem? How can i solve this issue?

config.ini

[configData]
baseurl = https://www.amd.com/en/processors/ryzen
sub_url = https://www.amd.com
all_keys = Model,Platform,Product Family,Product Line,# of CPU Cores,# of Threads, Max. Boost Clock, Base Clock, Total L2 Cache, Total L3 Cache,Default TDP, Processor Technology for CPU Cores, Unlocked for Overclocking, CPU Socket,Thermal Solution (PIB), Max. Operating Temperature (Tjmax), Launch Date, *OS Support

Main.py file code

import logging
from data_extraction import data_extraction
from data_processing import data_processing
from configparser import ConfigParser

class Main:

    def __init__(self):
        self.config = ConfigParser()
        self.config.read('config.ini')
        logging.basicConfig(filename='logfile.log', level=logging.DEBUG,
                            format='%(asctime)s:%(lineno)d:%(name)s:%(levelname)s:%(message)s')

        self.baseurl = self.config['configData']['baseurl']
        self.sub_url = self.config['configData']['sub_url']
        self.all_keys = self.config['configData']['all_keys']
        # print(all_keys)
        self.all_keys = [key.strip() for key in self.all_keys.split(',')]

    def __Processing__(self):
        de = data_extraction(self.baseurl)
        dp = data_processing()
        self.model_links = de.get_links_in_list(self.sub_url)
        logging.debug(self.model_links)
        each_link_data = de.data_extraction(self.baseurl, self.all_keys, self.model_links)
        logging.info('data extraction is called from main')
        all_link_data = dp.data_processing(each_link_data)

        # calling function write_to_csv
        dp.write_to_csv(all_link_data,self.all_keys)
        logging.info('data copied to csv')
        dp.rectify_csv(str(all_link_data))

Main().__Processing__()

DataExtraction.py

import logging
import requests
from bs4 import BeautifulSoup

class data_extraction:
    def __init__(self, baseurl):
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36',
            "Upgrade-Insecure-Requests": "1", "DNT": "1",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language": "en-US,en;q=0.5",
            "Accept-Encoding": "gzip, deflate"}

        r = requests.get(baseurl, headers=self.headers)
        status = r.status_code
        self.soup = BeautifulSoup(r.content, 'html.parser')
        self.model_links = []

    # function to get the model links in one list from soup object(1st page extraction)
    def get_links_in_list(self, sub_url):
        for model_list in self.soup.find_all('td', headers='view-name-table-column'):
            # model_list = model_list.a.text - to get the model names
            model_list = model_list.a.get('href')
            # print(model_list)
            model_list = sub_url + model_list
            # print(model_list)
            one_link = model_list.split(" ")[0]
            self.model_links.append(one_link)
        return self.model_links

    # function to get data for each link from the website(2nd page extraction)
    def data_extraction(self, baseurl, all_keys, model_links):
        r = requests.get(baseurl, headers=self.headers)
        status = r.status_code
        soup = BeautifulSoup(r.content, 'html.parser')
        each_link_data = []
        try:
            for link in model_links:
                r = requests.get(link, headers=self.headers)
                soup = BeautifulSoup(r.content, 'html.parser')
                specification = {}
                for key in all_keys:
                    spec = soup.select_one(
                        f'.field__label:-soup-contains("{key}") + .field__item, .field__label:-soup-contains("{key}") + .field__items .field__item')

                    # print(spec)
                    if spec is None:
                        specification[key] = ''
                        if key == 'Model':
                            specification[key] = [i.text for i in soup.select_one('.page-title')]
                            specification[key] = specification[key][0:1:1]
                            # print(specification[key])

                    else:

                        if key == '*OS Support':
                            specification[key] = [i.text for i in spec.parent.select('.field__item')]
                        else:
                            specification[key] = spec.text
                    specification['link'] = link
                    each_link_data.append(specification)
        except Exception as e:
            print('Error occurred')
            logging.info('data not extracted')

        return each_link_data
        # print(each_link_data)

Data processing.py

import pandas as pd

class data_processing:
    # function for data processing : converting the each link object into dataframe

    def data_processing(self, each_link_data):
        all_link_data = []
        for each_linkdata_obj in each_link_data:
            # make the nested dictionary to normal dict
            norm_dict = dict()
            for key in each_linkdata_obj:
                if isinstance(each_linkdata_obj[key], list):
                    norm_dict[key] = ','.join(each_linkdata_obj[key])
                else:
                    norm_dict[key] = each_linkdata_obj[key]

            all_link_data.append(norm_dict)
        return all_link_data

    # function to write dataframe data into csv
    def write_to_csv(self, all_link_data, all_keys):
        all_link_df = pd.DataFrame.from_dict(all_link_data)
        all_link_df2 = all_link_df.drop_duplicates()
        all_link_df3 = all_link_df2.reset_index()
        # print(all_link_df3)
        all_keys = all_keys + ['link']
        all_link_df4 = all_link_df3[all_keys]
        # print(all_link_df4)
        all_link_df4.to_csv('final_data.csv', index=False)
        # all_link_df4.to_csv('final_data.xlsx',index=False)

    # function to remove unwanted characters from the csv file.
    def rectify_csv(self, all_link_df4):
        all_link_data_str = str(all_link_df4)
        with open('readme.txt', 'w') as f:
            f.writelines(all_link_data_str)

readme.txt:

 'link': 'https://www.amd.com/en/products/cpu/amd-ryzen-9-5950x',
 'Platform': 'Boxed Processor',
 'Product Family': 'AMD Ryzen™ Processors',
 'Product Line': 'AMD Ryzen™ 9 Desktop Processors',
 '# of CPU Cores': '16',
 '# of Threads': '32',
 'Max. Boost Clock': 'Up to 4.9GHz',
 'Base Clock': '3.4GHz',
 'Total L2 Cache': '8MB',
 'Total L3 Cache': '64MB',
 'Default TDP': '105W',
 'Processor Technology for CPU Cores': 'TSMC 7nm FinFET',
 'Unlocked for Overclocking': 'Yes',
 'CPU Socket': 'AM4',
 'Thermal Solution (PIB)': 'Not included',
 'Max. Operating Temperature (Tjmax)': '90°C',
 'Launch Date': '11/5/2020',
 '*OS Support': 'Windows 10 - 64-Bit Edition,RHEL x86 64-Bit,Ubuntu x86 64-Bit,*Operating System (OS) support will vary by manufacturer.'},

final_data.csv

AMD Ryzenâ„¢ 9 5950X Desktop Processors
AMD Ryzenâ„¢ Processors
AMD Ryzenâ„¢ 9 Desktop Processors
90Â°C


问:
WebSocket connection to 'ws://localhost:8000/socket.io/?EIO=4&transport=websocket' failed:
This is a simple chat application project with Socket.io, but i am having problem connecting socket.io client which is in React to my server in Node

Connection code for my server is like this

```<code>const server = http.createServer(app)
const io = socketio(server, {
  cors: {
    origin: 'http://localhost:3000',
    methods: ['GET', 'POST'],
  }
})

const onSocketConnection = socket => {
    console.log('Socket connected')
    socketConnection(io, socket, db)
  }

  io.on("connection", onSocketConnection)
</code>```

Connection in client side is like this

```<code>import io from "socket.io-client"
const socket = io.connect('http://localhost:8000',{
    cors: {
        origin: "http://localhost:5000",
        credentials: true
    },transports : ['websocket']
})
</code>```

This is the error i am reviving

```<code>WebSocket connection to 'ws://localhost:8000/socket.io/?EIO=4&transport=websocket' failed:
</code>```

Error snapshot

答:
server side (http://localhost:8000):

```<code>import { Server } from 'socket.io';
...
const server = http.createServer(app)
const io = new Server(server, {
  cors: {
    origin: ['http://localhost:3000'],
  }
})

// listening for connections from clients
io.on('connection', (socket) =>{
  // listening to events from client
  socket.on('eventName', (params, callback) => {
     ...

    // send data back to client by using ack callback
    callback(data)

    // send data back to client by using emit
    socket.emit('eventName', data)

    // broadcasting data to all other connected clients
    socket.broadcast.emit('eventName', data)
  })
})
</code>```

client side (http://localhost:3000):

```<code>import { io } from "socket.io-client"
const socket = io('http://localhost:8000',{
    withCredentials: true
})

// emit:
socket.emit('eventName', params, callback => {
  ...
})

// listen to events from sever:
socket.on('eventName', callback => {
  ...
})
</code>```

Body:
This is a simple chat application project with Socket.io, but i am having problem connecting socket.io client which is in React to my server in Node

Connection code for my server is like this

const server = http.createServer(app)
const io = socketio(server, {
  cors: {
    origin: 'http://localhost:3000',
    methods: ['GET', 'POST'],
  }
})

const onSocketConnection = socket => {
    console.log('Socket connected')
    socketConnection(io, socket, db)
  }

  io.on("connection", onSocketConnection)

Connection in client side is like this

import io from "socket.io-client"
const socket = io.connect('http://localhost:8000',{
    cors: {
        origin: "http://localhost:5000",
        credentials: true
    },transports : ['websocket']
})

This is the error i am reviving

WebSocket connection to 'ws://localhost:8000/socket.io/?EIO=4&transport=websocket' failed:

Error snapshot

Body:
server side (http://localhost:8000):

import { Server } from 'socket.io';
...
const server = http.createServer(app)
const io = new Server(server, {
  cors: {
    origin: ['http://localhost:3000'],
  }
})

// listening for connections from clients
io.on('connection', (socket) =>{
  // listening to events from client
  socket.on('eventName', (params, callback) => {
     ...

    // send data back to client by using ack callback
    callback(data)

    // send data back to client by using emit
    socket.emit('eventName', data)

    // broadcasting data to all other connected clients
    socket.broadcast.emit('eventName', data)
  })
})

client side (http://localhost:3000):

import { io } from "socket.io-client"
const socket = io('http://localhost:8000',{
    withCredentials: true
})

// emit:
socket.emit('eventName', params, callback => {
  ...
})

// listen to events from sever:
socket.on('eventName', callback => {
  ...
})


问:
What is "->" operator called and purpose does it serve?
I'm looking at C-based Solana Smart Contracts and I see -> operator in the code.  How do I search for this as I don't even know what to call it (I have tried with no results)?

```<code>/**
 * @brief C-based Helloworld BPF program
 */
#include <solana_sdk.h>

uint64_t helloworld(SolParameters *params) {

  if (params->ka_num < 1) {
    sol_log("Greeted account not included in the instruction");
    return ERROR_NOT_ENOUGH_ACCOUNT_KEYS;
  }

  // Get the account to say hello to
  SolAccountInfo *greeted_account = &params->ka[0];

}

</code>```

答: It must be a pointer dereference operator ->.

Body:
I'm looking at C-based Solana Smart Contracts and I see -> operator in the code.  How do I search for this as I don't even know what to call it (I have tried with no results)?

/**
 * @brief C-based Helloworld BPF program
 */
#include <solana_sdk.h>

uint64_t helloworld(SolParameters *params) {

  if (params->ka_num < 1) {
    sol_log("Greeted account not included in the instruction");
    return ERROR_NOT_ENOUGH_ACCOUNT_KEYS;
  }

  // Get the account to say hello to
  SolAccountInfo *greeted_account = &params->ka[0];

}


问:
filtering objects from List with foreach
Hi Ive got a list of objects but how do I filter it out to another list?

Ex:

```<code>public class Person
{
    public string FirstName;
    public string Language;

    public Person (string FirstName, string Language)
    {
        this.FirstName = FirstName;
        this.LastName = Language;
    }
 }
</code>```

Creates a list:

```<code>public List<Person> createDummyList()
{
  List<Person> dummyList = new List<Person>();
  dummyList.Add(new Person("Per", "English"));
  dummyList.Add(new Person("Linda", "Spanish"));
}
</code>```

How can I get a List with just the language and then bind it to say a dropdown.? Ive tryed something like this but got a null reference...

```<code>public void filterList(List<Person> ListToBeFiltered)
{
    List<string> LanguageList = new List<string>();
    ListToBeFiltered.ForEach(delegate(Person P)
    {
       LanguageList.Add(P.Language);
    });
    DropDown.datasource = LanguageList;
    DropDown.databind();
 }
</code>```

Anyone can point me in the right direction?

答:
```<code>IEnumerable<string> languageList = listToBeFiltered.Select(p=>p.Language)
                                                   .Distinct()
                                                   .ToList();
</code>```

Body:
Hi Ive got a list of objects but how do I filter it out to another list?

Ex:

public class Person
{
    public string FirstName;
    public string Language;

    public Person (string FirstName, string Language)
    {
        this.FirstName = FirstName;
        this.LastName = Language;
    }
 }

Creates a list:

public List<Person> createDummyList()
{
  List<Person> dummyList = new List<Person>();
  dummyList.Add(new Person("Per", "English"));
  dummyList.Add(new Person("Linda", "Spanish"));
}

How can I get a List with just the language and then bind it to say a dropdown.? Ive tryed something like this but got a null reference...

public void filterList(List<Person> ListToBeFiltered)
{
    List<string> LanguageList = new List<string>();
    ListToBeFiltered.ForEach(delegate(Person P)
    {
       LanguageList.Add(P.Language);
    });
    DropDown.datasource = LanguageList;
    DropDown.databind();
 }

Anyone can point me in the right direction?


问:
Can I use Javascript to change div class when div class is not unique?
Is there a way through javascript to change the class below assigned to these three different divs. As you can see the class is the same on all but the styling is different and I want to be able to control styling by class:

```<code><div class="pending-task-value" style="background-color: rgb(232, 188, 13);"> 0 <!----></div>

<div class="pending-task-value" style="background-color: rgb(47, 145, 211);"> 0 <!----></div>

<div class="pending-task-value" style="background-color: rgb(19, 152, 126);"> 0 <!----></div>
</code>```

Effectively I want the outcome to be:

```<code><div class="pending-task-value-total";> 0 <!---></div>
<div class="pending-task-value-phone";> 0 <!---></div>
<div class="pending-task-value-sms";> 0 <!---></div>
</code>```

Edit, here is the HTML in place today... I can't directly edit the HTML so I need a way to change the colors of the background colors.

```<code><div class="card-body">
  <div class="row" style="text-align: center;">
    <div class="col-4 pending-task-value-col">
      <div class="pending-task-value" style="background-color: rgb(232, 188, 13);"> 0
        <!---->
      </div>
      <div><i class="fas fa-tasks"></i></div>
      <div>Total Pending</div>
    </div>
    <div class="col-4 pending-task-value-col">
      <div class="pending-task-value" style="background-color: rgb(47, 145, 211);"> 0
        <!---->
      </div>
      <div><i class="fas fa-phone"></i></div>
      <div>Phone</div>
    </div>
    <div class="col-4 pending-task-value-col">
      <div class="pending-task-value" style="background-color: rgb(19, 152, 126);"> 0
        <!---->
      </div>
      <div><i class="fas fa-sms"></i></div>
      <div>SMS</div>
    </div>
  </div>
</code>```

The only thing that is making each "pending-task-value" unique is the "background-color" style element. I want to change the background-color so that it would be the following below but I need javascript to do it and can't figure out how to make the update:

```<code><div class="card-body">
  <div class="row" style="text-align: center;">
    <div class="col-4 pending-task-value-col">
      <div class="pending-task-value" style="background-color: #2B32B2;"> 0
        <!---->
      </div>
      <div><i class="fas fa-tasks"></i></div>
      <div>Total Pending</div>
    </div>
    <div class="col-4 pending-task-value-col">
      <div class="pending-task-value" style="background-color: #1488CC;"> 0
        <!---->
      </div>
      <div><i class="fas fa-phone"></i></div>
      <div>Phone</div>
    </div>
    <div class="col-4 pending-task-value-col">
      <div class="pending-task-value" style="background-color: #d63384;"> 0
        <!---->
      </div>
      <div><i class="fas fa-sms"></i></div>
      <div>SMS</div>
    </div>
  </div>
</code>```

Or if there is a way to change/add a style to each "pending-task-value" to make them unique so I can then apply css to them would work for me too.

答:
Two approaches depending on whether you know the DOM structure in advance.

If the target div is consistently in the same DOM location i.e., the second div within a container, you can target it using the index of the document.querySelectorAll() method vis-a-vis document.querySelectorAll('div.pending-task-value')[1].classList.add('pending-task-value-phone').

On the other hand, if the order is not known in advance and the only unique property is, in your example, a CSS property, then the Window.getComputedStyle() method may solve your use case. MDN

One way of thinking about this:

Get the elements within the container using document.querySelectorAll()

For each matching element

Get the computed style

If the unique property value matches a target value, use Element.classList.add() to add the desired class name

Body:
Is there a way through javascript to change the class below assigned to these three different divs. As you can see the class is the same on all but the styling is different and I want to be able to control styling by class:

 0

 0

 0

Effectively I want the outcome to be:

 0

 0

Total Pending

 0

Phone

 0

SMS

The only thing that is making each "pending-task-value" unique is the "background-color" style element. I want to change the background-color so that it would be the following below but I need javascript to do it and can't figure out how to make the update:

 0

Total Pending

 0

Phone

 0

SMS

Or if there is a way to change/add a style to each "pending-task-value" to make them unique so I can then apply css to them would work for me too.