问:
How to change the color of marker-points dynamically based on y-position
I have below interactive plot using highchart js library in R

```<code>library(highcharter)
hchart(data.frame('Date' = seq(Sys.Date(), Sys.Date() - 10, by = '-1 day'), 'Value' = sample(c(-1, 1), 11, replace = T), 'variable' = 'aa') %>% mutate(color = ifelse(Value < 0, "#41c83b", "#E0245E")),
                            "line",
                            zIndex = 1, opacity = 0.9,
                            hcaes(x = Date, y = Value, group = variable),
                            zones = list(list(value = 0, color = hex_to_rgba("#41c83b", 1)), list(color = hex_to_rgba("#E0245E", 1))),
                            marker = list(fillColor = "#fff", lineColor = '#000', radius = 5, lineWidth = 2))
</code>```

I wanted to match the color of markers based on the line color which is dynamic based on the y-value. Currently color of all markers as set as black which I did not want.

Any pointer how to change the color dynamically will be highly helpful

答:
The is no such option in the API. You need to write some custom code.
The simplest way is to use chart.events.load event, loop through all points of your series, find the ones in the red or green zone and update their marker options separately.
To write a JavaScript code in R, you can use JS("") function.

Here is the whole sample code:

```<code>library(highcharter)
hchart(data.frame('Date' = seq(Sys.Date(), Sys.Date() - 10, by = '-1 day'), 'Value' = sample(c(-1, 1), 11, replace = T), 'variable' = 'aa') %>%
         mutate(color = ifelse(Value < 0, "#41c83b", "#E0245E")),
       "line",
       zIndex = 1, opacity = 0.9,
       hcaes(x = Date, y = Value, group = variable),
       zones = list(list(value = 0, color = hex_to_rgba("#41c83b", 1)), list(color = hex_to_rgba("#E0245E", 1))),
       marker = list(fillColor = "#fff", radius = 5, lineWidth = 2)) %>%
  hc_chart(events = list(load = JS("function () {
    this.series[0].points.forEach(function (point) {
      if (point.y > 0) {
        point.update({
          marker: {
            lineColor: 'red'
          }
        }, false);
      } else {
        point.update({
          marker: {
            lineColor: 'green'
          }
        }, false);
      }
    });
    this.redraw();
  }")))
</code>```

API Reference: https://api.highcharts.com/highcharts/chart.events.load
https://api.highcharts.com/class-reference/Highcharts.Chart#update
https://api.highcharts.com/class-reference/Highcharts.Point#update

Body:
I have below interactive plot using highchart js library in R

library(highcharter)
hchart(data.frame('Date' = seq(Sys.Date(), Sys.Date() - 10, by = '-1 day'), 'Value' = sample(c(-1, 1), 11, replace = T), 'variable' = 'aa') %>% mutate(color = ifelse(Value < 0, "#41c83b", "#E0245E")),
                            "line",
                            zIndex = 1, opacity = 0.9,
                            hcaes(x = Date, y = Value, group = variable),
                            zones = list(list(value = 0, color = hex_to_rgba("#41c83b", 1)), list(color = hex_to_rgba("#E0245E", 1))),
                            marker = list(fillColor = "#fff", lineColor = '#000', radius = 5, lineWidth = 2))

I wanted to match the color of markers based on the line color which is dynamic based on the y-value. Currently color of all markers as set as black which I did not want.

Any pointer how to change the color dynamically will be highly helpful

Body:
The is no such option in the API. You need to write some custom code.
The simplest way is to use chart.events.load event, loop through all points of your series, find the ones in the red or green zone and update their marker options separately.
To write a JavaScript code in R, you can use JS("") function.

Here is the whole sample code:

library(highcharter)
hchart(data.frame('Date' = seq(Sys.Date(), Sys.Date() - 10, by = '-1 day'), 'Value' = sample(c(-1, 1), 11, replace = T), 'variable' = 'aa') %>%
         mutate(color = ifelse(Value < 0, "#41c83b", "#E0245E")),
       "line",
       zIndex = 1, opacity = 0.9,
       hcaes(x = Date, y = Value, group = variable),
       zones = list(list(value = 0, color = hex_to_rgba("#41c83b", 1)), list(color = hex_to_rgba("#E0245E", 1))),
       marker = list(fillColor = "#fff", radius = 5, lineWidth = 2)) %>%
  hc_chart(events = list(load = JS("function () {
    this.series[0].points.forEach(function (point) {
      if (point.y > 0) {
        point.update({
          marker: {
            lineColor: 'red'
          }
        }, false);
      } else {
        point.update({
          marker: {
            lineColor: 'green'
          }
        }, false);
      }
    });
    this.redraw();
  }")))

API Reference: https://api.highcharts.com/highcharts/chart.events.load
https://api.highcharts.com/class-reference/Highcharts.Chart#update
https://api.highcharts.com/class-reference/Highcharts.Point#update


来源: stackexchange

问:
Preserve .md formatting in a new CSS paragraph selector
In the .css for a Hugo website, I've created a new selector to perform MLA-formatted indentation of references:

```<code>.mla-ref {
    padding-left: 36px;
    text-indent: -36px;
}
</code>```

This works as expected, creating a hanging indent. However, the markdown formatting is not applied. I get, for example, a title with literal asterisks: *Moby Dick*

Is there something I can do in the .css item above to preserve the markdown formatting for italics?

答:
Markdown to HTML

AFAIK, you can't wrap the input markdown into semantic sections, as you would with straight HTML, for instance. What you get out of

```<code># First
This is the first paragraph of the first section.

This is the second paragraph of the first section.

# Second
This is the first paragraph of the second section.
</code>```

is just a pile of

First

This is the first paragraph of the first section.

This is the second paragraph of the first section.

Second

This is the first paragraph of the second section.

```

<p>with those <code>id</code>s generated by the content of the heading.</p>

<p>This makes it easy, I guess, to write content and parsers, but hard to apply custom styling only for some elements.</p>

<h2>Markdown in Hugo</h2>

<p>Hugo 0.60+ uses goldmark as the default library for parsing <code>Markdown</code>, as per the Configure Markup docs.</p>

<p>Apparently, goldmark supports custom attributes, but only for headings.</p>

```## heading {#id .className attrName=attrValue class="class1 class2"}
```

<p>This means that at least for now, you could only mark a heading with an <code>.has-mla-ref</code> class, and then apply the styling to the immediate sibling.</p>

<h3>Example</h3>

<pre class="lang-css prettyprint-override"><code>.has-mla-ref + p {
    padding-left: 36px;
    text-indent: -36px;
}
</code>```

```<code>### Reference {.has-mla-ref}

Best, David, and Sharon Marcus. “Surface Reading: An Introduction.” Representations, vol. 108, no. 1, Fall 2009, pp. 1-21. JSTOR, doi:10.1525/rep.2009.108.1.1

Onwards with your content, this is not a ref anymore.
</code>```

I don't know if there's more to it than just the indentation to make it comply to the MLA format, or if you need more than a paragraph, but hopefully this puts you on the right track.

ContentLicense: CC BY-SA 4.0

Body:
In the .css for a Hugo website, I've created a new selector to perform MLA-formatted indentation of references:

.mla-ref {
    padding-left: 36px;
    text-indent: -36px;
}

This works as expected, creating a hanging indent. However, the markdown formatting is not applied. I get, for example, a title with literal asterisks: *Moby Dick*

Is there something I can do in the .css item above to preserve the markdown formatting for italics?

Body:
Markdown to HTML

AFAIK, you can't wrap the input markdown into semantic sections, as you would with straight HTML, for instance. What you get out of

# First
This is the first paragraph of the first section.

This is the second paragraph of the first section.

# Second
This is the first paragraph of the second section.

is just a pile of

<h1 id="first">First</h1>
<p>This is the first paragraph of the first section.</p>
<p>This is the second paragraph of the first section.</p>
<h1 id="second">Second</h1>
<p>This is the first paragraph of the second section.</p>

with those ids generated by the content of the heading.

This makes it easy, I guess, to write content and parsers, but hard to apply custom styling only for some elements.

Markdown in Hugo

Hugo 0.60+ uses goldmark as the default library for parsing Markdown, as per the Configure Markup docs.

Apparently, goldmark supports custom attributes, but only for headings.

## heading {#id .className attrName=attrValue class="class1 class2"}

This means that at least for now, you could only mark a heading with an .has-mla-ref class, and then apply the styling to the immediate sibling.

Example

.has-mla-ref + p {
    padding-left: 36px;
    text-indent: -36px;
}

### Reference {.has-mla-ref}

Best, David, and Sharon Marcus. “Surface Reading: An Introduction.” Representations, vol. 108, no. 1, Fall 2009, pp. 1-21. JSTOR, doi:10.1525/rep.2009.108.1.1

Onwards with your content, this is not a ref anymore.

I don't know if there's more to it than just the indentation to make it comply to the MLA format, or if you need more than a paragraph, but hopefully this puts you on the right track.


问:
ionic-4 Text-wrap on ion-select-option
HTML

```<code><ion-item>
    <ion-label>Popover</ion-label>
    <ion-select [interfaceOptions]="customPopoverOptions" interface="popover" placeholder="Select One">
      <ion-select-option value="brown" text-wrap>Brownasdfasdfasdfasdfadfadsfasdfadfasdfafdsadfaf</ion-select-option>
      <ion-select-option value="blonde">Blonde</ion-select-option>
      <ion-select-option value="black">Black</ion-select-option>
      <ion-select-option value="red">Red</ion-select-option>
    </ion-select>
  </ion-item>
</code>```

SASS:

```<code>ion-select-option{
   ion-label{
     white-space: normal !important;
   }
}
</code>```

I'm not able to override the existing white-space: nowrap

I would like to know how to override the shadow-dom css

答:
This worked for me on Ionic V5.4.15:</p>

```<code>.alert-checkbox-label.sc-ion-alert-ios{
    white-space: pre-line !important;
    padding-top: 4px;
}
</code>```

Title: ionic-4 Text-wrap on ion-select-option

Body:
HTML

<ion-item>
    <ion-label>Popover</ion-label>
    <ion-select [interfaceOptions]="customPopoverOptions" interface="popover" placeholder="Select One">
      <ion-select-option value="brown" text-wrap>Brownasdfasdfasdfasdfadfadsfasdfadfasdfafdsadfaf</ion-select-option>
      <ion-select-option value="blonde">Blonde</ion-select-option>
      <ion-select-option value="black">Black</ion-select-option>
      <ion-select-option value="red">Red</ion-select-option>
    </ion-select>
  </ion-item>

SASS:

ion-select-option{
   ion-label{
     white-space: normal !important;
   }
}

I'm not able to override the existing white-space: nowrap

I would like to know how to override the shadow-dom css

Body:
This worked for me on Ionic V5.4.15:

.alert-checkbox-label.sc-ion-alert-ios{
    white-space: pre-line !important;
    padding-top: 4px;
}


问:
How do I make shelve file empty in python?
I have created a shelve file and inserted a dictionary data. Now I want to cleanup that shelve file to reuse as a clean file.</p>

```<code>import shelve
dict = shelve.open("Sample.db")
# insert some data into sample.db
dict = { "foo" : "bar"}

#Now I want to clean entire shelve file to re-insert the data from begining.
</code>```

答:
I think this is what you're looking for.</p>

```<code>if os.path.isfile(mcbShelf):
   os.remove(mcbShelf)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have created a shelve file and inserted a dictionary data. Now I want to cleanup that shelve file to reuse as a clean file.

import shelve
dict = shelve.open("Sample.db")
# insert some data into sample.db
dict = { "foo" : "bar"}

#Now I want to clean entire shelve file to re-insert the data from begining.

Body:
I think this is what you're looking for.

if os.path.isfile(mcbShelf):
   os.remove(mcbShelf)


问:
How to delete last observations from rows in R
I have dataframe like so:

```<code>df <- data.frame("date" = c('2018','2019','2020'),
                 "var1" = c(21,15,47),
                 "var2" = c(0.24,0.43,0.87),
                 "var3" = c(0.23,0.35,NA),
                 "var4" = c(0.64,NA,NA),
                 "var5" = c(NA,NA,NA)
                 )
</code>```

How can I delete the last two observations in every row before the NA value?
Variables date and var1 should be intact.

```<code>df_want <- data.frame("date" = c('2018','2019','2020'),
                 "var1" = c(21,15,47),
                 "var2" = c(0.24,NA,NA),
                 "var3" = c(NA,NA,NA),
                 "var4" = c(NA,NA,NA),
                 "var5" = c(NA,NA,NA)
)
</code>```

答:
One approach is a for loop:</p>

```<code>for(i in seq(1,nrow(df))){
  y <- min(which(is.na(df[i,])))
  z <- max(y,which(colnames(df) == "var1") + 3)
  if (!is.infinite(y)) df[i,(z-2):ncol(df)] <- NA
}
df
  date var1 var2 var3 var4 var5
1 2018   21 0.24   NA   NA   NA
2 2019   15   NA   NA   NA   NA
3 2020   47   NA   NA   NA   NA
</code>```

Body:
I have dataframe like so:

df <- data.frame("date" = c('2018','2019','2020'),
                 "var1" = c(21,15,47),
                 "var2" = c(0.24,0.43,0.87),
                 "var3" = c(0.23,0.35,NA),
                 "var4" = c(0.64,NA,NA),
                 "var5" = c(NA,NA,NA)
                 )

How can I delete the last two observations in every row before the NA value?
Variables date and var1 should be intact.

df_want <- data.frame("date" = c('2018','2019','2020'),
                 "var1" = c(21,15,47),
                 "var2" = c(0.24,NA,NA),
                 "var3" = c(NA,NA,NA),
                 "var4" = c(NA,NA,NA),
                 "var5" = c(NA,NA,NA)
)

Body:
One approach is a for loop:

for(i in seq(1,nrow(df))){
  y <- min(which(is.na(df[i,])))
  z <- max(y,which(colnames(df) == "var1") + 3)
  if (!is.infinite(y)) df[i,(z-2):ncol(df)] <- NA
}
df
  date var1 var2 var3 var4 var5
1 2018   21 0.24   NA   NA   NA
2 2019   15   NA   NA   NA   NA
3 2020   47   NA   NA   NA   NA


问:
Are there any languages that handle functional impurity (side effects) without modeling them as RealWorld or IO?
One thing that always bothered me in Haskell (and other functional languages, for that matter) is that the entire language is pure, but side-effects are indirectly allowed by using an object that represents the entire "real world" (the IO monad, for example).

I wonder, are there languages that handle this without modeling the entire world? For example, representing network input as a byte array that is lazily filled as the network input is read.

答:
I've never really liked the real world analogy. I think it's popular because most people's first exposure to parametric polymorphism is containers, so their brain wants to know what an IO "contains." Really, it contains a lazily-evaluated sort of syntax tree data structure that is later interpreted to produce the side effects it describes, but that data structure isn't exposed to the user except through the much more abstract IO type.

At any rate, aside from @phipsgabler's excellent answer about what Haskell previously used, some kind of IO type is used pretty much everywhere people want pure FP nowadays. However, it's a sort of low-level, edge of your program abstraction. Many abstractions are built on top of it.

One example is functional reactive programming, which has several variations, but basically sets up streams of events over time. Elm has a command/subscription model.

Also, libraries usually set up abstractions that make sense for their domain, like web services are often modeled as a function that is called with a Request object and returns an IO of a Response object. Further down the stack from that function, where side effects aren't needed, your interface is just pure types, like a function that takes a User object and returns HTML for that user's profile.

But at some point, whether you call it an IO or a Command or an Observable, it all boils down to the very powerful idea of separating the specification of what side effects you want from the actual execution of those effects. The form may differ, but the fundamental concept isn't going away anytime soon.


问:
How to modify .xlsx containing pictures with Python3?
I need to modify existing .xlsx file which contains graphs in form of pictures from other program. When I try to modify it with openpyxl I lose all pictures which were previously in file. Even with a simple modification like this:

```<code>from openpyxl import load_workbook
wb2 = load_workbook('template.xlsx')
wb2.create_sheet('sid1')
wb2.save('template.xlsx')
</code>```

Is there a way to modify (add new sheets containing new data) without losing pictures?

答: As per the openpyxl documentation on Read an existing workbook there is a warning mentioned that the images/charts can't be read by openpyxl

Body:
I need to modify existing .xlsx file which contains graphs in form of pictures from other program. When I try to modify it with openpyxl I lose all pictures which were previously in file. Even with a simple modification like this:

from openpyxl import load_workbook
wb2 = load_workbook('template.xlsx')
wb2.create_sheet('sid1')
wb2.save('template.xlsx')

Is there a way to modify (add new sheets containing new data) without losing pictures?


问:
jquery fancybox triggered click only working once
I am calling a jquery.fancybox link from the click event bound to a table row.  The action works fine the first time, however, if I close the fancybox and click again on any row the anonymous function bound to the row still fires, but fancybox doesn't start up.  Here's the javascript I'm using:

```<code>$jq(document).ready(function() {

  $jq('a.edit').fancybox({
    'overlayShow': true,
    'hideOnContentClick': false
  });

  $jq('tr').click(function() {
    alert("clicked");
    $jq(this).find('a.edit').trigger("click");
  });

});
</code>```

So, then in the HTML I have anchors classed as "edit":

```<code><tr>
  <td>...</td>
  <td>
    <a href="/candidates/22/qualifications/16/edit" class="edit">edit</a>
  </td>
</tr>
</code>```

I can always see the alert box, and I can change the trigger / click() call to remove() and it will "work", removing the anchors on multiple occasions.  I can also repeatedly manually click the $('.edit') link itself and it's all good.

So how is it that the anchor click event fires only once when coming in turn from the row click event?  Is it something to do with the call I am making to $(this) when describing the function?

答:
Tuffkid got it working;
I was working on something to fix this issue too and I came to the same conclusion he did; just sharing, anyway.

On load:

```<code>$(document).ready(function(){
    $('#show').click(function(e){
        showPopUp($(this));
    });
});
</code>```

JS Function:

```<code>function showPopUp(obj){
    obj.fancybox({
        'href' : 'page.php',
        'onCleanup': function(){
             $(this).click(function(e) { showPopUp($(this)); });
    }
            });
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am calling a jquery.fancybox link from the click event bound to a table row.  The action works fine the first time, however, if I close the fancybox and click again on any row the anonymous function bound to the row still fires, but fancybox doesn't start up.  Here's the javascript I'm using:

$jq(document).ready(function() {

  $jq('a.edit').fancybox({
    'overlayShow': true,
    'hideOnContentClick': false
  });

  $jq('tr').click(function() {
    alert("clicked");
    $jq(this).find('a.edit').trigger("click");
  });

});

So, then in the HTML I have anchors classed as "edit":

  ...

    edit

I can always see the alert box, and I can change the trigger / click() call to remove() and it will "work", removing the anchors on multiple occasions.  I can also repeatedly manually click the $('.edit') link itself and it's all good.

So how is it that the anchor click event fires only once when coming in turn from the row click event?  Is it something to do with the call I am making to $(this) when describing the function?

Body:
Tuffkid got it working;
I was working on something to fix this issue too and I came to the same conclusion he did; just sharing, anyway.

On load:

$(document).ready(function(){
    $('#show').click(function(e){
        showPopUp($(this));
    });
});

JS Function:

function showPopUp(obj){
    obj.fancybox({
        'href' : 'page.php',
        'onCleanup': function(){
             $(this).click(function(e) { showPopUp($(this)); });
    }
            });
}


问:
How to connect to a remote Windows machine to execute commands using python?
I am new to Python and I am trying to make a script that connects to a remote windows machine and execute commands there and test ports connectivity.

Here is the code that I am writing but it is not working. Basically, I want to and it returns with the local machine data, not the remote one.

```<code>import wmi
import os
import subprocess
import re
import socket, sys

def main():

     host="remotemachine"
     username="adminaam"
     password="passpass!"
     server =connects(host, username, password)
     s = socket.socket()
     s.settimeout(5)
     print server.run_remote('hostname')

class connects:

    def __init__(self, host, username, password, s = socket.socket()):
        self.host=host
        self.username=username
        self.password=password
        self.s=s

        try:
            self.connection= wmi.WMI(self.host, user=self.username, password=self.password)
            self.s.connect(('10.10.10.3', 25))
            print "Connection established"
        except:
            print "Could not connect to machine"

   def run_remote(self, cmd, async=False, minimized=True):
       call=subprocess.check_output(cmd, shell=True,stderr=subprocess.STDOUT )
       print call

main()
</code>```

答:
pypsrp - Python PowerShell Remoting Protocol Client library

```<code>At a basic level, you can use this library to;

Execute a cmd command
Run another executable
Execute PowerShell scripts
Copy a file from the localhost to the remote Windows host
Fetch a file from the remote Windows host to the localhost
Create a Runspace Pool that contains one or multiple PowerShell pipelines and execute them asynchronously
Support for a reference host base implementation of PSRP for interactive scripts
</code>```

REF: https://github.com/jborean93/pypsrp

Body:
I am new to Python and I am trying to make a script that connects to a remote windows machine and execute commands there and test ports connectivity.

Here is the code that I am writing but it is not working. Basically, I want to and it returns with the local machine data, not the remote one.

import wmi
import os
import subprocess
import re
import socket, sys

def main():

     host="remotemachine"
     username="adminaam"
     password="passpass!"
     server =connects(host, username, password)
     s = socket.socket()
     s.settimeout(5)
     print server.run_remote('hostname')

class connects:

    def __init__(self, host, username, password, s = socket.socket()):
        self.host=host
        self.username=username
        self.password=password
        self.s=s

        try:
            self.connection= wmi.WMI(self.host, user=self.username, password=self.password)
            self.s.connect(('10.10.10.3', 25))
            print "Connection established"
        except:
            print "Could not connect to machine"

   def run_remote(self, cmd, async=False, minimized=True):
       call=subprocess.check_output(cmd, shell=True,stderr=subprocess.STDOUT )
       print call

main()

Body:
pypsrp - Python PowerShell Remoting Protocol Client library

At a basic level, you can use this library to;

Execute a cmd command
Run another executable
Execute PowerShell scripts
Copy a file from the localhost to the remote Windows host
Fetch a file from the remote Windows host to the localhost
Create a Runspace Pool that contains one or multiple PowerShell pipelines and execute them asynchronously
Support for a reference host base implementation of PSRP for interactive scripts

REF: https://github.com/jborean93/pypsrp


问:
Angular - the best approach to keep variables in a project
I'm wondering what's the best approach to keep variables in Angular project.

I have an example, let's suppose I have a component which includes many variables, but I don't like that it makes my component so long and less transparent.

```<code>...
@Component({
    selector: 'app-ballance',
    templateUrl: './balance.component.html',
    styleUrls: ['./balance.component.scss']
})
export class BalanceComponent implements OnInit {

    list = [];
    list3 = [];
    errorMsg;
    numbOfElem = 0;
    numbOfElem2 = 0;
    items: Array<any>;
    items2: Array<any>;
    pageOfItems: Array<any>;
    pageOfItems2: Array<any>;
    clickData = false;
    datas: any;
    correctBalance = false;
    wrongBalance = false;
    extraBalance  = false;
    administrator = false;
    doubleBalance = true;
    individualBalance  = false;
    groupBallance = false;
    verifiedBallance = true;
    blockedBallance = false;
    deletedBallance = false;
    unverifiedBallance = false;
    prepaidBallance = false;
...
    ballanceSelect: any[] = [{
        label: 'xxx',
        name: this.showName,
        inputName: 'showName',
        status: this.showName.status,
    }, {
        label: 'xxx',
        name: this.showEmail,
        inputName: 'showEmail',
        status: this.showEmail.status,
    }, {
        label: 'xxx',
        name: this.showMobilePhone,
        inputName: 'showMobilePhone',
        status: this.showMobilePhone.status,
    },
    ];
...
</code>```

My code is working but it doesn't look beautiful, is there some way to create extra file which would store my variables, objects, arrays etc and  how to connect that with component?

答:
Segregate your variables in category like class variable and local as per scope. We use the model classes in languages like C#, JAVA etc. You can also follow the same practice here as well. create a new class for class level variables and export it.
It will help you to maintain it and reuse it using inheritance/aggregation in some other places as well. </p>

Body:
I'm wondering what's the best approach to keep variables in Angular project.

I have an example, let's suppose I have a component which includes many variables, but I don't like that it makes my component so long and less transparent.

...
@Component({
    selector: 'app-ballance',
    templateUrl: './balance.component.html',
    styleUrls: ['./balance.component.scss']
})
export class BalanceComponent implements OnInit {

    list = [];
    list3 = [];
    errorMsg;
    numbOfElem = 0;
    numbOfElem2 = 0;
    items: Array<any>;
    items2: Array<any>;
    pageOfItems: Array<any>;
    pageOfItems2: Array<any>;
    clickData = false;
    datas: any;
    correctBalance = false;
    wrongBalance = false;
    extraBalance  = false;
    administrator = false;
    doubleBalance = true;
    individualBalance  = false;
    groupBallance = false;
    verifiedBallance = true;
    blockedBallance = false;
    deletedBallance = false;
    unverifiedBallance = false;
    prepaidBallance = false;
...
    ballanceSelect: any[] = [{
        label: 'xxx',
        name: this.showName,
        inputName: 'showName',
        status: this.showName.status,
    }, {
        label: 'xxx',
        name: this.showEmail,
        inputName: 'showEmail',
        status: this.showEmail.status,
    }, {
        label: 'xxx',
        name: this.showMobilePhone,
        inputName: 'showMobilePhone',
        status: this.showMobilePhone.status,
    },
    ];
...

My code is working but it doesn't look beautiful, is there some way to create extra file which would store my variables, objects, arrays etc and  how to connect that with component?


问:
How to SWIG in VS2010?
Hey Everybody,
    I'm trying to SWIG a multi file project that I made in VS2010 (c++) to python. I've managed to link the Python26.lib file, and have SWIG generating a wrapper .cpp file for my main .cpp file. I've set my code to build a .dll with the extension .pyd.

This is the .i file I have currently:

```<code>%module HiveGPS

%{
#include "ou_thread.h"
#include "HiveGPS.h"
%}

%include ou_thread.h
%include HiveGPS.h
</code>```

And I've mangaed to get a .py and .pyc file. Now, from my understanding in order to run my .py file, I need to link it to my .pyd file, but when I try to use VS2010 to build my project with the settings I listed above, it complains about a Thread class I'm using:

```<code>1>------ Build started: Project: HiveGPS, Configuration: Release Win32 ------
1>Build started 5/11/2011 1:41:30 PM.
1>InitializeBuildStatus:
1>  Touching "Release\HiveGPS.unsuccessfulbuild".
1>ClCompile:
1>  HiveGPS_wrap.cpp
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(57): error C2146: syntax error : missing ';' before identifier 'm_strName'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(57): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(57): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(64): error C2146: syntax error : missing ';' before identifier 'getName'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(64): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(64): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(64): warning C4183: 'getName': missing return type; assumed to be a member function returning 'int'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(98): error C2146: syntax error : missing ';' before identifier 'm_strName'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(98): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(98): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(104): error C2146: syntax error : missing ';' before identifier 'getName'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(104): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(104): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(104): warning C4183: 'getName': missing return type; assumed to be a member function returning 'int'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(115): error C2146: syntax error : missing ';' before identifier 'msg'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(115): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(115): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(118): error C2146: syntax error : missing ';' before identifier 'getMessage'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(118): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(118): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(118): warning C4183: 'getMessage': missing return type; assumed to be a member function returning 'int'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(51): error C2011: 'openutils::Thread' : 'class' type redefinition
1>          c:\users\*\desktop\hivegps\hivegps\ou_thread.h(51) : see declaration of 'openutils::Thread'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(93): error C2011: 'openutils::Mutex' : 'class' type redefinition
1>          c:\users\*\desktop\hivegps\hivegps\ou_thread.h(93) : see declaration of 'openutils::Mutex'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(113): error C2011: 'openutils::ThreadException' : 'class' type redefinition
1>          c:\users\*\desktop\hivegps\hivegps\ou_thread.h(113) : see declaration of 'openutils::ThreadException'
1>c:\users\*\desktop\hivegps\hivegps\HiveGPS.h(29): error C2504: 'openutils::Thread' : base class undefined
1>c:\users\*\desktop\hivegps\hivegps\HiveGPS.h(53): error C2079: 'HiveGPS::readWriteMutex' uses undefined class 'openutils::Mutex'
1>HiveGPS_wrap.cpp(3086): error C2027: use of undefined type 'openutils::Thread'
1>          c:\users\*\desktop\hivegps\hivegps\ou_thread.h(51) : see declaration of 'openutils::Thread'
1>HiveGPS_wrap.cpp(3086): fatal error C1903: unable to recover from previous error(s); stopping compilation
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:02.10
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
</code>```

All of these errors (minus the last one) are basically saying that the String class is implemented somehow, is it conflicting with Python's definition of the String class? The last error is complaining about the Thread class, could that be the same problem?

All of that said:
   Can somebody tell me what I'm doing wrong, or better yet, point me to a tutorial of how to do this for VS2010 (the SWIG site is for 2008).

And if that can't be done, can I link the .py file I have generated to the .dll file somehow?

Sorry for the long explanation but I'm kinda lost on this one so I decided to explain everything.

答:
It seems that some #include is missing in the ou_thread.h.

Further more, the "'class' type redefinition" can indicate that you don't have something like

```<code>#ifndef __ou_thread_h__
#define __ou_thread_h__

// your stuff, classes, etc.

#endif
</code>```

in your ou_thread.h

It's a guessing...

Title: How to SWIG in VS2010?

Body:
Hey Everybody,
    I'm trying to SWIG a multi file project that I made in VS2010 (c++) to python. I've managed to link the Python26.lib file, and have SWIG generating a wrapper .cpp file for my main .cpp file. I've set my code to build a .dll with the extension .pyd.

This is the .i file I have currently:

%module HiveGPS

%{
#include "ou_thread.h"
#include "HiveGPS.h"
%}

%include ou_thread.h
%include HiveGPS.h

And I've mangaed to get a .py and .pyc file. Now, from my understanding in order to run my .py file, I need to link it to my .pyd file, but when I try to use VS2010 to build my project with the settings I listed above, it complains about a Thread class I'm using:

1>------ Build started: Project: HiveGPS, Configuration: Release Win32 ------
1>Build started 5/11/2011 1:41:30 PM.
1>InitializeBuildStatus:
1>  Touching "Release\HiveGPS.unsuccessfulbuild".
1>ClCompile:
1>  HiveGPS_wrap.cpp
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(57): error C2146: syntax error : missing ';' before identifier 'm_strName'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(57): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(57): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(64): error C2146: syntax error : missing ';' before identifier 'getName'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(64): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(64): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(64): warning C4183: 'getName': missing return type; assumed to be a member function returning 'int'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(98): error C2146: syntax error : missing ';' before identifier 'm_strName'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(98): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(98): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(104): error C2146: syntax error : missing ';' before identifier 'getName'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(104): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(104): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(104): warning C4183: 'getName': missing return type; assumed to be a member function returning 'int'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(115): error C2146: syntax error : missing ';' before identifier 'msg'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(115): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(115): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(118): error C2146: syntax error : missing ';' before identifier 'getMessage'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(118): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(118): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(118): warning C4183: 'getMessage': missing return type; assumed to be a member function returning 'int'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(51): error C2011: 'openutils::Thread' : 'class' type redefinition
1>          c:\users\*\desktop\hivegps\hivegps\ou_thread.h(51) : see declaration of 'openutils::Thread'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(93): error C2011: 'openutils::Mutex' : 'class' type redefinition
1>          c:\users\*\desktop\hivegps\hivegps\ou_thread.h(93) : see declaration of 'openutils::Mutex'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(113): error C2011: 'openutils::ThreadException' : 'class' type redefinition
1>          c:\users\*\desktop\hivegps\hivegps\ou_thread.h(113) : see declaration of 'openutils::ThreadException'
1>c:\users\*\desktop\hivegps\hivegps\HiveGPS.h(29): error C2504: 'openutils::Thread' : base class undefined
1>c:\users\*\desktop\hivegps\hivegps\HiveGPS.h(53): error C2079: 'HiveGPS::readWriteMutex' uses undefined class 'openutils::Mutex'
1>HiveGPS_wrap.cpp(3086): error C2027: use of undefined type 'openutils::Thread'
1>          c:\users\*\desktop\hivegps\hivegps\ou_thread.h(51) : see declaration of 'openutils::Thread'
1>HiveGPS_wrap.cpp(3086): fatal error C1903: unable to recover from previous error(s); stopping compilation
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:02.10
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

All of these errors (minus the last one) are basically saying that the String class is implemented somehow, is it conflicting with Python's definition of the String class? The last error is complaining about the Thread class, could that be the same problem?

All of that said:
   Can somebody tell me what I'm doing wrong, or better yet, point me to a tutorial of how to do this for VS2010 (the SWIG site is for 2008).

And if that can't be done, can I link the .py file I have generated to the .dll file somehow?

Sorry for the long explanation but I'm kinda lost on this one so I decided to explain everything.

Body:
It seems that some #include is missing in the ou_thread.h.

Further more, the "'class' type redefinition" can indicate that you don't have something like

#ifndef __ou_thread_h__
#define __ou_thread_h__

// your stuff, classes, etc.

#endif

in your ou_thread.h

It's a guessing...


问:
Reading a text file word by word in C
I am trying to learn file I/O operations in C. My aim is storing all the words to a string array from a text file.

I tried to write a code that reads text file char by char and creates words from those chars. What I want to do is accessing to a word with line and word index. Would you help me about this?

This is my code.

```<code>char words[MAX_LINE][MAX_WORDS][MAX_CHAR];
int i=1, j=1, k=1;

FILE* ptrbook;
if((ptrbook = fopen("trial.txt", "r")) == NULL)
{
    printf("Failed to open the file %s\n", filename);
}
else
{
    while((words[i][j][k] = getc(ptrbook)) != EOF)
    {
        while((words[i][j][k] = getc(ptrbook)) != '\n')
        {
            while((words[i][j][k] = getc(ptrbook)) != ' ')
            {
                words[i][j][k] = getc(ptrbook);
                k++;
            }
            if((words[i][j][k] = getc(ptrbook)) == ' ' )
            {
                j++;
                k=1;
            }
            if((words[i][j][k] = getc(ptrbook)) == '\n')
            {
                i++;
                j=1;
                k=1;
            }
        }
    }
}
printf("%s\n", words[1][1]);
</code>```

答:
For doing this issue is easiest reading all the content from file into a dynamic variable in the heap. So after define a variable use the below function to allocate the dimension for the variable.

```<code>#define SIZE 4096
char * malloc_buff(int dim){
    char *buf;
    buf=malloc(sizeof(char)*dim);
    if(buf==NULL){
        perror("Errore in malloc");
    }
    return buf;
}
</code>```

Then you perform a variable and store all the information of the file in that variable using the below function. Instead of database_prenotazioni.txt insert the name of your file name

```<code>char * lettura_database_prenotazioni(){
    FILE* fd;
    char* disponibili;
    disponibili=malloc_buff(SIZE);
    errno=0;
    fd=fopen("database_prenotazioni.txt","r+");
    if(errno!=0){
        fprintf(stderr,"error in open\n");
        exit(-1);
    }
    fread(disponibili,sizeof(char),SIZE,fd);
    if(fclose(fd)){
        fprintf(stderr,"error in closure\n");
        exit(-1);
    }
    return disponibili;
}
</code>```

Now you need to make a strtok of the variable in which you have all the content with the del \t. Remember to allocate a new variable as array_stringhe variable in the below function that should be used for the return of the function

```<code>char ** tokenize_elem(char *buffer,char *del){
    int c=1;
    char **array_stringhe=malloc((sizeof(char*)*SIZE));
    if(array_stringhe==NULL){
        fprintf(stderr,"errore in malloc\n");
        exit(EXIT_FAILURE);
    }

    char *token=malloc_buff(SIZE);
    memset(token,'\0',SIZE);
    memset(array_stringhe,'\0',SIZE);
    array_stringhe[0] = strtok (buffer,del);
    //fprintf(stdout,"%s\n",array_stringhe[0]);
    while(token!=NULL){
        token=strtok(NULL,del);
        if(token==NULL){
            break;
        }
        array_stringhe[c]=token;

        //fprintf(stdout,"%s\n",array_stringhe[c]);
        c++;

    }
    free(token);
    return array_stringhe;
}
</code>```

Title: Reading a text file word by word in C

Body:
I am trying to learn file I/O operations in C. My aim is storing all the words to a string array from a text file.

I tried to write a code that reads text file char by char and creates words from those chars. What I want to do is accessing to a word with line and word index. Would you help me about this?

This is my code.

char words[MAX_LINE][MAX_WORDS][MAX_CHAR];
int i=1, j=1, k=1;

FILE* ptrbook;
if((ptrbook = fopen("trial.txt", "r")) == NULL)
{
    printf("Failed to open the file %s\n", filename);
}
else
{
    while((words[i][j][k] = getc(ptrbook)) != EOF)
    {
        while((words[i][j][k] = getc(ptrbook)) != '\n')
        {
            while((words[i][j][k] = getc(ptrbook)) != ' ')
            {
                words[i][j][k] = getc(ptrbook);
                k++;
            }
            if((words[i][j][k] = getc(ptrbook)) == ' ' )
            {
                j++;
                k=1;
            }
            if((words[i][j][k] = getc(ptrbook)) == '\n')
            {
                i++;
                j=1;
                k=1;
            }
        }
    }
}
printf("%s\n", words[1][1]);

Body:
For doing this issue is easiest reading all the content from file into a dynamic variable in the heap. So after define a variable use the below function to allocate the dimension for the variable.

#define SIZE 4096
char * malloc_buff(int dim){
    char *buf;
    buf=malloc(sizeof(char)*dim);
    if(buf==NULL){
        perror("Errore in malloc");
    }
    return buf;
}

Then you perform a variable and store all the information of the file in that variable using the below function. Instead of database_prenotazioni.txt insert the name of your file name

char * lettura_database_prenotazioni(){
    FILE* fd;
    char* disponibili;
    disponibili=malloc_buff(SIZE);
    errno=0;
    fd=fopen("database_prenotazioni.txt","r+");
    if(errno!=0){
        fprintf(stderr,"error in open\n");
        exit(-1);
    }
    fread(disponibili,sizeof(char),SIZE,fd);
    if(fclose(fd)){
        fprintf(stderr,"error in closure\n");
        exit(-1);
    }
    return disponibili;
}

Now you need to make a strtok of the variable in which you have all the content with the del \t. Remember to allocate a new variable as array_stringhe variable in the below function that should be used for the return of the function

char ** tokenize_elem(char *buffer,char *del){
    int c=1;
    char **array_stringhe=malloc((sizeof(char*)*SIZE));
    if(array_stringhe==NULL){
        fprintf(stderr,"errore in malloc\n");
        exit(EXIT_FAILURE);
    }

    char *token=malloc_buff(SIZE);
    memset(token,'\0',SIZE);
    memset(array_stringhe,'\0',SIZE);
    array_stringhe[0] = strtok (buffer,del);
    //fprintf(stdout,"%s\n",array_stringhe[0]);
    while(token!=NULL){
        token=strtok(NULL,del);
        if(token==NULL){
            break;
        }
        array_stringhe[c]=token;

        //fprintf(stdout,"%s\n",array_stringhe[c]);
        c++;

    }
    free(token);
    return array_stringhe;
}


问:
Getting the following error "PortForwardingL:local port 127.0.0.1:10005 can't be bound" while connecting to Corda Explorer UI using SSH
Getting the following error "PortForwardingL:local port 127.0.0.1:10005 can't be bound" while connecting to corda explorer ui using SSH.

I'm not sure what port number I need to pass in "Node Port section" on Node Explorer Explorer screen?? tried giving p2p port and RPC port but didn't work out.

I have enabled the SSH server by specifying sshd {port = 2222} in node.conf file.

Kindly suggest whether i need to do something related to port forwarding to establish a SSH connection or something else??

答:
Generally, the port can't be bound is generally an issue relating to the unavailability of a port since its being used by another program. Please check if port 10005 is free.

From the node explorer side here is how you should connect to a node via SSH:

The Node Port should be the RPC port of the node. The username and password should be the RPC username and password for both SSH and RPC.

The image below is an example for connecting to a local node exposing RPC port at 10006 and SSH port at 2222.


问:
MLPRegressor working but results don't make any sense
I am building a neural network with my research data in two ways: with a statistical programm (SPSS) and with python.
I am using the scikit learn MLPRegressor. The problem I have is that whereas my code is , apparently, well written (because it runs), the results do not make sense. The r2score should be around 0.70 ( it is-4147.64) and the correlation represented in the graph should be almost linear. (it is just a straight line at a constant distance from X axis).  Also the x and y axis should have values ranging from 0 to 180, which is not the case ( X from 20 to 100, y from -4100 to -3500)

If any of you can give a hand I would really appreciate it.
Thank you!!!!!!

```<code>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

from sklearn import neighbors, datasets, preprocessing
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPRegressor
from sklearn.metrics import r2_score

vhdata = pd.read_csv('vhrawdata.csv')
vhdata.head()

X = vhdata[['PA NH4', 'PH NH4', 'PA K', 'PH K', 'PA NH4 + PA K', 'PH NH4 + PH K', 'PA IS', 'PH IS']]
y = vhdata['PMI']

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

from sklearn.preprocessing import Normalizer
scaler = Normalizer().fit(X_train)
X_train_norm = scaler.transform(X_train)
X_test_norm = scaler.transform(X_test)

nnref = MLPRegressor(hidden_layer_sizes = [4], activation = 'logistic', solver = 'sgd', alpha = 1,
                     learning_rate= 'constant', learning_rate_init= 0.6, max_iter=40000, momentum=
                     0.3).fit(X_train, y_train)

y_predictions= nnref.predict(X_test)

print('Accuracy of NN classifier on training set (R2 score): {:.2f}'.format(nnref.score(X_train_norm, y_train)))
print('Accuracy of NN classifier on test set (R2 score): {:.2f}'.format(nnref.score(X_test_norm, y_test)))

plt.figure()
plt.scatter(y_test,y_predictions, marker = 'o', color='red')
plt.xlabel('PMI expected (hrs)')
plt.ylabel('PMI predicted (hrs)')
plt.title('Correlation of PMI predicted by MLP regressor and the actual PMI')
plt.show()
</code>```

答:
You have a couple of issues. First, it is important to use the right scaler or normalization to work with an MLP. NNs work best between 0 and 1, so consider using sklearn's MinMaxScaler to accomplish this.

So:

```<code>from sklearn.preprocessing import Normalizer
scaler = Normalizer().fit(X_train)
X_train_norm = scaler.transform(X_train)
X_test_norm = scaler.transform(X_test)
</code>```

Should be:

```<code>from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
X_train_norm = scaler.fit_transform(X_train)
X_test_norm = scaler.fit_transform(X_test)
</code>```

Next, you are training and testing on the unscaled data, but then performing your scores on the scaled data. Meaning:

```<code>nnref = MLPRegressor(hidden_layer_sizes = [4], activation = 'logistic', solver = 'sgd', alpha = 1,
                     learning_rate= 'constant', learning_rate_init= 0.6, max_iter=40000, momentum=
                     0.3).fit(X_train, y_train)
</code>```

should be:

```<code>nnref = MLPRegressor(hidden_layer_sizes = [4], activation = 'logistic', solver = 'sgd', alpha = 1,
                     learning_rate= 'constant', learning_rate_init= 0.6, max_iter=40000, momentum=
                     0.3).fit(X_train_norm , y_train)
</code>```

And...

```<code>y_predictions= nnref.predict(X_test)
</code>```

Should be:

```<code>y_predictions= nnref.predict(X_test_norm)
</code>```

Additional notes...

It doesn't make any sense to predict on your training data. That provides no value, as it is testing the same data it learned from and should predict 100%. That is an example of overfitting.

Body:
I am building a neural network with my research data in two ways: with a statistical programm (SPSS) and with python.
I am using the scikit learn MLPRegressor. The problem I have is that whereas my code is , apparently, well written (because it runs), the results do not make sense. The r2score should be around 0.70 ( it is-4147.64) and the correlation represented in the graph should be almost linear. (it is just a straight line at a constant distance from X axis).  Also the x and y axis should have values ranging from 0 to 180, which is not the case ( X from 20 to 100, y from -4100 to -3500)

If any of you can give a hand I would really appreciate it.
Thank you!!!!!!

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

from sklearn import neighbors, datasets, preprocessing
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPRegressor
from sklearn.metrics import r2_score

vhdata = pd.read_csv('vhrawdata.csv')
vhdata.head()

X = vhdata[['PA NH4', 'PH NH4', 'PA K', 'PH K', 'PA NH4 + PA K', 'PH NH4 + PH K', 'PA IS', 'PH IS']]
y = vhdata['PMI']

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

from sklearn.preprocessing import Normalizer
scaler = Normalizer().fit(X_train)
X_train_norm = scaler.transform(X_train)
X_test_norm = scaler.transform(X_test)

nnref = MLPRegressor(hidden_layer_sizes = [4], activation = 'logistic', solver = 'sgd', alpha = 1,
                     learning_rate= 'constant', learning_rate_init= 0.6, max_iter=40000, momentum=
                     0.3).fit(X_train, y_train)

y_predictions= nnref.predict(X_test)

print('Accuracy of NN classifier on training set (R2 score): {:.2f}'.format(nnref.score(X_train_norm, y_train)))
print('Accuracy of NN classifier on test set (R2 score): {:.2f}'.format(nnref.score(X_test_norm, y_test)))

plt.figure()
plt.scatter(y_test,y_predictions, marker = 'o', color='red')
plt.xlabel('PMI expected (hrs)')
plt.ylabel('PMI predicted (hrs)')
plt.title('Correlation of PMI predicted by MLP regressor and the actual PMI')
plt.show()

Body:
You have a couple of issues. First, it is important to use the right scaler or normalization to work with an MLP. NNs work best between 0 and 1, so consider using sklearn's MinMaxScaler to accomplish this.

So:

from sklearn.preprocessing import Normalizer
scaler = Normalizer().fit(X_train)
X_train_norm = scaler.transform(X_train)
X_test_norm = scaler.transform(X_test)

Should be:

from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
X_train_norm = scaler.fit_transform(X_train)
X_test_norm = scaler.fit_transform(X_test)

Next, you are training and testing on the unscaled data, but then performing your scores on the scaled data. Meaning:

nnref = MLPRegressor(hidden_layer_sizes = [4], activation = 'logistic', solver = 'sgd', alpha = 1,
                     learning_rate= 'constant', learning_rate_init= 0.6, max_iter=40000, momentum=
                     0.3).fit(X_train, y_train)

should be:

nnref = MLPRegressor(hidden_layer_sizes = [4], activation = 'logistic', solver = 'sgd', alpha = 1,
                     learning_rate= 'constant', learning_rate_init= 0.6, max_iter=40000, momentum=
                     0.3).fit(X_train_norm , y_train)

And...

y_predictions= nnref.predict(X_test)

Should be:

y_predictions= nnref.predict(X_test_norm)

Additional notes...

It doesn't make any sense to predict on your training data. That provides no value, as it is testing the same data it learned from and should predict 100%. That is an example of overfitting.


问:
Conditional Statement inside Lambda Expression c#
I'm trying to remove strings from List by given command.
The command is to remove all strings that starts or ends with given string.

List input = new List() {"Pesho", "Misho", "Stefan"};

string command = "Remove StartsWith P"; or "Remove EndsWith P"

I'm trying to do it with lambda. Smth like this:

```<code>input.RemoveAll(x =>
{
if (command[1] == "StartsWith")
    x.StartsWith(command[2]);

else if (command[1] == "EndsWith")
    x.EndsWith(command[2]);
});
</code>```

The compiler says:
Not all code paths return a value in lambda expression of type Predicate

I'm asking is it possible to do it inside one lambda,
or I have to write it for both cases.

答:
You can convert multiple if statements into one switch statement and use a return for every case label

input.RemoveAll(x =>
{
    switch (command[1])
    {
        case "StartsWith":
            return x.StartsWith(command[2]);
        case "EndsWith":
            return x.EndsWith(command[2]);
        default:
            return false;
    }
});
```

<p>If you can target C# 8, it can be simplified using <code>switch</code> expression</p>

<pre class="lang-cs prettyprint-override"><code>input.RemoveAll(x =>
{
    return command[1] switch
    {
        "StartsWith" => x.StartsWith(command[2]),
        "EndsWith" => x.EndsWith(command[2]),
        _ => false
    };
});
</code>```

But in both cases you should maintain a default case to return a false value

Body:
I'm trying to remove strings from List by given command.
The command is to remove all strings that starts or ends with given string.

List input = new List() {"Pesho", "Misho", "Stefan"};

string command = "Remove StartsWith P"; or "Remove EndsWith P"

I'm trying to do it with lambda. Smth like this:

input.RemoveAll(x =>
{
if (command[1] == "StartsWith")
    x.StartsWith(command[2]);

else if (command[1] == "EndsWith")
    x.EndsWith(command[2]);
});

The compiler says:
Not all code paths return a value in lambda expression of type Predicate

I'm asking is it possible to do it inside one lambda,
or I have to write it for both cases.

Body:
You can convert multiple if statements into one switch statement and use a return for every case label

input.RemoveAll(x =>
{
    switch (command[1])
    {
        case "StartsWith":
            return x.StartsWith(command[2]);
        case "EndsWith":
            return x.EndsWith(command[2]);
        default:
            return false;
    }
});

If you can target C# 8, it can be simplified using switch expression

input.RemoveAll(x =>
{
    return command[1] switch
    {
        "StartsWith" => x.StartsWith(command[2]),
        "EndsWith" => x.EndsWith(command[2]),
        _ => false
    };
});

But in both cases you should maintain a default case to return a false value


问:
Get max ID row from individual rows in SQK Server with only 2 columns
I have data like below with multiple rows with same data which can be identified by ID.

```<code>A   2784762
A   2788523
A   2789063
B   3423390
B   3423396
</code>```

I need the data like below. Get only individual max ID value for every set of duplicate records with can be done by taking individual max ID

```<code>A   2789063
B   3423396
</code>```

Can you help me with this?

答:
Use MAX function to achieve this:

```<code>SELECT COL1,MAX(COL2)
FROM TABLE
GROUP BY COL1
</code>```

Instead of COL1,COL2 use your Table Column Names and Table use your Table Name.

Body:
I have data like below with multiple rows with same data which can be identified by ID.

A   2784762
A   2788523
A   2789063
B   3423390
B   3423396

I need the data like below. Get only individual max ID value for every set of duplicate records with can be done by taking individual max ID

A   2789063
B   3423396

Can you help me with this?

Body:
Use MAX function to achieve this:

SELECT COL1,MAX(COL2)
FROM TABLE
GROUP BY COL1

Instead of COL1,COL2 use your Table Column Names and Table use your Table Name.


问:
Flutter ListTile title overflow issue
I'm displaying a long text inside ListTile's title using the following code and I'm having UI issue with the Text overflow feature:

ListTile(
  contentPadding: const EdgeInsets.symmetric(horizontal: 32.0),
  leading: SizedBox(
    width: 32.0,
    child: Center(
      child: Container(
        width: 32.0,
        height: 32.0,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: HexColor.fromHex(_clientStatusList.first.color)
              .withOpacity(0.2),
          border: Border.all(
              color: HexColor.fromHex(_clientStatusList.first.color)),
        ),
        child: Center(
            child: Icon(
          CustomIcons.customer_important,
          size: 14.0,
          color: HexColor.fromHex(_clientStatusList.first.color),
        )),
      ),
    ),
  ),
  title: Text(
    _clientStatusList.map((e) => e.name).join(", "),
    maxLines: 1,
    overflow: TextOverflow.ellipsis,
  ),
  subtitle: Text("Status"),
),
```

<p>Result from the above code:
https://i.stack.imgur.com/O5Euf.png</p>

<p>Result without <code>maxLines</code> and <code>overflow</code>:
https://i.stack.imgur.com/VWOpF.png</p>

<p>I guess that the expected result is:
https://i.stack.imgur.com/OFMoT.png</p>

<p>Flutter doctor:</p>

```[✓] Flutter (Channel stable, v1.17.2, on Mac OS X 10.15.5 19F96, locale en-IL)

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[✓] Xcode - develop for iOS and macOS (Xcode 11.5)
[✓] Android Studio (version 4.0)
[✓] VS Code (version 1.45.1)
[✓] Connected device (1 available)
```

答:
The documentation fo maxLine says:

If this is 1 (the default), the text will not wrap, but will scroll horizontally instead.

so, the output is right according to widget.

I would suggest link 1 and link 2 to take a look.

NB: You can try with Expanded() Widget, sometimes it is handy to use full empty space .

Title: Flutter ListTile title overflow issue

Body:
I'm displaying a long text inside ListTile's title using the following code and I'm having UI issue with the Text overflow feature:

ListTile(
  contentPadding: const EdgeInsets.symmetric(horizontal: 32.0),
  leading: SizedBox(
    width: 32.0,
    child: Center(
      child: Container(
        width: 32.0,
        height: 32.0,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: HexColor.fromHex(_clientStatusList.first.color)
              .withOpacity(0.2),
          border: Border.all(
              color: HexColor.fromHex(_clientStatusList.first.color)),
        ),
        child: Center(
            child: Icon(
          CustomIcons.customer_important,
          size: 14.0,
          color: HexColor.fromHex(_clientStatusList.first.color),
        )),
      ),
    ),
  ),
  title: Text(
    _clientStatusList.map((e) => e.name).join(", "),
    maxLines: 1,
    overflow: TextOverflow.ellipsis,
  ),
  subtitle: Text("Status"),
),

Result from the above code:
https://i.stack.imgur.com/O5Euf.png

Result without maxLines and overflow:
https://i.stack.imgur.com/VWOpF.png

I guess that the expected result is:
https://i.stack.imgur.com/OFMoT.png

Flutter doctor:

[✓] Flutter (Channel stable, v1.17.2, on Mac OS X 10.15.5 19F96, locale en-IL)

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[✓] Xcode - develop for iOS and macOS (Xcode 11.5)
[✓] Android Studio (version 4.0)
[✓] VS Code (version 1.45.1)
[✓] Connected device (1 available)


问:
Unable to edit form fields in Reactjs after fetched from server
I have a user edit page in Reactjs where I fetch the user details and populate it to corresponding input fields. The problem is after fetching and displaying the data I'm not able to edit the fields.

My code is:

```<code>function EditProfile(props) {
    const [user, setUser] = useState()
    useEffect(() => {
        const fetchUserInfo = async () => {
            const profileConfig = {
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + auth.token
                }
            };
            fetch(`http://localhost:4000/api/v1/user/me`, profileConfig)
            .then(response => response.json())
            .then(response => {
                console.log("response: ", response.user);
                if (response.success === true) {
                    setUser(response.user)
                } else {
                    alert(response.message)
                }
            },
            (error) => {
                alert('User fetching faied: ' + error)
            })
        }
        fetchUserInfo()
    }, [])

    return (
       <form>
           <input type="text" value={user.name} name="name" />
       </form>
    )
}
</code>```

The corresponding name is displayed in this input field but not editable. How to solve the issue?

答:
You have not added onChange function on your input which React recommends to make it a controlled component. The advantages of having a controlled input is that you have the value available throughout you React component and you do not need an event to be fired on input or access the DOM to get the value.

If you don't want to create a controlled component you do it this way:

```<code><input type="text" defaultValue={user.name} name="name" />
</code>```

Using defaultValue instead of value. Because in the React rendering lifecycle, the value attribute on form elements will override the value in the DOM. With this you want React to specify the initial value, but leave subsequent updates uncontrolled hence creating an uncontrolled component.

If you create a controlled component you will have to specify a function to handle the change and set that to the state as specified by this answer below by @Vaibhav: https://stackoverflow.com/a/62133180/4207394

Body:
I have a user edit page in Reactjs where I fetch the user details and populate it to corresponding input fields. The problem is after fetching and displaying the data I'm not able to edit the fields.

My code is:

function EditProfile(props) {
    const [user, setUser] = useState()
    useEffect(() => {
        const fetchUserInfo = async () => {
            const profileConfig = {
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + auth.token
                }
            };
            fetch(`http://localhost:4000/api/v1/user/me`, profileConfig)
            .then(response => response.json())
            .then(response => {
                console.log("response: ", response.user);
                if (response.success === true) {
                    setUser(response.user)
                } else {
                    alert(response.message)
                }
            },
            (error) => {
                alert('User fetching faied: ' + error)
            })
        }
        fetchUserInfo()
    }, [])

    return (
       <form>
           <input type="text" value={user.name} name="name" />
       </form>
    )
}

The corresponding name is displayed in this input field but not editable. How to solve the issue?

Body:
You have not added onChange function on your input which React recommends to make it a controlled component. The advantages of having a controlled input is that you have the value available throughout you React component and you do not need an event to be fired on input or access the DOM to get the value.

If you don't want to create a controlled component you do it this way:

<input type="text" defaultValue={user.name} name="name" />

Using defaultValue instead of value. Because in the React rendering lifecycle, the value attribute on form elements will override the value in the DOM. With this you want React to specify the initial value, but leave subsequent updates uncontrolled hence creating an uncontrolled component.

If you create a controlled component you will have to specify a function to handle the change and set that to the state as specified by this answer below by @Vaibhav: https://stackoverflow.com/a/62133180/4207394


问:
How do I add the like facebook button to a silverlight application?
I'm new to silverlight 4 development.
I need the facebook I like button to be integrated integrated on my website application?

Can someone tell me how to do that?

Can I download a library that will provide me a user control that is visible in my toolbox, and thus I will be able to just drag and drop this item on my page?
If not, how can I implement this functionality?

答: If you want to invoke the "I like" feature from silverlight you can just call javascript code (rise the onclick event) from silverlight which located on your page.</p>


问:
Error TS2339: What's the difference when using Array vs ReadonlyArray?
Can someone explain the difference between Array and ReadonlyArray for the following use case?

Array works fine:

```<code>function example(text: string | string[]): string[] {
  if (Array.isArray(text)) {
    return text.map(s => s.trim());
  }
  return [text.trim()];
}
</code>```

However ReadonlyArray throws ts2339 - Property 'trim' does not exist on type 'string | readyonly string[]. Why?

```<code>function example(text: string | ReadonlyArray<string>): string[] {
  if (Array.isArray(text)) {
    return text.map(s => s.trim());
  }
  return [text.trim()];
}
</code>```

答:
That's...surprising behavior, and it's discussed in issue #17002. Apparently, Array.isArray isn't sufficient for TypeScript to narrow the type of text from string | ReadonlyArray<string> to string, even though it works for narrowing string | string[]. See the full issue thread for details, but basically it's because Array.isArray isn't defined in readonly terms.

You can work around it in your case using typeof:

```<code>function example(text: string | ReadonlyArray<string>): string[] {
  if (typeof text === "string") {
    return [text.trim()];
  }
  return text.map(s => s.trim());
}
</code>```

Playground link

Alternatively, you can do as jcalz suggests here and modify the ArrayConstructor interface to specify behavior for isArray for readonly arrays:

```<code>interface ArrayConstructor {
    isArray<T>(arg: ReadonlyArray<T> | T): arg is ReadonlyArray<T>;
}
</code>```

With that, your original code works just fine - Playground link

Later in the issue thread, though, he says

I would probably do this if I wanted a workaround:

```<code>interface ReadonlyArrayConstructor  {
    new(arrayLength?: number): ReadonlyArray<any>;
    new <T>(arrayLength: number): ReadonlyArray<T>;
    new <T>(...items: T[]): ReadonlyArray<T>;
    (arrayLength?: number): ReadonlyArray<any>;
    <T>(arrayLength: number): ReadonlyArray<T>;
    <T>(...items: T[]): ReadonlyArray<T>;
    isArray(arg: any): arg is ReadonlyArray<any>;
    readonly prototype: ReadonlyArray<any>;
}
const ReadonlyArray = Array as ReadonlyArrayConstructor;
</code>```

And then later

```<code>if (ReadonlyArray.isArray(immutable)) {
  const x = immutable; // ReadonlyArray<T>
}
if (immutable instanceof ReadonlyArray) {
  const x = immutable; //  ReadonlyArray<T>
}
</code>```

In your case, that would be the ReadonlyArrayConstructor from the above and

```<code>function example(text: string | ReadonlyArray<string>): string[] {
  if (ReadonlyArray.isArray(text)) {
    return text.map(s => s.trim());
  }
  return [text.trim()];
}
</code>```

Playground link

Body:
Can someone explain the difference between Array and ReadonlyArray for the following use case?

Array works fine:

function example(text: string | string[]): string[] {
  if (Array.isArray(text)) {
    return text.map(s => s.trim());
  }
  return [text.trim()];
}

However ReadonlyArray throws ts2339 - Property 'trim' does not exist on type 'string | readyonly string[]. Why?

function example(text: string | ReadonlyArray<string>): string[] {
  if (Array.isArray(text)) {
    return text.map(s => s.trim());
  }
  return [text.trim()];
}

Body:
That's...surprising behavior, and it's discussed in issue #17002. Apparently, Array.isArray isn't sufficient for TypeScript to narrow the type of text from string | ReadonlyArray<string> to string, even though it works for narrowing string | string[]. See the full issue thread for details, but basically it's because Array.isArray isn't defined in readonly terms.

You can work around it in your case using typeof:

function example(text: string | ReadonlyArray<string>): string[] {
  if (typeof text === "string") {
    return [text.trim()];
  }
  return text.map(s => s.trim());
}

Playground link

Alternatively, you can do as jcalz suggests here and modify the ArrayConstructor interface to specify behavior for isArray for readonly arrays:

interface ArrayConstructor {
    isArray<T>(arg: ReadonlyArray<T> | T): arg is ReadonlyArray<T>;
}

With that, your original code works just fine - Playground link

Later in the issue thread, though, he says

I would probably do this if I wanted a workaround:

interface ReadonlyArrayConstructor  {
    new(arrayLength?: number): ReadonlyArray<any>;
    new <T>(arrayLength: number): ReadonlyArray<T>;
    new <T>(...items: T[]): ReadonlyArray<T>;
    (arrayLength?: number): ReadonlyArray<any>;
    <T>(arrayLength: number): ReadonlyArray<T>;
    <T>(...items: T[]): ReadonlyArray<T>;
    isArray(arg: any): arg is ReadonlyArray<any>;
    readonly prototype: ReadonlyArray<any>;
}
const ReadonlyArray = Array as ReadonlyArrayConstructor;

And then later

if (ReadonlyArray.isArray(immutable)) {
  const x = immutable; // ReadonlyArray<T>
}
if (immutable instanceof ReadonlyArray) {
  const x = immutable; //  ReadonlyArray<T>
}

In your case, that would be the ReadonlyArrayConstructor from the above and

function example(text: string | ReadonlyArray<string>): string[] {
  if (ReadonlyArray.isArray(text)) {
    return text.map(s => s.trim());
  }
  return [text.trim()];
}

<a href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgEoTgEwPYgDYCeAglFHAQMK4DOYUArgmNlMsgN4BQbbIEA7gAo4pcgBkIIAOZgAFgH4AXMhD0AtgCNoASmXosuQiTIEAPHBAEAfAG5uPPv2SmAKleGiCE6XOWrNOnoYOPjEnq629rwCzm6CAHSJwJBq1MouANoAurpowYZhJhF2PMgeJt4yCn7qWlC5%20iFG4RbWJTwR5eKSVTUB9UEGocbkxVGx7onxyRCp6dkN%20cPhbu1swNQjBB5Syq25IlLIG3lDzUWtkaVQS4TIAA5Q2MxgBPcQg02Fo5d2AL6cBA0MCnL5bZAAXmQ4Lg1FBBS2VBAtAYTBYdk4MHoICYwFwyAgAA84Gp7ngIIJIISwMoUaAjgAfeHLIp06RWXJsqTZDj2YAwMqNBGeaabTyUolgbTaXnXCBgehQEDIKlgeJqOD3QRwiFWZDUeJ0YBqQTS9oAtg3BVK5AZVWGqDG01Zf5AA" rel="nofollow noreferrer">Playground link


问:
SSRS Show Base64 String or Byte Array From URL as Image
I have a wevservice that returns an image as a Base64 string, or as a byte array, that I need to show as an image in SSRS. Not sure how to do that.

I tried using an expression in the image properties:

```<code>=System.Convert.FromBase64String("http://localhost:5460/api/Report/GetImage")
</code>```

but that does not work. How do I get the string or array from the URL, then display it as an image?

I have also tried a Code block, but when I try

```<code>Dim hwr As System.Net.HttpWebRequest
hwr = System.Net.WebRequest.Create("http://localhost:5460/api/Report/GetImage")
</code>```

I get the error:

```<code>Severity    Code    Description Project File    Line    Suppression State
Warning     [rsRuntimeErrorInExpression] The Value expression for the textrun 'Textbox2.Paragraphs[0].TextRuns[0]' contains an error:
Insufficient permissions for setting the configuration property 'maximumErrorResponseLength'. (c:\program files (x86)\microsoft visual studio\2017\sql\common7\ide\commonextensions\microsoft\ssrs\PreviewProcessingService.exe.Config line 42)     C:\Users\Desktop\REP90011\REP90011.rdl  0
</code>```

This is on my local machine, not on the SSRS server or through IIS. Just through the preview pane in VS 2017.

答:
The problem was that I need to allow permissions in the file RSPreviewPolicy.config on my desktop to be 'FullTrust' instead of 'Nothing' in order to be able to use 'System.Net.WebRequest.Create'.

Edit:
I have been asked to expand on how my process works, so here it is:

I have a webservice that fetches an image and returns it as a base64 string.

Put an image object on the report, set it to 'Database', 'image/bmp', and use this expression as the field:

```<code>=Convert.FromBase64String(Code.GetImageString("http://localhost:5460/api/Report/GetImage")
</code>```

The URL being the webservice that returns the string.

The function GetImageString is in the Code section of report properties:

```<code>Public Function GetImageString(Url As String) As String
   'create web request
   Dim hwr As System.Net.HttpWebRequest
   'this line is what I needed to change the permissions for
   hwr = System.Net.WebRequest.Create(Url)
   hwr .Credentials = System.Net.CredentialCache.DefaultCredentials
   'get response from request
   Dim wr As System.Net.WebResponse
   wr = hwr.GetResponse()
   'get stream from response
   Dim sr as System.IO.Stream
   sr = wr.GetResponseStream()
   'read response stream
   Dim read As IO.StreamReader
   read = new IO.StreamReader(sr, System.Text.Encoding.UTF8)
   'convert stream to string
   Dim result as string
   result = read.ReadToEnd
   return result.substring(1, result.length - 2) 'remove first and last characters, it's putting in quotes
 End Function
</code>```

In VS 2017 this worked fine on my desktop. In VS 2019 it shows a red x on my desktop, but still works when deployed to the server.

Body:
I have a wevservice that returns an image as a Base64 string, or as a byte array, that I need to show as an image in SSRS. Not sure how to do that.

I tried using an expression in the image properties:

=System.Convert.FromBase64String("http://localhost:5460/api/Report/GetImage")

but that does not work. How do I get the string or array from the URL, then display it as an image?

I have also tried a Code block, but when I try

Dim hwr As System.Net.HttpWebRequest
hwr = System.Net.WebRequest.Create("http://localhost:5460/api/Report/GetImage")

I get the error:

Severity    Code    Description Project File    Line    Suppression State
Warning     [rsRuntimeErrorInExpression] The Value expression for the textrun 'Textbox2.Paragraphs[0].TextRuns[0]' contains an error:
Insufficient permissions for setting the configuration property 'maximumErrorResponseLength'. (c:\program files (x86)\microsoft visual studio\2017\sql\common7\ide\commonextensions\microsoft\ssrs\PreviewProcessingService.exe.Config line 42)     C:\Users\Desktop\REP90011\REP90011.rdl  0

This is on my local machine, not on the SSRS server or through IIS. Just through the preview pane in VS 2017.

Body:
The problem was that I need to allow permissions in the file RSPreviewPolicy.config on my desktop to be 'FullTrust' instead of 'Nothing' in order to be able to use 'System.Net.WebRequest.Create'.

Edit:
I have been asked to expand on how my process works, so here it is:

I have a webservice that fetches an image and returns it as a base64 string.

Put an image object on the report, set it to 'Database', 'image/bmp', and use this expression as the field:

=Convert.FromBase64String(Code.GetImageString("http://localhost:5460/api/Report/GetImage")

The URL being the webservice that returns the string.

The function GetImageString is in the Code section of report properties:

Public Function GetImageString(Url As String) As String
   'create web request
   Dim hwr As System.Net.HttpWebRequest
   'this line is what I needed to change the permissions for
   hwr = System.Net.WebRequest.Create(Url)
   hwr .Credentials = System.Net.CredentialCache.DefaultCredentials
   'get response from request
   Dim wr As System.Net.WebResponse
   wr = hwr.GetResponse()
   'get stream from response
   Dim sr as System.IO.Stream
   sr = wr.GetResponseStream()
   'read response stream
   Dim read As IO.StreamReader
   read = new IO.StreamReader(sr, System.Text.Encoding.UTF8)
   'convert stream to string
   Dim result as string
   result = read.ReadToEnd
   return result.substring(1, result.length - 2) 'remove first and last characters, it's putting in quotes
 End Function

In VS 2017 this worked fine on my desktop. In VS 2019 it shows a red x on my desktop, but still works when deployed to the server.


问:
Finding transpose of each element of list separately in python
I have a List of N items, each of d dimensions (so essentially a N x d list). For each of the items, I want to find the product of item transposed with itself, So, x.xT for each of the N items. This will give me a N x d x d array. How can I do it efficiently in numpy. At this moment, I am looping through each of the items and finding the transpose separately.

```<code>for i in range(len(mu[0])):
    current_mu = mu[i] # list of d elements
    distances = []
    for index in range(len(samples)):
        distance = np.asarray(current_mu - samples[index])[:, None] # list of d elements
        distances.append(distance * distance.T) # each becomes d x d
</code>```

Can I remove the second nested loop or is it required?

答:
The previous answer by @FBruzzesi works perfectly, but if anyone prefers a solution without using einsum (and completeness in general):</p>

```<code>n,d=1000,500
x=np.random.randn(n,d,1)
x_einsum=x.reshape(n,d)

%timeit x * x.transpose((0,2,1))
744 ms ± 48.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit np.einsum('ni,nj->nij', x_einsum, x_einsum)
777 ms ± 18.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code>```

Body:
I have a List of N items, each of d dimensions (so essentially a N x d list). For each of the items, I want to find the product of item transposed with itself, So, x.xT for each of the N items. This will give me a N x d x d array. How can I do it efficiently in numpy. At this moment, I am looping through each of the items and finding the transpose separately.

for i in range(len(mu[0])):
    current_mu = mu[i] # list of d elements
    distances = []
    for index in range(len(samples)):
        distance = np.asarray(current_mu - samples[index])[:, None] # list of d elements
        distances.append(distance * distance.T) # each becomes d x d

Can I remove the second nested loop or is it required?

Body:
The previous answer by @FBruzzesi works perfectly, but if anyone prefers a solution without using einsum (and completeness in general):

n,d=1000,500
x=np.random.randn(n,d,1)
x_einsum=x.reshape(n,d)

%timeit x * x.transpose((0,2,1))
744 ms ± 48.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit np.einsum('ni,nj->nij', x_einsum, x_einsum)
777 ms ± 18.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


问:
Python, remove all non-alphabet chars from string
I am writing a python MapReduce word count program. Problem is that there are many non-alphabet chars strewn about in the data, I have found this post Stripping everything but alphanumeric chars from a string in Python which shows a nice solution using regex, but I am not sure how to implement it

```<code>def mapfn(k, v):
    print v
    import re, string
    pattern = re.compile('[\W_]+')
    v = pattern.match(v)
    print v
    for w in v.split():
        yield w, 1
</code>```

I'm afraid I am not sure how to use the library re or even regex for that matter. I am not sure how to apply the regex pattern to the incoming string (line of a book) v properly to retrieve the new line without any non-alphanumeric chars.

Suggestions?

答:
It is advisable to use PyPi regex module if you plan to match specific Unicode property classes. This library has also proven to be more stable, especially handling large texts, and yields consistent results across various Python versions. All you need to do is to keep it up-to-date.

If you install it (using pip install regex or pip3 install regex), you may use

```<code>import regex
print ( regex.sub(r'\P{L}+', '', 'ABCŁąć1-2!Абв3§4“5def”') )
// => ABCŁąćАбвdef
</code>```

to remove all chunks of 1 or more characters other than Unicode letters from text. See an online Python demo. You may also use "".join(regex.findall(r'\p{L}+', 'ABCŁąć1-2!Абв3§4“5def”')) to get the same result.

In Python re, in order to match any Unicode letter, one may use the [^\W\d_] construct (Match any unicode letter?).

So, to remove all non-letter characters, you may either match all letters and join the results:

```<code>result = "".join(re.findall(r'[^\W\d_]', text))
</code>```

Or, remove all chars matching the [\W\d_] pattern (opposite to [^\W\d_]):

```<code>result = re.sub(r'[\W\d_]+', '', text)
</code>```

See the regex demo online. However, you may get inconsistent results across various Python versions because the Unicode standard is evolving, and the set of chars matched with \w will depend on the Python version. Using PyPi regex library is highly recommended to get consistent results.

Body:
I am writing a python MapReduce word count program. Problem is that there are many non-alphabet chars strewn about in the data, I have found this post Stripping everything but alphanumeric chars from a string in Python which shows a nice solution using regex, but I am not sure how to implement it

def mapfn(k, v):
    print v
    import re, string
    pattern = re.compile('[\W_]+')
    v = pattern.match(v)
    print v
    for w in v.split():
        yield w, 1

I'm afraid I am not sure how to use the library re or even regex for that matter. I am not sure how to apply the regex pattern to the incoming string (line of a book) v properly to retrieve the new line without any non-alphanumeric chars.

Suggestions?

Body:
It is advisable to use PyPi regex module if you plan to match specific Unicode property classes. This library has also proven to be more stable, especially handling large texts, and yields consistent results across various Python versions. All you need to do is to keep it up-to-date.

If you install it (using pip install regex or pip3 install regex), you may use

import regex
print ( regex.sub(r'\P{L}+', '', 'ABCŁąć1-2!Абв3§4“5def”') )
// => ABCŁąćАбвdef

to remove all chunks of 1 or more characters other than Unicode letters from text. See an online Python demo. You may also use "".join(regex.findall(r'\p{L}+', 'ABCŁąć1-2!Абв3§4“5def”')) to get the same result.

In Python re, in order to match any Unicode letter, one may use the [^\W\d_] construct (Match any unicode letter?).

So, to remove all non-letter characters, you may either match all letters and join the results:

result = "".join(re.findall(r'[^\W\d_]', text))

Or, remove all chars matching the [\W\d_] pattern (opposite to [^\W\d_]):

result = re.sub(r'[\W\d_]+', '', text)

See the regex demo online. However, you may get inconsistent results across various Python versions because the Unicode standard is evolving, and the set of chars matched with \w will depend on the Python version. Using PyPi regex library is highly recommended to get consistent results.


问:
Angular loading files from backend using the wrong port
My Angular frontend application is using default port 4200. My Django backend application is running on port 8000. Frontend can upload files and images to backend, a then get their links to show on page. Uploading is working fine, but then when I try to get images from backend, Angular is downloading them from frontend port 4200 and all views are breaking, because there is no such files on that path.
Briefly, I need file path in that way - http://localhost:8000/media/uploads/myfile, but I get http://localhost:4200/media/uploads/myfile.
I use proxy to get backend api:

```<code>{
  "/api": {
  "target": "http://localhost:8000",
  "secure": false
  }
}
</code>```

I do not know where the problem may be.

答:
change proxy.conf.json:

```<code>{
  "/api": {
  "target": "http://localhost:8000",
  "secure": false,
  "changeOrigin": true,
  "pathRewrite": {
    "^/api": "http://localhost:8000/api"
  }
}
</code>```

}

Body:
My Angular frontend application is using default port 4200. My Django backend application is running on port 8000. Frontend can upload files and images to backend, a then get their links to show on page. Uploading is working fine, but then when I try to get images from backend, Angular is downloading them from frontend port 4200 and all views are breaking, because there is no such files on that path.
Briefly, I need file path in that way - http://localhost:8000/media/uploads/myfile, but I get http://localhost:4200/media/uploads/myfile.
I use proxy to get backend api:

{
  "/api": {
  "target": "http://localhost:8000",
  "secure": false
  }
}

I do not know where the problem may be.

Body:
change proxy.conf.json:

{
  "/api": {
  "target": "http://localhost:8000",
  "secure": false,
  "changeOrigin": true,
  "pathRewrite": {
    "^/api": "http://localhost:8000/api"
  }
}

}


问:
Best way to typecheck key or value in 'foreach' construct?
I'd like to typecheck the key (if a hash) and value of an array expression that's iterated over in a foreach construct, something like:

```<code>foreach ($reasons as AuthenticationResponse $reason)
...
</code>```

Is there any alternative to doing this as an instanceof check in the loop body?

答:
No, but this is just one line of code and should not be any problem.

class Test {
    public int $number;
}

class Dummy {
    public int $number;
}

$tests = [];

for($i = 0; $i < 10; $i++) {
    $test = new Test();
    $test->number = $i;
    $dummy = new Dummy();
    $dummy->number = $i;
    $tests[] = $test;
    $tests[] = $dummy;
}

foreach($tests as $test) {
    if(!$test instanceof Test) continue;
    echo get_class($test), $test->number, PHP_EOL;
}

```

<p>This will skip all non Tests and output:</p>

```Test0
Test1
Test2
Test3
Test4
Test5
Test6
Test7
Test8
Test9
```

Body:
I'd like to typecheck the key (if a hash) and value of an array expression that's iterated over in a foreach construct, something like:

foreach ($reasons as AuthenticationResponse $reason)
...

Is there any alternative to doing this as an instanceof check in the loop body?

Body:
No, but this is just one line of code and should not be any problem.

class Test {
    public int $number;
}

class Dummy {
    public int $number;
}

$tests = [];

for($i = 0; $i < 10; $i++) {
    $test = new Test();
    $test->number = $i;
    $dummy = new Dummy();
    $dummy->number = $i;
    $tests[] = $test;
    $tests[] = $dummy;
}

foreach($tests as $test) {
    if(!$test instanceof Test) continue;
    echo get_class($test), $test->number, PHP_EOL;
}

This will skip all non Tests and output:

Test0
Test1
Test2
Test3
Test4
Test5
Test6
Test7
Test8
Test9


问:
Partition structure for 2 kafka consumers on same topic
If I create

2 kafka consumer instances

passing same properties

subscribe on same topic

Will these 2 Consumer instances (at diff group Id), have similar partition structures, or could be different ?

i.e, if I do .assignment() will I get same result at both

My actual problem statement, where I will be using this validation

In my application, I am attaining offset of broker, at a particular state(This is being done through my 1st kafka consumer object).

Later, I am creating the 2nd kafka consumer object, and using this to iterate over the topic, seeking from the earlier offset attained.

(So if the supposition mentioned at question is false, my logic will fail)

答:
Let me clear this up.

Kafka has topics, and the consumers can subscribe to them. Each topic has partitions (which you can define when you create them). When there are multiple partitions for a given topic, each topic partition is assigned to a consumer in a consumer group. If you have more consumers than the number of partitions, those extra consumers become idle.

If you want your two Kafka consumers to consume messages separately, you have to add them into two different consumer groups. If you have a single Kafka consumer within a Consumer group, all the partitions are assigned to that consumer.

So if you want to get the same result for the two consumers, you may add them into two different consumer groups.