问:
How to pass email address and password for creating emails in GMail?
I need my Access Database to create emails that are sent at the press of a button.

This works for Outlook, and I adapted the code for Gmail.

I don't want to hardcode the email username and password. I want to pick it up from a combobox on the main form.

I get the error

Private Sub Email_Allocation_List_Click()

    Dim newMail As CDO.Message
    Dim mailConfiguration As CDO.Configuration
    Dim fields As Variant
    Dim msConfigURL As String

    On Error GoTo errHandle

    Set newMail = New CDO.Message
    Set mailConfiguration = New CDO.Configuration

    mailConfiguration.Load -1

    Set fields = mailConfiguration.fields

    With newMail
        .Subject = "subject"
        .From = [Forms]![Main form]![EmailAddress].Column(1)
        .To = "email address"
        .CC = "email address"
        .BCC = ""
        .TextBody = "Hello, " & vbNewLine & vbNewLine & _
          "Please find attached todays list of lines to be allocated." & _
           vbNewLine & vbNewLine & "Kind Regards." & vbNewLine & vbNewLine & "Carly"
        .AddAttachment "file location"
    End With

    msConfigURL = "http://schemas.microsoft.com/cdo/configuration"

    With fields
        .Item(msConfigURL & "/smtpusessl") = True
        .Item(msConfigURL & "/smtpauthenticate") = 1

        .Item(msConfigURL & "/smtpserver") = "smtp.gmail.com"
        .Item(msConfigURL & "/smtpserverport") = 465
        .Item(msConfigURL & "/sendusing") = 2

        .Item(msConfigURL & "/sendusername") = [Forms]![Main form]![EmailAddress].Column(1)
        .Item(msConfigURL & "/sendpassword") = [Forms]![Main form]![EmailAddress].Column(2)

        .Update

    End With

    newMail.Configuration = mailConfiguration
    newMail.Send

    MsgBox "E-Mail has been sent", vbInformation

    exit_line:
    '// Release object memory
    Set newMail = Nothing
    Set mailConfiguration = Nothing

    Exit Sub

    errHandle:

    MsgBox "Error: " & Err.Description, vbInformation

    GoTo exit_line

End Sub
```

I checked the comboboxes work with a text box.

答: After a lot of messing around, you are correct, the code is fine - and it was reading the contents of the combo box correctly - however GMail didn't accept the log in information if there was a capital letter on the email address!!! Now working beautifully.</p>

Body:
I need my Access Database to create emails that are sent at the press of a button.

This works for Outlook, and I adapted the code for Gmail.

I don't want to hardcode the email username and password. I want to pick it up from a combobox on the main form.

I get the error

Private Sub Email_Allocation_List_Click()

    Dim newMail As CDO.Message
    Dim mailConfiguration As CDO.Configuration
    Dim fields As Variant
    Dim msConfigURL As String

    On Error GoTo errHandle

    Set newMail = New CDO.Message
    Set mailConfiguration = New CDO.Configuration

    mailConfiguration.Load -1

    Set fields = mailConfiguration.fields

    With newMail
        .Subject = "subject"
        .From = [Forms]![Main form]![EmailAddress].Column(1)
        .To = "email address"
        .CC = "email address"
        .BCC = ""
        .TextBody = "Hello, " & vbNewLine & vbNewLine & _
          "Please find attached todays list of lines to be allocated." & _
           vbNewLine & vbNewLine & "Kind Regards." & vbNewLine & vbNewLine & "Carly"
        .AddAttachment "file location"
    End With

    msConfigURL = "http://schemas.microsoft.com/cdo/configuration"

    With fields
        .Item(msConfigURL & "/smtpusessl") = True
        .Item(msConfigURL & "/smtpauthenticate") = 1

        .Item(msConfigURL & "/smtpserver") = "smtp.gmail.com"
        .Item(msConfigURL & "/smtpserverport") = 465
        .Item(msConfigURL & "/sendusing") = 2

        .Item(msConfigURL & "/sendusername") = [Forms]![Main form]![EmailAddress].Column(1)
        .Item(msConfigURL & "/sendpassword") = [Forms]![Main form]![EmailAddress].Column(2)

        .Update

    End With

    newMail.Configuration = mailConfiguration
    newMail.Send

    MsgBox "E-Mail has been sent", vbInformation

    exit_line:
    '// Release object memory
    Set newMail = Nothing
    Set mailConfiguration = Nothing

    Exit Sub

    errHandle:

    MsgBox "Error: " & Err.Description, vbInformation

    GoTo exit_line

End Sub

I checked the comboboxes work with a text box.


来源: stackexchange

问:
How does Go update third-party packages?
Looking how actively golang packages grow and improve I wonder how the problem with package versions is solved?

I see that one way is to store third-party packages under a project folder.

But what if I install it with go get?

答:
go 1.13

(exec from module root directory)

Update specified dependencies:

go get -u <package-name>
```

<p>Update all direct and indirect dependencies to latest minor or patch upgrades (pre-releases are ignored):</p>

<pre class="lang-sh prettyprint-override"><code>go get -u ./...
# or
go get -u=patch ./...
</code>```

Reference:

https://github.com/golang/go/wiki/Modules#daily-workflow

go help get

ContentLicense: CC BY-SA 3.0

Body:
go 1.13

(exec from module root directory)

Update specified dependencies:

go get -u <package-name>

Update all direct and indirect dependencies to latest minor or patch upgrades (pre-releases are ignored):

go get -u ./...
# or
go get -u=patch ./...

Reference:

https://github.com/golang/go/wiki/Modules#daily-workflow

go help get

ContentLicense: CC BY-SA 4.0


问:
ITfoxtec Idp-initiated SSO to SP
I am currently implementing a .NET Framework IdP using ITfoxtec Identity SAML 2.0.

I understand that the AuthController Login API endpoint in the TestIdPCore test project receives a SSO request from the SP for SP-initated SSO.

However, I don't understand how to do a IdP-initiated SSO. Any help would be much appreciated.

答:
You can find the .NET Framework IdP-Initiated SSO sample in the TestWebApp https://github.com/ITfoxtec/ITfoxtec.Identity.Saml2/blob/master/test/TestWebApp/Controllers/IdPInitiatedController.cs

The sample show an SP acting as an IdP.

Title: ITfoxtec Idp-initiated SSO to SP


问:
Calling a function within ReReplace function
Is there a way to write in coldfusion something like:

```<code>< cfset ReReplace(value,"&#\d+;","#decodeHtmlEntity(\1)#", "all") >
</code>```

Thanks a lot

答:
The short answer is "No".

CF doesn't handle the regular expression execution natively.  It hands off to a Java library (Oro, IIRC) to handle that.  This means that any CF functions you call get executed before toe regex.

There is a workaround, although it's not nearly as elegant as being able to pass functions would be.  Use reFind() to discover all the instances of what you are looking for, and repolace them one-by-one. If you do the replaces last-to-first (eg if there are 3 instances, do the 3rd, then the 2nd, then the 1st) your starting point for each match will remain in the same location, so you can do an reFind all, instead of doing the reFind in the loop.

HTH.

Body:
Is there a way to write in coldfusion something like:

< cfset ReReplace(value,"&#\d+;","#decodeHtmlEntity(\1)#", "all") >

Thanks a lot


问:
Kafka Camel Spring Boot AutoConfiguration is not picked up when multiple kafkaComponent beans are defined
I'm currently using this camel-kafka-starter maven dependency to autoconfigure my kafka camel component in Spring Boot.

If I add say, a setting like this camel.component.kafka.configuration.linger-ms=20. The camel kafka component picks it up in the route and I can see its config value in the log output.
e.g.

```<code>@Component
public class route extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("file://target/inbox")
        .to("kafka:topic?brokers=localhost:9092");
    }
}
</code>```

Now, if i define another camelKafkaComponent Bean, it loses the autoconfiguration! I'd expect it to maintain the settings defined in application.propeties...

```<code>@Configuration
public class MyConfiguration {
  @Bean
  public KafkaComponent myKafkaComponent() {
    return new KafkaComponent();  //missing the linger-ms=20 i set in application.properties!
  }

  @Component
  public class route extends RouteBuilder {
     @Override
     public void configure() throws Exception {
        from("file://target/inbox")
        .to("myKafkaComponent:topic?brokers=localhost:9092");
     }
  }
}
</code>```

Is there a way to maintain the autoconfiguration by some setting e.g.

```<code>myKafkaComponent.useAutoConfig()
</code>```

Ideally in my application.properties I'd have ~40+ settings that I would like to just transfer over to my user defined camel kafkaComponent. Is it necessary to create another Config class and map all those values defined in the camel docs? (with something like String @Value annotations)

edit:
I was looking at the source code and was also wondering if there was a way to call it inside my bean definition.

答:
You can create a bean of type

```<code>ComponentCustomizer<KafkaComponent>
</code>```

which can be used to customize the kafka component auto configured by camel

Body:
I'm currently using this camel-kafka-starter maven dependency to autoconfigure my kafka camel component in Spring Boot.

If I add say, a setting like this camel.component.kafka.configuration.linger-ms=20. The camel kafka component picks it up in the route and I can see its config value in the log output.
e.g.

@Component
public class route extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("file://target/inbox")
        .to("kafka:topic?brokers=localhost:9092");
    }
}

Now, if i define another camelKafkaComponent Bean, it loses the autoconfiguration! I'd expect it to maintain the settings defined in application.propeties...

@Configuration
public class MyConfiguration {
  @Bean
  public KafkaComponent myKafkaComponent() {
    return new KafkaComponent();  //missing the linger-ms=20 i set in application.properties!
  }

  @Component
  public class route extends RouteBuilder {
     @Override
     public void configure() throws Exception {
        from("file://target/inbox")
        .to("myKafkaComponent:topic?brokers=localhost:9092");
     }
  }
}

Is there a way to maintain the autoconfiguration by some setting e.g.

myKafkaComponent.useAutoConfig()

Ideally in my application.properties I'd have ~40+ settings that I would like to just transfer over to my user defined camel kafkaComponent. Is it necessary to create another Config class and map all those values defined in the camel docs? (with something like String @Value annotations)

edit:
I was looking at the source code and was also wondering if there was a way to call it inside my bean definition.

Body:
You can create a bean of type

ComponentCustomizer<KafkaComponent>

which can be used to customize the kafka component auto configured by camel


问:
Python for-loop repeatedly outputting the input() for every iteration of dictionary contact_emails(not what I want)
```<code>   contact_emails = {

         'Sue Reyn' : 's.reyn@email.com',
         'Mike Filt': 'mike.filt@bmail.com',
         'Nate Arty': 'narty042@nmail.com'
             }

         new_contact = input()

         new_email = input()
         contact_emails[new_contact] = new_email

         for contact in contact_emails:
                      print(new_contact + ' is ' + new_email)
</code>```

The output I want is

```<code>s.reyn@email.com is Sue Reyn
mike.filt@bmail.com is Mike Filt
narty042@nmail.com is Nate Arty
alf1@hmail.com is Alf
</code>```

the output I get it

```<code>Alf is alf1@hmail.com
Alf is alf1@hmail.com
Alf is alf1@hmail.com
Alf is alf1@hmail.com
</code>```

What am I doing wrong? How should I fix this code to make it output what I would like it to output?

答:
```<code>for contact in contact_emails:
    print(new_contact + ' is ' + new_email)
</code>```

You are printing the new contact again and again. What you need to do is something like this:

```<code>for contact, email in contact_emails.items():
    print(email + ' is ' + contact)
</code>```

This iterates all the key, value pairs of your dictionary.

Body:
   contact_emails = {

         'Sue Reyn' : 's.reyn@email.com',
         'Mike Filt': 'mike.filt@bmail.com',
         'Nate Arty': 'narty042@nmail.com'
             }

         new_contact = input()

         new_email = input()
         contact_emails[new_contact] = new_email

         for contact in contact_emails:
                      print(new_contact + ' is ' + new_email)

The output I want is

s.reyn@email.com is Sue Reyn
mike.filt@bmail.com is Mike Filt
narty042@nmail.com is Nate Arty
alf1@hmail.com is Alf

the output I get it

Alf is alf1@hmail.com
Alf is alf1@hmail.com
Alf is alf1@hmail.com
Alf is alf1@hmail.com

What am I doing wrong? How should I fix this code to make it output what I would like it to output?

Body:
for contact in contact_emails:
    print(new_contact + ' is ' + new_email)

You are printing the new contact again and again. What you need to do is something like this:

for contact, email in contact_emails.items():
    print(email + ' is ' + contact)

This iterates all the key, value pairs of your dictionary.


问:
How to Monitor/listen aws Services?
Suppose multiple aws services are running (like EC2,S3) and If someone changes the configuration of these services , I want to know immediately and want to pull the updated configuration. So how can i listen to these services to pull configuration immediately . I went through couple of options like aws SNS and all. But i don't want to implement this using any aws services for this.
I am using spring boot application. Any help is appreciated , Thanks in advance.  </p>

答:
The two services you should be interested in are:

AWS CloudTrail:

AWS CloudTrail is an AWS service that helps you enable governance, compliance, and operational and risk auditing of your AWS account. Actions taken by a user, role, or an AWS service are recorded as events in CloudTrail. Events include actions taken in the AWS Management Console, AWS Command Line Interface, and AWS SDKs and APIs.

AWS Config:

AWS Config provides a detailed view of the configuration of AWS resources in your AWS account. This includes how the resources are related to one another and how they were configured in the past so that you can see how the configurations and relationships change over time.

You can also configure Amazon CloudWatch Events rules that trigger when a particular API call is made (eg when a user changes some configuration). This could trigger a notification, a Lambda function, etc.

See:

Creating a CloudWatch Events Rule That Triggers on an AWS API Call Using AWS CloudTrail - Amazon CloudWatch Events

How to monitor AWS account activity with Cloudtrail, Cloudwatch Events and Serverless

Title: How to Monitor/listen aws Services?


问:
Show x-Axis line but hide all data points
I want the second datetime x-Axis to show, but I want none of the points from that series to be visible. I just want the x-Axis line. How can I do this?

```<code> Highcharts.chart("container", {
      chart: {
        type: "line",
      },
      xAxis: [
        {
          type: "category"
        },
        {
          type: "datetime",
        }
      ]
    });
</code>```

https://codepen.io/austeng/pen/mdJrRRm

Edit: I want the black line to be gone, but I want to keep the Date x-Axis line. The black line are the points from the date x-Axis. I just the date x-Axis grid line to show... not the points associated with it.

答:
I think that a good solution for your requirements is to use the second series which will be a null series, but with defined pointStart, pointInterval and is attached to the second yAxis, which is hidden.

Demo: https://jsfiddle.net/BlackLabel/b0j5o7Lw/

```<code>  plotOptions: {
    column: {
      pointStart: Date.UTC(2010, 0, 1),
      pointInterval: 24 * 3600 * 1000 // one day
    }
  },
</code>```

and

```<code>   {
      yAxis: 1,
      type: 'column',
      name: "Date",
      data: [
        null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null

      ],
      xAxis: 1,
      showInLegend: false,
    }
</code>```

API: https://api.highcharts.com/highcharts/series.line.pointStart

Body:
I want the second datetime x-Axis to show, but I want none of the points from that series to be visible. I just want the x-Axis line. How can I do this?

 Highcharts.chart("container", {
      chart: {
        type: "line",
      },
      xAxis: [
        {
          type: "category"
        },
        {
          type: "datetime",
        }
      ]
    });

https://codepen.io/austeng/pen/mdJrRRm

Edit: I want the black line to be gone, but I want to keep the Date x-Axis line. The black line are the points from the date x-Axis. I just the date x-Axis grid line to show... not the points associated with it.

Body:
I think that a good solution for your requirements is to use the second series which will be a null series, but with defined pointStart, pointInterval and is attached to the second yAxis, which is hidden.

Demo: https://jsfiddle.net/BlackLabel/b0j5o7Lw/

  plotOptions: {
    column: {
      pointStart: Date.UTC(2010, 0, 1),
      pointInterval: 24 * 3600 * 1000 // one day
    }
  },

and

   {
      yAxis: 1,
      type: 'column',
      name: "Date",
      data: [
        null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null

      ],
      xAxis: 1,
      showInLegend: false,
    }

API: https://api.highcharts.com/highcharts/series.line.pointStart


问:
Get most upper descendant descendant(s) in jQuery
From page=$("#page") I want to get all the specified SVGs but not the subsequent inner ones.

```<code><div id="page">
    <div ...>
        <svg> /* THIS ONE */
            <rect ...>
            <circle ...>
            <svg> /* NOT THIS ONE */
                <foo> ... </foo>
            </svg>
        </svg>
    </div>
    <div ...>
        <div ...>
            <svg> /* THIS ONE */
                <rect ...>
                <circle ...>
                <svg> /* NOT THIS ONE */
                    <foo> ... </foo>
                </svg>
            </svg>
        </div>
   </div>
</div>
</code>```

EDIT I've updated the markup to clearly specify what I mean.

One solution is to use :not(svg svg) which i find ugly and performance heavy.

答:
Just get the first child level with >.

```<code>#page > svg
</code>```

Body:
From page=$("#page") I want to get all the specified SVGs but not the subsequent inner ones.

        <svg> /* THIS ONE */
            <rect ...>
            <circle ...>
            <svg> /* NOT THIS ONE */
                <foo> ... </foo>
            </svg>
        </svg>

            <svg> /* THIS ONE */
                <rect ...>
                <circle ...>
                <svg> /* NOT THIS ONE */
                    <foo> ... </foo>
                </svg>
            </svg>

EDIT I've updated the markup to clearly specify what I mean.

One solution is to use :not(svg svg) which i find ugly and performance heavy.

Body:
Just get the first child level with >.

#page > svg


问:
Alerting if share on VM has had no activity in a specified period
I have a folder on a windows VM in azure.
An external process copies files onto this folder on a very regular basis.

I want to monitor this folder and get a notification if the number of files does not change within a specified period, as this tells me there is an issue with the file writer process or the file reader process.

I thought i may be able to do this with azure monitor but am now unsure if it is possible.

My questions are:

is this possible with azure monitor?

if not, is there a relatively simple way of monitoring this without scheduling scripts?

Thank you

答:
Unfortunately, azure monitor does not support this kind of operation, and there is no other simple way for this.

The only way I can think of is using code to check the folder(seems you don't like this) periodically, then send proper notification to you.


问:
Angular material table dynamic rows
I am creating a project using angular and material. In my project i want to add customised footer row in material table on click of button and delete that row on click of delete button.

Here is my code:

https://stackblitz.com/edit/angular-dshjiz-beqnrj?file=src/app/table-basic-example.html

答:
You need to push data in datasource

```<code>this.dataSource.data.push({id: 1, name: 'test'})
</code>```

There is stackblitz example

Title: Angular material table dynamic rows

Body:
You need to push data in datasource

this.dataSource.data.push({id: 1, name: 'test'})

There is stackblitz example


问:
find intersection point of two lines drawn using houghlines opencv
How can I get the intersection points of lines down using opencv Hough lines algorithm?

Here is my code:

```<code>import cv2
import numpy as np
import imutils

im = cv2.imread('../data/test1.jpg')
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 60, 150, apertureSize=3)

img = im.copy()
lines = cv2.HoughLines(edges,1,np.pi/180,200)

for line in lines:
    for rho,theta in line:
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a*rho
        y0 = b*rho
        x1 = int(x0 + 3000*(-b))
        y1 = int(y0 + 3000*(a))
        x2 = int(x0 - 3000*(-b))
        y2 = int(y0 - 3000*(a))
        cv2.line(img,(x1,y1),(x2,y2),(0,255,0),10)

cv2.imshow('houghlines',imutils.resize(img, height=650))
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Output:

I want to get all the points of intersection.

答:
Here I have processed my image with some methods;

1.Grayscale

2.Either bitwise conversion or edge detection, it depends on the image I guess,here I have gone with bitwise conversion.
First carrying out all detected line into a list.

```<code>listOflines = cv2.HoughLines(mask_inv,1,np.pi/180,200)
</code>```

We will be getting values of 'rho' and 'theta',
What I am doing is here creating two empty list one for vertical lines one for the horizontal lines,and appending the values of both lines in respective list.

```<code>rowsValue = []
columnValue = []
</code>```

Here is the logic for vertical and horizontal lines.

```<code>for line in listOflines:
if line[0][1] == 0:
    columnValue.append(line[0][0])
else:
    rowsValue.append(line[0][0])
</code>```

Now the important part is here,
When every line passing through and intersecting one another it is intersecting that line on a particular pixel value.
And we have that pixel value in terms of 'rho'.

Now lets create tuples to pass as a co-ordinate into 'cv2' function i.e. in the form of (x,y).

```<code>tupsList = [(r,c) for r in rowsValue for c in columnValue]
for tups in tupsList:
     cv2.circle(image, tups, 1,(0,0,255), 2)
cv2.imshow('image',image)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Thats It!!
Now here the images before and after.

Original Image

Intersection Image

Body:
How can I get the intersection points of lines down using opencv Hough lines algorithm?

Here is my code:

import cv2
import numpy as np
import imutils

im = cv2.imread('../data/test1.jpg')
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 60, 150, apertureSize=3)

img = im.copy()
lines = cv2.HoughLines(edges,1,np.pi/180,200)

for line in lines:
    for rho,theta in line:
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a*rho
        y0 = b*rho
        x1 = int(x0 + 3000*(-b))
        y1 = int(y0 + 3000*(a))
        x2 = int(x0 - 3000*(-b))
        y2 = int(y0 - 3000*(a))
        cv2.line(img,(x1,y1),(x2,y2),(0,255,0),10)

cv2.imshow('houghlines',imutils.resize(img, height=650))
cv2.waitKey(0)
cv2.destroyAllWindows()

Output:

I want to get all the points of intersection.

Body:
Here I have processed my image with some methods;

1.Grayscale

2.Either bitwise conversion or edge detection, it depends on the image I guess,here I have gone with bitwise conversion.
First carrying out all detected line into a list.

listOflines = cv2.HoughLines(mask_inv,1,np.pi/180,200)

We will be getting values of 'rho' and 'theta',
What I am doing is here creating two empty list one for vertical lines one for the horizontal lines,and appending the values of both lines in respective list.

rowsValue = []
columnValue = []

Here is the logic for vertical and horizontal lines.

for line in listOflines:
if line[0][1] == 0:
    columnValue.append(line[0][0])
else:
    rowsValue.append(line[0][0])

Now the important part is here,
When every line passing through and intersecting one another it is intersecting that line on a particular pixel value.
And we have that pixel value in terms of 'rho'.

Now lets create tuples to pass as a co-ordinate into 'cv2' function i.e. in the form of (x,y).

tupsList = [(r,c) for r in rowsValue for c in columnValue]
for tups in tupsList:
     cv2.circle(image, tups, 1,(0,0,255), 2)
cv2.imshow('image',image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Thats It!!
Now here the images before and after.

Original Image

Intersection Image


问:
constexpr difference between gcc v10 and v9: bug or feature
If compiled with gcc v10 the code below exibits an error but for gcc v9 the code is ok.

```<code>template<auto N>
struct A {
    constexpr auto size() const {
        return N;
    }
};

template<typename T>
void foo1(const T& a) {
    constexpr auto s = a.size(); // Why error here?
}
template<typename T>
void foo2(T a) {
    constexpr auto s = a.size(); // OK
}
int main() {
    A<10> x1;
    foo1(x1);
    foo2(x1);
    A<x1.size()> x2; // OK
    constexpr auto s = x1.size(); // OK
}
</code>```

In my understanding the memberfunction size() could be called constexpr in all cases. But there is one case where the behaviour of gcc10 changed compared to gcc9: if the argument is passed by const-ref.
I don't understand why this should not be constexpr?

Another example:

```<code>template<auto N>
struct A {
    constexpr auto size() const {
        return N;
    }
};

template<typename T>
constexpr void foo1(const T& a) {
    constexpr auto s = a.size(); // Why error here?
    return s;
}
template<typename T>
constexpr auto foo2(const T& a) {
    return a.size(); // Why OK here
}
int main() {
    A<10> x1;
    constexpr auto s1 = foo1(x1);
    constexpr auto s2 = foo2(x1);
}
</code>```

I don't understand the difference.

答:
This is GCC bug 66477. It mentions that GCC wrongly accepts reference-type parameters in constant expressions.

This bug is fixed for GCC 10.

The reason why a.size() is not allowed in constant expressions is mentioned in this post.

Body:
If compiled with gcc v10 the code below exibits an error but for gcc v9 the code is ok.

template<auto N>
struct A {
    constexpr auto size() const {
        return N;
    }
};

template<typename T>
void foo1(const T& a) {
    constexpr auto s = a.size(); // Why error here?
}
template<typename T>
void foo2(T a) {
    constexpr auto s = a.size(); // OK
}
int main() {
    A<10> x1;
    foo1(x1);
    foo2(x1);
    A<x1.size()> x2; // OK
    constexpr auto s = x1.size(); // OK
}

In my understanding the memberfunction size() could be called constexpr in all cases. But there is one case where the behaviour of gcc10 changed compared to gcc9: if the argument is passed by const-ref.
I don't understand why this should not be constexpr?

Another example:

template<auto N>
struct A {
    constexpr auto size() const {
        return N;
    }
};

template<typename T>
constexpr void foo1(const T& a) {
    constexpr auto s = a.size(); // Why error here?
    return s;
}
template<typename T>
constexpr auto foo2(const T& a) {
    return a.size(); // Why OK here
}
int main() {
    A<10> x1;
    constexpr auto s1 = foo1(x1);
    constexpr auto s2 = foo2(x1);
}

I don't understand the difference.


问:
Can I change the color of Angular Material checkbox with some custom color and how?
I'm trying to do this, but is looks like it is only possible to change it to primary or warn.</p>

答:
These answers didn't work for me for indeterminate boxes. Following did:</p>

```<code>::ng-deep .mat-checkbox-checked .mat-checkbox-background,
::ng-deep .mat-checkbox-indeterminate .mat-checkbox-background {
  background-color: #222d32 !important;
}
</code>```

Body:
These answers didn't work for me for indeterminate boxes. Following did:

::ng-deep .mat-checkbox-checked .mat-checkbox-background,
::ng-deep .mat-checkbox-indeterminate .mat-checkbox-background {
  background-color: #222d32 !important;
}


问:
Rounding 64 bit integers to 32 bit integers
I have a function that does rounding operation as shown below. It takes 64bit integer as input and gives 32bit integer as output. While converting, a factor of 0x40000000 is being added to the input. What is the reason behind it?</p>

```<code>int rounder(long long int in)
{
  INT64 out;
  if ((in >> 32) == 0x7FFFFFFF)
    out = in;
  else
    out = (INT64)0x40000000 + in;
  out = out >> 31;
  return (INT32)out;
}
</code>```

答:
Let's start with some smaller numbers, because they're easier!

Using conventional rounding, x.49999... or less should round down to x, x.50000... or more should round up to (x+1).

(There are lots of different rounding methods, but this is the one most learn at school.)

Whenever you do integer division (or conversion of a floating point value to an integer), you simply throw away the fractional part.  Hence:

```<code>6/2 == 3.0  --> 3
5/2 == 2.5  --> 2
</code>```

A neat 'trick' is to add half-the-divisor (1, in this case) before division.  As if by magic, you get the right rounding!  eg:

```<code>6/2  becomes  (6+1)/2  == 7/2 == 3.5  --> 3
5/2  becomes  (5+1)/2  == 6/2 == 3.0  --> 3
</code>```

You can see why this works by looking at it this way:

```<code> 5/2  becomes  (5+1)/2  ==   5/2 + 1/2
13/6  becomes (13+3)/6  ==  13/6 + 3/6   == 13/6 + 1/2
</code>```

You're adding half to the real answer.  Anything less than x.5 will still be less than x+1 so will still round down, anything of x.5 or more will become x+1 or more so will round up.

Now to your actual question:
This idea works with all divisors; you're shifting down by 31, which is the same as dividing by 2^31.  So 'half-the-divisor' is 2^30, or 0x40000000.

Beware: as others have noted, this 'trick' only works for positive numbers (you need to subtract if it's negative, but it's a can of worms).

There is a lot to consider in this topic; it's not simple to get your head around.  As ever, try some easy examples for yourself and see what happens.

Body:
I have a function that does rounding operation as shown below. It takes 64bit integer as input and gives 32bit integer as output. While converting, a factor of 0x40000000 is being added to the input. What is the reason behind it?

int rounder(long long int in)
{
  INT64 out;
  if ((in >> 32) == 0x7FFFFFFF)
    out = in;
  else
    out = (INT64)0x40000000 + in;
  out = out >> 31;
  return (INT32)out;
}

Body:
Let's start with some smaller numbers, because they're easier!

Using conventional rounding, x.49999... or less should round down to x, x.50000... or more should round up to (x+1).

(There are lots of different rounding methods, but this is the one most learn at school.)

Whenever you do integer division (or conversion of a floating point value to an integer), you simply throw away the fractional part.  Hence:

6/2 == 3.0  --> 3
5/2 == 2.5  --> 2

A neat 'trick' is to add half-the-divisor (1, in this case) before division.  As if by magic, you get the right rounding!  eg:

6/2  becomes  (6+1)/2  == 7/2 == 3.5  --> 3
5/2  becomes  (5+1)/2  == 6/2 == 3.0  --> 3

You can see why this works by looking at it this way:

 5/2  becomes  (5+1)/2  ==   5/2 + 1/2
13/6  becomes (13+3)/6  ==  13/6 + 3/6   == 13/6 + 1/2

You're adding half to the real answer.  Anything less than x.5 will still be less than x+1 so will still round down, anything of x.5 or more will become x+1 or more so will round up.

Now to your actual question:
This idea works with all divisors; you're shifting down by 31, which is the same as dividing by 2^31.  So 'half-the-divisor' is 2^30, or 0x40000000.

Beware: as others have noted, this 'trick' only works for positive numbers (you need to subtract if it's negative, but it's a can of worms).

There is a lot to consider in this topic; it's not simple to get your head around.  As ever, try some easy examples for yourself and see what happens.


问:
displaying laravel show method on vue component
i have a list of movies am trying to display the details of one movie using the show method
here is my component for all movies

```<code><template>
    <div>
        <el-row :gutter="10">
            <el-col :span="6" v-for="movie in movies" v-bind:key="movie">
                <el-card shadow="always" :body-style="{ padding: '0px'} ">
                    <img v-bind:src="movie.cover_photo" class="image" >
                        <div style="padding: 14px;">
                            <div class="bottom clearfix">

                                <router-link :to="{name:'details',params:{id:movie.id}}">{{movie.title}}</router-link>
                                    <router-view></router-view>
                                    <h4>{{ movie.year }}</h4>
                                    <h4>{{ movie.type }}</h4>
                            </div>
                            <div class="block">
                                <el-rate  :max="10" ></el-rate>
                            </div>
                        </div>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script>
    import axios from 'axios'
    export default {
        data() {
            return {
                movies: [],
                movie:{
                    id:'',
                }
            };
        },
        created(){
          this. fetchMovieList();
          this.showMovie
        },
        methods: {
            fetchMovieList() {
                    axios.get('/movies').then(response => {
                        this.movies = response.data;
                    })
                   .catch(error=>console.log(error))
            },
            showMovie(id){
                axios.get('/movies/'+id).then((res)=>{

                if(res.data.status==true){
                    this.movie= res.data.movie;
                    console.log(res.data.movie)
                }else{
                    alert('No Movie founded with this id')
                }
            })
            .catch((err)=>{alert('error')})
            }
        }
    }
</script>

<style scoped>
.image {
    width: 100%;
    display: block;
  }

</style>
</code>```

my show method:

```<code>public function show($id)
{
        $movie=Movie::find($id);
    if($movie){
        return response()->json(['status'=>true,'movie'=>$movie]);
    }else{
        return response()->json(['status'=>false]);
    }
}
</code>```

my router on app.js:

```<code>const movie=Vue.component('details', require('./components/DetailsComponent.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */
const router=new VueRouter({
    mode:'history',
    routes:[
        {
            path:'/movie/:id',
            name:'movie',
            component:movie
        },

    ],

});

const app = new Vue({
    el: '#app',
   router,
});
</code>```

when i click on the router link it just changes the url to the id of the movie but it doesnt show the component with details when i hit the show endpoint with a specific id  it returns the movie in json format on the browser

答:
Hope this helps you: Reacting to Params Changes

Regards,

Body:
i have a list of movies am trying to display the details of one movie using the show method
here is my component for all movies

<template>

        <el-row :gutter="10">
            <el-col :span="6" v-for="movie in movies" v-bind:key="movie">
                <el-card shadow="always" :body-style="{ padding: '0px'} ">

                                <router-link :to="{name:'details',params:{id:movie.id}}">{{movie.title}}</router-link>
                                    <router-view></router-view>

{{ movie.year }}

{{ movie.type }}

                                <el-rate  :max="10" ></el-rate>

                </el-card>
            </el-col>
        </el-row>

</template>

my show method:

public function show($id)
{
        $movie=Movie::find($id);
    if($movie){
        return response()->json(['status'=>true,'movie'=>$movie]);
    }else{
        return response()->json(['status'=>false]);
    }
}

my router on app.js:

const movie=Vue.component('details', require('./components/DetailsComponent.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */
const router=new VueRouter({
    mode:'history',
    routes:[
        {
            path:'/movie/:id',
            name:'movie',
            component:movie
        },

    ],

});

const app = new Vue({
    el: '#app',
   router,
});

when i click on the router link it just changes the url to the id of the movie but it doesnt show the component with details when i hit the show endpoint with a specific id  it returns the movie in json format on the browser


问:
both forms in formset need to be selected
I have a formset that have two forms.

forms:

```<code>class PresClinicForm(forms.Form):
    _names = list(PresClinic.objects.values_list('pres_clinic_id', 'pres_clinic_name'))
    _names.append(["New", u'Nova entrada'])

    pres_name = forms.ChoiceField(widget=RadioSelect(), choices=_names, label=
        "", required=True)

PresClinicFormSet = formset_factory(PresClinicForm, extra=2)
</code>```

views:

```<code>if request.method == 'POST':
    formset1 = PresClinicFormSet(request.POST, request.FILES, prefix='pres_clinic')
    if formset1.is_valid():
        choice = formset1.cleaned_data
    return render_to_response('template.html', {'options': options})
</code>```

template:

```<code>    <form method="post" action="">
    <div>
    {{ formset1.management_form}}
        {% for form in formset1.forms %}
            {{ form }}
        {% endfor %}
        <input type="submit" value="Guardar" />
    </div>
</form>
</code>```

The user has to select one option in each form.

I tried required=True into forms.py but if I select only one option, it works anyway..

It shouldn't work if the user only select an option. That's what I trying to implement..

Does someone knows how to do this?

Thanks in advance for any help!

答:
Please check Mark's question for this answer:
Django: Make all formset forms required?

Be careful, you can only use formset with django 1.3, with django 1.1 cleaned_data gives an error.

Body:
I have a formset that have two forms.

forms:

class PresClinicForm(forms.Form):
    _names = list(PresClinic.objects.values_list('pres_clinic_id', 'pres_clinic_name'))
    _names.append(["New", u'Nova entrada'])

    pres_name = forms.ChoiceField(widget=RadioSelect(), choices=_names, label=
        "", required=True)

PresClinicFormSet = formset_factory(PresClinicForm, extra=2)

views:

if request.method == 'POST':
    formset1 = PresClinicFormSet(request.POST, request.FILES, prefix='pres_clinic')
    if formset1.is_valid():
        choice = formset1.cleaned_data
    return render_to_response('template.html', {'options': options})

template:

    <form method="post" action="">

    {{ formset1.management_form}}
        {% for form in formset1.forms %}
            {{ form }}
        {% endfor %}
        <input type="submit" value="Guardar" />

</form>

The user has to select one option in each form.

I tried required=True into forms.py but if I select only one option, it works anyway..

It shouldn't work if the user only select an option. That's what I trying to implement..

Does someone knows how to do this?

Thanks in advance for any help!


问:
How do I fix this challenge of have any password login a user in on codeigniter
I had been trying to fix a challenge I am having on my code which will allow any password to login a user to the dashboard. For instance, any user registered on the platform can use his email and any password to login in. The password is saved as hash in the database but when I want to login, in any password can login the user which should not be. For example 123456 will log in the user, and 656565656 can login in the same user. Please help me I know I am not getting it right somewhere but I can't figure out where I am going wrong.

Here is my controller:

```<code>public function __construct()
{
    parent::__construct();
    $this->load->database();
    $this->load->helper('url');
}

public function index()
{
    $this->form_validation->set_rules('emailid','Email id','required|valid_email');
    $this->form_validation->set_rules('password','Password','required|min_length[6]');
    if($this->form_validation->run())
    {
        $emailid=$this->input->post('emailid');
        $password=password_verify($this->input->post('password'),$account->password);
        $status=1;

        $this->load->model('User_Login_Model');
        $validate=$this->User_Login_Model->validatelogin($emailid,$password,$status);
        if($validate)
        {
            $this->session->set_userdata('uid',$validate);
            redirect('user/dashboard');
        } else
        {
            $this->session->set_flashdata('error', 'Invalid details. Please try again with valid details');
            redirect('user/login');
        }
    }
}
</code>```

Here is my model file for user login

```<code>public function __construct()
{
    parent::__construct();
    $this->load->database();
    $this->load->helper('url');
}

public function validatelogin($emailid,$password,$status)
{

    $query=$this->db->where(['emailId'=>$emailid,'userPassword'=>$password]);
    $account=$this->db->get('tblusers')->row();
    if($account!=NULL)
    {
        $dbstatus=$account->isActive;
        //verifying status
        if( $dbstatus==$status)
        {
            return $account->id;
        }
        else
        {
            return NULL;
            $this->session->set_flashdata('error', 'Your accounis is not active contact admin');
            redirect('user/login');
        }
    }
    return NULL;
}
</code>```

答:
Your question is when you are trying to login to an account with the wrong password it still takes you to the user dashboard. Right?

It is because you are not comparing the password from the database.

Following is the code which may help you:

My_model.php

```<code>public function check_login_model(){
    $email = $this->input->post('email');
    $password = $this->input->post('password');
    $query = $this->db->query("SELECT * FROM login_table WHERE email='$email' AND password='$password' LIMIT 1");
    $row = $query->row_array();
    $count = $query->num_rows();
    if ($count==1) {
        $this->session->login_user = $email;
    }else{
        return "No records found.";
    }
}
</code>```

My_controller.php

```<code>public function index(){
    if ($this->session->login_user) {
        $this->load->view('user/dashboard');
    }else{
        $this->load->view('user/login');
    }
}
</code>```

I hope this simple login method may help you.

Body:
I had been trying to fix a challenge I am having on my code which will allow any password to login a user to the dashboard. For instance, any user registered on the platform can use his email and any password to login in. The password is saved as hash in the database but when I want to login, in any password can login the user which should not be. For example 123456 will log in the user, and 656565656 can login in the same user. Please help me I know I am not getting it right somewhere but I can't figure out where I am going wrong.

Here is my controller:

public function __construct()
{
    parent::__construct();
    $this->load->database();
    $this->load->helper('url');
}

public function index()
{
    $this->form_validation->set_rules('emailid','Email id','required|valid_email');
    $this->form_validation->set_rules('password','Password','required|min_length[6]');
    if($this->form_validation->run())
    {
        $emailid=$this->input->post('emailid');
        $password=password_verify($this->input->post('password'),$account->password);
        $status=1;

        $this->load->model('User_Login_Model');
        $validate=$this->User_Login_Model->validatelogin($emailid,$password,$status);
        if($validate)
        {
            $this->session->set_userdata('uid',$validate);
            redirect('user/dashboard');
        } else
        {
            $this->session->set_flashdata('error', 'Invalid details. Please try again with valid details');
            redirect('user/login');
        }
    }
}

Here is my model file for user login

public function __construct()
{
    parent::__construct();
    $this->load->database();
    $this->load->helper('url');
}

public function validatelogin($emailid,$password,$status)
{

    $query=$this->db->where(['emailId'=>$emailid,'userPassword'=>$password]);
    $account=$this->db->get('tblusers')->row();
    if($account!=NULL)
    {
        $dbstatus=$account->isActive;
        //verifying status
        if( $dbstatus==$status)
        {
            return $account->id;
        }
        else
        {
            return NULL;
            $this->session->set_flashdata('error', 'Your accounis is not active contact admin');
            redirect('user/login');
        }
    }
    return NULL;
}

Body:
Your question is when you are trying to login to an account with the wrong password it still takes you to the user dashboard. Right?

It is because you are not comparing the password from the database.

Following is the code which may help you:

My_model.php

public function check_login_model(){
    $email = $this->input->post('email');
    $password = $this->input->post('password');
    $query = $this->db->query("SELECT * FROM login_table WHERE email='$email' AND password='$password' LIMIT 1");
    $row = $query->row_array();
    $count = $query->num_rows();
    if ($count==1) {
        $this->session->login_user = $email;
    }else{
        return "No records found.";
    }
}

My_controller.php

public function index(){
    if ($this->session->login_user) {
        $this->load->view('user/dashboard');
    }else{
        $this->load->view('user/login');
    }
}

I hope this simple login method may help you.


问:
How to extract texts from text node isolating the
 tags within table?

I'm having an issue printing out in the same row, table data. Of course, I could just identify with css_selector("td"), but that prints out:
Name
Address
City/State
Phone in the same column
whereas I'm trying to create:
Name, Address, City/State, Phone to the same row

HTML: (see attached photo)

This seems like such a stupid problem to be hung up on... but I've been stuck for quite some time, and haven't been able to isolate
 tags.

Code:

```<code>for x in link:
driver.get(x)
try:
    i = 0
    while 0 < 20:
        name = driver.find_elements_by_xpath("/html/body/div[2]/div/div[1]/div/div/table/tbody/tr/td[1]/table/tbody/tr['"+str(i)+"']/td/strong")
        if name[i].is_displayed():
            print(name[i].text)

            i = i + 1
        else:
            i = i + 1
except(NoSuchElementException,JavascriptException, IndexError):
    continue
</code>```

I've identified it this way to try to simply return text of proceding siblings... again to no avail. driver.find_elements_by_css_selector("td")
Also returns the entire table data... but with it's breaks

答:
BeautifulSoup can also be used in this scenario.

```<code>>>>from bs4 import beautifulsoup
>>>import requests
>>>contents=requests.get(url).text

>>>soup=beautifulsoup('lxml',contents)

>>>>Text=soup.find('body').text
</code>```

and check for condition if 'br' tag is there then skip

Title: How to extract texts from text node isolating the <br> tags within table?

Body:
I'm having an issue printing out in the same row, table data. Of course, I could just identify with css_selector("td"), but that prints out:
Name
Address
City/State
Phone in the same column
whereas I'm trying to create:
Name, Address, City/State, Phone to the same row

HTML: (see attached photo)

This seems like such a stupid problem to be hung up on... but I've been stuck for quite some time, and haven't been able to isolate
 tags.

Code:

for x in link:
driver.get(x)
try:
    i = 0
    while 0 < 20:
        name = driver.find_elements_by_xpath("/html/body/div[2]/div/div[1]/div/div/table/tbody/tr/td[1]/table/tbody/tr['"+str(i)+"']/td/strong")
        if name[i].is_displayed():
            print(name[i].text)

            i = i + 1
        else:
            i = i + 1
except(NoSuchElementException,JavascriptException, IndexError):
    continue

I've identified it this way to try to simply return text of proceding siblings... again to no avail. driver.find_elements_by_css_selector("td")
Also returns the entire table data... but with it's breaks

Body:
BeautifulSoup can also be used in this scenario.

>>>from bs4 import beautifulsoup
>>>import requests
>>>contents=requests.get(url).text

>>>soup=beautifulsoup('lxml',contents)

>>>>Text=soup.find('body').text

and check for condition if 'br' tag is there then skip


问:
os.listdir() returns nothing, not even an empty list
During a presentation yesterday I had a colleague run one of my scripts on a fresh installation of Python 3.8.1. It was able to create and write to a csv file in his folder (proof that the csv library was working correctly), but everything else failed due to not being able to find the needed files. To try and isolate the problem and figure out why, we tried the below simple script, which also failed.

He had this test.py script in "D:/TEST", which also contained some folders and image files. Running this script printed nothing to the console. No empty list, no error message, no newline. Maybe the print() function was also not working, but I didn't get around to testing that.

```<code>import os

print(os.listdir())
</code>```

This script works fine on my computer and my other colleagues computers (all Windows 10, similar hardware). I didn't have time to look into the issue more thoroughly and don't have access to his computer anymore. What could be the problem? What other things could I have him look into in order to fix this? In case this problem appears again during a future presentation, what steps could I take to figure out the cause of it?

答: My colleague uninstalled Python and reinstalled it. After doing this apparently the "python" command will no longer run his scripts, but using "py" instead will. Now that he is using "py" to run his scripts, it is working as expected.</p>

Body:
During a presentation yesterday I had a colleague run one of my scripts on a fresh installation of Python 3.8.1. It was able to create and write to a csv file in his folder (proof that the csv library was working correctly), but everything else failed due to not being able to find the needed files. To try and isolate the problem and figure out why, we tried the below simple script, which also failed.

He had this test.py script in "D:/TEST", which also contained some folders and image files. Running this script printed nothing to the console. No empty list, no error message, no newline. Maybe the print() function was also not working, but I didn't get around to testing that.

import os

print(os.listdir())

This script works fine on my computer and my other colleagues computers (all Windows 10, similar hardware). I didn't have time to look into the issue more thoroughly and don't have access to his computer anymore. What could be the problem? What other things could I have him look into in order to fix this? In case this problem appears again during a future presentation, what steps could I take to figure out the cause of it?


问:
PHP backend inside vuejs project folder
I created a vue/cli 3 project and its in my documents/project folder. Im running it on port 3000 with "npm run serve" command. Now, i want to have a backend folder somewhere to serve PHP files. But i want both the frontend and backend to be in the same folder structure.

Currently, my vue is in my documents folder and my php is in my xampp folder. The problem im having with this is managing 2 folders and git for the same application. Also, this causes my ajax calls from my vue projet to use a silly url such a "http://localhost:80/project/file.php". Id like to use relative paths like "backend/clients/getClient.php" that would be somewhere within my vue project.

This is what i would like:

```<code>myProject
  frontend
    my vue stuff like public and src folders
  backend
    my php files
</code>```

It doesnt have to be exactly that way but the point is that now i have a single folder and git for a single project.

thank you.

答:
The way I do this is as follows:

1)
I put the php files in a subfolder the public/ folder in the vue/cli project structure.
That way, these files will get copied to the dist folder on building the project.

For example: I have the file /public/api/endpoint.php, this will end up in dist/api/endpoint.php.

For testing locally I now copy the php files to the xampp/htdocs dir whenever I change them. But I guess you could skip this step by setting up a xampp alias directory. (But I haven't tried this myself yet)

2)
The ajax urls still differ between local development mode and production. To solve this I define a webpack plugin in my vue.config.js:

```<code>const webpack = require('webpack')

const API_URL = {
  production: JSON.stringify('https://www.project.com/api/endpoint.php'),
  development: JSON.stringify('http://localhost/project/api/endpoint.php')
}

// check environment mode
const environment =
  process.env.NODE_ENV === 'production' ? 'production' : 'development'

module.exports = {
  ...
  configureWebpack: {
    plugins: [
      new webpack.DefinePlugin({
        API_URL: API_URL[environment]
      })
    ]
  },
  ...
}
</code>```

Then use this in a vue/js file like:

```<code>const apiUrl = API_URL  // eslint-disable-line
</code>```

(the eslint directive is only needed If you have linting turned on with eslint, it will throw an error that API_URL is not defined.)

Title: PHP backend inside vuejs project folder

Body:
I created a vue/cli 3 project and its in my documents/project folder. Im running it on port 3000 with "npm run serve" command. Now, i want to have a backend folder somewhere to serve PHP files. But i want both the frontend and backend to be in the same folder structure.

Currently, my vue is in my documents folder and my php is in my xampp folder. The problem im having with this is managing 2 folders and git for the same application. Also, this causes my ajax calls from my vue projet to use a silly url such a "http://localhost:80/project/file.php". Id like to use relative paths like "backend/clients/getClient.php" that would be somewhere within my vue project.

This is what i would like:

myProject
  frontend
    my vue stuff like public and src folders
  backend
    my php files

It doesnt have to be exactly that way but the point is that now i have a single folder and git for a single project.

thank you.

Body:
The way I do this is as follows:

1)
I put the php files in a subfolder the public/ folder in the vue/cli project structure.
That way, these files will get copied to the dist folder on building the project.

For example: I have the file /public/api/endpoint.php, this will end up in dist/api/endpoint.php.

For testing locally I now copy the php files to the xampp/htdocs dir whenever I change them. But I guess you could skip this step by setting up a xampp alias directory. (But I haven't tried this myself yet)

2)
The ajax urls still differ between local development mode and production. To solve this I define a webpack plugin in my vue.config.js:

const webpack = require('webpack')

const API_URL = {
  production: JSON.stringify('https://www.project.com/api/endpoint.php'),
  development: JSON.stringify('http://localhost/project/api/endpoint.php')
}

// check environment mode
const environment =
  process.env.NODE_ENV === 'production' ? 'production' : 'development'

module.exports = {
  ...
  configureWebpack: {
    plugins: [
      new webpack.DefinePlugin({
        API_URL: API_URL[environment]
      })
    ]
  },
  ...
}

Then use this in a vue/js file like:

const apiUrl = API_URL  // eslint-disable-line

(the eslint directive is only needed If you have linting turned on with eslint, it will throw an error that API_URL is not defined.)


问:
What is the Correct Flow for a JavaScript Application Pipeline with Buildtime Variables?
Consider the following development flow for a frontend JavaScript application:

Whilst there are endless ways to design a development->staging->production pipeline, the above is fairly standard right?

Given this, why is it that pipeline providers such as Bitbucket and Azure do not allow Environment dependant variables for the build step?

Like most JavaScript applications, our application is specifically built for the environment that it will be run in e.g. development, staging, and production. Each environment has their own uniquely defined set of variables, for example; APP_URL sets the URL that the application will be accessible under.

The environment variables are specifically read during the build process of the application i.e. they are buildtime variables, not runtime variables.

Is there a reason why these providers do not support different environment variables for the build step? This seems like such an obvious thing which makes me think that actually, our entire pipeline flow is incorrect and it is us that is doing this wrong... Can any suggest a way to overcome this issue? Ideally without setting these variables within the xyz-pipelines.yml as the whole purpose of these variables is to keep them out of the repository...

答:
In DevOps, it is expected you get an artifact in Build pipeline and then release that artifact into environments using a Release workflow.

You could try to build the frontend JavaScript application in the Release pipeline, in Release pipeline, which can get artifacts from continuous integration systems such as Azure Pipelines, Jenkins, or TeamCity. You might also use version control systems such as Git or TFVC to store your artifacts. More details, please refer to the following link:

https://learn.microsoft.com/en-us/azure/devops/pipelines/release/artifacts?view=azure-devops#sources


问:
return type for deployments list using Kubernetes go client
```<code>    package main

    import (
          "fmt"
        "html/template"
        "net/http"
        "os"
        log "github.com/kubernetes/klog"
        "k8s.io/apimachinery/pkg/apis/meta/v1"
        "k8s.io/client-go/kubernetes"
        "k8s.io/client-go/tools/clientcmd"
    )

    type NamespaceDetails struct { //namespace details struct
        Namespace []string
    }

    var templates = template.Must(template.ParseGlob("./*.html"))
    var microservice = "/microservice/"
    var detailed_view = "/detailed/"
    var kube_config_path = os.Getenv("HOME")+"/.kube/config"
    var config, _ = clientcmd.BuildConfigFromFlags("", kube_config_path)
    var clientset,_ = kubernetes.NewForConfig(config)
   var NamespaceClient, _ = clientset.CoreV1().Namespaces().List(v1.ListOptions{})

    func main() {
        http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
        http.Handle("/jpeg/", http.StripPrefix("/jpeg/", http.FileServer(http.Dir("css"))))
        http.HandleFunc("/", Homepage)             // calling homepage function at '/' url
        http.HandleFunc(microservice, Deployments) //calling Deployments function at '/microserivce/' url
        http.HandleFunc(detailed_view, DetailedView)
        // http.HandleFunc("/onlyme", onlyme)
        http.ListenAndServe(":8801", nil) // server runs at this port
    }

    func Homepage(w http.ResponseWriter, r *http.Request) {
        NamespaceStruct := NamespaceDetails{}
        for _, Namespaces := range NamespaceClient.Items {
            log.V(5).Info("inside namespace items loop in homepage")
            NamespaceStruct.Namespace = append(NamespaceStruct.Namespace, Namespaces.Name)
        }
                templates.ExecuteTemplate(w, "homepage2.html", NamespaceStruct)
    }

    func deployments(namespace string)(*"k8s.io/api/apps/v1".DeploymentList, error){
        return  clientset.AppsV1().Deployments(namespace).List(v1.ListOptions{})
    }
</code>```

when i am trying to run this code it is giving error:

syntax error: unexpected literal "k8s.io/api/apps/v1", expecting type

i want to return deploymentslist using deploymnets function.i dont know what return type to use so that i succesfully return deployments list.

答:
in imports add this line

```<code>v2 "k8s.io/api/apps/v1"
</code>```

and update the function parameter as following

```<code>func deployments(namespace string)(*v2.DeploymentList, error){
</code>```

incase if u r looking for podslist/namespacelist

```<code>import  v3 "k8s.io/api/core/v1"
</code>```

and update function as,

```<code> func func_name (input paramteters)(*v3.NamespaceList/PodList , error){
</code>```

Body:
    package main

    import (
          "fmt"
        "html/template"
        "net/http"
        "os"
        log "github.com/kubernetes/klog"
        "k8s.io/apimachinery/pkg/apis/meta/v1"
        "k8s.io/client-go/kubernetes"
        "k8s.io/client-go/tools/clientcmd"
    )

    type NamespaceDetails struct { //namespace details struct
        Namespace []string
    }

    var templates = template.Must(template.ParseGlob("./*.html"))
    var microservice = "/microservice/"
    var detailed_view = "/detailed/"
    var kube_config_path = os.Getenv("HOME")+"/.kube/config"
    var config, _ = clientcmd.BuildConfigFromFlags("", kube_config_path)
    var clientset,_ = kubernetes.NewForConfig(config)
   var NamespaceClient, _ = clientset.CoreV1().Namespaces().List(v1.ListOptions{})

    func main() {
        http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
        http.Handle("/jpeg/", http.StripPrefix("/jpeg/", http.FileServer(http.Dir("css"))))
        http.HandleFunc("/", Homepage)             // calling homepage function at '/' url
        http.HandleFunc(microservice, Deployments) //calling Deployments function at '/microserivce/' url
        http.HandleFunc(detailed_view, DetailedView)
        // http.HandleFunc("/onlyme", onlyme)
        http.ListenAndServe(":8801", nil) // server runs at this port
    }

    func Homepage(w http.ResponseWriter, r *http.Request) {
        NamespaceStruct := NamespaceDetails{}
        for _, Namespaces := range NamespaceClient.Items {
            log.V(5).Info("inside namespace items loop in homepage")
            NamespaceStruct.Namespace = append(NamespaceStruct.Namespace, Namespaces.Name)
        }
                templates.ExecuteTemplate(w, "homepage2.html", NamespaceStruct)
    }

    func deployments(namespace string)(*"k8s.io/api/apps/v1".DeploymentList, error){
        return  clientset.AppsV1().Deployments(namespace).List(v1.ListOptions{})
    }

when i am trying to run this code it is giving error:

syntax error: unexpected literal "k8s.io/api/apps/v1", expecting type

i want to return deploymentslist using deploymnets function.i dont know what return type to use so that i succesfully return deployments list.

Body:
in imports add this line

v2 "k8s.io/api/apps/v1"

and update the function parameter as following

func deployments(namespace string)(*v2.DeploymentList, error){

incase if u r looking for podslist/namespacelist

import  v3 "k8s.io/api/core/v1"

and update function as,

 func func_name (input paramteters)(*v3.NamespaceList/PodList , error){


问:
Cassandra auto-complete does not work
I have a problem with the auto-complete within Cassandra 3.9 client "cqlsh", I don't know why? I did an update my brew command on MacOS Sierra. I suppose this problem is for a python update, but how it's related?

I tried to execute the tests:

```<code>$ cd apache-cassandra-3.9/pylib/cqlshlib/test
$ python test_cqlsh_completion.py
</code>```

but I got this error:

```<code>Traceback (most recent call last):
  File "test_cqlsh_completion.py", line 23, in <module>
    from .basecase import BaseTestCase, cqlsh
ValueError: Attempted relative import in non-package
</code>```

Someone know any solution?

If I list the directory it shows:

```<code>$ ls apache-cassandra-3.9/pylib/cqlshlib/test

__init__.py              basecase.py
run_cqlsh.py             test_cqlsh_commands.py
test_cqlsh_invocation.py test_cqlsh_parsing.py
winpty.py                ansi_colors.py
cassconnect.py           test_cql_parsing.py
test_cqlsh_completion.py test_cqlsh_output.py
test_keyspace_init.cql
</code>```

答:
I had a similar issue. The root of the problem was with python's readline package

please, try

```<code>python -c 'import readline'
</code>```

if you get an error, it will guide you to the solution

Title: Cassandra auto-complete does not work

Body:
I have a problem with the auto-complete within Cassandra 3.9 client "cqlsh", I don't know why? I did an update my brew command on MacOS Sierra. I suppose this problem is for a python update, but how it's related?

I tried to execute the tests:

$ cd apache-cassandra-3.9/pylib/cqlshlib/test
$ python test_cqlsh_completion.py

but I got this error:

Traceback (most recent call last):
  File "test_cqlsh_completion.py", line 23, in <module>
    from .basecase import BaseTestCase, cqlsh
ValueError: Attempted relative import in non-package

Someone know any solution?

If I list the directory it shows:

$ ls apache-cassandra-3.9/pylib/cqlshlib/test

__init__.py              basecase.py
run_cqlsh.py             test_cqlsh_commands.py
test_cqlsh_invocation.py test_cqlsh_parsing.py
winpty.py                ansi_colors.py
cassconnect.py           test_cql_parsing.py
test_cqlsh_completion.py test_cqlsh_output.py
test_keyspace_init.cql

Body:
I had a similar issue. The root of the problem was with python's readline package

please, try

python -c 'import readline'

if you get an error, it will guide you to the solution


问:
Connection Java - MySQL : Public Key Retrieval is not allowed
I try to connect MySQL database with Java using connector 8.0.11.   Everything seems to be OK, but I get this exception:

```<code>Exception in thread "main" java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed at
     com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:108) at
     com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95) at
     com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) at
     com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:862) at
     com.mysql.cj.jdbc.ConnectionImpl.(ConnectionImpl.java:444) at
     com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:230) at
     com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:226) at
     com.mysql.cj.jdbc.MysqlDataSource.getConnection(MysqlDataSource.java:438) at
     com.mysql.cj.jdbc.MysqlDataSource.getConnection(MysqlDataSource.java:146) at
     com.mysql.cj.jdbc.MysqlDataSource.getConnection(MysqlDataSource.java:119) at
     ConnectionManager.getConnection(ConnectionManager.java:28) at
     Main.main(Main.java:8)

</code>```

Here is my Connection Manager class:

```<code>public class ConnectionManager {

    public static final String serverTimeZone = "UTC";
    public static final String serverName = "localhost";
    public static final String databaseName ="biblioteka";
    public static final int portNumber = 3306;
    public static final String user = "anyroot";
    public static final String password = "anyroot";

    public static Connection getConnection() throws SQLException {

        MysqlDataSource dataSource = new MysqlDataSource();

        dataSource.setUseSSL( false );
        dataSource.setServerTimezone( serverTimeZone );
        dataSource.setServerName( serverName );
        dataSource.setDatabaseName( databaseName );
        dataSource.setPortNumber( portNumber );
        dataSource.setUser( user );
        dataSource.setPassword( password );

        return dataSource.getConnection();
    }
}
</code>```

答:
I was also facing such an issue while dockerizing our existing application. The solution si to add allowPublicKeyRetrieval connection option of MySQL with a value of true to the JDBC connection string.
If that is not working , try adding useSSL option to false as well .

The resultant string would look like this :

```<code>jdbc:mysql://<database server ip>:3306/databaseName?allowPublicKeyRetrieval=true&useSSL=false
</code>```

Body:
I try to connect MySQL database with Java using connector 8.0.11.   Everything seems to be OK, but I get this exception:

Exception in thread "main" java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed at
     com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:108) at
     com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95) at
     com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) at
     com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:862) at
     com.mysql.cj.jdbc.ConnectionImpl.(ConnectionImpl.java:444) at
     com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:230) at
     com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:226) at
     com.mysql.cj.jdbc.MysqlDataSource.getConnection(MysqlDataSource.java:438) at
     com.mysql.cj.jdbc.MysqlDataSource.getConnection(MysqlDataSource.java:146) at
     com.mysql.cj.jdbc.MysqlDataSource.getConnection(MysqlDataSource.java:119) at
     ConnectionManager.getConnection(ConnectionManager.java:28) at
     Main.main(Main.java:8)

Here is my Connection Manager class:

public class ConnectionManager {

    public static final String serverTimeZone = "UTC";
    public static final String serverName = "localhost";
    public static final String databaseName ="biblioteka";
    public static final int portNumber = 3306;
    public static final String user = "anyroot";
    public static final String password = "anyroot";

    public static Connection getConnection() throws SQLException {

        MysqlDataSource dataSource = new MysqlDataSource();

        dataSource.setUseSSL( false );
        dataSource.setServerTimezone( serverTimeZone );
        dataSource.setServerName( serverName );
        dataSource.setDatabaseName( databaseName );
        dataSource.setPortNumber( portNumber );
        dataSource.setUser( user );
        dataSource.setPassword( password );

        return dataSource.getConnection();
    }
}

Body:
I was also facing such an issue while dockerizing our existing application. The solution si to add allowPublicKeyRetrieval connection option of MySQL with a value of true to the JDBC connection string.
If that is not working , try adding useSSL option to false as well .

The resultant string would look like this :

jdbc:mysql://<database server ip>:3306/databaseName?allowPublicKeyRetrieval=true&useSSL=false


问:
How to serve static content over an Azure CDN with a dynamic resolver redirecting Urls from Ids?
What we already have in place

Azure Blob Storage with static files, ir our case images

Azure CDN in front of the Blob Storage

ASP.NET Core Service

uploading images to the blob storage

saving meta data about the logical collection of images, called Asset

let's call this the media service

How we use that

Let's say we have another service called the product service.

Each product has a product picture associated with it.

We create a new asset in the media service and get back an AssetId.

The product service now stores this AssetId in his local database

What we're looking for

As long as we operate with the assets meta data in the back end life's good.

But at the end of the day we want to visualize the pictures in a WebUI. To do that we need to have the Url pointing back to the image on the blob storage / CDN.

Right now the back end actively resolves the Urls before the data flows to the WebUI. But there must be better way of doing this.

One feasible approach that comes to mind is to have a simple resolver middleware

/images/{assetid}/{assetType} -> Redirect to CDN Url

but then each call flows over this middleware instead of going to the CDN in first place before falling back to a resolver to get the correct Url.

What do I miss? What's the best practice any way to solve such basic thing in the micro-service area?

Thanks

答: I would not use a middleware component to redirect the URLs, because as you mentioned, the client will always contact first your middleware component, and there is an additional unnecessary call and overhead. The nature of the CDN is to serve the assets in a global distributed network, so your assets will be indexed to the CDN edges and it will be served from the closest edge to the client. You should be able to use the WebUI component and use the CDN Urls (https://.azureedge.net/*). In case you need to use redirect rules, you can use the CDN features to perform redirect rules. Note: Depending on the CDN service you are using, you may need to upgrade CDN pricing tier to Premium. Eg. Verizon you need to use Premium tier to have ability for redirect rules.</p>


问:
How to make the if statement without repetition of code?
Following is the if statement that execute some part of the code before it checks some condition, it is working fine but it looks very basic and repeated lines.</p>

```<code>    if(allTasks[t].status === "Completed"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","completed");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Past Due"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","pastdue");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Duetoday"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","duetoday");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Onhold"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","onhold");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Canceled"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","canceled");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }
</code>```

答:
You can use the switch statement.

```<code>switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}
</code>```

You should also remove duplicated code from the conditions, like this:

```<code>
arrow.setAttribute("class","arrow2");
tag.innerHTML = allTasks[t].status;
taskCont.appendChild(tag);

switch (allTasks[t].status) {
  case "Completed":
    tag.setAttribute("class","completed");
    break;
  case "Past Due":
    tag.setAttribute("class","pastdue");
    break;
  case "Duetoday":
    tag.setAttribute("class","duetoday");
    break;
  case "Onhold":
    tag.setAttribute("class","onhold");
    break;
  case "Canceled":
    tag.setAttribute("class","canceled");
    break;
}
</code>```

Body:
Following is the if statement that execute some part of the code before it checks some condition, it is working fine but it looks very basic and repeated lines.

    if(allTasks[t].status === "Completed"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","completed");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Past Due"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","pastdue");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Duetoday"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","duetoday");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Onhold"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","onhold");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Canceled"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","canceled");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }

Body:
You can use the switch statement.

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

You should also remove duplicated code from the conditions, like this:

arrow.setAttribute("class","arrow2");
tag.innerHTML = allTasks[t].status;
taskCont.appendChild(tag);

switch (allTasks[t].status) {
  case "Completed":
    tag.setAttribute("class","completed");
    break;
  case "Past Due":
    tag.setAttribute("class","pastdue");
    break;
  case "Duetoday":
    tag.setAttribute("class","duetoday");
    break;
  case "Onhold":
    tag.setAttribute("class","onhold");
    break;
  case "Canceled":
    tag.setAttribute("class","canceled");
    break;
}


问:
Making a WPF application retain focus at all times
I've got an issue with a WPF application that I'm writing. The app needs to be able to keep focus at all times. The computer it's running on is a highly specialized machine with the only purpose of running this application.

There is no keyboard connected to the machine (it has a touch screen), so the only thing that can steal focus is windows own "needy windows", such as windows update etc.

How can I make it so that my app retains focus at all times? Is it possible to make the entire app modal?

EDIT:

Thank you both for your answers. I think I'll end up using Topsmost for now, but I'll definitely check out the source of babysmash as that application works exactly the way I want mine to, in regards to the way it handles focus.

答: Look at the source of BabySmash. It is specifically designed to keep focus even under quite bizar circumstances. (It is a program designed to run at full screen and let babys smash on a keyboard - so quite some focus went into capturing all kinds of weird keyboard combinations and alert messages).</p>

OwnerDisplayName: Ciddan

LastEditorDisplayName: Ciddan

ContentLicense: CC BY-SA 2.5


问:
What does the pipe | do in this bash script?
I am trying to understand this so called "Fork Bomb" written in bash. (for more information see https://en.wikipedia.org/wiki/Fork_bomb)

My understanding is that the Ampersand caused the function Bomb to be forked and to run in the background. Is that correct?

Presuming so... my question then is, what does the Pipe | do?

Is the pipe in this case an OR condition, or is it the same as "piping" a command from one to the other as done on the command line? Why do I want to pipe the second Bomb function call back to the first Bomb function call?

Can someone please explain why the pipe is necessary?

```<code>bomb(){
  bomb | bomb &
}
bomb
</code>```

答:
Each call of function bomb starts 2 new instances of bommb in the background. Because of the pipe sign, the output (is empty here) of the first bomb is redirected to the second one.

Because of background execution, each new bomb creates 2 new bombs. That is done endless, so that at any time the number of available processes is reached. Dependent of available resources and rights, the system goes very slow for a time or crashes.

Body:
I am trying to understand this so called "Fork Bomb" written in bash. (for more information see https://en.wikipedia.org/wiki/Fork_bomb)

My understanding is that the Ampersand caused the function Bomb to be forked and to run in the background. Is that correct?

Presuming so... my question then is, what does the Pipe | do?

Is the pipe in this case an OR condition, or is it the same as "piping" a command from one to the other as done on the command line? Why do I want to pipe the second Bomb function call back to the first Bomb function call?

Can someone please explain why the pipe is necessary?

bomb(){
  bomb | bomb &
}
bomb


问:
Design Patterns used in IOT based home automation system like Alexa
I am trying to design a basic IOT based home automation system like Alexa or Google Home. So can anyone explain what are the basic design patterns used in Alexa or Google Home to dynamically register new devices like Lights and Fans and perform operations on them.

I have implemented this using a command pattern using fixed set of devices, but need to scale this to take care of registering dynamic run time new objects without changing code like Alexa

```<code>public SmartHomeDevice getSmartHomeDevice(String deviceName) {
        SmartHomeDevice smartHomeDevice = null;

        if (SmartHomeDeviceCategoryConstants.DRAWING_ROOM_LIGHT.getName().equalsIgnoreCase(deviceName)) {
            smartHomeDevice = new Light(deviceName);
        } else if (SmartHomeDeviceCategoryConstants.LIVING_ROOM_FAN.getName().equalsIgnoreCase(deviceName)) {
            smartHomeDevice = new Fan(deviceName);
        } else if (SmartHomeDeviceCategoryConstants.SMART_CHARGER.getName().equalsIgnoreCase(deviceName)) {
            smartHomeDevice = new ElectricalDevice(deviceName);
        }
        return smartHomeDevice;
    }
}
</code>```

答: For Home Automation , you have to use Command Design Pattern Refer to https://www.geeksforgeeks.org/command-pattern/.</p>

Body:
I am trying to design a basic IOT based home automation system like Alexa or Google Home. So can anyone explain what are the basic design patterns used in Alexa or Google Home to dynamically register new devices like Lights and Fans and perform operations on them.

I have implemented this using a command pattern using fixed set of devices, but need to scale this to take care of registering dynamic run time new objects without changing code like Alexa

public SmartHomeDevice getSmartHomeDevice(String deviceName) {
        SmartHomeDevice smartHomeDevice = null;

        if (SmartHomeDeviceCategoryConstants.DRAWING_ROOM_LIGHT.getName().equalsIgnoreCase(deviceName)) {
            smartHomeDevice = new Light(deviceName);
        } else if (SmartHomeDeviceCategoryConstants.LIVING_ROOM_FAN.getName().equalsIgnoreCase(deviceName)) {
            smartHomeDevice = new Fan(deviceName);
        } else if (SmartHomeDeviceCategoryConstants.SMART_CHARGER.getName().equalsIgnoreCase(deviceName)) {
            smartHomeDevice = new ElectricalDevice(deviceName);
        }
        return smartHomeDevice;
    }
}


问:
Loop in Firebase Recycler Adapter
I'm getting the list of user ids from database. And its getting the values correctly. I'm using FirebaseRecyclerAdapter and when I iterate that list in onBindViewHolder the loops runs as the size of list. For example over here  :

```<code> adapter = new FirebaseRecyclerAdapter<Profiles, DonarViewHolder>(model) {
            @Override
            protected void onBindViewHolder(@NonNull DonarViewHolder holder, int position, @NonNull Profiles profiles) {
               for (int i = 0 ; i<list.size() ; i++){
                  Toast.makeText(List.this,"List :" +list.get(i), Toast.LENGTH_SHORT).show();
               }
            }
 }
</code>```

Over here I have 5 item in list and while iterating I'm toasting each item . So in here the loop run for 25 time, its shows each item 5 time in sequence. First it shows 5 items orderly after showing last item it start toasting from first one again and continues till 5 time as the size of list.
So how do I cater this and make it only iterate the whole items for once only?

答:
I think you are missing a method that you can use to call each item individually.
create a setter and getter for your item. In your loop you can then call it list.get(position).getItem .</p>

Title: Loop in Firebase Recycler Adapter

Body:
I'm getting the list of user ids from database. And its getting the values correctly. I'm using FirebaseRecyclerAdapter and when I iterate that list in onBindViewHolder the loops runs as the size of list. For example over here  :

 adapter = new FirebaseRecyclerAdapter<Profiles, DonarViewHolder>(model) {
            @Override
            protected void onBindViewHolder(@NonNull DonarViewHolder holder, int position, @NonNull Profiles profiles) {
               for (int i = 0 ; i<list.size() ; i++){
                  Toast.makeText(List.this,"List :" +list.get(i), Toast.LENGTH_SHORT).show();
               }
            }
 }

Over here I have 5 item in list and while iterating I'm toasting each item . So in here the loop run for 25 time, its shows each item 5 time in sequence. First it shows 5 items orderly after showing last item it start toasting from first one again and continues till 5 time as the size of list.
So how do I cater this and make it only iterate the whole items for once only?


问:
How to do concurrent jsonrpc using gevent and requests in volttron
I am trying to do concurrent JSONRPC calls to remote agents in Volttron. And am using Volttron 5.1.0 (with gevent 1.1.2 & requests 2.11.1).

The code works as expected. However, from the log files, I notice that the requests are not run concurrently. I am not sure what I am missing.

I tried suggestions mentioned in how enable requests async mode? (i.e,, handling async part in the request, monkey patch, etc.,). But none work-out, either the solution is outdated or required modules not available in volttron env (I am a bit worried about version requirements).

Any suggestions or inputs would be of great help.

The relevant part of the agent code is as follows:

Agent Code

import gevent
import requests

url_roots = ['http://192.168.1.51:8080/', 'http://192.168.1.52:8080/']
jobs = [gevent.spawn(do_rpc, self._agent_id, url_root, 'pricepoint'
                                , get_json_params()
                                ) for url_root in url_roots
                                ]
gevent.joinall(jobs, timeout=11)

def do_rpc(id, url_root, method, params=None):
    result = False
    json_package = {
        'jsonrpc': '2.0',
        'id': id,
        'method':method,
    }
    json_package['params'] = params
    response = requests.post(url_root, data=json.dumps(json_package), timeout=10)
    if response.ok:
        if 'result' in response.json().keys():
            success = response.json()['result']
            if success:
                result = True
    return result
```

Log

2020-02-19 21:12:15,913 (xyzagent-0.4 28079) xyz.ispace_msg_utils DEBUG: validate_bustopic_msg()

  2020-02-19 21:12:15,918 (xyzagent-0.4 28079) xyz.agent DEBUG: New price point (pp) msg on the local-bus, topic: building/pricepoint ...

  2020-02-19 21:12:15,919 (xyzagent-0.4 28079) xyz.agent DEBUG: ***** New bid price point from local: 0.20 price_id: 2218566

  2020-02-19 21:12:15,931 (xyzagent-0.4 28079) xyz.agent DEBUG: post_ds_new_pp()...

  2020-02-19 21:12:15,932 (xyzagent-0.4 28079) xyz.agent DEBUG: us pp messages count: 1...

  2020-02-19 21:12:15,933 (xyzagent-0.4 28079) xyz.agent DEBUG: processing pp msg 1/1, price id: 2218566

  2020-02-19 21:12:15,938 (xyzagent-0.4 28079) xyz.agent DEBUG: new ttl: 28.

  2020-02-19 21:12:15,942 (xyzagent-0.4 28079) xyz.agent DEBUG: _ds_rpc_1_to_m()...

  2020-02-19 21:12:15,953 (xyzagent-0.4 28079) requests.packages.urllib3.connectionpool INFO: Starting new HTTP connection (1): 192.168.1.51

  2020-02-19 21:12:16,079 () volttron.platform.web DEBUG: {'jsonrpc': '2.0', 'id': '2503402', 'result': True}

  2020-02-19 21:12:16,080 () volttron.platform.web DEBUG: res is a dictionary.

  2020-02-19 21:12:16,238 (xyzagent-0.4 28079) requests.packages.urllib3.connectionpool DEBUG: "POST /bridge HTTP/1.1" 200 53

  2020-02-19 21:12:16,245 (xyzagent-0.4 28079) requests.packages.urllib3.connectionpool INFO: Starting new HTTP connection (1): 192.168.1.52

  2020-02-19 21:12:16,526 (xyzagent-0.4 28079) requests.packages.urllib3.connectionpool DEBUG: "POST /bridge HTTP/1.1" 200 53

  2020-02-19 21:12:16,529 (xyzagent-0.4 28079) xyz.agent DEBUG: post pp to ds (ZoneController-51), result: success!!!

  2020-02-19 21:12:16,529 (xyzagent-0.4 28079) xyz.agent DEBUG: post pp to ds (ZoneController-52), result: success!!!

  2020-02-19 21:12:16,530 (xyzagent-0.4 28079) xyz.agent DEBUG: _ds_rpc_1_to_m()...done

  2020-02-19 21:12:16,530 (xyzagent-0.4 28079) xyz.agent DEBUG: msg successfully posted to all ds, removing it from the queue

  2020-02-19 21:12:16,530 (xyzagent-0.4 28079) xyz.agent DEBUG: reset the retry counter for success ds msg

  2020-02-19 21:12:16,530 (xyzagent-0.4 28079) xyz.agent DEBUG: post_ds_new_pp()...done

答:
The below changes did the trick. Please note that just monkey.patch_all() breaks volttron. Need to set flag thread=False.

Agent Code

import gevent
from gevent import monkey
monkey.patch_all(thread=False, select=False)
import requests
```

Logs

2020-02-20 14:36:29,981 (xyzagent-0.4 8657) xyz.agent DEBUG: _ds_rpc_1_to_m()...

  2020-02-20 14:36:29,987 (xyzagent-0.4 8657) requests.packages.urllib3.connectionpool INFO: Starting new HTTP connection (1): 192.168.1.51

  2020-02-20 14:36:29,992 (xyzagent-0.4 8657) requests.packages.urllib3.connectionpool INFO: Starting new HTTP connection (1): 192.168.1.52

  2020-02-20 14:36:30,260 (xyzagent-0.4 8657) requests.packages.urllib3.connectionpool DEBUG: "POST /bridge HTTP/1.1" 200 53

  2020-02-20 14:36:30,333 (xyzagent-0.4 8657) requests.packages.urllib3.connectionpool DEBUG: "POST /bridge HTTP/1.1" 200 53

  2020-02-20 14:36:30,341 (xyzagent-0.4 8657) xyz.agent DEBUG: post pp to ds (ZoneController-51), result: success!!!

  2020-02-20 14:36:30,342 (xyzagent-0.4 8657) xyz.agent DEBUG: post pp to ds (ZoneController-52), result: success!!!

  2020-02-20 14:36:30,344 (xyzagent-0.4 8657) xyz.agent DEBUG: _ds_rpc_1_to_m()...done

Body:
I am trying to do concurrent JSONRPC calls to remote agents in Volttron. And am using Volttron 5.1.0 (with gevent 1.1.2 & requests 2.11.1).

The code works as expected. However, from the log files, I notice that the requests are not run concurrently. I am not sure what I am missing.

I tried suggestions mentioned in how enable requests async mode? (i.e,, handling async part in the request, monkey patch, etc.,). But none work-out, either the solution is outdated or required modules not available in volttron env (I am a bit worried about version requirements).

Any suggestions or inputs would be of great help.

The relevant part of the agent code is as follows:

Agent Code

import gevent
import requests

url_roots = ['http://192.168.1.51:8080/', 'http://192.168.1.52:8080/']
jobs = [gevent.spawn(do_rpc, self._agent_id, url_root, 'pricepoint'
                                , get_json_params()
                                ) for url_root in url_roots
                                ]
gevent.joinall(jobs, timeout=11)

def do_rpc(id, url_root, method, params=None):
    result = False
    json_package = {
        'jsonrpc': '2.0',
        'id': id,
        'method':method,
    }
    json_package['params'] = params
    response = requests.post(url_root, data=json.dumps(json_package), timeout=10)
    if response.ok:
        if 'result' in response.json().keys():
            success = response.json()['result']
            if success:
                result = True
    return result

Log

2020-02-19 21:12:15,913 (xyzagent-0.4 28079) xyz.ispace_msg_utils DEBUG: validate_bustopic_msg()

  2020-02-19 21:12:15,918 (xyzagent-0.4 28079) xyz.agent DEBUG: New price point (pp) msg on the local-bus, topic: building/pricepoint ...

  2020-02-19 21:12:15,919 (xyzagent-0.4 28079) xyz.agent DEBUG: ***** New bid price point from local: 0.20 price_id: 2218566

  2020-02-19 21:12:15,931 (xyzagent-0.4 28079) xyz.agent DEBUG: post_ds_new_pp()...

  2020-02-19 21:12:15,932 (xyzagent-0.4 28079) xyz.agent DEBUG: us pp messages count: 1...

  2020-02-19 21:12:15,933 (xyzagent-0.4 28079) xyz.agent DEBUG: processing pp msg 1/1, price id: 2218566

  2020-02-19 21:12:15,938 (xyzagent-0.4 28079) xyz.agent DEBUG: new ttl: 28.

  2020-02-19 21:12:15,942 (xyzagent-0.4 28079) xyz.agent DEBUG: _ds_rpc_1_to_m()...

  2020-02-19 21:12:15,953 (xyzagent-0.4 28079) requests.packages.urllib3.connectionpool INFO: Starting new HTTP connection (1): 192.168.1.51

  2020-02-19 21:12:16,079 () volttron.platform.web DEBUG: {'jsonrpc': '2.0', 'id': '2503402', 'result': True}

  2020-02-19 21:12:16,080 () volttron.platform.web DEBUG: res is a dictionary.

  2020-02-19 21:12:16,238 (xyzagent-0.4 28079) requests.packages.urllib3.connectionpool DEBUG: "POST /bridge HTTP/1.1" 200 53

  2020-02-19 21:12:16,245 (xyzagent-0.4 28079) requests.packages.urllib3.connectionpool INFO: Starting new HTTP connection (1): 192.168.1.52

  2020-02-19 21:12:16,526 (xyzagent-0.4 28079) requests.packages.urllib3.connectionpool DEBUG: "POST /bridge HTTP/1.1" 200 53

  2020-02-19 21:12:16,529 (xyzagent-0.4 28079) xyz.agent DEBUG: post pp to ds (ZoneController-51), result: success!!!

  2020-02-19 21:12:16,529 (xyzagent-0.4 28079) xyz.agent DEBUG: post pp to ds (ZoneController-52), result: success!!!

  2020-02-19 21:12:16,530 (xyzagent-0.4 28079) xyz.agent DEBUG: _ds_rpc_1_to_m()...done

  2020-02-19 21:12:16,530 (xyzagent-0.4 28079) xyz.agent DEBUG: msg successfully posted to all ds, removing it from the queue

  2020-02-19 21:12:16,530 (xyzagent-0.4 28079) xyz.agent DEBUG: reset the retry counter for success ds msg

  2020-02-19 21:12:16,530 (xyzagent-0.4 28079) xyz.agent DEBUG: post_ds_new_pp()...done

Body:
The below changes did the trick. Please note that just monkey.patch_all() breaks volttron. Need to set flag thread=False.

Agent Code

import gevent
from gevent import monkey
monkey.patch_all(thread=False, select=False)
import requests

Logs

2020-02-20 14:36:29,981 (xyzagent-0.4 8657) xyz.agent DEBUG: _ds_rpc_1_to_m()...

  2020-02-20 14:36:29,987 (xyzagent-0.4 8657) requests.packages.urllib3.connectionpool INFO: Starting new HTTP connection (1): 192.168.1.51

  2020-02-20 14:36:29,992 (xyzagent-0.4 8657) requests.packages.urllib3.connectionpool INFO: Starting new HTTP connection (1): 192.168.1.52

  2020-02-20 14:36:30,260 (xyzagent-0.4 8657) requests.packages.urllib3.connectionpool DEBUG: "POST /bridge HTTP/1.1" 200 53

  2020-02-20 14:36:30,333 (xyzagent-0.4 8657) requests.packages.urllib3.connectionpool DEBUG: "POST /bridge HTTP/1.1" 200 53

  2020-02-20 14:36:30,341 (xyzagent-0.4 8657) xyz.agent DEBUG: post pp to ds (ZoneController-51), result: success!!!

  2020-02-20 14:36:30,342 (xyzagent-0.4 8657) xyz.agent DEBUG: post pp to ds (ZoneController-52), result: success!!!

  2020-02-20 14:36:30,344 (xyzagent-0.4 8657) xyz.agent DEBUG: _ds_rpc_1_to_m()...done


问:
How to get the path of image android?
I am selecting an image of the gallery from my app,
using

ACTION_GET_CONTENT

Now I want the path of this image:

But i get it like this:

content://com.android.providers.media.documents/document/image%3A5793

How can i get the path?

I tried this to get path:

```<code>Uri uri = data.getData();
Log.e("Path is: "+uri);
</code>```

答:
Try this :</p>

```<code>Uri uri = data.getData();
        String picturePath = getPath( getActivity( ).getApplicationContext( ), uri);
        Log.e("Picture Path", picturePath);

public static String getPath( Context context, Uri uri ) {
    String result = null;
    String[] proj = { MediaStore.Images.Media.DATA };
    Cursor cursor = context.getContentResolver( ).query( uri, proj, null, null, null );
    if(cursor != null){
        if ( cursor.moveToFirst( ) ) {
            int column_index = cursor.getColumnIndexOrThrow( proj[0] );
            result = cursor.getString( column_index );
        }
        cursor.close( );
    }
    if(result == null) {
        result = "Not found";
    }
    return result;
}
</code>```

Title: How to get the path of image android?

Body:
I am selecting an image of the gallery from my app,
using

ACTION_GET_CONTENT

Now I want the path of this image:

But i get it like this:

content://com.android.providers.media.documents/document/image%3A5793

How can i get the path?

I tried this to get path:

Uri uri = data.getData();
Log.e("Path is: "+uri);

Body:
Try this :

Uri uri = data.getData();
        String picturePath = getPath( getActivity( ).getApplicationContext( ), uri);
        Log.e("Picture Path", picturePath);

public static String getPath( Context context, Uri uri ) {
    String result = null;
    String[] proj = { MediaStore.Images.Media.DATA };
    Cursor cursor = context.getContentResolver( ).query( uri, proj, null, null, null );
    if(cursor != null){
        if ( cursor.moveToFirst( ) ) {
            int column_index = cursor.getColumnIndexOrThrow( proj[0] );
            result = cursor.getString( column_index );
        }
        cursor.close( );
    }
    if(result == null) {
        result = "Not found";
    }
    return result;
}