问:
Shadow of a custom shape
I have to implement a banner according to the following designs:

The complexity here is in the shadow of the round logo, the shadow of the logo circle is the continuation of the shadow of the rectangular card of the banner. The border of the shadow is outlined in the following image:

Of course the shadow shouldn't be casted on the surface below the top side of the card. Also the logo center has some offset from the border of the card.

How can I achieve this effect? Standard android shapes doesn't allow to form such a contour. Drawing everything manually seems to be too complex decision for the problem. We have minSdkVersion 21.

答:
You can achieve it using this trick

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.cardview.widget.CardView
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="20dp"
        app:cardCornerRadius="56dp"
        app:cardElevation="16dp"
        android:layout_width="56dp"
        android:layout_height="56dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <de.hdodenhof.circleimageview.CircleImageView
                android:layout_width="match_parent"
                android:src="@color/colorPrimary"
                android:layout_height="match_parent"/>
        </LinearLayout>
    </androidx.cardview.widget.CardView>

    <androidx.cardview.widget.CardView
        app:cardElevation="16dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="48dp"
        android:layout_width="350dp"
        android:layout_height="500dp">

        <LinearLayout
            android:layout_marginTop="-28dp"
            android:layout_gravity="center_horizontal"
            android:layout_width="56dp"
            android:layout_height="56dp">
            <de.hdodenhof.circleimageview.CircleImageView
                android:layout_width="match_parent"
                android:src="@color/colorPrimary"
                android:layout_height="match_parent"/>
        </LinearLayout>

    </androidx.cardview.widget.CardView>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

The result will be:

The main idea create two cardview with images, one under the main card and another one in the cardview and using margins make the look like one circle.

Title: Shadow of a custom shape

Body:
You can achieve it using this trick

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.cardview.widget.CardView
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="20dp"
        app:cardCornerRadius="56dp"
        app:cardElevation="16dp"
        android:layout_width="56dp"
        android:layout_height="56dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <de.hdodenhof.circleimageview.CircleImageView
                android:layout_width="match_parent"
                android:src="@color/colorPrimary"
                android:layout_height="match_parent"/>
        </LinearLayout>
    </androidx.cardview.widget.CardView>

    <androidx.cardview.widget.CardView
        app:cardElevation="16dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="48dp"
        android:layout_width="350dp"
        android:layout_height="500dp">

        <LinearLayout
            android:layout_marginTop="-28dp"
            android:layout_gravity="center_horizontal"
            android:layout_width="56dp"
            android:layout_height="56dp">
            <de.hdodenhof.circleimageview.CircleImageView
                android:layout_width="match_parent"
                android:src="@color/colorPrimary"
                android:layout_height="match_parent"/>
        </LinearLayout>

    </androidx.cardview.widget.CardView>

</androidx.constraintlayout.widget.ConstraintLayout>

The result will be:

The main idea create two cardview with images, one under the main card and another one in the cardview and using margins make the look like one circle.


来源: stackexchange

问:
HTML "body onload" only works when manually refreshing the browser
I have a JS function that should execute with onload in HTML. The function does not run when arriving on the page, only when I refresh the browser. I have the same problem locally and on the published website.

In html I have :

```<code><body class="theme-light" data-background="none" data-highlight="red2" onload="myRequest()">
</code>```

And in JS:

    const myRequest = () => {
      const seasonProductSelector = Math.floor(Math.random() * 13);
      let inputValue = getSeasonalProductsArray(n)[seasonProductSelector];
      let url = 'https://api.spoonacular.com/recipes/search?apiKey=**************&query='+inputValue+'&number=1';
      xhr.open('GET', url);
      xhr.send();
      };```

I know the function itself works fine, when I manually refresh the page. But it won't run upon the page loading the first time.

Thanks for any help.

答: Thanks a lot for your answers. Turns out the template I'm using requires to place JS in a specific file for it to work.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a JS function that should execute with onload in HTML. The function does not run when arriving on the page, only when I refresh the browser. I have the same problem locally and on the published website.

In html I have :

And in JS:

    const myRequest = () => {
      const seasonProductSelector = Math.floor(Math.random() * 13);
      let inputValue = getSeasonalProductsArray(n)[seasonProductSelector];
      let url = 'https://api.spoonacular.com/recipes/search?apiKey=**************&query='+inputValue+'&number=1';
      xhr.open('GET', url);
      xhr.send();
      };

I know the function itself works fine, when I manually refresh the page. But it won't run upon the page loading the first time.

Thanks for any help.


问:
Webclient on Eclipse Java CXF 2.7.9 - Fixing a malformed .wsdl file
I'm having a very hard time creating a WSDL client, thanks to a malformed WSDL definition created using Apache Axis version 1.4 by someone else.

Let me show you the steps I'm following:

First I load up my WSDL endpoint http://xxxxx/uglySoap?wsdl on SOAP IU. The program automatically generates the following Request:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:bal="http://xxxx/uglySoap.xsd">
   <soapenv:Header/>
   <soapenv:Body>
      <bal:CreditRequest>
         <bal:MSISDN>?</bal:MSISDN>
         <bal:amountToCredit>?</bal:amountToCredit>
         <!--Optional:-->
         <bal:reason>?</bal:reason>
         <bal:transId>?</bal:transId>
      </bal:CreditRequest>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

This request is wrong because it is missing the header (where you provide the credentials). On SOAP UI that's not a problem, I can add the missing text by hand and it will work perfectly.

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:msp="http:xxxxxx/uglySoap.xsd" xmlns:bal="http://xxxxxx/uglySoap.xsd">
   <soapenv:Header>

          <msp:messageHeader>
         <msp:trackingMessageHeader>
            <msp:messageId>xxx</msp:messageId>
            <msp:carrierId>xxx</msp:carrierId>
            <msp:userId>xxxx</msp:userId>
            <msp:password>xxxx</msp:password>
         </msp:trackingMessageHeader>
      </msp:messageHeader>
   </soapenv:Header>

<!--from here is the same thing as before-->
   <soapenv:Body>
      <bal:CreditRequest>
         <bal:MSISDN>xxxxx</bal:MSISDN>
         <bal:amountToCredit>xxxx</bal:amountToCredit>
         <!--Optional:-->
         <bal:reason>xxxx</bal:reason>
         <bal:transId>xxxx</bal:transId>
      </bal:CreditRequest>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

The real pain starts when I try to consume the web service on Java. The Eclipse CXF 2.7.9. tool will import the botched wsdl version without any trouble, but invoking its methods is useless since they are well... botched.

creditResponse = balanceManager.getBalanceManagement().applyCredit(creditRequest, authHeader);

JAVA ERROR: The method credit(CreditRequest, MessageHeader) is undefined for the type BalanceManagement. Really dude? You already knew this was going to happen.

So...

I tried to manually edit the @WebMethod entries to include the missing features. That failed.

I tried (for hours) to create a local version of uglySoap.wsdl, include the missing header and then importing it to Java, but it throws cryptic org.apache.cxf.interceptor.ClientFaultConverter.processFaultDetail errors.

I even tried switching to Axis, to no avail.

Please, is there any solution for Java where I could just punch my SOAP request, the URL, and get the response as an .XML file (or even as plain text, no problem!) just as SOAP UI does?

Thank you!

答:
Ok guys, I found a working solution to make the requests by hand.

Create a new Maven project:

```<code>package main;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;

import io.restassured.path.xml.XmlPath;

public class Client {

    public void executeRequest() {

        try

        {

            CloseableHttpClient client = HttpClients.createDefault(); // create client
            HttpPost request = new HttpPost("http://172.27.241.11:8195/mspgwservices/services/BalanceManagement"); // Create
                                                                                // the

            String requestXmlText = "<soapenv:Envelope ...INCLUDE YOUR XML REQUEST HERE, ON THE SAME WAY YOU WOULD DO IT ON SOAP UI... </soapenv:Envelope>";

            StringEntity stringEntity = new StringEntity(requestXmlText, "utf-8");

            request.addHeader("soapAction", "Credit");
            request.addHeader("Accept", "text/xml");
            request.addHeader("Content-Type", "text/xml;charset=utf-8");
            request.setEntity(stringEntity);

            CloseableHttpResponse response = client.execute(request);// Execute the command

            int statusCode = response.getStatusLine().getStatusCode();
// Get the status code and assert
            System.out.println("Status code: " + statusCode);

            Assert.assertEquals(200, statusCode);

            String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");

// Getting the Response body
            System.out.println(responseString);

            XmlPath jsXpath = new XmlPath(responseString);
            String textResult = jsXpath.getString("respDescription");
            System.out.println("result: " + textResult );

        }

        catch (Exception ex)

        {
            System.out.println("Error." + ex.toString());
        }

    }

}
</code>```

Also don't forget to add the following lines to your POM.XML in order to import all requred libraries

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>BalanceadorLineas</groupId>
  <artifactId>BalanceadorLineas</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>

      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>

    <dependency>
        <groupId>org.springframework.restdocs</groupId>
        <artifactId>spring-restdocs-restassured</artifactId>
        <version>2.0.4.RELEASE</version>
    </dependency>

    <dependency>
    <groupId>org.scala-js</groupId>
    <artifactId>scalajs-junit-test-runtime_2.11</artifactId>
    <version>1.1.0</version>
</dependency>

  </dependencies>
</project>
</code>```

Finally the pain is over! Hope it works for you too.

Body:
I'm having a very hard time creating a WSDL client, thanks to a malformed WSDL definition created using Apache Axis version 1.4 by someone else.

Let me show you the steps I'm following:

First I load up my WSDL endpoint http://xxxxx/uglySoap?wsdl on SOAP IU. The program automatically generates the following Request:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:bal="http://xxxx/uglySoap.xsd">
   <soapenv:Header/>
   <soapenv:Body>
      <bal:CreditRequest>
         <bal:MSISDN>?</bal:MSISDN>
         <bal:amountToCredit>?</bal:amountToCredit>

         <bal:reason>?</bal:reason>
         <bal:transId>?</bal:transId>
      </bal:CreditRequest>
   </soapenv:Body>
</soapenv:Envelope>

This request is wrong because it is missing the header (where you provide the credentials). On SOAP UI that's not a problem, I can add the missing text by hand and it will work perfectly.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:msp="http:xxxxxx/uglySoap.xsd" xmlns:bal="http://xxxxxx/uglySoap.xsd">
   <soapenv:Header>

          <msp:messageHeader>
         <msp:trackingMessageHeader>
            <msp:messageId>xxx</msp:messageId>
            <msp:carrierId>xxx</msp:carrierId>
            <msp:userId>xxxx</msp:userId>
            <msp:password>xxxx</msp:password>
         </msp:trackingMessageHeader>
      </msp:messageHeader>
   </soapenv:Header>

   <soapenv:Body>
      <bal:CreditRequest>
         <bal:MSISDN>xxxxx</bal:MSISDN>
         <bal:amountToCredit>xxxx</bal:amountToCredit>

         <bal:reason>xxxx</bal:reason>
         <bal:transId>xxxx</bal:transId>
      </bal:CreditRequest>
   </soapenv:Body>
</soapenv:Envelope>

The real pain starts when I try to consume the web service on Java. The Eclipse CXF 2.7.9. tool will import the botched wsdl version without any trouble, but invoking its methods is useless since they are well... botched.

creditResponse = balanceManager.getBalanceManagement().applyCredit(creditRequest, authHeader);

JAVA ERROR: The method credit(CreditRequest, MessageHeader) is undefined for the type BalanceManagement. Really dude? You already knew this was going to happen.

So...

I tried to manually edit the @WebMethod entries to include the missing features. That failed.

I tried (for hours) to create a local version of uglySoap.wsdl, include the missing header and then importing it to Java, but it throws cryptic org.apache.cxf.interceptor.ClientFaultConverter.processFaultDetail errors.

I even tried switching to Axis, to no avail.

Please, is there any solution for Java where I could just punch my SOAP request, the URL, and get the response as an .XML file (or even as plain text, no problem!) just as SOAP UI does?

Thank you!

Body:
Ok guys, I found a working solution to make the requests by hand.

Create a new Maven project:

package main;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;

import io.restassured.path.xml.XmlPath;

public class Client {

    public void executeRequest() {

        try

        {

            CloseableHttpClient client = HttpClients.createDefault(); // create client
            HttpPost request = new HttpPost("http://172.27.241.11:8195/mspgwservices/services/BalanceManagement"); // Create
                                                                                // the

            String requestXmlText = "<soapenv:Envelope ...INCLUDE YOUR XML REQUEST HERE, ON THE SAME WAY YOU WOULD DO IT ON SOAP UI... </soapenv:Envelope>";

            StringEntity stringEntity = new StringEntity(requestXmlText, "utf-8");

            request.addHeader("soapAction", "Credit");
            request.addHeader("Accept", "text/xml");
            request.addHeader("Content-Type", "text/xml;charset=utf-8");
            request.setEntity(stringEntity);

            CloseableHttpResponse response = client.execute(request);// Execute the command

            int statusCode = response.getStatusLine().getStatusCode();
// Get the status code and assert
            System.out.println("Status code: " + statusCode);

            Assert.assertEquals(200, statusCode);

            String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");

// Getting the Response body
            System.out.println(responseString);

            XmlPath jsXpath = new XmlPath(responseString);
            String textResult = jsXpath.getString("respDescription");
            System.out.println("result: " + textResult );

        }

        catch (Exception ex)

        {
            System.out.println("Error." + ex.toString());
        }

    }

}

Also don't forget to add the following lines to your POM.XML in order to import all requred libraries

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>BalanceadorLineas</groupId>
  <artifactId>BalanceadorLineas</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>

      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>

    <dependency>
        <groupId>org.springframework.restdocs</groupId>
        <artifactId>spring-restdocs-restassured</artifactId>
        <version>2.0.4.RELEASE</version>
    </dependency>

    <dependency>
    <groupId>org.scala-js</groupId>
    <artifactId>scalajs-junit-test-runtime_2.11</artifactId>
    <version>1.1.0</version>
</dependency>

  </dependencies>
</project>

Finally the pain is over! Hope it works for you too.


问:
How do I add an object array to the Route Value when I submit a form?
I have an MVC view with a bunch of inputs.  When I submit the form, I want to add an object array to the route values, in addition to passing the model.  Basically I have a child grid on the page that users can add/remove items.  I don't want to save the changes until they are ready to save the entire page.

I have seen elsewhere on Stack Overflow how to add a field to the routing by using a hidden field, but how would I do an array of objects?

My View:

```<code>    using (Html.BeginForm("SaveThis", "Report", FormMethod.Post, new { @style = "width: 100%;", @id = "myPage" }))
    {
        //bunch of fields
        <div class="col-md-6">
            <input type="button" value="Submit" onclick="submitForm(this)" class="btn btn-default btn-block bg-MBRBlue" />
        </div>
    }
</code>```

The javascript I currently have:

```

<p>The Controller code I would pass this to:</p>

<pre class="lang-cs prettyprint-override"><code>    [HttpPost]
    public ActionResult SaveThis(MyViewModel viewModel, GridDataViewModel[] gridData)
    {
        //code to save model info here

        //code to create/update/delete grid stuff here
    }
</code>```

Any help would be much appreciated.

答:
I don't know if there's a better way, but i solved this by using Editor Templates like below:

Class Models:

```<code>public class MyViewModel
{
    public int? Id { get; set; }
    public string Name { get; set; }

    public List<GridDataViewModel> GridDataViewModels { get; set; }
}

class GridDataViewModel
{
    public int Id { get; set; }
    public string Value { get; set; }
}
</code>```

MyViewModel view:

```<code>   <form asp-action="Create">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="Id" class="control-label"></label>
            <input asp-for="Id" class="form-control" />
            <span asp-validation-for="Id" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="Name" class="control-label"></label>
            <input asp-for="Name" class="form-control" />
            <span asp-validation-for="Name" class="text-danger"></span>
        </div>

        @Html.EditorFor(m => m.GridDataViewModels)

        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-primary" />
        </div>
    </form>
</code>```

Then you add a new directory inside your view directory called "EditorTemplates" and inside it you add a new view with the exactly name of your ViewModel list. In this example i put the name "GridDataViewModel.cshtml".

Inside view of editor templates you put:

```<code>@model WebApplication1.Models.GridDataViewModel
<div class="form-group">
     <label asp-for="Id" class="control-label"></label>
     <input asp-for="Id" class="form-control" />
     <span asp-validation-for="Id" class="text-danger"></span>
</div>
<div class="form-group">
     <label asp-for="Value" class="control-label"></label>
     <input asp-for="Value" class="form-control" />
     <span asp-validation-for="Value" class="text-danger"></span>
</div>
</code>```

When you post your list will be inside your MyViewModel param. You can explore more things, but i think that this will give you some ideas.

This is my first answer, forgive me if i committed some english mistakes or my answer is not in the best format.

Body:
I have an MVC view with a bunch of inputs.  When I submit the form, I want to add an object array to the route values, in addition to passing the model.  Basically I have a child grid on the page that users can add/remove items.  I don't want to save the changes until they are ready to save the entire page.

I have seen elsewhere on Stack Overflow how to add a field to the routing by using a hidden field, but how would I do an array of objects?

My View:

    using (Html.BeginForm("SaveThis", "Report", FormMethod.Post, new { @style = "width: 100%;", @id = "myPage" }))
    {
        //bunch of fields

            <input type="button" value="Submit" onclick="submitForm(this)" class="btn btn-default btn-block bg-MBRBlue" />

    }

The javascript I currently have:

The Controller code I would pass this to:

    [HttpPost]
    public ActionResult SaveThis(MyViewModel viewModel, GridDataViewModel[] gridData)
    {
        //code to save model info here

        //code to create/update/delete grid stuff here
    }

Any help would be much appreciated.

Body:
I don't know if there's a better way, but i solved this by using Editor Templates like below:

Class Models:

public class MyViewModel
{
    public int? Id { get; set; }
    public string Name { get; set; }

    public List<GridDataViewModel> GridDataViewModels { get; set; }
}

class GridDataViewModel
{
    public int Id { get; set; }
    public string Value { get; set; }
}

MyViewModel view:

   <form asp-action="Create">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="Id" class="control-label"></label>
            <input asp-for="Id" class="form-control" />
            <span asp-validation-for="Id" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="Name" class="control-label"></label>
            <input asp-for="Name" class="form-control" />
            <span asp-validation-for="Name" class="text-danger"></span>
        </div>

        @Html.EditorFor(m => m.GridDataViewModels)

        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-primary" />
        </div>
    </form>

Then you add a new directory inside your view directory called "EditorTemplates" and inside it you add a new view with the exactly name of your ViewModel list. In this example i put the name "GridDataViewModel.cshtml".

Inside view of editor templates you put:

@model WebApplication1.Models.GridDataViewModel
<div class="form-group">
     <label asp-for="Id" class="control-label"></label>
     <input asp-for="Id" class="form-control" />
     <span asp-validation-for="Id" class="text-danger"></span>
</div>
<div class="form-group">
     <label asp-for="Value" class="control-label"></label>
     <input asp-for="Value" class="form-control" />
     <span asp-validation-for="Value" class="text-danger"></span>
</div>

When you post your list will be inside your MyViewModel param. You can explore more things, but i think that this will give you some ideas.

This is my first answer, forgive me if i committed some english mistakes or my answer is not in the best format.


问:
Inconsitent results with same logic inside and outside a function
I am writing code to check how many times the string "TIME_DATA" shows up in my log file. I am new to Python so I wrote out the logic then put the logic inside a function to modularize it for my final task.

However when I uncomment the logic outisde of the function I get inconsistent results between the two. So the code is suppose to print out "time data complete" if the count is greater than 7. With the same logic in the two seperate scopes, the top logic returns "time data complete" but this same logic when called after returns "imcomplete time data". Why is this?:

```<code>tfile = open ('timetest.log', 'r')
tflines1 = tfile.readlines()

time_data_count = 0
for line in tflines1:
    if 'TIME_DATA' in line :
        time_data_count += 1
if time_data_count > 7 :
    print("time_data complete")
else:
    print("incomplete time_data data")

def file_check (f):
    tflines = f.readlines()
    time_data_count = 0
    for line in tflines:
        if 'TIME_DATA' in line:
            time_data_count += 1
    if time_data_count > 7:
        return "time_data complete"
    else:
        return "incomplete time_data data"

print(file_check(tfile))
</code>```

Why does it pass for the top but not for the bottom in the file_check function

If I comment out the top part, the logic outside the function, the file_check function behaves as it should and returns "time_data complete"

答:
Using tfile.readlines() moves the file pointer to the end of the file, so when you try to read it again it returns an empty list. Try adding f.seek(0) to your function like so:

def file_check(f):
    f.seek(0)
    tflines = f.readlines()
    time_data_count = 0
    for line in tflines:
        if 'TIME_DATA' in line:
            time_data_count += 1
    if time_data_count > 7:
        return "time_data complete"
    else:
        return "incomplete time_data data"
```

You could also just store the lines in a list instead of reading them twice.

Body:
I am writing code to check how many times the string "TIME_DATA" shows up in my log file. I am new to Python so I wrote out the logic then put the logic inside a function to modularize it for my final task.

However when I uncomment the logic outisde of the function I get inconsistent results between the two. So the code is suppose to print out "time data complete" if the count is greater than 7. With the same logic in the two seperate scopes, the top logic returns "time data complete" but this same logic when called after returns "imcomplete time data". Why is this?:

tfile = open ('timetest.log', 'r')
tflines1 = tfile.readlines()

time_data_count = 0
for line in tflines1:
    if 'TIME_DATA' in line :
        time_data_count += 1
if time_data_count > 7 :
    print("time_data complete")
else:
    print("incomplete time_data data")

def file_check (f):
    tflines = f.readlines()
    time_data_count = 0
    for line in tflines:
        if 'TIME_DATA' in line:
            time_data_count += 1
    if time_data_count > 7:
        return "time_data complete"
    else:
        return "incomplete time_data data"

print(file_check(tfile))

Why does it pass for the top but not for the bottom in the file_check function

If I comment out the top part, the logic outside the function, the file_check function behaves as it should and returns "time_data complete"

Body:
Using tfile.readlines() moves the file pointer to the end of the file, so when you try to read it again it returns an empty list. Try adding f.seek(0) to your function like so:

def file_check(f):
    f.seek(0)
    tflines = f.readlines()
    time_data_count = 0
    for line in tflines:
        if 'TIME_DATA' in line:
            time_data_count += 1
    if time_data_count > 7:
        return "time_data complete"
    else:
        return "incomplete time_data data"

You could also just store the lines in a list instead of reading them twice.


问:
FFMPEG - preview the FFMPEG command syntax before executing it
Before executing the FFMPEG command line syntax, can we preview the command syntax, whether its is the actual we needed.

if so, pl provide a simple FFMPEG command syntax for Crop.

答:
Use ffplay:

```<code>ffplay -vf crop=iw/2:ih/2 video.mp4
</code>```

Or ffmpeg (if yours supports SDL output):

```<code>ffmpeg -i input.mp4 -vf realtime,crop=iw/2:ih/2 -f sdl -
</code>```

Or mpv:

```<code>mpv input.mp4 --vf=crop=iw/2:ih/2
</code>```

or VLC:

Tools → Effects and Filters (Ctrl+E) → Video Effects → Crop

Body:
Use ffplay:

ffplay -vf crop=iw/2:ih/2 video.mp4

Or ffmpeg (if yours supports SDL output):

ffmpeg -i input.mp4 -vf realtime,crop=iw/2:ih/2 -f sdl -

Or mpv:

mpv input.mp4 --vf=crop=iw/2:ih/2

or VLC:

Tools → Effects and Filters (Ctrl+E) → Video Effects → Crop


问:
Python: getopt, batch files, and paths with spaces
I'm using getopt to parse options and arguments.
I wrote a batch file to call a python script so I don't have to type the same command over and over.

When I printed out the list of arguments, the path was split on spaces and each was parsed separately.

The path is enclosed in double quotes, but I'm not sure what the problem is. Is it the batch file, or is getopt not treating it as one string?

If so, what alternatives can I use to correctly parse the options and arguments (especially paths with spaces)?

EDIT: nvm, found the problem. I was putting double quotes around the loop variable in the batch file (ie: "%%X"). It already had double quotes so when I put my own double quotes the path itself was no longer a single string =(

答:
We'll need to see code to be sure but make sure you quote the argument everywhere not just on the command line.

Command line...

```<code>$script.sh "/my/path with/spaces"
</code>```

Bash Script...

```<code>#!/bin/bash
python /path/to/script "$1"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We'll need to see code to be sure but make sure you quote the argument everywhere not just on the command line.

Command line...

$script.sh "/my/path with/spaces"

Bash Script...

#!/bin/bash
python /path/to/script "$1"


问:
What's the link to my DevOps repo for integration with Git?
I'm using Git to pull a remote branch. My project name is AZ and the name of the repo is Working. My assumption was the link would be https://AltaZia.visualstudio.com/AZ but when trying to pull from that location I get a "fatal: not a git repository" error.

Any help is appreciated.

答:
This usually means that you tried to run a git command but you are not in a Git repository. You can use

```<code>git status
</code>```

Check this out

OR
If you're stuck with a URL to pull from, then

Check this out

Body:
This usually means that you tried to run a git command but you are not in a Git repository. You can use

git status

Check this out

OR
If you're stuck with a URL to pull from, then

Check this out


问:
Terraform - Resource dependency on module
I have a Terraform module, which we'll call parent and a child module used inside of it that we'll refer to as child. The goal is to have the child module run the provisioner before the kubernetes_deployment resource is created. Basically, the child module builds and pushes a Docker image. If the image is not already present, the kubernetes_deployment will wait and eventually timeout because there's no image for the Deployment to use for creation of pods. I've tried everything I've been able to find online, output variables in the child module, using depends_on in the kubernetes_deployment resource, etc and have hit a wall. I would greatly appreciate any help!

parent.tf

```<code>module "child" {
  source       = ".\\child-module-path"
  ...
}

resource "kubernetes_deployment" "kub_deployment" {
  ...
}

</code>```

child-module-path\child.tf

```<code>data "external" "hash_folder" {
  program = ["powershell.exe", "${path.module}\\bin\\hash_folder.ps1"]
}

resource "null_resource" "build" {
  triggers = {
    md5 = data.external.hash_folder.result.md5
  }

  provisioner "local-exec" {
    command     = "${path.module}\\bin\\build.ps1 ${var.argument_example}"
    interpreter = ["powershell.exe"]
  }
}
</code>```

Example Terraform error output:

```<code>module.parent.kubernetes_deployment.kub_deployment: Still creating... [10m0s elapsed]
 Error output:
 Error: Waiting for rollout to finish: 0 of 1 updated replicas are available...
</code>```

答:
In your child module, declare an output value that depends on the null resource that has the provisioner associated with it:

```<code>output "build_complete" {
  # The actual value here doesn't really matter,
  # as long as this output refers to the null_resource.
  value = null_resource.build.triggers.md5
}
</code>```

Then in your "parent" module, you can either make use of module.child.build_complete in an expression (if including the MD5 string in the deployment somewhere is useful), or you can just declare that the resource depends on the output.

```<code>resource "kubernetes_deployment" "example" {
  depends_on = [module.child.build_complete]

  ...
}
</code>```

Because the output depends on the null_resource and the kubernetes_deployment depends on the output, transitively the kubernetes_deployment now effectively depends on the null_resource, creating the ordering you wanted.

Body:
I have a Terraform module, which we'll call parent and a child module used inside of it that we'll refer to as child. The goal is to have the child module run the provisioner before the kubernetes_deployment resource is created. Basically, the child module builds and pushes a Docker image. If the image is not already present, the kubernetes_deployment will wait and eventually timeout because there's no image for the Deployment to use for creation of pods. I've tried everything I've been able to find online, output variables in the child module, using depends_on in the kubernetes_deployment resource, etc and have hit a wall. I would greatly appreciate any help!

parent.tf

module "child" {
  source       = ".\\child-module-path"
  ...
}

resource "kubernetes_deployment" "kub_deployment" {
  ...
}

child-module-path\child.tf

data "external" "hash_folder" {
  program = ["powershell.exe", "${path.module}\\bin\\hash_folder.ps1"]
}

resource "null_resource" "build" {
  triggers = {
    md5 = data.external.hash_folder.result.md5
  }

  provisioner "local-exec" {
    command     = "${path.module}\\bin\\build.ps1 ${var.argument_example}"
    interpreter = ["powershell.exe"]
  }
}

Example Terraform error output:

module.parent.kubernetes_deployment.kub_deployment: Still creating... [10m0s elapsed]
 Error output:
 Error: Waiting for rollout to finish: 0 of 1 updated replicas are available...

Body:
In your child module, declare an output value that depends on the null resource that has the provisioner associated with it:

output "build_complete" {
  # The actual value here doesn't really matter,
  # as long as this output refers to the null_resource.
  value = null_resource.build.triggers.md5
}

Then in your "parent" module, you can either make use of module.child.build_complete in an expression (if including the MD5 string in the deployment somewhere is useful), or you can just declare that the resource depends on the output.

resource "kubernetes_deployment" "example" {
  depends_on = [module.child.build_complete]

  ...
}

Because the output depends on the null_resource and the kubernetes_deployment depends on the output, transitively the kubernetes_deployment now effectively depends on the null_resource, creating the ordering you wanted.


问:
R - Find if characters of a vector are in another vector
I have a doubt very similar to this topic here: Find matches of a vector of strings in another vector of strings.

I have a vector of clients, and if the name indicates that is a commercial client, I need to change the type in my data.frame.

So, suppose that:

```<code>commercial_names <- c("BAKERY","MARKET", "SCHOOL", "CINEMA")
clients <- c("JOHN XX","REESE YY","BAKERY ZZ","SAMANTHA WW")
</code>```

I tried the code in the topic cited before, but I had an error:

```<code>> grepl(paste(commercial_names, collape="|"),clients)
[1] TRUE TRUE TRUE TRUE
Warning message:
In grepl(paste(commercial_names, collape = "|"), clients) :
  argument 'pattern' has length > 1 and only the first element will be used
</code>```

What am I doing wrong? I would thank any help.

答:
I found another way of to do this, with the command %like% of package data.table:

```<code>> clients %like% paste(commercial_names,collapse = "|")
[1] FALSE FALSE  TRUE FALSE
</code>```

Body:
I have a doubt very similar to this topic here: Find matches of a vector of strings in another vector of strings.

I have a vector of clients, and if the name indicates that is a commercial client, I need to change the type in my data.frame.

So, suppose that:

commercial_names <- c("BAKERY","MARKET", "SCHOOL", "CINEMA")
clients <- c("JOHN XX","REESE YY","BAKERY ZZ","SAMANTHA WW")

I tried the code in the topic cited before, but I had an error:

> grepl(paste(commercial_names, collape="|"),clients)
[1] TRUE TRUE TRUE TRUE
Warning message:
In grepl(paste(commercial_names, collape = "|"), clients) :
  argument 'pattern' has length > 1 and only the first element will be used

What am I doing wrong? I would thank any help.

Body:
I found another way of to do this, with the command %like% of package data.table:

> clients %like% paste(commercial_names,collapse = "|")
[1] FALSE FALSE  TRUE FALSE


问:
How to join in swarm using the tutorial, Hyperledger fabric on multiple hosts by wahab
In the tutorial:
https://medium.com/@wahabjawed/hyperledger-fabric-on-multiple-hosts-a33b08ef24f
We are struck on some point,

My doubts are:

"docker swarm init" command need to execute in both PC's or only in PC1.

After executing "docker swarm join-token manager" command in PC1, it produce output like
docker swarm join — token SWMTKN-1–3as8cvf3yxk8e7zj98954jhjza3w75mngmxh543llgpo0c8k7z-61zyibtaqjjimkqj8p6t9lwgu 172.16.0.153:2377

We copy it and execute it on PC2 terminal to make it join PC1,
In this step we are getting error like: Error response from daemon: Timeout was reached before node joined. The attempt to join the swarm will continue in the background. Use the "docker info" command to see the current swarm status of your node.

If we try to execute "docker swarm join" another time, it is showing error like: Error response from daemon: This node is already part of a swarm. Use "docker swarm leave" to leave this swarm and join another one.

If we leave and try to connect docker swarm again, still problem continue like Timeout reached before joined.

Now shall we proceed on PC1 even above error is present or shall we have to wait until PC2 joins in swarm.

How to solve the above problem.

In our case, PC2 running ubuntu on Windows using VMVirtualBox. Is it any problem for our error.
We tried to solve the problem by opening up port numbers and enabling firewall also. But we did not succeed.

Kindly suggest me to solve this problem.

答:
Answers for your questions:

1) No. No need to Swarm init in both the PCs. PC1 alone needs to be initialized.
For the further steps to function make sure that all your PCs are in the same network. I mean in the same internet connection.

If you want to join all PCs accross different network then go through --listen-addr & --advertise-addr in docker swarm.


问:
Ternary operator in perl yields unexpected result when assigning a variable in the statement
I'm trying to make a transition from php to perl and expectedly running into some weirdness.  I cannot understand why one version of my code works vs another.

This fails:

```<code>sub tester
{
$return;
($_[0] < 10) ? $return = "youre a youngin" : $return = "youre an old person";
return $return;
}

print "how old are you?";
$a = <>;
chomp $a;

print  tester($a);  #both result in "youre an old person"
</code>```

however this one works:

```<code>sub tester
{
    return ($_[0] < 10) ? "youre a youngin" : "youre an old person";
}

print "how old are you?";
$a = <>;
chomp $a;
print  tester($a);
</code>```

what is the real difference here?!

答: Basically, operator precedence.</p>

Body:
I'm trying to make a transition from php to perl and expectedly running into some weirdness.  I cannot understand why one version of my code works vs another.

This fails:

sub tester
{
$return;
($_[0] < 10) ? $return = "youre a youngin" : $return = "youre an old person";
return $return;
}

print "how old are you?";
$a = <>;
chomp $a;

print  tester($a);  #both result in "youre an old person"

however this one works:

sub tester
{
    return ($_[0] < 10) ? "youre a youngin" : "youre an old person";
}

print "how old are you?";
$a = <>;
chomp $a;
print  tester($a);

what is the real difference here?!

Body: Basically, operator precedence.


问:
Is it possible for async method to ever return null in C#?
Digging through some old code, I have noticed a call to an asyncmethod and then a check for the task being returned for null.

```<code>async Task<Something> DoSomeStuffAsync()
{
    //...
    return null; //not the actual return, but I guess it doesn't matter
}

var result = DoSomeStuffAsync(); //without await
if(result == null)
{
    //does this part makes any sense
}
</code>```

From my understanding of the async keyword, this scenario will never be possible because the result of an async method will always be wrapped in a Task but just to check, am I missing something?

Is there any case when an async method will return null in C#?

答:
While it's true that DoSomeStuffAsync() could someday be changed into a method that is not async, it's pretty clear that it's intended to be async and you've probably found a bug. The call was probably meant to be awaited. If the call wasn't meant to be awaited (i.e., result was really meant to be a Task) then the null check is pointless, and there should probably be a comment explaining why the call wasn't awaited.

Testing for potential future API changes like it becoming possible for DoSomeStuffAsync() to return null is not something that belongs in production code. Not trusting API contracts and documentation ("Async" in the method name is a form of documentation) and littering code with pointless null checks is characteristic of inexperienced coders.

Body:
Digging through some old code, I have noticed a call to an asyncmethod and then a check for the task being returned for null.

async Task<Something> DoSomeStuffAsync()
{
    //...
    return null; //not the actual return, but I guess it doesn't matter
}

var result = DoSomeStuffAsync(); //without await
if(result == null)
{
    //does this part makes any sense
}

From my understanding of the async keyword, this scenario will never be possible because the result of an async method will always be wrapped in a Task but just to check, am I missing something?

Is there any case when an async method will return null in C#?


问:
Why do we write [0] after get_or_create in model_name.object.get_or_create() in django
A function in Faker script to add data in my model Department.

department = ['I.T.','C.S.E','M.E.','E.C.']
def add_dept():
    d = Department.objects.get_or_create(dept_name=random.choice(depatment))[0]

答:
Because .get_or_create(…) [Django-doc] return a 2-tuple where the first item is the Department object that is constructed or obtained, and the second is a boolean (True or False) that is True if the object was constructed, as specified in the documentation:

Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created.

By adding [0], you thus obtain the first item of the 2-tuple: the department, and thus discard the boolean.


问:
How to stop Excel from mangling a formula inserted by my VBA script
I have a VBA script in an Excel workbook that gathers results from all the workbooks in a particular folder.

```<code>Private Sub Workbook_Open()

    Dim path As String
    Dim fso As Object
    Dim folder As Object
    Dim file As Object

    Dim i As Integer

    Dim data As Object

    Set data = Worksheets("RawData")
    path = data.Range("A1").Value

    i = 3

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder(path)

    data.Rows("2:" & data.Rows.Count).ClearContents

    For Each file In folder.Files
        If Right(UCase(file.name), 5) = ".XLSX" And Left(file.name, 1) <> "~" Then
            data.Cells(i, 2) = "='" + path + "\[" + file.name + "]Summary'!A1:J1"
            i = i + 1
        End If
    Next file

End Sub
</code>```

The idea is for each .xlsx file in a given folder, I add a reference to the results range in that file. For example, if there is a file Test1.xlsx in folder C:\Sheets, the VBA puts the following formula into some row on the sheet containing the script:

```<code>='C:\Sheets\[Test1.xlsx]Summary'!A1:J1
</code>```

Excel then pulls values out of Test1 and puts them in the current workbook's RawData sheet.

This worked until today, when my formulas started ending up with @ right after the = sign, like this:

```<code>=@'C:\Sheets\[Test1.xlsx]Summary'!A1:J1
</code>```

This gives me a #VALUE?.

Excel helpfully gave me a message stating that it has just now started inserting @ into formulas due to some syntax changes, but that it wouldn't affect calculations. I can't get this message to show up again, but that was the gist of it. Obviously it does affect calculations. If I manually remove the @ from the formula, it works fine.

I have Office 365 and I guess I must have received an update recently that added this "feature" because all this used to work fine.

If I modify the VBA script to reference only a single cell, the @ does not get inserted. But using a named range for the results (rather than A1:J1) still has the problem.

Anyone have any ideas for a workaround?

答:
To avoid the @ from being inserted, use the .Formula2 property of the range object.
This change has to do with the dynamic array feature of Excel O365

Body:
I have a VBA script in an Excel workbook that gathers results from all the workbooks in a particular folder.

Private Sub Workbook_Open()

    Dim path As String
    Dim fso As Object
    Dim folder As Object
    Dim file As Object

    Dim i As Integer

    Dim data As Object

    Set data = Worksheets("RawData")
    path = data.Range("A1").Value

    i = 3

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder(path)

    data.Rows("2:" & data.Rows.Count).ClearContents

    For Each file In folder.Files
        If Right(UCase(file.name), 5) = ".XLSX" And Left(file.name, 1) <> "~" Then
            data.Cells(i, 2) = "='" + path + "\[" + file.name + "]Summary'!A1:J1"
            i = i + 1
        End If
    Next file

End Sub

The idea is for each .xlsx file in a given folder, I add a reference to the results range in that file. For example, if there is a file Test1.xlsx in folder C:\Sheets, the VBA puts the following formula into some row on the sheet containing the script:

='C:\Sheets\[Test1.xlsx]Summary'!A1:J1

Excel then pulls values out of Test1 and puts them in the current workbook's RawData sheet.

This worked until today, when my formulas started ending up with @ right after the = sign, like this:

=@'C:\Sheets\[Test1.xlsx]Summary'!A1:J1

This gives me a #VALUE?.

Excel helpfully gave me a message stating that it has just now started inserting @ into formulas due to some syntax changes, but that it wouldn't affect calculations. I can't get this message to show up again, but that was the gist of it. Obviously it does affect calculations. If I manually remove the @ from the formula, it works fine.

I have Office 365 and I guess I must have received an update recently that added this "feature" because all this used to work fine.

If I modify the VBA script to reference only a single cell, the @ does not get inserted. But using a named range for the results (rather than A1:J1) still has the problem.

Anyone have any ideas for a workaround?


问:
How to call one asynchronous function after another?
This is what I have:

```<code>  ngOnInit() {
    this._addServ.getDefaultAddress().subscribe((res)=>{
      if(res.status){
        //I need these next two functions to finish their async API requests
        //before selectNormalDelivery is called
        this.selectShippingAddress();
        this.selectBillingAddress();
        this.selectNormalDelivery();
      }
    })
  }
</code>```

I need selectShippingAddress and selectBillingAddress to finish their calls, and then for selectNormalDelivery to be called. How can I accomplish this? I don't want to convert them into promises as they're called other times without needing to be chained. Is this something involving .then?

This is the code for the functions:

```<code>  selectShippingAddress(){
    this.addressService.setShippingAddresses(this.cartService.shippingAddress.address_id).subscribe((res) => {
      console.log('Set shipping address!')
      console.log(res);
    }, err => {
      console.log('Failed to set shipping address')
      console.log(err);
    })
  }

  selectBillingAddress(){
    this.addressService.setPaymentAddresses(this.cartService.billingAddress.address_id).subscribe((res) => {
      console.log('Set billing address!')
      console.log(res);
    }, err => {
      console.log('Failed to set billing address')
      console.log(err);
    })
  }
</code>```

If I try a .then, I get the error Property 'then' does not exist on type 'void'., which makes sense as I'm not trying to return anything, I just need them to complete their calls for the API's sake.

Suggestions?

答:
```<code>ngOnInit() {
    this._addServ.getDefaultAddress().subscribe((res)=>{
      if(res.status){
        //I need these next two functions to finish their async API requests
        //before selectNormalDelivery is called
        forkJoin([this.selectShippingAddress(),this.selectBillingAddress()].subscribe(() => {

            this.selectNormalDelivery();
        });
      }
    })
  }

 selectShippingAddress(){
    return this.addressService.setShippingAddresses(this.cartService.shippingAddress.address_id).pipe(map((res) => {
      console.log('Set shipping address!')
      console.log(res);
    }, err => {
      console.log('Failed to set shipping address')
      console.log(err);
    }));
  }

  selectBillingAddress(){
    return this.addressService.setPaymentAddresses(this.cartService.billingAddress.address_id).pipe(map((res) => {
      console.log('Set billing address!')
      console.log(res);
    }, err => {
      console.log('Failed to set billing address')
      console.log(err);
    }));
  }
</code>```

Body:
This is what I have:

  ngOnInit() {
    this._addServ.getDefaultAddress().subscribe((res)=>{
      if(res.status){
        //I need these next two functions to finish their async API requests
        //before selectNormalDelivery is called
        this.selectShippingAddress();
        this.selectBillingAddress();
        this.selectNormalDelivery();
      }
    })
  }

I need selectShippingAddress and selectBillingAddress to finish their calls, and then for selectNormalDelivery to be called. How can I accomplish this? I don't want to convert them into promises as they're called other times without needing to be chained. Is this something involving .then?

This is the code for the functions:

  selectShippingAddress(){
    this.addressService.setShippingAddresses(this.cartService.shippingAddress.address_id).subscribe((res) => {
      console.log('Set shipping address!')
      console.log(res);
    }, err => {
      console.log('Failed to set shipping address')
      console.log(err);
    })
  }

  selectBillingAddress(){
    this.addressService.setPaymentAddresses(this.cartService.billingAddress.address_id).subscribe((res) => {
      console.log('Set billing address!')
      console.log(res);
    }, err => {
      console.log('Failed to set billing address')
      console.log(err);
    })
  }

If I try a .then, I get the error Property 'then' does not exist on type 'void'., which makes sense as I'm not trying to return anything, I just need them to complete their calls for the API's sake.

Suggestions?


问:
Apache Airflow - use python result in the next steps
I am working on some simple Apache Airflow DAG. My goal is to:

1. calculate the data parameter based on the DAG run date - I try achieve that by the Python operator.

2. pass the parameter calculated above as a bq query parameter.

Any ideas are welcom.

My code below - I have marked the two points with I am struggling with by the 'TODO' label.

```<code>...

def set_date_param(dag_run_time):
    # a business logic applied here
    ....

    return "2020-05-28" # example result

# --------------------------------------------------------
# DAG definition below
# --------------------------------------------------------

# Python operator
set_data_param = PythonOperator(
  task_id='set_data_param',
  python_callable=set_data_param,
  provide_cotext=True,
  op_kwargs={
    "dag_run_date": #TODO - how to pass the DAG running date as a function input parameter
  },
  dag=dag
)

# bq operator
load_data_to_bq_table = BigQueryOperator(
    task_id='load_data_to_bq_table',
    sql="""SELECT ccustomer_id, sales
    FROM `my_project.dataset1.table1`
    WHERE date_key = {date_key_param}
    """.format(
       date_key_param =
   ), #TODO - how to get the python operator results from the previous step
    use_legacy_sql=False,
    destination_dataset_table="my_project.dataset2.table2}",
    trigger_rule='all_success',
    dag=dag
)

set_data_param >> load_data_to_bq_table
</code>```

答:
For PythonOperator to pass the execution date to the python_callable, you only need to set provide_cotext=True (as it has been already done in your example). This way, Airflow automatically passes a collection of keyword arguments to the python callable, such that the names and values of these arguments are equivalent to the template variables described here. That is, if you define the python callable as set_data_param(ds, **kwargs): ..., the ds parameter will automatically get the execution date as a string value in the format YYYY-MM-DD.

XCOM allows task instances to exchange messages. To use the date returned by set_date_param() inside the sql query string of BigQueryOperator, you can combine XCOM with Jinja templating:

```<code>sql="""SELECT ccustomer_id, sales
    FROM `my_project.dataset1.table1`
    WHERE date_key = {{ task_instance.xcom_pull(task_ids='set_data_param') }}
    """
</code>```

The following complete example puts all pieces together. In the example, the get_date task creates a date string based on the execution date. After that, the use_date task uses XCOM and Jinja templating to retrieve the date string and writes it to a log.

```<code>import logging
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from airflow.utils.dates import days_ago

default_args = {'start_date': days_ago(1)}

def calculate_date(ds, execution_date, **kwargs):
    return f'{ds} ({execution_date.strftime("%m/%d/%Y")})'

def log_date(date_string):
    logging.info(date_string)

with DAG(
    'a_dag',
    schedule_interval='*/5 * * * *',
    default_args=default_args,
    catchup=False,
) as dag:
    get_date = PythonOperator(
        task_id='get_date',
        python_callable=calculate_date,
        provide_context=True,
    )
    use_date = PythonOperator(
        task_id='use_date',
        python_callable=log_date,
        op_args=['Date: {{ task_instance.xcom_pull(task_ids="get_date") }}'],
    )
get_date >> use_date
</code>```

Body:
I am working on some simple Apache Airflow DAG. My goal is to:

1. calculate the data parameter based on the DAG run date - I try achieve that by the Python operator.

2. pass the parameter calculated above as a bq query parameter.

Any ideas are welcom.

My code below - I have marked the two points with I am struggling with by the 'TODO' label.

...

def set_date_param(dag_run_time):
    # a business logic applied here
    ....

    return "2020-05-28" # example result

# --------------------------------------------------------
# DAG definition below
# --------------------------------------------------------

# Python operator
set_data_param = PythonOperator(
  task_id='set_data_param',
  python_callable=set_data_param,
  provide_cotext=True,
  op_kwargs={
    "dag_run_date": #TODO - how to pass the DAG running date as a function input parameter
  },
  dag=dag
)

# bq operator
load_data_to_bq_table = BigQueryOperator(
    task_id='load_data_to_bq_table',
    sql="""SELECT ccustomer_id, sales
    FROM `my_project.dataset1.table1`
    WHERE date_key = {date_key_param}
    """.format(
       date_key_param =
   ), #TODO - how to get the python operator results from the previous step
    use_legacy_sql=False,
    destination_dataset_table="my_project.dataset2.table2}",
    trigger_rule='all_success',
    dag=dag
)

set_data_param >> load_data_to_bq_table

Body:
For PythonOperator to pass the execution date to the python_callable, you only need to set provide_cotext=True (as it has been already done in your example). This way, Airflow automatically passes a collection of keyword arguments to the python callable, such that the names and values of these arguments are equivalent to the template variables described here. That is, if you define the python callable as set_data_param(ds, **kwargs): ..., the ds parameter will automatically get the execution date as a string value in the format YYYY-MM-DD.

XCOM allows task instances to exchange messages. To use the date returned by set_date_param() inside the sql query string of BigQueryOperator, you can combine XCOM with Jinja templating:

sql="""SELECT ccustomer_id, sales
    FROM `my_project.dataset1.table1`
    WHERE date_key = {{ task_instance.xcom_pull(task_ids='set_data_param') }}
    """

The following complete example puts all pieces together. In the example, the get_date task creates a date string based on the execution date. After that, the use_date task uses XCOM and Jinja templating to retrieve the date string and writes it to a log.

import logging
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from airflow.utils.dates import days_ago

default_args = {'start_date': days_ago(1)}

def calculate_date(ds, execution_date, **kwargs):
    return f'{ds} ({execution_date.strftime("%m/%d/%Y")})'

def log_date(date_string):
    logging.info(date_string)

with DAG(
    'a_dag',
    schedule_interval='*/5 * * * *',
    default_args=default_args,
    catchup=False,
) as dag:
    get_date = PythonOperator(
        task_id='get_date',
        python_callable=calculate_date,
        provide_context=True,
    )
    use_date = PythonOperator(
        task_id='use_date',
        python_callable=log_date,
        op_args=['Date: {{ task_instance.xcom_pull(task_ids="get_date") }}'],
    )
get_date >> use_date


问:
Do I need OAuth to get public twitter status updates?
I just need to retrieve a public user feed, but some aspects of Twitter's documentation are terrible (unless someone else knows of a "What you can do with the API" page). Do I need to use OAuth for something as simple as that? Does registering an application with Twitter make it public in any way? (I would expect not, but the "Application Name" must be unique, which makes me worry.)</p>

答:
Using Twitter API v1 you do not need OAuth to retrieve public user_timelines. OAuth could be useful for an increased rate limit however.

In Twitter API v1.1 authentication with OAuth is required for all API requests.


问:
AWS Api Gateway Custom Domain Name with undefined stage
I'm trying to set up a Custom Domain Name in AWS API Gateway where callers have to specify explicitly the stage name after any base path name. It is something I did in the past but now it seems that, since AWS updated the console interface, it is no more possible.
The final url should be like:

https://example.com/{basePath}/{stage}/function

I tried using the console, but stage is now a mandatory field (chose from a drop-down).

I tried using AWS CLI, but stage is again a mandatory field

aws: error: the following arguments are required: --stage

I tried using Boto3, following the documentation (https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/apigateway.html#APIGateway.Client.create_base_path_mapping) but, even if stage can be specified as 'none' (The name of the API's stage that you want to use for this mapping. Specify '(none)' if you want callers to explicitly specify the stage name after any base path name.), doing this returns an error:

botocore.errorfactory.BadRequestException: An error occurred (BadRequestException) when calling the CreateBasePathMapping operation: Invalid stage identifier specified

What is funny (or frustrating) is that I have some custom domain names created with the old console and that are perfectly working, without any stage defined.

答:
It is still possible to specify only the "API ID" and "Path" and leave out the "stage" parameter. I have tried this both from the console and the CLI:

From console: The "Stage" setting is a drop-down as you mentioned, but can be left blank (don't select anything). If you did select a stage, delete the API mapping and add it again

From CLI: Just tried this as well and works fine for me on CLI version aws-cli/1.18.69 Python/3.7.7 Darwin/18.7.0 botocore/1.16.19

```<code>$ aws apigateway create-base-path-mapping --domain-name **** --rest-api-id *** --base-path test
{
    "basePath": "test",
    "restApiId": "***"
}
</code>```

Body:
It is still possible to specify only the "API ID" and "Path" and leave out the "stage" parameter. I have tried this both from the console and the CLI:

From console: The "Stage" setting is a drop-down as you mentioned, but can be left blank (don't select anything). If you did select a stage, delete the API mapping and add it again

From CLI: Just tried this as well and works fine for me on CLI version aws-cli/1.18.69 Python/3.7.7 Darwin/18.7.0 botocore/1.16.19

$ aws apigateway create-base-path-mapping --domain-name **** --rest-api-id *** --base-path test
{
    "basePath": "test",
    "restApiId": "***"
}


问:
I'm having issues using generators with the input function in python 3
```<code>def prime():
    n = 1000
    if n<2:
        return 0
    yield 2
    x = 3
    while x <= n:
        for i in range(3,x,2):
            if x%i==0:
                x+=2
                break
        else:
            yield x
            x+=2

#if i try to call each yielded value with an input function i don't get anything!

def next_prime():
    generator = prime()
    y = input('Find next prime? yes/no or y/n: ')
    if y[0].lower == 'y':
        print(generator.next())

next_prime()

#but if i call the function without using an input i get my values back

generator = prime()
def next_prime():
    print(next(generator))

next_prime()
</code>```

How do I make the first next_prime function work with the input function. If I try to call each yielded value with an input function, I don't get anything but if I call the function without using an input, I get my values back. Is it that generators don't work with the input function?

答:
The mistake you have done is you have forgot the round brackets of the lower keyword</p>

```<code>def next_prime():
    generator = prime()
    y = input('Find next prime? yes/no or y/n: ')
    #forgot the round brackets
    if y[0].lower() == 'y':
        print(next(generator))

next_prime()
</code>```

Body:
def prime():
    n = 1000
    if n<2:
        return 0
    yield 2
    x = 3
    while x <= n:
        for i in range(3,x,2):
            if x%i==0:
                x+=2
                break
        else:
            yield x
            x+=2

#if i try to call each yielded value with an input function i don't get anything!

def next_prime():
    generator = prime()
    y = input('Find next prime? yes/no or y/n: ')
    if y[0].lower == 'y':
        print(generator.next())

next_prime()

#but if i call the function without using an input i get my values back

generator = prime()
def next_prime():
    print(next(generator))

next_prime()

How do I make the first next_prime function work with the input function. If I try to call each yielded value with an input function, I don't get anything but if I call the function without using an input, I get my values back. Is it that generators don't work with the input function?

Body:
The mistake you have done is you have forgot the round brackets of the lower keyword

def next_prime():
    generator = prime()
    y = input('Find next prime? yes/no or y/n: ')
    #forgot the round brackets
    if y[0].lower() == 'y':
        print(next(generator))

next_prime()


问:
I have a problem with the in django search function
I have a problem with my search function.
He's tasked to search for movies by name
and I don't know how to write it and it works

My Views:

```<code>class AllMovies(ListView):
    model = Movie
    template_name = 'All_movies.html'
    cats = Category.objects.all()

    def get_context_data(self, *args, **kwargs):
        cat_menu = Category.objects.all()
        search_term = ''
        context = super(AllMovies, self).get_context_data(*args, **kwargs)
        context["cat_menu"] = cat_menu
        return context

    def search(request):  # wszytskie filmy (lista)
        movier = Movie.objects.all()

        search_term = ''
        if 'search' in request.GET:
            search_term = request.GET['search']
            movier = Movie.objects.filter(name__icontains=search_term)
        paginator = Paginator(movier, 30)
        page = request.GET.get('page')
        movier = paginator.get_page(page)
        get_dict_copy = request.GET.copy()
        params = get_dict_copy.pop('page', True) and get_dict_copy.urlencode()

        return render(request, 'AllMovies.html',
              {'movie': movie, 'params': params, 'search_term': search_term})
</code>```

Here, two functions should be divided and combined, but I don't know how

My urls:

```<code>   path("AllMovies/", AllMovies.as_view(), name="AllMovies"),
</code>```

My templates:

```<code>    <form class="form-inline">
             <input class="form-control mr-sm-2 " align="middle" type="search" placeholder="Name Movie"
                     aria-label="Search" name='search' value = "{{ search_term }}">
              <button class="btn btn-success my-2 my-sm-0" type="submit">Search</button>
     </form>
</code>```

The most important thing is for the search engine to work.
Help me!

答:
Here is a way to implement the search in your ListView getting your queryset parameter:</p>

```<code>class AllMovies(ListView):
    model = Movie
    template_name = 'All_movies.html'
    cats = Category.objects.all()

    if 'search' in request.GET and request.GET['search']:
        search_term = request.GET.get('search')
        movier = Movie.objects.filter(name__icontains=search_term)

    #...
</code>```

Body:
I have a problem with my search function.
He's tasked to search for movies by name
and I don't know how to write it and it works

My Views:

class AllMovies(ListView):
    model = Movie
    template_name = 'All_movies.html'
    cats = Category.objects.all()

    def get_context_data(self, *args, **kwargs):
        cat_menu = Category.objects.all()
        search_term = ''
        context = super(AllMovies, self).get_context_data(*args, **kwargs)
        context["cat_menu"] = cat_menu
        return context

    def search(request):  # wszytskie filmy (lista)
        movier = Movie.objects.all()

        search_term = ''
        if 'search' in request.GET:
            search_term = request.GET['search']
            movier = Movie.objects.filter(name__icontains=search_term)
        paginator = Paginator(movier, 30)
        page = request.GET.get('page')
        movier = paginator.get_page(page)
        get_dict_copy = request.GET.copy()
        params = get_dict_copy.pop('page', True) and get_dict_copy.urlencode()

        return render(request, 'AllMovies.html',
              {'movie': movie, 'params': params, 'search_term': search_term})

Here, two functions should be divided and combined, but I don't know how

My urls:

   path("AllMovies/", AllMovies.as_view(), name="AllMovies"),

My templates:

    <form class="form-inline">
             <input class="form-control mr-sm-2 " align="middle" type="search" placeholder="Name Movie"
                     aria-label="Search" name='search' value = "{{ search_term }}">
              <button class="btn btn-success my-2 my-sm-0" type="submit">Search</button>
     </form>

The most important thing is for the search engine to work.
Help me!

Body:
Here is a way to implement the search in your ListView getting your queryset parameter:

class AllMovies(ListView):
    model = Movie
    template_name = 'All_movies.html'
    cats = Category.objects.all()

    if 'search' in request.GET and request.GET['search']:
        search_term = request.GET.get('search')
        movier = Movie.objects.filter(name__icontains=search_term)

    #...


问:
Spring RequestMapping with custom isLoggedIn parameter
I've been searching internet for several hours now, and cannot find a way to add my own variables into request mapping.

We are using a custom user authentication system. And I want to serve 2 different controllers for the same path depending on if the user is authenticated or not. More specifically, I want to create controllers that only mapped to if the user is not authenticated.

How can I achieve something like this: (I want to define isLoggedIn myself).

```<code>public class PageController {
  @RequestMapping(value = "/page", isLoggedIn = false)
  @ResponseBody
  String getPage(){
    return "Page content";
  }
}
</code>```

I want request to hit this controller if user is not logged in, and fallback to catch all if user is logged in. I am open to solutions using Interceptors, Custom Annotations, or extending RequestMapping or anything else.

答:
```<code>@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(
        method = {RequestMethod.GET}
)
public @interface CustomGetRequestMapping {

    @AliasFor(value = "value", annotation = RequestMapping.class)
    String path();

    boolean isLoggedIn() default false;
}
</code>```

I guess this is not enough because you have to write interceptor and catch the logged in user.

Body:
I've been searching internet for several hours now, and cannot find a way to add my own variables into request mapping.

We are using a custom user authentication system. And I want to serve 2 different controllers for the same path depending on if the user is authenticated or not. More specifically, I want to create controllers that only mapped to if the user is not authenticated.

How can I achieve something like this: (I want to define isLoggedIn myself).

public class PageController {
  @RequestMapping(value = "/page", isLoggedIn = false)
  @ResponseBody
  String getPage(){
    return "Page content";
  }
}

I want request to hit this controller if user is not logged in, and fallback to catch all if user is logged in. I am open to solutions using Interceptors, Custom Annotations, or extending RequestMapping or anything else.

Body:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(
        method = {RequestMethod.GET}
)
public @interface CustomGetRequestMapping {

    @AliasFor(value = "value", annotation = RequestMapping.class)
    String path();

    boolean isLoggedIn() default false;
}

I guess this is not enough because you have to write interceptor and catch the logged in user.


答: did you clone the git repository correctly from azure and are you in the correct folder?</p>

Title: What's the link to my DevOps repo for integration with Git?

Body:
I'm using Git to pull a remote branch. My project name is AZ and the name of the repo is Working. My assumption was the link would be https://AltaZia.visualstudio.com/AZ but when trying to pull from that location I get a "fatal: not a git repository" error.

Any help is appreciated.


问:
Plotly Bar Chart Not showing Zip Code Correctly on xaxis
I'm creating a Bar Chart with the top 10 highest amounts for each zip code. I've converted the zip code to a string, but in the Bar Chart the x axis is showing as an int 20K, 50K, etc. When checking the astype on zip code it return object type instead of string. I'm confused. How do I show the zip code on the x axis (i.e. '95519', '47905', '44720')?

```<code>Data Set is as follows
        zip code  index
54      95519        1.70
61      81212        1.70
160     47905        1.70
421     57201        1.70
208      1930        1.69
366     44720        1.69
298     28401        1.68
532     82214        1.68
102     30165        1.67
125     50501        1.67

df3 = df2[['zip code', 'index']]
df3 = df3.nlargest(10, 'index')

 df3['zip code'] = df3[['zip code']].astype(str)

 fig = px.bar(df3, x='zip code', y='index',
         hover_data=['zip code', 'index'], color='index',
         labels={'index':'INDEX'}, height=400)
</code>```

答:
If you add fig.update_xaxes(type='category') your code will work, as this ensures that the zip code is treated as categorical rather than numerical.

```<code>import pandas as pd
import plotly.express as px

df3 = pd.DataFrame({'zip code': [95519, 81212, 47905, 57201, 1930, 44720, 28401, 82214, 30165, 50501],
                    'index': [1.70, 1.70, 1.70, 1.70, 1.69, 1.69, 1.68, 1.68, 1.67, 1.67]})

fig = px.bar(df3, x='zip code', y='index', hover_data=['zip code', 'index'], color='index', labels={'index': 'INDEX'}, height=400)

fig.update_xaxes(type='category')

fig.show()
</code>```

Body:
I'm creating a Bar Chart with the top 10 highest amounts for each zip code. I've converted the zip code to a string, but in the Bar Chart the x axis is showing as an int 20K, 50K, etc. When checking the astype on zip code it return object type instead of string. I'm confused. How do I show the zip code on the x axis (i.e. '95519', '47905', '44720')?

Data Set is as follows
        zip code  index
54      95519        1.70
61      81212        1.70
160     47905        1.70
421     57201        1.70
208      1930        1.69
366     44720        1.69
298     28401        1.68
532     82214        1.68
102     30165        1.67
125     50501        1.67

df3 = df2[['zip code', 'index']]
df3 = df3.nlargest(10, 'index')

 df3['zip code'] = df3[['zip code']].astype(str)

 fig = px.bar(df3, x='zip code', y='index',
         hover_data=['zip code', 'index'], color='index',
         labels={'index':'INDEX'}, height=400)

Body:
If you add fig.update_xaxes(type='category') your code will work, as this ensures that the zip code is treated as categorical rather than numerical.

import pandas as pd
import plotly.express as px

df3 = pd.DataFrame({'zip code': [95519, 81212, 47905, 57201, 1930, 44720, 28401, 82214, 30165, 50501],
                    'index': [1.70, 1.70, 1.70, 1.70, 1.69, 1.69, 1.68, 1.68, 1.67, 1.67]})

fig = px.bar(df3, x='zip code', y='index', hover_data=['zip code', 'index'], color='index', labels={'index': 'INDEX'}, height=400)

fig.update_xaxes(type='category')

fig.show()


问:
How to close the widgte by dragging it down
I wish Widget could close in two ways, the way below and drag Widget down.  </p>

```<code>  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new ... (...),
          floatingActionButton: new FloatingActionButton(
            onPressed: ()=> exit(0),
            tooltip: 'Close app',
            child: new Icon(Icons.close),
          ),
    );
  }```
</code>```

答: You can use the Draggable widget for drag down dismissal.https://api.flutter.dev/flutter/widgets/Draggable-class.html</p>

Body:
I wish Widget could close in two ways, the way below and drag Widget down.

  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new ... (...),
          floatingActionButton: new FloatingActionButton(
            onPressed: ()=> exit(0),
            tooltip: 'Close app',
            child: new Icon(Icons.close),
          ),
    );
  }```


问:
Matplotlib plot for loop issue
I'm trying to plot time series data in matplotlib using a for loop.  The goal is to dynamically plot 'n' years worth of daily closing price data.  If i load 7 years of data, I get 7 unique plots.  I have created a summary of the start and end dates for a data set, yearly_date_ranges (date is the index).  I use this to populate start and end dates.  The code I've written so far produces 7 plots of all daily data instead of 7 unique plots, one for each year.  Any help is appreciated. Thanks in advance!</p>

```<code>    yearly_date_ranges
              start        end
    Date
    2014 2014-04-01 2014-12-31
    2015 2015-01-01 2015-12-31
    2016 2016-01-01 2016-12-31
    2017 2017-01-01 2017-12-31
    2018 2018-01-01 2018-12-31
    2019 2019-01-01 2019-12-31
    2020 2020-01-01 2020-05-28

    import pandas as pd
    import matplotlib.pyplot as plt
    %matplotlib inline

    fig = plt.figure(figsize=(12,20))
    for i in range(len(yearly_date_ranges)):
        ax = fig.add_subplot(len(yearly_date_ranges),1,i + 1)
        for row in yearly_date_ranges.itertuples(index=False):
            start = row.start
            end = row.end
            subset = data[start:end]
            ax.plot(subset['Close'])

    plt.show()
</code>```

答:
This worked!  Thank you for the help</p>

```<code>    fig, axes = plt.subplots(7,1, figsize=(12,20))

    years = data.index.year

    for ax, (k,d) in zip(axes.ravel(), data['Close'].groupby(years)):
        d.plot(x='Close', ax=ax)
</code>```

Title: Matplotlib plot for loop issue

Body:
I'm trying to plot time series data in matplotlib using a for loop.  The goal is to dynamically plot 'n' years worth of daily closing price data.  If i load 7 years of data, I get 7 unique plots.  I have created a summary of the start and end dates for a data set, yearly_date_ranges (date is the index).  I use this to populate start and end dates.  The code I've written so far produces 7 plots of all daily data instead of 7 unique plots, one for each year.  Any help is appreciated. Thanks in advance!

    yearly_date_ranges
              start        end
    Date
    2014 2014-04-01 2014-12-31
    2015 2015-01-01 2015-12-31
    2016 2016-01-01 2016-12-31
    2017 2017-01-01 2017-12-31
    2018 2018-01-01 2018-12-31
    2019 2019-01-01 2019-12-31
    2020 2020-01-01 2020-05-28

    import pandas as pd
    import matplotlib.pyplot as plt
    %matplotlib inline

    fig = plt.figure(figsize=(12,20))
    for i in range(len(yearly_date_ranges)):
        ax = fig.add_subplot(len(yearly_date_ranges),1,i + 1)
        for row in yearly_date_ranges.itertuples(index=False):
            start = row.start
            end = row.end
            subset = data[start:end]
            ax.plot(subset['Close'])

    plt.show()

Body:
This worked!  Thank you for the help

    fig, axes = plt.subplots(7,1, figsize=(12,20))

    years = data.index.year

    for ax, (k,d) in zip(axes.ravel(), data['Close'].groupby(years)):
        d.plot(x='Close', ax=ax)


问:
Uglifying Template Strings Webpack
I'm using node-fetch to send over GraphQL requests in a lambda function. The requests are written as template strings; they therefore naturally are formatted and displayed "beautifully" by my IDE.

Just to save bandwidth, is there any way I can use Webpack to "uglify" these strings, for instance to remove the \n characters when compiling my Typescript file?

Thank you!

答: This depends on how you're loading the files in webpack. The babel plugin doesn't have a minify option. Neither does the loader from graphql-tag. Other loaders, like this one, do.

Title: Uglifying Template Strings Webpack


问:
How to find total size of user attachments in active storage
I'm using Rails 6.
How to get the total size of user attachments in active storage?

======

Update:

If I have User A and User B

How to get the total size of  User A attachments?

答:
If you want to get size of all attachments associated with some record (e.g. user = User.first) you can use this:

ActiveStorage::Attachment.where(record: user).map(&:byte_size).sum
```
<p>or more efficient with such query</p>
<pre class="lang-rb prettyprint-override"><code>ActiveStorage::Attachment.joins(:blob).where(record: user).sum(:byte_size)
</code>```

or like this

ActiveStorage::Blob.
  joins(:attachments).
  where(active_storage_attachments: { record_id: user.id, record_type: user.class.name }).
  sum(:byte_size)
```
<p>For example this user <code>has_many_attached :images</code></p>
<p>In this case you can get size only of <em><strong>all images</strong></em> of this user as:</p>
<pre class="lang-rb prettyprint-override"><code>user.images.map(&:byte_size).sum
</code>```

or more efficient with such query

user.images.joins(:blob).sum(:byte_size)
```
<p>or like this</p>
<pre class="lang-rb prettyprint-override"><code>user.images_blobs.sum(:byte_size)
</code>```

Using include ActionView::Helpers::NumberHelper you can convert byte size (integer) to human format:

number_to_human_size(size_of_all_attachments)
```

Body:
If you want to get size of all attachments associated with some record (e.g. user = User.first) you can use this:

ActiveStorage::Attachment.where(record: user).map(&:byte_size).sum

or more efficient with such query

ActiveStorage::Attachment.joins(:blob).where(record: user).sum(:byte_size)

or like this

ActiveStorage::Blob.
  joins(:attachments).
  where(active_storage_attachments: { record_id: user.id, record_type: user.class.name }).
  sum(:byte_size)

For example this user has_many_attached :images

In this case you can get size only of all images of this user as:

user.images.map(&:byte_size).sum

or more efficient with such query

user.images.joins(:blob).sum(:byte_size)

or like this

user.images_blobs.sum(:byte_size)

Using include ActionView::Helpers::NumberHelper you can convert byte size (integer) to human format:

number_to_human_size(size_of_all_attachments)


问:
Discord.js if user has role?
I need help with my bot.
My bot should only respond if a user has a specific role. It should be definable by name and not by ID.
I user Discord.js 12.0.2

my code

```<code>//DBD embed
client.on("message", async message => {
  let cmd = message
    if (message.content === '/code-embed') {
      message.channel.send("Der angefragte Bot code", { files: [ "./dbd/embed.txt" ] })
}})
</code>```

答:
you can use some() on the roles collection of the GuildMember to check if they have a specific role.

if (!message.member.roles.cache.some((role) => role.name === 'RoleName')) return
```

Title: Discord.js if user has role?

Body:
I need help with my bot.
My bot should only respond if a user has a specific role. It should be definable by name and not by ID.
I user Discord.js 12.0.2

my code

//DBD embed
client.on("message", async message => {
  let cmd = message
    if (message.content === '/code-embed') {
      message.channel.send("Der angefragte Bot code", { files: [ "./dbd/embed.txt" ] })
}})


问:
Postgres: monitor what part of the execution plan is running for long queries
The information in pg_stat_activity is sort of scarce, and does not give progress information for long queries.

This information is sort of available in v$session_longops in Oracle, which gives which object is being processed (target), the number of items it needs to go through (totalwork), and the number of item done so far (sofar). One can then use that to infer what part of the execution plan the engine is in. This information is available in Spark and Flink as well.

I was wondering if there was a way to have access to that in Postgres, either in system tables, or by observing the processes, or where one might look in the internals if he wants to implement a patch.

Cheers!

答:
AFAIK there is no existing feature to monitor long running queries in detail (there is such a feature only for 3 DDL statements).

A patch has been proposed 3 years ago. It looks like it was not integrated.

See discussion in hackers mailing list:
https://www.postgresql.org/message-id/CADdR5nxQUSh5kCm9MKmNga8+c1JLxLHDzLhAyXpfo9-Wmc6s5g@mail.gmail.com


问:
StreamBuilder doesn't rebuild after Navigator.pop
I have a simple service which is tracking the current user position :

class LocationService {
  LatLng _lastLocation;
  Location location = Location();

 StreamController<LatLng> _locationController = StreamController<LatLng>();
 Stream<LatLng> get locationStream => _locationController.stream;

  LocationService() {
    location.onLocationChanged().listen((locationData) {
      LatLng location = LatLng(locationData.latitude, locationData.longitude);
      if(_lastLocation == null || _lastLocation != location) {
        _lastLocation = location;
        _locationController.add(location);
      }
    });
  }
}
```

<p>Then, I'm using this service to create a Map (thanks to flutter_map) which is following the current user position :</p>

<pre class="lang-dart prettyprint-override"><code>class SelfUpdatingMap extends StatelessWidget {
  final Icon currentPositionIcon;

  final MapController _controller = MapController();

  SelfUpdatingMap({
    this.currentPositionIcon,
  });

  @override
  Widget build(BuildContext context) => StreamBuilder<LatLng>(
        stream: LocationService().locationStream,
        builder: (context, asyncSnapshot) {
          if (asyncSnapshot.hasError || asyncSnapshot.data == null) {
            return Text('Loading...');
          }

          try {
            _controller?.move(asyncSnapshot.data, 18);
          } catch (ignored) {}
          return _createMapWidget(context, asyncSnapshot.data);
        },
      );

  Widget _createMapWidget(BuildContext context, LatLng location) => FlutterMap(
        options: MapOptions(
          center: location,
          zoom: 18,
        ),
        layers: [
          TileLayerOptions(
            urlTemplate: 'https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}.png', // https://a.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png is good too.
            subdomains: ['a', 'b', 'c'],
          ),
          MarkerLayerOptions(
            markers: [
              Marker(
                  width: 40,
                  height: 40,
                  point: location,
                  builder: (contact) => currentPositionIcon,
                ),
            ]
          ),
        ],
        mapController: _controller,
      );
}
</code>```

Then, I use the SelfUpdating widget in two places :

The page 1, ancestor of page 2.

And in the page 3, successor of page 2.

So here is the situation :

I launch my app, I'm on the page 1. I have my SelfUpdatingMap.

I call Navigator.pushNamed(context, '/page-2').

I call Navigator.pushNamed(context, '/page-3'). I have another SelfUpdatingMap.

I call two times Navigator.pop(context), I get the page 1 BUT the SelfUpdatingMap doesn't update itself anymore.

The builder is not even called anymore. So please, what is wrong with this code ?

Thank you !

答:
When you push and after pop a page, the build metod doesn't restart.
I found the same problem with the FlutterBluetoothSerial.instance.onStateChanged() stream and the solution that I found is to add the stream to a local static final variable and use it instead of calling every time the original method (you can do that only if the stream is a broadcast one I think).

Solution example:

```<code>class ExampleClass {
    static final Stream<LatLng> locationStream = LocationService().locationStream;
}

class SelfUpdatingMap extends StatelessWidget {
    ...
    @override
    Widget build(BuildContext context) => StreamBuilder<LatLng>(
        stream: ExampleClass.locationStream,
        builder: (context, asyncSnapshot) {
            if (asyncSnapshot.hasError || asyncSnapshot.data == null) {
                return Text('Loading...');
            }
            try {
                _controller?.move(asyncSnapshot.data, 18);
            } catch (ignored) {}
            return _createMapWidget(context, asyncSnapshot.data);
        },
    );
    ...
}

class Page3Widget extends StatelessWidget {
    ...
    @override
    Widget build(BuildContext context) => StreamBuilder<LatLng>(
        stream: ExampleClass.locationStream,
        builder: (context, asyncSnapshot) {
            //do something
        },
    );
    ...
}
</code>```

Body:
I have a simple service which is tracking the current user position :

class LocationService {
  LatLng _lastLocation;
  Location location = Location();

 StreamController<LatLng> _locationController = StreamController<LatLng>();
 Stream<LatLng> get locationStream => _locationController.stream;

  LocationService() {
    location.onLocationChanged().listen((locationData) {
      LatLng location = LatLng(locationData.latitude, locationData.longitude);
      if(_lastLocation == null || _lastLocation != location) {
        _lastLocation = location;
        _locationController.add(location);
      }
    });
  }
}

Then, I'm using this service to create a Map (thanks to flutter_map) which is following the current user position :

class SelfUpdatingMap extends StatelessWidget {
  final Icon currentPositionIcon;

  final MapController _controller = MapController();

  SelfUpdatingMap({
    this.currentPositionIcon,
  });

  @override
  Widget build(BuildContext context) => StreamBuilder<LatLng>(
        stream: LocationService().locationStream,
        builder: (context, asyncSnapshot) {
          if (asyncSnapshot.hasError || asyncSnapshot.data == null) {
            return Text('Loading...');
          }

          try {
            _controller?.move(asyncSnapshot.data, 18);
          } catch (ignored) {}
          return _createMapWidget(context, asyncSnapshot.data);
        },
      );

  Widget _createMapWidget(BuildContext context, LatLng location) => FlutterMap(
        options: MapOptions(
          center: location,
          zoom: 18,
        ),
        layers: [
          TileLayerOptions(
            urlTemplate: 'https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}.png', // https://a.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png is good too.
            subdomains: ['a', 'b', 'c'],
          ),
          MarkerLayerOptions(
            markers: [
              Marker(
                  width: 40,
                  height: 40,
                  point: location,
                  builder: (contact) => currentPositionIcon,
                ),
            ]
          ),
        ],
        mapController: _controller,
      );
}

Then, I use the SelfUpdating widget in two places :

The page 1, ancestor of page 2.

And in the page 3, successor of page 2.

So here is the situation :

I launch my app, I'm on the page 1. I have my SelfUpdatingMap.

I call Navigator.pushNamed(context, '/page-2').

I call Navigator.pushNamed(context, '/page-3'). I have another SelfUpdatingMap.

I call two times Navigator.pop(context), I get the page 1 BUT the SelfUpdatingMap doesn't update itself anymore.

The builder is not even called anymore. So please, what is wrong with this code ?

Thank you !

Body:
When you push and after pop a page, the build metod doesn't restart.
I found the same problem with the FlutterBluetoothSerial.instance.onStateChanged() stream and the solution that I found is to add the stream to a local static final variable and use it instead of calling every time the original method (you can do that only if the stream is a broadcast one I think).

Solution example:

class ExampleClass {
    static final Stream<LatLng> locationStream = LocationService().locationStream;
}

class SelfUpdatingMap extends StatelessWidget {
    ...
    @override
    Widget build(BuildContext context) => StreamBuilder<LatLng>(
        stream: ExampleClass.locationStream,
        builder: (context, asyncSnapshot) {
            if (asyncSnapshot.hasError || asyncSnapshot.data == null) {
                return Text('Loading...');
            }
            try {
                _controller?.move(asyncSnapshot.data, 18);
            } catch (ignored) {}
            return _createMapWidget(context, asyncSnapshot.data);
        },
    );
    ...
}

class Page3Widget extends StatelessWidget {
    ...
    @override
    Widget build(BuildContext context) => StreamBuilder<LatLng>(
        stream: ExampleClass.locationStream,
        builder: (context, asyncSnapshot) {
            //do something
        },
    );
    ...
}


问:
Is there a reason '\0' is not supported in F#?
When I try to use '\0' as a character in F# it doesn't work.  Here is what I see:

I have read elsewhere that Char.MinValue will accomplish the same thing though.

Is there any reason why '\0' is not supported?

答:
The F# specification describes the grammar for char literals:

3.5 Strings and Characters

regexp escape-char=  '\' ["\'ntbrafv]

regexp non-escape-chars=  '\' [^"\'ntbrafv]

regexp simple-char-char= | (any char except '\n' '\t' '\r' '\b' '\a'
  '\f' '\v' ' \")

regexp unicodegraph-short = '\''u' hexdigit hexdigit hexdigit hexdigit

regexp unicodegraph-long=  '\''U' hexdigit hexdigit hexdigit hexdigit
  hexdigit hexdigit hexdigit hexdigit

regexp trigraph = '\' digit-char digit-char digit-char

regexp char-char= | simple-char-char | escape-char | trigraph |
  unicodegraph-short

\0 matches none of these - if you want the null character you can use

```<code>let c = '\000'
</code>```

or Char.MinValue

Body:
The F# specification describes the grammar for char literals:

3.5 Strings and Characters

regexp escape-char=  '\' ["\'ntbrafv]

regexp non-escape-chars=  '\' [^"\'ntbrafv]

regexp simple-char-char= | (any char except '\n' '\t' '\r' '\b' '\a'
  '\f' '\v' ' \")

regexp unicodegraph-short = '\''u' hexdigit hexdigit hexdigit hexdigit

regexp unicodegraph-long=  '\''U' hexdigit hexdigit hexdigit hexdigit
  hexdigit hexdigit hexdigit hexdigit

regexp trigraph = '\' digit-char digit-char digit-char

regexp char-char= | simple-char-char | escape-char | trigraph |
  unicodegraph-short

\0 matches none of these - if you want the null character you can use

let c = '\000'

or Char.MinValue


问:
Prevent SC_METHOD from executing without event/trigger
My method fsm1 executes once even without event and therefore id1_cmd.read() and id1_value.read() contain 0 and not the correct values.

```<code>//------------------------------------------------------------------
//  Method:  control::fsm1()
//  Parameter: None
//  @Sensitivity: ID_1_cmd (unsigned int)
//------------------------------------------------------------------
void control::fsm1() {
   cout << id1_cmd.read() << endl;
   cout << id1_value.read() << endl;

}

//------------------------------------------------------------------
//  Method: Constructor
//------------------------------------------------------------------
SC_CTOR(control) {
    SC_METHOD(fsm1);
    sensitive << id1_cmd;
}
</code>```

Exists there a way to prevent it from executing once or do i have to handle that case always in my methods?

答:
Use the dont_initialize method see the Language Reference Manual

```<code>SC_CTOR(control) {
    SC_METHOD(fsm1);
    sensitive << id1_cmd;
    dont_initialize();
}
</code>```

Body:
My method fsm1 executes once even without event and therefore id1_cmd.read() and id1_value.read() contain 0 and not the correct values.

//------------------------------------------------------------------
//  Method:  control::fsm1()
//  Parameter: None
//  @Sensitivity: ID_1_cmd (unsigned int)
//------------------------------------------------------------------
void control::fsm1() {
   cout << id1_cmd.read() << endl;
   cout << id1_value.read() << endl;

}

//------------------------------------------------------------------
//  Method: Constructor
//------------------------------------------------------------------
SC_CTOR(control) {
    SC_METHOD(fsm1);
    sensitive << id1_cmd;
}

Exists there a way to prevent it from executing once or do i have to handle that case always in my methods?

Body:
Use the dont_initialize method see the Language Reference Manual

SC_CTOR(control) {
    SC_METHOD(fsm1);
    sensitive << id1_cmd;
    dont_initialize();
}