问:
Using for range variable as function argument while looping through map of maps
I'm trying to loop through a map of maps and pass each pair to a function which modifies the contents.  When I try to compile the below code, I get the following error with respect to the item range variable declaration:

```<code>error: invalid initialization of non-const reference of type 'std::pair<std::__cxx11::basic_string<char>, std::map<std::__cxx11::basic_string<char>, int> >&' from an rvalue of type 'std::pair<std::__cxx11::basic_string<char>, std::map<std::__cxx11::basic_string<char>, int> >'
     for(std::pair<std::string, std::map<std::string, int>>& index : names)
</code>```

When I try to use auto& to declare range variable index, the error moves from the range variable declaration to the function call incrementAndPrintIt(index);

```<code>#include <iostream>
#include <vector>
#include <map>

void incrementAndPrintIt(std::pair<std::string, std::map<std::string, int>>& value)
{
    for(auto& j : value.second) {
        j.second = j.second + 1;
        std::cout << "j:  " << j.second << std::endl;
    }
}

int main() {

    //initialize a map of maps
    std::map<std::string, std::map<std::string, int>> names = {{"women",{{"Rita",2}}},{"men",{{"Jack",4}}}};

    for(std::pair<std::string, std::map<std::string, int>>& index : names) {
        incrementAndPrintIt(index);
    }
    return 0;
}
</code>```

答:
```<code> for(std::pair<std::string, std::map<std::string, int>>& index : names)
</code>```

In a std::map, the map's key, the first value in the pair, is a constant value.

This should be:

```<code> for(std::pair<const std::string, std::map<std::string, int>>& index : names)
</code>```

incrementAndPrintIt()'s parameter should also be adjusted to the same.

It's easy to use auto to avoid this entire headache in the first place:

```<code> for(auto& index : names)
</code>```

But this doesn't help with incrementAndPrintIt()'s parameter. However it doesn't need map's key, so you can simply pass index.second to it, and save a lot of wear and tear on your keyboard:

```<code>#include <iostream>
#include <vector>
#include <map>

void incrementAndPrintIt(std::map<std::string, int> &value)
{
    for(auto& j : value) {
        j.second = j.second + 1;
        std::cout << "j:  " << j.second << std::endl;
    }
}

int main() {

    //initialize a map of maps
    std::map<std::string, std::map<std::string, int>> names = {{"women",{{"Rita",2}}},{"men",{{"Jack",4}}}};

    for(auto& index : names) {
        incrementAndPrintIt(index.second);
    }
    return 0;
}
</code>```

You must admit: this is much simpler, isn't it?

Body:
I'm trying to loop through a map of maps and pass each pair to a function which modifies the contents.  When I try to compile the below code, I get the following error with respect to the item range variable declaration:

error: invalid initialization of non-const reference of type 'std::pair<std::__cxx11::basic_string<char>, std::map<std::__cxx11::basic_string<char>, int> >&' from an rvalue of type 'std::pair<std::__cxx11::basic_string<char>, std::map<std::__cxx11::basic_string<char>, int> >'
     for(std::pair<std::string, std::map<std::string, int>>& index : names)

When I try to use auto& to declare range variable index, the error moves from the range variable declaration to the function call incrementAndPrintIt(index);

#include <iostream>
#include <vector>
#include <map>

void incrementAndPrintIt(std::pair<std::string, std::map<std::string, int>>& value)
{
    for(auto& j : value.second) {
        j.second = j.second + 1;
        std::cout << "j:  " << j.second << std::endl;
    }
}

int main() {

    //initialize a map of maps
    std::map<std::string, std::map<std::string, int>> names = {{"women",{{"Rita",2}}},{"men",{{"Jack",4}}}};

    for(std::pair<std::string, std::map<std::string, int>>& index : names) {
        incrementAndPrintIt(index);
    }
    return 0;
}

Body:
 for(std::pair<std::string, std::map<std::string, int>>& index : names)

In a std::map, the map's key, the first value in the pair, is a constant value.

This should be:

 for(std::pair<const std::string, std::map<std::string, int>>& index : names)

incrementAndPrintIt()'s parameter should also be adjusted to the same.

It's easy to use auto to avoid this entire headache in the first place:

 for(auto& index : names)

But this doesn't help with incrementAndPrintIt()'s parameter. However it doesn't need map's key, so you can simply pass index.second to it, and save a lot of wear and tear on your keyboard:

#include <iostream>
#include <vector>
#include <map>

void incrementAndPrintIt(std::map<std::string, int> &value)
{
    for(auto& j : value) {
        j.second = j.second + 1;
        std::cout << "j:  " << j.second << std::endl;
    }
}

int main() {

    //initialize a map of maps
    std::map<std::string, std::map<std::string, int>> names = {{"women",{{"Rita",2}}},{"men",{{"Jack",4}}}};

    for(auto& index : names) {
        incrementAndPrintIt(index.second);
    }
    return 0;
}

You must admit: this is much simpler, isn't it?


来源: stackexchange

问:
how to add check symbol in excel cell SXSSFSheet java
I need to put a check symbol in this cell if the condition met. Here's my sample code:

```<code>private SXSSFWorkbook RepWkBook = null;
private SXSSFSheet RepSheet = null;
private int RepRowNum = 0;
private ResultSet RepResult = null;
private Row RepRow = null;

    RepSheet = RepWkBook.createSheet(reportType);
    RepRowNum = 0;
    Row row = RepSheet.createRow(RepRowNum++);
    CellStyle cellStyle = RepWkBook.createCellStyle();
    Font font = RepWkBook.createFont();
    font.setBold(true);
    cellStyle.setFont(font);cell = RepRow.createCell(col++);

        boolean isMOBhigherThanArea = RepResult.getString("IS_MOB_HIGHER_THAN_AREA").equalsIgnoreCase("1");

        char st = '\u2713';

        if(isMOBhigherThanArea && (!areaStr.equalsIgnoreCase("No Data") || !mobStr.equalsIgnoreCase("No Data"))) {
            cell.setCellValue(st);}
</code>```

I already used

UTF-16 - feff2713

UTF-16BE - 2713

UTF-16LE - 1327

UTF-8 - e29c93

click here for sample output
SAMPLE EXPECTED OUTPUT

Area | MOB Target | Area Result | MOB > Area

City |     85%    |       80%   |     ✔

答:
Try using

```<code>ChrW(&H2713)
</code>```

(source: https://www.mrexcel.com/board/threads/how-to-insert-a-checkmark-with-vba.607363/)

ContentLicense: CC BY-SA 4.0

Body:
I need to put a check symbol in this cell if the condition met. Here's my sample code:

private SXSSFWorkbook RepWkBook = null;
private SXSSFSheet RepSheet = null;
private int RepRowNum = 0;
private ResultSet RepResult = null;
private Row RepRow = null;

    RepSheet = RepWkBook.createSheet(reportType);
    RepRowNum = 0;
    Row row = RepSheet.createRow(RepRowNum++);
    CellStyle cellStyle = RepWkBook.createCellStyle();
    Font font = RepWkBook.createFont();
    font.setBold(true);
    cellStyle.setFont(font);cell = RepRow.createCell(col++);

        boolean isMOBhigherThanArea = RepResult.getString("IS_MOB_HIGHER_THAN_AREA").equalsIgnoreCase("1");

        char st = '\u2713';

        if(isMOBhigherThanArea && (!areaStr.equalsIgnoreCase("No Data") || !mobStr.equalsIgnoreCase("No Data"))) {
            cell.setCellValue(st);}

I already used

UTF-16 - feff2713

UTF-16BE - 2713

UTF-16LE - 1327

UTF-8 - e29c93

click here for sample output
SAMPLE EXPECTED OUTPUT

Area | MOB Target | Area Result | MOB > Area

City |     85%    |       80%   |     ✔

Body:
Try using

ChrW(&H2713)

(source: https://www.mrexcel.com/board/threads/how-to-insert-a-checkmark-with-vba.607363/)


问:
Webapi controller without authentication
I have some controllers in a webapi core project that requires authentication. I want to create another controller that will not require authentication and will be accessible from outside. How can I create such a controller without authentication?</p>

答:
Assume that you've done the process of verifying the user for authentication/authorization.

The [AllowAnonymous] attribute will skip authentication and authorization during an access request to a controller decorated with this attribute or to a specific action method decorated with this attribute

```<code> [Authorize]
 public class SampleController : BaseController
 {
     [AllowAnonymous]
     public IActionResult Get() { ... }
     public IActionResult Post() { ... }
 }
</code>```

Body:
Assume that you've done the process of verifying the user for authentication/authorization.

The [AllowAnonymous] attribute will skip authentication and authorization during an access request to a controller decorated with this attribute or to a specific action method decorated with this attribute

 [Authorize]
 public class SampleController : BaseController
 {
     [AllowAnonymous]
     public IActionResult Get() { ... }
     public IActionResult Post() { ... }
 }


问:
How to access Provided (Provider.of()) value inside showModalBottomSheet?
I have a FloatingActionButton inside a widget tree which has a BlocProvider from flutter_bloc. Something like this:

```<code>BlocProvider(
  builder: (context) {
    SomeBloc someBloc = SomeBloc();
    someBloc.dispatch(SomeEvent());

    return someBloc;
  },
  child: Scaffold(
    body: ...
    floatingActionButton: FloatingActionButton(
      onPressed: _openFilterSchedule,
      child: Icon(Icons.filter_list),
    ),
  )
);
</code>```

Which opens a modal bottom sheet:

```<code>void _openFilterSchedule() {
    showModalBottomSheet<void>(
      context: context,
      builder: (BuildContext context) {
        return TheBottomSheet();
      },
    );
  }
</code>```

I am trying to access SomeBloc using BlocProvider.of<SomeBloc>(context) inside TheBottomSheet but I get the following error:

```<code>BlocProvider.of() called with a context that does not contain a Bloc of type SomeBloc.
</code>```

I have tried to use the solution described in https://stackoverflow.com/a/56533611/2457045 but only works for BottomSheet and not ModalBottomSheet.

Note: This is not restricted to BlocProvider or flutter_bloc. Any Provider from the provider package has the same behaviour.

How can I access BlocProvider.of<SomeBloc>(context) inside the showModalBottomSheet?

In case it's not possible to do that, how to adapt https://stackoverflow.com/a/56533611/2457045 solution to Modal Bottom Sheet?

答:
You need move Provider to top layer(MaterialApp)

According to picture, Dialog widget is under MaterialApp, so this is why you using wrong context

Body:
I have a FloatingActionButton inside a widget tree which has a BlocProvider from flutter_bloc. Something like this:

BlocProvider(
  builder: (context) {
    SomeBloc someBloc = SomeBloc();
    someBloc.dispatch(SomeEvent());

    return someBloc;
  },
  child: Scaffold(
    body: ...
    floatingActionButton: FloatingActionButton(
      onPressed: _openFilterSchedule,
      child: Icon(Icons.filter_list),
    ),
  )
);

Which opens a modal bottom sheet:

void _openFilterSchedule() {
    showModalBottomSheet<void>(
      context: context,
      builder: (BuildContext context) {
        return TheBottomSheet();
      },
    );
  }

I am trying to access SomeBloc using BlocProvider.of<SomeBloc>(context) inside TheBottomSheet but I get the following error:

BlocProvider.of() called with a context that does not contain a Bloc of type SomeBloc.

I have tried to use the solution described in https://stackoverflow.com/a/56533611/2457045 but only works for BottomSheet and not ModalBottomSheet.

Note: This is not restricted to BlocProvider or flutter_bloc. Any Provider from the provider package has the same behaviour.

How can I access BlocProvider.of<SomeBloc>(context) inside the showModalBottomSheet?

In case it's not possible to do that, how to adapt https://stackoverflow.com/a/56533611/2457045 solution to Modal Bottom Sheet?


问:
How to solve catch error in Observable in angular 8?
I do error handler code, but I got error in catch. undefined method.

This is my serivce.ts code.

```<code>import { Injectable } from "@angular/core";
import { HttpClient, HttpErrorResponse } from "@angular/common/http";
import { user } from "./user";
import { Observable } from "rxjs";
import "rxjs/add/operator/catch";
import "rxjs/add/Observable/throw";
@Injectable({
  providedIn: "root"
})
export class DemoService {
  private url: string = "/assets/demo/user.json";
  constructor(private http: HttpClient) {}

  getuserdetails(): Observable<user[]> {
    return this.http.get<user[]>(this.url).catch(this.errorHandler);
  }
  errorHandler(error: HttpErrorResponse) {
    return Observable.throw(error.message || "server error.");
  }
}
</code>```

This is my app.component.ts file code

```<code> public userdetails = [];
  public errorMsg;
  constructor(private user: DemoService) {}
  ngOnInit() {
    this.user
      .getuserdetails()
      .subscribe(
        $data => (this.userdetails = $data),
        error => (this.errorMsg = error)
      );
  }
</code>```

I got error in catch. and error message is Property 'catch' does not exist on type 'Observable'.

答:
```<code>import { Observable, throwError } from 'rxjs';
import { catchError, } from 'rxjs/operators';

return this.http.get<user[]>(this.url).pipe(catchError(this.errorHandler))

errorHandler(error: HttpErrorResponse) {
    return throwError(error.message || "server error.");
}
</code>```

Body:
I do error handler code, but I got error in catch. undefined method.

This is my serivce.ts code.

import { Injectable } from "@angular/core";
import { HttpClient, HttpErrorResponse } from "@angular/common/http";
import { user } from "./user";
import { Observable } from "rxjs";
import "rxjs/add/operator/catch";
import "rxjs/add/Observable/throw";
@Injectable({
  providedIn: "root"
})
export class DemoService {
  private url: string = "/assets/demo/user.json";
  constructor(private http: HttpClient) {}

  getuserdetails(): Observable<user[]> {
    return this.http.get<user[]>(this.url).catch(this.errorHandler);
  }
  errorHandler(error: HttpErrorResponse) {
    return Observable.throw(error.message || "server error.");
  }
}

This is my app.component.ts file code

 public userdetails = [];
  public errorMsg;
  constructor(private user: DemoService) {}
  ngOnInit() {
    this.user
      .getuserdetails()
      .subscribe(
        $data => (this.userdetails = $data),
        error => (this.errorMsg = error)
      );
  }

I got error in catch. and error message is Property 'catch' does not exist on type 'Observable'.


问:
Incremental data transfer using Azure Data Factory
In an on-premises SQL Server database, I have a number of tables in to which various sales data for a chain of stores is inserted during the day. I would like to "harvest" these data to Azure every, say 15, minutes via Data Factory and an on-premises data management gateway. Clearly, I am not interested in copying all table data every 15 minutes, but only in copying the rows that have been inserted since last fetch.
As far as I can see, the documentation suggests using data "slices" for this purpose. However, as far as I can see, these slices require a timestamp (e.g. a datetime) column to exist on the tables where data is fetched from.

Can I perform a "delta" fetch (i.e. only fetch the rows inserted since last fetch) without having such a timestamp column? Could I use a sequential integer column instead? Or even have no incrementally increasing column at all?

Assume that the last slice fetched had a window from 08:15 to 08:30. Now, if the clock on the database server is a bit behind the Azure clock, it might add some rows with the timestamp being set to 08:29 after that slice was fetched, and these rows will not be included when the next slice (08:30 to 08:45) is fetched. Is there a smart way to avoid this problem? Shifting the slice window a few minutes into the past could minimize the risk, but not totally eliminate it.

答:
By enabling "Change Tracking" on SQL Server, you can leverage on the "SYS_CHANGE_VERSION " to incrementally load data from On-premise SQL Server or Azure SQL Database via Azure Data Factory.

https://learn.microsoft.com/en-us/azure/data-factory/tutorial-incremental-copy-change-tracking-feature-portal

ContentLicense: CC BY-SA 3.0


问:
Get Count for Each Column values
Input

```<code>Create Table #t1 (CaseId Int, NewValue  char(2),Attribute char(2),TimeStamp datetime)

insert into #t1 values
(1,      'A',         'X'   ,       '2020-01-01 13:01'),
(1,      'Au',        'WB' ,        '2020-01-01 13:02'),
(1 ,     'C'  ,       'P'   ,       '2020-01-01 13:03'),
(1 ,     'Ma',        'WB' ,        '2020-01-01 13:04'),
(1 ,     'C'   ,      'D',          '2020-01-01 13:05'),
(1,      'D'  ,       'E',          '2020-01-01 13:04'),
(2 ,     'M'  ,       'P' ,         '2020-05-01 15:20'),
(2 ,     'X'  ,       'WB' ,        '2020-05-01 15:26'),
(2  ,    'Y' ,        'WB',         '2020-05-01 15:29'),
(2  ,    'X'  ,       'P'  ,         '2020-05-01 15:31')
</code>```

I need output like the following.

```<code>CaseId  NewValue    Attribute   TimeStamp   NewColumn   NewColumn   Count
1        A            X         01:00.0         NULL    NULL         0
1        Au           WB        02:00.0         Au-WB   Au-WB        2
1        C            P         03:00.0         Au-WB   Au-WB        2
1        Ma           WB        04:00.0         Ma-WB   Ma-WB        3
1        C            D         05:00.0         Ma-WB   Ma-WB        3
1        D            E         04:00.0         Ma-WB   Ma-WB        3
2        M            P         20:00.0         NULL    NULL         0
2        X            WB        26:00.0         X -WB   X -WB        1
2        Y            WB        29:00.0         Y -WB   Y -WB        2
2        X            P         31:00.0         Y -WB   Y -WB        2
</code>```

Squirrel helped to get everything minus count.  The query is as follows. Does anyone know how to get that count?

```<code>select  *, wb.NewColumn
from    #t1 t
        outer apply
        (
            select top 1 x.NewValue + '-' + x.Attibute as NewColumn
            from    #t1 x
            where   x.CaseId    = t.CaseId
            and     x.TimeStamp <= t.TimeStamp
            and     x.Attibute  = 'WB'
            order by x.TimeStamp desc
        ) wb
</code>```

答:
Using your query output, create a cte and perform the count using the windowing function by partition on caseid,newcolumn as follows</p>

```<code>with data
 as (
select  *, wb.NewColumn
from    #t1 t
        outer apply
        (
            select top 1 x.NewValue + '-' + x.Attibute as NewColumn
            from    #t1 x
            where   x.CaseId    = t.CaseId
            and     x.TimeStamp <= t.TimeStamp
            and     x.Attibute  = 'WB'
            order by x.TimeStamp desc
        ) wb
    )
select *,count(*) over(partition by caseid,newcolumn) as cnt
 from data
</code>```

Title: Get Count for Each Column values

Body:
Input

Create Table #t1 (CaseId Int, NewValue  char(2),Attribute char(2),TimeStamp datetime)

insert into #t1 values
(1,      'A',         'X'   ,       '2020-01-01 13:01'),
(1,      'Au',        'WB' ,        '2020-01-01 13:02'),
(1 ,     'C'  ,       'P'   ,       '2020-01-01 13:03'),
(1 ,     'Ma',        'WB' ,        '2020-01-01 13:04'),
(1 ,     'C'   ,      'D',          '2020-01-01 13:05'),
(1,      'D'  ,       'E',          '2020-01-01 13:04'),
(2 ,     'M'  ,       'P' ,         '2020-05-01 15:20'),
(2 ,     'X'  ,       'WB' ,        '2020-05-01 15:26'),
(2  ,    'Y' ,        'WB',         '2020-05-01 15:29'),
(2  ,    'X'  ,       'P'  ,         '2020-05-01 15:31')

I need output like the following.

CaseId  NewValue    Attribute   TimeStamp   NewColumn   NewColumn   Count
1        A            X         01:00.0         NULL    NULL         0
1        Au           WB        02:00.0         Au-WB   Au-WB        2
1        C            P         03:00.0         Au-WB   Au-WB        2
1        Ma           WB        04:00.0         Ma-WB   Ma-WB        3
1        C            D         05:00.0         Ma-WB   Ma-WB        3
1        D            E         04:00.0         Ma-WB   Ma-WB        3
2        M            P         20:00.0         NULL    NULL         0
2        X            WB        26:00.0         X -WB   X -WB        1
2        Y            WB        29:00.0         Y -WB   Y -WB        2
2        X            P         31:00.0         Y -WB   Y -WB        2

Squirrel helped to get everything minus count.  The query is as follows. Does anyone know how to get that count?

select  *, wb.NewColumn
from    #t1 t
        outer apply
        (
            select top 1 x.NewValue + '-' + x.Attibute as NewColumn
            from    #t1 x
            where   x.CaseId    = t.CaseId
            and     x.TimeStamp <= t.TimeStamp
            and     x.Attibute  = 'WB'
            order by x.TimeStamp desc
        ) wb

Body:
Using your query output, create a cte and perform the count using the windowing function by partition on caseid,newcolumn as follows

with data
 as (
select  *, wb.NewColumn
from    #t1 t
        outer apply
        (
            select top 1 x.NewValue + '-' + x.Attibute as NewColumn
            from    #t1 x
            where   x.CaseId    = t.CaseId
            and     x.TimeStamp <= t.TimeStamp
            and     x.Attibute  = 'WB'
            order by x.TimeStamp desc
        ) wb
    )
select *,count(*) over(partition by caseid,newcolumn) as cnt
 from data


问:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY
I am trying to parse the incoming Json (given below) to Java object using Gson. The Json request seems to be a valid one, but I am getting the following exception while parsing it.

```<code>com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 5 column 19 path $.metadata.
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226) ~[gson-2.8.5.jar:?]
        at com.google.gson.Gson.fromJson(Gson.java:927) ~[gson-2.8.5.jar:?]
</code>```

Incoming Json request :

```<code>{
    "metadata": {
        "salesId": "123",
        "promoCode": "2010",
        "items": [
            {
                "0": {
                    "productCode": "1234",
                    "total": 169900
                },
                "1": {
                    "productCode": "4567",
                    "total": 19900
                }
            }
        ]
    }
}
</code>```

Parsing logic :

```<code>protected <T extends GenericModel> Optional<T> convertFromJson(final String json, final Class<T> clazz) {
        if (StringUtils.isEmpty(json)) {
            return Optional.empty();
        }
        return Optional.of(new Gson().fromJson(json, clazz));
    }
</code>```

Java class :

```<code>public class Metadata {
    private String salesId;
    private String promoCode;
    private ArrayList<Object> items = new ArrayList<Object>();

    public String getSalesId() {
        return salesId;
    }

    public void setSalesId(String salesId) {
        this.salesId = salesId;
    }

    public String getPromoCode() {
        return promoCode;
    }

    public void setPromoCode(String promoCode) {
        this.promoCode = promoCode;
    }

    public ArrayList<Object> getItems() {
        return items;
    }

    public void setItems(ArrayList<Object> items) {
        this.items = items;
    }

    @Override
    public String toString() {
        return "Metadata{" +
                "salesId=" + getSalesId() +
                "promoCode=" + getPromoCode() +
                "items=" + getItems() +
                '}';
    }
}
</code>```

Please note that Metadata.java is an inner class.

Have been trying to resolve the issue, but no luck. Could anyone let me know how to solve it? TIA.

答:
I'd guess the problem is with the items object in the json you are trying to deserialize.

In the Metadata class items is an ArrayList<Object> but that doesn't tell gson how to deserialize it.

Instead you should try creating another POJO for Item and then making the items an ArrayList<Item>. Something like this: Gson and deserializing an array of objects with arrays in it

You could check if items is the problem by commenting out that attribute and sending in just the salesId and promoCode.

Body:
I am trying to parse the incoming Json (given below) to Java object using Gson. The Json request seems to be a valid one, but I am getting the following exception while parsing it.

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 5 column 19 path $.metadata.
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226) ~[gson-2.8.5.jar:?]
        at com.google.gson.Gson.fromJson(Gson.java:927) ~[gson-2.8.5.jar:?]

Incoming Json request :

{
    "metadata": {
        "salesId": "123",
        "promoCode": "2010",
        "items": [
            {
                "0": {
                    "productCode": "1234",
                    "total": 169900
                },
                "1": {
                    "productCode": "4567",
                    "total": 19900
                }
            }
        ]
    }
}

Parsing logic :

protected <T extends GenericModel> Optional<T> convertFromJson(final String json, final Class<T> clazz) {
        if (StringUtils.isEmpty(json)) {
            return Optional.empty();
        }
        return Optional.of(new Gson().fromJson(json, clazz));
    }

Java class :

public class Metadata {
    private String salesId;
    private String promoCode;
    private ArrayList<Object> items = new ArrayList<Object>();

    public String getSalesId() {
        return salesId;
    }

    public void setSalesId(String salesId) {
        this.salesId = salesId;
    }

    public String getPromoCode() {
        return promoCode;
    }

    public void setPromoCode(String promoCode) {
        this.promoCode = promoCode;
    }

    public ArrayList<Object> getItems() {
        return items;
    }

    public void setItems(ArrayList<Object> items) {
        this.items = items;
    }

    @Override
    public String toString() {
        return "Metadata{" +
                "salesId=" + getSalesId() +
                "promoCode=" + getPromoCode() +
                "items=" + getItems() +
                '}';
    }
}

Please note that Metadata.java is an inner class.

Have been trying to resolve the issue, but no luck. Could anyone let me know how to solve it? TIA.


问:
problem with serial communcation in vc++ mfc
I am working on an embeeded device.and it is connected on COM6 port

when i use putty to write to that port it replies me with result.

example is when you say hello,it replies hello.

I wrote a program to write to COM6,i am able to write to the COM6 port but when i am reading i am not getting anything.

my code is...

// HelloWorld.cpp : Defines the entry point for the console application.
//

```<code>#include "stdafx.h"
#include <iostream>
#include <windows.h>
int main()
{
    using namespace std;
//  cout << "Hello world!" << endl;

    HANDLE hSerial;

    hSerial = CreateFile("COM6",
    GENERIC_READ | GENERIC_WRITE,
    FILE_SHARE_WRITE | FILE_SHARE_READ,
    0,
    OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL,
    0);

    if(hSerial==INVALID_HANDLE_VALUE)
    {
        if(GetLastError()==ERROR_FILE_NOT_FOUND)
        {
//          TRACE("serial port does not exist for reading\n");
        //serial port does not exist. Inform user.
        }
//          TRACE("some other error,serial port does not exist for reading\n");
        //some other error occurred. Inform user.
    }

    DCB dcbSerialParams = {0};

    dcbSerialParams.DCBlength=sizeof(dcbSerialParams);

    if (!GetCommState(hSerial, &dcbSerialParams))
    {
//                  TRACE("error getting state for reading\n");
    //error getting state
    }

    dcbSerialParams.BaudRate=9600;
    dcbSerialParams.ByteSize=8;
    dcbSerialParams.StopBits=ONESTOPBIT;
    dcbSerialParams.Parity=NOPARITY;

    if(!SetCommState(hSerial, &dcbSerialParams))
    {
//                  TRACE("error setting state for reading\n");
    //error setting serial port state
    }
    COMMTIMEOUTS timeouts={0};

    timeouts.ReadIntervalTimeout=50;
    timeouts.ReadTotalTimeoutConstant=50;
    timeouts.ReadTotalTimeoutMultiplier=10;

    timeouts.WriteTotalTimeoutConstant=50;
    timeouts.WriteTotalTimeoutMultiplier=10;

    if(!SetCommTimeouts(hSerial, &timeouts))
    {
//                  TRACE("some error occured for reading\n");
        //error occureed. Inform user
    }
    int n=100;
    char szBuff[100];
    DWORD dwBytesRead = 0;
    char szBuff1[100]="LIST";

    DWORD dwByteswrote = 0;

    if(!WriteFile(hSerial, szBuff1, n, &dwByteswrote, NULL))
    {
                    cout << "error writing" ;
    }
    cout << dwByteswrote;
    while(1)
    {
        if(!ReadFile(hSerial, szBuff, n, &dwBytesRead, NULL))
        {
            cout << "error reading";
        }
        else
        {
            cout << dwBytesRead;
            if(dwBytesRead>0)
            {
                cout << szBuff;
                break;
            }
        }
    }
}
</code>```

Can anyone help me in this??
what is the wrong thing i am making??

答:
It might be that you have to send a "line feed" or a "carriage return" after the "LIST" command to actually make the device send data?

Try sending "LIST\r", "LIST\n" or "LIST\r\n".

Body:
I am working on an embeeded device.and it is connected on COM6 port

when i use putty to write to that port it replies me with result.

example is when you say hello,it replies hello.

I wrote a program to write to COM6,i am able to write to the COM6 port but when i am reading i am not getting anything.

my code is...

// HelloWorld.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <windows.h>
int main()
{
    using namespace std;
//  cout << "Hello world!" << endl;

    HANDLE hSerial;

    hSerial = CreateFile("COM6",
    GENERIC_READ | GENERIC_WRITE,
    FILE_SHARE_WRITE | FILE_SHARE_READ,
    0,
    OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL,
    0);

    if(hSerial==INVALID_HANDLE_VALUE)
    {
        if(GetLastError()==ERROR_FILE_NOT_FOUND)
        {
//          TRACE("serial port does not exist for reading\n");
        //serial port does not exist. Inform user.
        }
//          TRACE("some other error,serial port does not exist for reading\n");
        //some other error occurred. Inform user.
    }

    DCB dcbSerialParams = {0};

    dcbSerialParams.DCBlength=sizeof(dcbSerialParams);

    if (!GetCommState(hSerial, &dcbSerialParams))
    {
//                  TRACE("error getting state for reading\n");
    //error getting state
    }

    dcbSerialParams.BaudRate=9600;
    dcbSerialParams.ByteSize=8;
    dcbSerialParams.StopBits=ONESTOPBIT;
    dcbSerialParams.Parity=NOPARITY;

    if(!SetCommState(hSerial, &dcbSerialParams))
    {
//                  TRACE("error setting state for reading\n");
    //error setting serial port state
    }
    COMMTIMEOUTS timeouts={0};

    timeouts.ReadIntervalTimeout=50;
    timeouts.ReadTotalTimeoutConstant=50;
    timeouts.ReadTotalTimeoutMultiplier=10;

    timeouts.WriteTotalTimeoutConstant=50;
    timeouts.WriteTotalTimeoutMultiplier=10;

    if(!SetCommTimeouts(hSerial, &timeouts))
    {
//                  TRACE("some error occured for reading\n");
        //error occureed. Inform user
    }
    int n=100;
    char szBuff[100];
    DWORD dwBytesRead = 0;
    char szBuff1[100]="LIST";

    DWORD dwByteswrote = 0;

    if(!WriteFile(hSerial, szBuff1, n, &dwByteswrote, NULL))
    {
                    cout << "error writing" ;
    }
    cout << dwByteswrote;
    while(1)
    {
        if(!ReadFile(hSerial, szBuff, n, &dwBytesRead, NULL))
        {
            cout << "error reading";
        }
        else
        {
            cout << dwBytesRead;
            if(dwBytesRead>0)
            {
                cout << szBuff;
                break;
            }
        }
    }
}

Can anyone help me in this??
what is the wrong thing i am making??


问:
C# Trying to get the printer status when it is offline
I need to get the printer status when it is offline, below is how I am getting the status;

```<code> // Set management scope
                ManagementScope scope = new ManagementScope(@"\root\cimv2");
                scope.Connect();

                // Select Printers from WMI Object Collections
                ManagementObjectSearcher searcher = new
                 ManagementObjectSearcher("SELECT * FROM Win32_Printer");

                string printerName = "";
                foreach (ManagementObject printer in searcher.Get())
                {
                    printerName = printer["Name"].ToString();
                    if (printerName.Equals(@"TEC B-EV4-T"))
                    {
                        //Console.WriteLine("Printer = " + printer["Name"]);
                        if (printer.Properties["PrinterStatus"].Value.ToString() == "7")
                        {
                            // printer is offline by user
                            MessageBox.Show("TEC B-EV4-T is offline");
                        }
                        else
                        {
                            // printer is not offline
                            //Check API first then print
                            ReportDocument cryRpt = new ReportDocument();
                            cryRpt.Load(Environment.CurrentDirectory + "\\Report.rpt");

                            dialog.PrintQueue = new PrintQueue(new PrintServer(), "TEC B-EV4-T");

                            //to the data table here
                            //To data table
                            DataTable dt = ToDataTable(lotinstruct);

                            cryRpt.SetDataSource(dt);

                            cryRpt.PrintToPrinter(1, true, 0, 0);

                            //}

                            MessageBox.Show("Already save result please check label!");
                        }
                    }
                }
</code>```

The problem is here if (printer.Properties["PrinterStatus"].Value.ToString() == "7") it seems like the printer status is always 3 when I debug (printer status 3 means that it is idle 7 means that it is offline). Is there any way to find out if the printer TEC B-EV4-T is offline?

答:
You can refer PrintQueue in built in .Net framework to check printer status. There are many properties in it to check different status:</p>

```<code>string printerName = "TEC B-EV4-T";
var server = new LocalPrintServer();
PrintQueue queue = server.GetPrintQueue(printerName , Array.Empty<string>());
bool isOffline = queue.IsOffline;
bool isBusy = queue.IsBusy;
</code>```

Body:
I need to get the printer status when it is offline, below is how I am getting the status;

 // Set management scope
                ManagementScope scope = new ManagementScope(@"\root\cimv2");
                scope.Connect();

                // Select Printers from WMI Object Collections
                ManagementObjectSearcher searcher = new
                 ManagementObjectSearcher("SELECT * FROM Win32_Printer");

                string printerName = "";
                foreach (ManagementObject printer in searcher.Get())
                {
                    printerName = printer["Name"].ToString();
                    if (printerName.Equals(@"TEC B-EV4-T"))
                    {
                        //Console.WriteLine("Printer = " + printer["Name"]);
                        if (printer.Properties["PrinterStatus"].Value.ToString() == "7")
                        {
                            // printer is offline by user
                            MessageBox.Show("TEC B-EV4-T is offline");
                        }
                        else
                        {
                            // printer is not offline
                            //Check API first then print
                            ReportDocument cryRpt = new ReportDocument();
                            cryRpt.Load(Environment.CurrentDirectory + "\\Report.rpt");

                            dialog.PrintQueue = new PrintQueue(new PrintServer(), "TEC B-EV4-T");

                            //to the data table here
                            //To data table
                            DataTable dt = ToDataTable(lotinstruct);

                            cryRpt.SetDataSource(dt);

                            cryRpt.PrintToPrinter(1, true, 0, 0);

                            //}

                            MessageBox.Show("Already save result please check label!");
                        }
                    }
                }

The problem is here if (printer.Properties["PrinterStatus"].Value.ToString() == "7") it seems like the printer status is always 3 when I debug (printer status 3 means that it is idle 7 means that it is offline). Is there any way to find out if the printer TEC B-EV4-T is offline?

Body:
You can refer PrintQueue in built in .Net framework to check printer status. There are many properties in it to check different status:

string printerName = "TEC B-EV4-T";
var server = new LocalPrintServer();
PrintQueue queue = server.GetPrintQueue(printerName , Array.Empty<string>());
bool isOffline = queue.IsOffline;
bool isBusy = queue.IsBusy;


问:
Populating SQLite Db Table from CSV File
I'm struggling to get my code to work.

I'm combining the examples I found here:
Parsing CSV using OleDb using C# and
Save Dataset to SQLite format file

I'm reading a CSV file into a DataSet using an OleDbConnection and OleDbDataAdapter (which is working), and then saving that DataSet to an SQLite Db using an SQLiteConnection and SQLiteDataAdapter (which is not working).

The test code from the 2nd example above works just fine, where the DataSet is created from code and then saved to the database.

The MasterDataTable in the database exists already.  I created it directly in the target db.

Here's my code:

```<code>using System;
using System.Data;
using System.Data.OleDb;
using System.Data.SQLite;
using System.IO;

namespace DataAdapterExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a simple dataset
            DataTable table = new DataTable("MasterDataTable");
            DataSet ds = new DataSet();
            ds.Tables.Add(table);
            var filename = @"C:\Users\willi\Downloads\MasterDataReport2.csv";
            var connString = string.Format(
                @"Provider=Microsoft.Jet.OleDb.4.0;
                Data Source={0};
                Extended Properties=""Text;
                HDR=YES;
                FMT=Delimited""",
                Path.GetDirectoryName(filename));
            using (var conn = new OleDbConnection(connString))
            {
                conn.Open();
                var query = "SELECT * FROM [" + Path.GetFileName(filename) + "]";
                using (var adaptr = new OleDbDataAdapter(query,conn))
                {
                    adaptr.Fill(table);
                }
            }
            // Save in an SQLite file
            string desktopPath =
                Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            string fullPath = desktopPath + "\\class.db";
            SQLiteConnection con = new SQLiteConnection("Data Source=" + fullPath);
            con.Open();
            // Create a table in the database to receive the information from the DataSet
            SQLiteCommand cmd = new SQLiteCommand(con);
            SQLiteDataAdapter adaptor = new SQLiteDataAdapter("SELECT * from MasterDataTable", con);
            adaptor.InsertCommand = new SQLiteCommand("INSERT INTO MasterDataTable VALUES (" +
                ":startTime, " +
                ":entryId, " +
                ":entryType, " +
                ":category, " +
                ":class, " +
                ":participants, " +
                ":studioName, " +
                ":routineTitle)",
                con
            );
            adaptor.InsertCommand.Parameters.Add("startTime", DbType.String, 0, "StartTime");
            adaptor.InsertCommand.Parameters.Add("entryId", DbType.Int16, 0, "EntryID");
            adaptor.InsertCommand.Parameters.Add("entryType", DbType.String, 0, "EntryType");
            adaptor.InsertCommand.Parameters.Add("category", DbType.String, 0, "Category");
            adaptor.InsertCommand.Parameters.Add("class", DbType.String, 0, "Class");
            adaptor.InsertCommand.Parameters.Add("participants", DbType.String, 0, "Participants");
            adaptor.InsertCommand.Parameters.Add("studioName", DbType.String, 0, "StudioName");
            adaptor.InsertCommand.Parameters.Add("routineTitle", DbType.String, 0, "Routine Title");
            adaptor.Update(ds, "MasterDataTable");
            //Check database by filling the dataset in the other direction and displaying
            ds = new DataSet();
            adaptor.Fill(ds, "MasterDataTable");
            foreach (DataTable dt in ds.Tables)
            {
                Console.WriteLine("Table {0}", dt.TableName);
                foreach (DataRow dr in dt.Rows)
                {
                    foreach (DataColumn dc in dt.Columns)
                    {
                        Console.Write("{0,-18}", dr[dc]);
                    }
                    Console.WriteLine();
                }
            }
        }
    }
}
</code>```

Any help would be much appreciated.

答:
I found the cause and a solution.

The cause was that rows are added to the DataSet from the OleDbDataAdapter.Fill() with a state of "Unchanged".  The SQLiteDataAdapter.Update() method reads the "Unchanged" RowState and doesn't execute the INSERT query.

My solution was to put:

```<code>foreach (DataRow row in ds.Tables[0].Rows)
{
   row.SetAdded();
}
</code>```

after the Fill() call to set the RowState of each row to "Added".

The final working solution is:

```<code>using System;
using System.Data;
using System.Data.OleDb;
using System.Data.SQLite;
using System.IO;

namespace DataAdapterExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a simple dataset
            DataSet ds = new DataSet();
            var filename = @"C:\Users\willi\Downloads\MasterDataReport2.csv";
            var connString = string.Format(
                @"Provider=Microsoft.Jet.OleDb.4.0;
                Data Source={0};
                Extended Properties=""Text;
                HDR=YES;
                FMT=Delimited""",
                Path.GetDirectoryName(filename));
            using (var conn = new OleDbConnection(connString))
            {
                conn.Open();
                var query = "SELECT * FROM [" + Path.GetFileName(filename) + "]";
                using (var adaptr = new OleDbDataAdapter(query,conn))
                {
                    adaptr.Fill(ds);
                }
            }

            // Change the RowState to "Added" for the Update() method
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                row.SetAdded();
            }

            // Save in an SQLite file
            string desktopPath =
                Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            string fullPath = desktopPath + "\\class.db";
            SQLiteConnection con = new SQLiteConnection("Data Source=" + fullPath);
            con.Open();
            // receive the information from the DataSet into the db
            SQLiteCommand cmd = new SQLiteCommand(con);
            SQLiteDataAdapter adaptor = new SQLiteDataAdapter("SELECT * from MasterDataTable", con);
            adaptor.InsertCommand = new SQLiteCommand("INSERT INTO MasterDataTable VALUES (" +
                ":startTime, " +
                ":entryId, " +
                ":entryType, " +
                ":category, " +
                ":class, " +
                ":participants, " +
                ":studioName, " +
                ":routineTitle)",
                con
            );
            adaptor.InsertCommand.Parameters.Add("startTime", DbType.String, 0, "StartTime");
            adaptor.InsertCommand.Parameters.Add("entryId", DbType.Int16, 0, "EntryID");
            adaptor.InsertCommand.Parameters.Add("entryType", DbType.String, 0, "EntryType");
            adaptor.InsertCommand.Parameters.Add("category", DbType.String, 0, "Category");
            adaptor.InsertCommand.Parameters.Add("class", DbType.String, 0, "Class");
            adaptor.InsertCommand.Parameters.Add("participants", DbType.String, 0, "Participants");
            adaptor.InsertCommand.Parameters.Add("studioName", DbType.String, 0, "StudioName");
            adaptor.InsertCommand.Parameters.Add("routineTitle", DbType.String, 0, "Routine Title");
            adaptor.Update(ds);
            //Check database by filling the dataset in the other direction and displaying
            ds = new DataSet();
            adaptor.Fill(ds);
            foreach (DataTable dt in ds.Tables)
            {
                Console.WriteLine("Table {0}", dt.TableName);
                foreach (DataRow dr in dt.Rows)
                {
                    foreach (DataColumn dc in dt.Columns)
                    {
                        Console.Write("{0,-18}", dr[dc]);
                    }
                    Console.WriteLine();
                }
            }
        }
    }
}

</code>```

This code is just a working prototype for a larger project, but it works as expected.

Body:
I'm struggling to get my code to work.

I'm combining the examples I found here:
Parsing CSV using OleDb using C# and
Save Dataset to SQLite format file

I'm reading a CSV file into a DataSet using an OleDbConnection and OleDbDataAdapter (which is working), and then saving that DataSet to an SQLite Db using an SQLiteConnection and SQLiteDataAdapter (which is not working).

The test code from the 2nd example above works just fine, where the DataSet is created from code and then saved to the database.

The MasterDataTable in the database exists already.  I created it directly in the target db.

Here's my code:

using System;
using System.Data;
using System.Data.OleDb;
using System.Data.SQLite;
using System.IO;

namespace DataAdapterExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a simple dataset
            DataTable table = new DataTable("MasterDataTable");
            DataSet ds = new DataSet();
            ds.Tables.Add(table);
            var filename = @"C:\Users\willi\Downloads\MasterDataReport2.csv";
            var connString = string.Format(
                @"Provider=Microsoft.Jet.OleDb.4.0;
                Data Source={0};
                Extended Properties=""Text;
                HDR=YES;
                FMT=Delimited""",
                Path.GetDirectoryName(filename));
            using (var conn = new OleDbConnection(connString))
            {
                conn.Open();
                var query = "SELECT * FROM [" + Path.GetFileName(filename) + "]";
                using (var adaptr = new OleDbDataAdapter(query,conn))
                {
                    adaptr.Fill(table);
                }
            }
            // Save in an SQLite file
            string desktopPath =
                Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            string fullPath = desktopPath + "\\class.db";
            SQLiteConnection con = new SQLiteConnection("Data Source=" + fullPath);
            con.Open();
            // Create a table in the database to receive the information from the DataSet
            SQLiteCommand cmd = new SQLiteCommand(con);
            SQLiteDataAdapter adaptor = new SQLiteDataAdapter("SELECT * from MasterDataTable", con);
            adaptor.InsertCommand = new SQLiteCommand("INSERT INTO MasterDataTable VALUES (" +
                ":startTime, " +
                ":entryId, " +
                ":entryType, " +
                ":category, " +
                ":class, " +
                ":participants, " +
                ":studioName, " +
                ":routineTitle)",
                con
            );
            adaptor.InsertCommand.Parameters.Add("startTime", DbType.String, 0, "StartTime");
            adaptor.InsertCommand.Parameters.Add("entryId", DbType.Int16, 0, "EntryID");
            adaptor.InsertCommand.Parameters.Add("entryType", DbType.String, 0, "EntryType");
            adaptor.InsertCommand.Parameters.Add("category", DbType.String, 0, "Category");
            adaptor.InsertCommand.Parameters.Add("class", DbType.String, 0, "Class");
            adaptor.InsertCommand.Parameters.Add("participants", DbType.String, 0, "Participants");
            adaptor.InsertCommand.Parameters.Add("studioName", DbType.String, 0, "StudioName");
            adaptor.InsertCommand.Parameters.Add("routineTitle", DbType.String, 0, "Routine Title");
            adaptor.Update(ds, "MasterDataTable");
            //Check database by filling the dataset in the other direction and displaying
            ds = new DataSet();
            adaptor.Fill(ds, "MasterDataTable");
            foreach (DataTable dt in ds.Tables)
            {
                Console.WriteLine("Table {0}", dt.TableName);
                foreach (DataRow dr in dt.Rows)
                {
                    foreach (DataColumn dc in dt.Columns)
                    {
                        Console.Write("{0,-18}", dr[dc]);
                    }
                    Console.WriteLine();
                }
            }
        }
    }
}

Any help would be much appreciated.

Body:
I found the cause and a solution.

The cause was that rows are added to the DataSet from the OleDbDataAdapter.Fill() with a state of "Unchanged".  The SQLiteDataAdapter.Update() method reads the "Unchanged" RowState and doesn't execute the INSERT query.

My solution was to put:

foreach (DataRow row in ds.Tables[0].Rows)
{
   row.SetAdded();
}

after the Fill() call to set the RowState of each row to "Added".

The final working solution is:

using System;
using System.Data;
using System.Data.OleDb;
using System.Data.SQLite;
using System.IO;

namespace DataAdapterExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a simple dataset
            DataSet ds = new DataSet();
            var filename = @"C:\Users\willi\Downloads\MasterDataReport2.csv";
            var connString = string.Format(
                @"Provider=Microsoft.Jet.OleDb.4.0;
                Data Source={0};
                Extended Properties=""Text;
                HDR=YES;
                FMT=Delimited""",
                Path.GetDirectoryName(filename));
            using (var conn = new OleDbConnection(connString))
            {
                conn.Open();
                var query = "SELECT * FROM [" + Path.GetFileName(filename) + "]";
                using (var adaptr = new OleDbDataAdapter(query,conn))
                {
                    adaptr.Fill(ds);
                }
            }

            // Change the RowState to "Added" for the Update() method
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                row.SetAdded();
            }

            // Save in an SQLite file
            string desktopPath =
                Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            string fullPath = desktopPath + "\\class.db";
            SQLiteConnection con = new SQLiteConnection("Data Source=" + fullPath);
            con.Open();
            // receive the information from the DataSet into the db
            SQLiteCommand cmd = new SQLiteCommand(con);
            SQLiteDataAdapter adaptor = new SQLiteDataAdapter("SELECT * from MasterDataTable", con);
            adaptor.InsertCommand = new SQLiteCommand("INSERT INTO MasterDataTable VALUES (" +
                ":startTime, " +
                ":entryId, " +
                ":entryType, " +
                ":category, " +
                ":class, " +
                ":participants, " +
                ":studioName, " +
                ":routineTitle)",
                con
            );
            adaptor.InsertCommand.Parameters.Add("startTime", DbType.String, 0, "StartTime");
            adaptor.InsertCommand.Parameters.Add("entryId", DbType.Int16, 0, "EntryID");
            adaptor.InsertCommand.Parameters.Add("entryType", DbType.String, 0, "EntryType");
            adaptor.InsertCommand.Parameters.Add("category", DbType.String, 0, "Category");
            adaptor.InsertCommand.Parameters.Add("class", DbType.String, 0, "Class");
            adaptor.InsertCommand.Parameters.Add("participants", DbType.String, 0, "Participants");
            adaptor.InsertCommand.Parameters.Add("studioName", DbType.String, 0, "StudioName");
            adaptor.InsertCommand.Parameters.Add("routineTitle", DbType.String, 0, "Routine Title");
            adaptor.Update(ds);
            //Check database by filling the dataset in the other direction and displaying
            ds = new DataSet();
            adaptor.Fill(ds);
            foreach (DataTable dt in ds.Tables)
            {
                Console.WriteLine("Table {0}", dt.TableName);
                foreach (DataRow dr in dt.Rows)
                {
                    foreach (DataColumn dc in dt.Columns)
                    {
                        Console.Write("{0,-18}", dr[dc]);
                    }
                    Console.WriteLine();
                }
            }
        }
    }
}

This code is just a working prototype for a larger project, but it works as expected.


问:
MDCChipField Swift - scrollable direction
I am trying to use MDCChipField, the material design component for Swift.
I am implementing the 'input chip' type and am able to add the entered text as a chip with

```<code>let mdcSearchField = MDCSearchField()
mdcSearchField.addChip(chipView)
</code>```

When the chips overflow in MDCChipField, they get added to next row. How can i set the scrollable direction to horizontal instead of vertical?

In the link,
https://material.io/design/components/chips.html#input-chips,
The placement section explains

Input chips can be integrated with other components. They can appear:

```<code> - Inline with the text input cursor in a field
 - In a stacked list
 - In a horizontally scrollable list
</code>```

How do i do a a horizontally scrollable list in code?

Thanks.

答:
My approach was this:

Create a scrollable view

create an offset of say 10 for padding between chips

Add chips to the scrollable view

Set the frame origin of the chip with the declared offset

Add the chip's width to the offset plus the initial offset value (in this case 10)

Increase the content width of the scrollable view, set the width to the total
offset

(add more chips/repeat)

On chip removal (if needed)

Set initial offset back to 10

Remove chip from parent scrollable view

Loop through subviews and set the offset again to each of them

Set the scrollable view new width using the total offset

Here is a sample in Swift
Configure initial layout

```<code>class ChipSample
{
    var tagXOffset = 10
    var tagPadding = 10
    func configureTagsView()
    {
        tagView = UIScrollView(frame: CGRect(x: 0, y: 120, width: view.bounds.width, height: 40))
        view.addSubview(tagView)
    }

</code>```

Add a chip

```<code>    func addChip(name:String)
    {
        let chip = MDCChipView()
        chip.titleLabel.text = name
        chip.setTitleColor(.gray, for: .normal)
        chip.sizeToFit()
        chip.addTarget(self, action: #selector(removeChip), for: .touchUpInside)
        tagView.addSubview(chip)
        chip.frame.origin.x = tagXOffset
        chip.frame.origin.y = 0
        tagXOffset += tagPadding + chip.frame.width
        tagView.contentSize = CGSize(width: tagXOffset, height: tagViewHeight)
    }
</code>```

Remove the chip

```<code>    @objc func removeChip(sender: MDCChipView!)
    {
        tagXOffset = tagPadding
        sender.removeFromSuperview()
        for subview in tagView.subviews {
            subview.frame.origin.x = tagXOffset
            tagXOffset += tagPadding + subview.frame.width
        }
    }
</code>```

Body:
I am trying to use MDCChipField, the material design component for Swift.
I am implementing the 'input chip' type and am able to add the entered text as a chip with

let mdcSearchField = MDCSearchField()
mdcSearchField.addChip(chipView)

When the chips overflow in MDCChipField, they get added to next row. How can i set the scrollable direction to horizontal instead of vertical?

In the link,
https://material.io/design/components/chips.html#input-chips,
The placement section explains

Input chips can be integrated with other components. They can appear:

 - Inline with the text input cursor in a field
 - In a stacked list
 - In a horizontally scrollable list

How do i do a a horizontally scrollable list in code?

Thanks.

Body:
My approach was this:

Create a scrollable view

create an offset of say 10 for padding between chips

Add chips to the scrollable view

Set the frame origin of the chip with the declared offset

Add the chip's width to the offset plus the initial offset value (in this case 10)

Increase the content width of the scrollable view, set the width to the total
offset

(add more chips/repeat)

On chip removal (if needed)

Set initial offset back to 10

Remove chip from parent scrollable view

Loop through subviews and set the offset again to each of them

Set the scrollable view new width using the total offset

Here is a sample in Swift
Configure initial layout

class ChipSample
{
    var tagXOffset = 10
    var tagPadding = 10
    func configureTagsView()
    {
        tagView = UIScrollView(frame: CGRect(x: 0, y: 120, width: view.bounds.width, height: 40))
        view.addSubview(tagView)
    }

Add a chip

    func addChip(name:String)
    {
        let chip = MDCChipView()
        chip.titleLabel.text = name
        chip.setTitleColor(.gray, for: .normal)
        chip.sizeToFit()
        chip.addTarget(self, action: #selector(removeChip), for: .touchUpInside)
        tagView.addSubview(chip)
        chip.frame.origin.x = tagXOffset
        chip.frame.origin.y = 0
        tagXOffset += tagPadding + chip.frame.width
        tagView.contentSize = CGSize(width: tagXOffset, height: tagViewHeight)
    }

Remove the chip

    @objc func removeChip(sender: MDCChipView!)
    {
        tagXOffset = tagPadding
        sender.removeFromSuperview()
        for subview in tagView.subviews {
            subview.frame.origin.x = tagXOffset
            tagXOffset += tagPadding + subview.frame.width
        }
    }


问:
An implicit MessagesProvider instance was not found. Java Play Framework 2.8
I'm having a problem injecting FormFactory to my Controller, when I try to pass the Form to the view it gives me a compilation error "An implicit MessagesProvider instance was not found.  Please see https://www.playframework.com/documentation/latest/ScalaForms#Passing-MessagesProvider-to-Form-Helpers".

ProjectController.java

```<code>package controllers;

import java.util.List;

import javax.inject.Inject;

import models.Project;
import play.data.Form;
import play.data.FormFactory;
import play.mvc.*;
import play.twirl.api.Content;
import views.html.Project.*;

public class ProjectsController extends Controller implements ControllerInterfase{
    private Form<Project> projectForm;

    @Inject
    public ProjectsController(FormFactory formFactory) {
        this.projectForm = formFactory.form(Project.class).withDirectFieldAccess(true);
    }

    // Create - Crea un modelo
    @Override
    public Result create() {
        return ok((Content)create.render(projectForm));
    }

}

</code>```

create.scala.html

```<code>@import helper._

@(projectForm : Form[Project])
@layout("Create Project"){
        <main>
            @form(action = routes.ProjectsController.store()){
                @inputText(projectForm("id"))
                @inputText(projectForm("owner_id"))
                @inputText(projectForm("name"))

                <input type="submit" value="Create">
            }

        </main>

}
</code>```

Project.java (model)

```<code>package models;

import javax.persistence.Entity;
import javax.persistence.Id;

import io.ebean.Finder;
import io.ebean.Model;

@Entity
public class Project extends Model{

    public Project() {}

    @Id
    public Integer id;
    public Integer owner_id;
    public String name;

    public static Finder<Integer, Project> find = new Finder<>(Project.class);

}
</code>```

Any idea?

答:
The answer, at least for me, was found in the example play-java-forms code

Specifically:

1) Injecting MessagesApi into the controller:

```<code>@Inject
    public MyController(FormFactory formFactory, MessagesApi messagesApi) {
...
    }
</code>```

2) Adding the implicit parameter to the view:

```<code>@(form: Form[MyForm])(implicit request: Http.Request, messages: play.i18n.Messages)
</code>```

3) Passing it to the implicit parameter on the form:

```<code>public Result create(Http.Request request) {
        Form<MyForm> form = formFactory.form(MyForm.class);
        return ok(views.html.example.render(form, request, messagesApi.preferred(request)));
}
</code>```

Body:
I'm having a problem injecting FormFactory to my Controller, when I try to pass the Form to the view it gives me a compilation error "An implicit MessagesProvider instance was not found.  Please see https://www.playframework.com/documentation/latest/ScalaForms#Passing-MessagesProvider-to-Form-Helpers".

ProjectController.java

package controllers;

import java.util.List;

import javax.inject.Inject;

import models.Project;
import play.data.Form;
import play.data.FormFactory;
import play.mvc.*;
import play.twirl.api.Content;
import views.html.Project.*;

public class ProjectsController extends Controller implements ControllerInterfase{
    private Form<Project> projectForm;

    @Inject
    public ProjectsController(FormFactory formFactory) {
        this.projectForm = formFactory.form(Project.class).withDirectFieldAccess(true);
    }

    // Create - Crea un modelo
    @Override
    public Result create() {
        return ok((Content)create.render(projectForm));
    }

}

create.scala.html

@import helper._

@(projectForm : Form[Project])
@layout("Create Project"){

            @form(action = routes.ProjectsController.store()){
                @inputText(projectForm("id"))
                @inputText(projectForm("owner_id"))
                @inputText(projectForm("name"))

                <input type="submit" value="Create">
            }

}

Project.java (model)

package models;

import javax.persistence.Entity;
import javax.persistence.Id;

import io.ebean.Finder;
import io.ebean.Model;

@Entity
public class Project extends Model{

    public Project() {}

    @Id
    public Integer id;
    public Integer owner_id;
    public String name;

    public static Finder<Integer, Project> find = new Finder<>(Project.class);

}

Any idea?

Body:
The answer, at least for me, was found in the example play-java-forms code

Specifically:

1) Injecting MessagesApi into the controller:

@Inject
    public MyController(FormFactory formFactory, MessagesApi messagesApi) {
...
    }

2) Adding the implicit parameter to the view:

@(form: Form[MyForm])(implicit request: Http.Request, messages: play.i18n.Messages)

3) Passing it to the implicit parameter on the form:

public Result create(Http.Request request) {
        Form<MyForm> form = formFactory.form(MyForm.class);
        return ok(views.html.example.render(form, request, messagesApi.preferred(request)));
}


问:
inverse cartesian product - given the product, find the index
I have a function which computes the n'th element of the cartesian product of a number of input arrays:

```<code>def prod(arrs, n):
    out = []

    for i,arr in enumerate(arrs):
        denom = numpy.prod([ len(p) for p in arrs[i+1:] ], dtype=int)
        idx = n // denom % len(arr)
        out.append( arr[idx] )

    return out
</code>```

This function works great:

```<code>a = [ 1000, 1100, 1200, 1300, 1400 ]
b = [ 1.0, 1.5, 2.0, 2.5, 3.0, 3.5 ]
c = [ -2, -1, 0, 1, 2 ]

for n in range(20, 30):
    i = prod([a, b, c], n)
    print(i)
</code>```

```<code>[1000, 3.0, -2]
[1000, 3.0, -1]
[1000, 3.0, 0]
[1000, 3.0, 1]
[1000, 3.0, 2]
[1000, 3.5, -2]
[1000, 3.5, -1]
[1000, 3.5, 0]
[1000, 3.5, 1]
[1000, 3.5, 2]
</code>```

Now I need to "go backwards".

That is, given the input arrays [ a, b, c ], and a single permutation, find which element in the cartesian product that permutation is. (each array can be assumed to contain only distinct elements.)

Eg:

```<code>def n_from_prod(arrs, arr):
    # TODO: calculate n

n = n_from_prod([a, b, c], [1000, 3.5, -2])

assert n == 25
</code>```

Question:

Given a single permutation of the cartesian product of a number of input arrays, how can I find n, which number in the series, that permutation is?

Body:
I have a function which computes the n'th element of the cartesian product of a number of input arrays:

def prod(arrs, n):
    out = []

    for i,arr in enumerate(arrs):
        denom = numpy.prod([ len(p) for p in arrs[i+1:] ], dtype=int)
        idx = n // denom % len(arr)
        out.append( arr[idx] )

    return out

This function works great:

a = [ 1000, 1100, 1200, 1300, 1400 ]
b = [ 1.0, 1.5, 2.0, 2.5, 3.0, 3.5 ]
c = [ -2, -1, 0, 1, 2 ]

for n in range(20, 30):
    i = prod([a, b, c], n)
    print(i)

[1000, 3.0, -2]
[1000, 3.0, -1]
[1000, 3.0, 0]
[1000, 3.0, 1]
[1000, 3.0, 2]
[1000, 3.5, -2]
[1000, 3.5, -1]
[1000, 3.5, 0]
[1000, 3.5, 1]
[1000, 3.5, 2]

Now I need to "go backwards".

That is, given the input arrays [ a, b, c ], and a single permutation, find which element in the cartesian product that permutation is. (each array can be assumed to contain only distinct elements.)

Eg:

def n_from_prod(arrs, arr):
    # TODO: calculate n

n = n_from_prod([a, b, c], [1000, 3.5, -2])

assert n == 25

Question:

Given a single permutation of the cartesian product of a number of input arrays, how can I find n, which number in the series, that permutation is?

Body:
Assuming a,b,c are sorted; otherwise you have to use index or similar:

def get_idx(x,a,b,c):
    return np.ravel_multi_index([np.searchsorted(A,B) for B,A in zip(x,(a,b,c))],[*map(len,(a,b,c))])

Test:

import itertools as it

[get_idx(p,a,b,c) for p in it.product(a,b,c)]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149]


问:
react navigation process when user log in and log out in react native
I have two bottom tab navigator. A, B.

Both of them has login, logout.

Don't ask me why both of them has.

When user log in and log out, I want to reset all of stack and go to stack A.

```<code> const resetAction = StackActions.reset({
    index: 0,
    actions: [NavigationActions.navigate({ routeName: "A" })]
  });

  goToA = () => {
   props.navigation.dispatch(resetAction)
  }
</code>```

when I login in stack A, there are no problem. but when I login in stack B
It crashes. because in B there are no A route name.

how can I solve this?

Thanks.

答:
I might find solution.

previously, I put stack navigator into each switch navigator.

But it's not efficient.

I should put switch navigator into stack navigator.

if you have more efficient way to solve this, feel free to tell me.

Thanks!

Body:
I have two bottom tab navigator. A, B.

Both of them has login, logout.

Don't ask me why both of them has.

When user log in and log out, I want to reset all of stack and go to stack A.

 const resetAction = StackActions.reset({
    index: 0,
    actions: [NavigationActions.navigate({ routeName: "A" })]
  });

  goToA = () => {
   props.navigation.dispatch(resetAction)
  }

when I login in stack A, there are no problem. but when I login in stack B
It crashes. because in B there are no A route name.

how can I solve this?

Thanks.


问:
Is Θ(log(n!)) = Θ(n log(n))?
From what I understand saying that if an algorithm is in Θ(log(n!)) then it is in O(n log(n)) is correct, as big-O denotes an upper bound. Would it be also correct to say that if an algorithm is in Θ(log(n!)) then it is in Θ(n log(n))?

By plotting the two growths I can see they are similar but is it correct to say that they are equivalent?

答:
Yes.  n! < nn, so log(n!) < n * log(n).

At the same time, n! > (n/2)n/2 (for even n), so log(n!) > (n/2) * (log(n)-1)

Title: Is Θ(log(n!)) = Θ(n log(n))?


问:
Corrupted PDF from direct url in SSRS
I am trying to generate a direct url to my report so it can be downloaded as PDF instead of redirect to the report UI.
If I paste the url on the browser it just redirects me to the report's page.
I found 2 solutions to my problem but both generate a corrupted pdf.</p>

```<code>        public ActionResult GetReportingData()
        {
            var theURL = "http://servername/Reports_DomainName/Pages/Report.aspx?ItemPath=%2fMQMS2_TST%2fReportTest&year=2019&rs:Format=PDF";

            WebClient Client = new WebClient();
            Client.Credentials = new NetworkCredential(@"username", "password");

            byte[] myDataBuffer = Client.DownloadData(theURL);

            var filename = "Test.pdf";
            var path = "C:\\Test";

            var fileLocation = path + "\\" + filename;

            System.IO.File.WriteAllBytes(fileLocation, myDataBuffer);
            return RedirectToAction("Index", "Case");
        }
</code>```

```<code>        public ActionResult GetReportingData()
        {
            var url = "http://servername/Reports_DomainName/Pages/Report.aspx?ItemPath=%2fMQMS2_TST%2fReportTest&year=2019&rs:Format=PDF";
            try
            {
                url = url.Replace("\n", "");
                WebRequest request = WebRequest.Create(url);

                NetworkCredential credentials = new NetworkCredential(@"username", "password");
                request.Credentials = credentials;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream stream = response.GetResponseStream();

                return new FileStreamResult(stream, "application/pdf");
            }
            catch (Exception ex)
            {
                return RedirectToAction("Index", "Case");
            }
        }
</code>```

答:
I'm more familiar with generating the PDF from data (via SSRS LocalReport), which gives me full control.  However, what happens if you tweak your first option like so:

```<code>public async Task<ActionResult> GetReportingData()
{
    var theURL = "http://servername/Reports_DomainName/Pages/Report.aspx?ItemPath=%2fMQMS2_TST%2fReportTest&year=2019&rs:Format=PDF";

    try
    {
        WebClient Client = new WebClient();
        Client.Credentials = new NetworkCredential(@"username", "password");

        byte[] data = Client.DownloadData(theURL);

        return new FileContentResult(data, "PDF") { FileDownloadName = String.Format("SomeReport_{0}.pdf", DateTime.Now.ToString("yyyyMMddhhmmss")) };
    }
    catch(Exception ex)
    {
        // do something
    }
}
</code>```

This should prompt you to save the file from browser.  Then try opening the file to see if it's still corrupt.  It's possible the URL you're calling to gen the PDF is returning other noise in the response content and therefore not just a byte array of the report/pdf.

Title: Corrupted PDF from direct url in SSRS

Body:
I am trying to generate a direct url to my report so it can be downloaded as PDF instead of redirect to the report UI.
If I paste the url on the browser it just redirects me to the report's page.
I found 2 solutions to my problem but both generate a corrupted pdf.

        public ActionResult GetReportingData()
        {
            var theURL = "http://servername/Reports_DomainName/Pages/Report.aspx?ItemPath=%2fMQMS2_TST%2fReportTest&year=2019&rs:Format=PDF";

            WebClient Client = new WebClient();
            Client.Credentials = new NetworkCredential(@"username", "password");

            byte[] myDataBuffer = Client.DownloadData(theURL);

            var filename = "Test.pdf";
            var path = "C:\\Test";

            var fileLocation = path + "\\" + filename;

            System.IO.File.WriteAllBytes(fileLocation, myDataBuffer);
            return RedirectToAction("Index", "Case");
        }

        public ActionResult GetReportingData()
        {
            var url = "http://servername/Reports_DomainName/Pages/Report.aspx?ItemPath=%2fMQMS2_TST%2fReportTest&year=2019&rs:Format=PDF";
            try
            {
                url = url.Replace("\n", "");
                WebRequest request = WebRequest.Create(url);

                NetworkCredential credentials = new NetworkCredential(@"username", "password");
                request.Credentials = credentials;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream stream = response.GetResponseStream();

                return new FileStreamResult(stream, "application/pdf");
            }
            catch (Exception ex)
            {
                return RedirectToAction("Index", "Case");
            }
        }

Body:
I'm more familiar with generating the PDF from data (via SSRS LocalReport), which gives me full control.  However, what happens if you tweak your first option like so:

public async Task<ActionResult> GetReportingData()
{
    var theURL = "http://servername/Reports_DomainName/Pages/Report.aspx?ItemPath=%2fMQMS2_TST%2fReportTest&year=2019&rs:Format=PDF";

    try
    {
        WebClient Client = new WebClient();
        Client.Credentials = new NetworkCredential(@"username", "password");

        byte[] data = Client.DownloadData(theURL);

        return new FileContentResult(data, "PDF") { FileDownloadName = String.Format("SomeReport_{0}.pdf", DateTime.Now.ToString("yyyyMMddhhmmss")) };
    }
    catch(Exception ex)
    {
        // do something
    }
}

This should prompt you to save the file from browser.  Then try opening the file to see if it's still corrupt.  It's possible the URL you're calling to gen the PDF is returning other noise in the response content and therefore not just a byte array of the report/pdf.


问:
How to pass a variable from views to base.html in Django?
I want to show the user's first name on the navbar of my project. This navbar is on the base.html file.

In my views.py I have created a variable that does this

```<code>def base(request):
    user = request.user
    u = User.objects.get(username=user)
    us = u.clients.first_name
    context = {'u': u, 'us': us}
    return render(request, "backend/base.html", context)
</code>```

I can get it to work on any other .html file, but not on the base.html, that looks like this

```<code><span class="mb-0 text-sm  font-weight-bold">{{us}}</span>
</code>```

This is my model

```<code>class Clients(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=30, verbose_name="Primeiro Nome")
    last_name = models.CharField(max_length=30, verbose_name="Apelido")
    address = models.CharField(max_length=200, verbose_name="Morada")
    nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], primary_key=True)
    mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')])
    email = models.CharField(max_length=200, null=True, verbose_name="Email")

    def __str__(self):
        return "%s %s" % (self.first_name, self.last_name)

    class Meta:
        verbose_name_plural = "Clientes"
</code>```

答:
In views.py try to use render_to_string function.  And dont forget to configure the static files settings in configuration file.

```<code>from django.template.loader import render_to_string

context = {'u': u, 'us': us}
render_to_string('html_name.html', context)
</code>```

Body:
I want to show the user's first name on the navbar of my project. This navbar is on the base.html file.

In my views.py I have created a variable that does this

def base(request):
    user = request.user
    u = User.objects.get(username=user)
    us = u.clients.first_name
    context = {'u': u, 'us': us}
    return render(request, "backend/base.html", context)

I can get it to work on any other .html file, but not on the base.html, that looks like this

{{us}}

This is my model

class Clients(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=30, verbose_name="Primeiro Nome")
    last_name = models.CharField(max_length=30, verbose_name="Apelido")
    address = models.CharField(max_length=200, verbose_name="Morada")
    nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], primary_key=True)
    mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')])
    email = models.CharField(max_length=200, null=True, verbose_name="Email")

    def __str__(self):
        return "%s %s" % (self.first_name, self.last_name)

    class Meta:
        verbose_name_plural = "Clientes"

Body:
In views.py try to use render_to_string function.  And dont forget to configure the static files settings in configuration file.

from django.template.loader import render_to_string

context = {'u': u, 'us': us}
render_to_string('html_name.html', context)


问:
Javascript SetTimeout Function Not Pausing After Execution
I am checking for a change in a CSS class. I want the check to happen every 1000 milliseconds. Currently in the Google Chrome console, I can see it checking without any delay, causing the webpage to crash. What is the issue with the below setTimeout function? Perhaps there is another way of checking for a change in a CSS class also?</p>

```<code>var itemInfo = null;

itemInfo = document.getElementById('option-item-info');
while (itemInfo.className == "disabled") {
    console.log("Test 1");
    getOptionItemInfo();
}

function getOptionItemInfo() {
    setTimeout(function() {
        console.log("Checking...");
        itemInfo = document.getElementById('option-item-info');
    }, 1000);
}
</code>```

答:
Your while loop isn't going to wait for the setTimeout async callback, it's just going to trigger tons of setTimeouts until your browser crashes. Instead, just kick off the setTimeout once and then only call it again from within the callback if you haven't met the desired condition.

```<code>getOptionItemInfo();

function getOptionItemInfo() {
    setTimeout(function() {
        console.log("Checking...");
        var itemInfo = document.getElementById('option-item-info');
        if (itemInfo.className == "disabled") {
            getOptionItemInfo();
        } else {
            console.log("done!");
        }
    }, 1000);
}
</code>```

Body:
I am checking for a change in a CSS class. I want the check to happen every 1000 milliseconds. Currently in the Google Chrome console, I can see it checking without any delay, causing the webpage to crash. What is the issue with the below setTimeout function? Perhaps there is another way of checking for a change in a CSS class also?

var itemInfo = null;

itemInfo = document.getElementById('option-item-info');
while (itemInfo.className == "disabled") {
    console.log("Test 1");
    getOptionItemInfo();
}

function getOptionItemInfo() {
    setTimeout(function() {
        console.log("Checking...");
        itemInfo = document.getElementById('option-item-info');
    }, 1000);
}

Body:
Your while loop isn't going to wait for the setTimeout async callback, it's just going to trigger tons of setTimeouts until your browser crashes. Instead, just kick off the setTimeout once and then only call it again from within the callback if you haven't met the desired condition.

getOptionItemInfo();

function getOptionItemInfo() {
    setTimeout(function() {
        console.log("Checking...");
        var itemInfo = document.getElementById('option-item-info');
        if (itemInfo.className == "disabled") {
            getOptionItemInfo();
        } else {
            console.log("done!");
        }
    }, 1000);
}


问:
Run a batch file from its parent directory in NotePad++
I made a batch file that identifies java files kept in that particular folder and compiles them. But when I was running it from notepad++, the batch file was going to notepad++ working directory i.e. C:\Program Files\Notepad++, and then starting, so I was not getting desired output.

```<code><Command name="Java_Executor" Ctrl="no" Alt="no" Shift="no" Key="0">"D:\Projects\Java\Executor Java.bat"</Command>
</code>```

I tried to edit it many times but didn't got desired output.

```<code><Command name="second try" Ctrl="no" Alt="no" Shift="no" Key="0">cmd /C "cd /d D:\Projects\Java\ && D:\Projects\Java\Executor Java.bat"</Command>
</code>```

This was my second try.

This is the third try:

```<code><Command name="Java_Executor" Ctrl="no" Alt="no" Shift="no" Key="0">cmd /k cd $(CURRENT_DIRECTORY) && "D:\Projects\Java\Executor_Java.bat"</Command>
</code>```

What should I edit so that my batch file runs from the same folder where it is located?
Assuming my bat file is D:\Projects\Java\Executor Java.bat with the contents of:

```<code>@ECHO OFF
color F0
ECHO                                        WELCOME TO EXECUTOR
ECHO                                                         -Garvit Joshi(garvitjoshi9@gmail.com)
ECHO                                                          USER:%USERNAME%
cd %cd%
:first
ECHO LOOKING FOR FILES IN:%cd%
color F0
ECHO Name Of Java Executable Files Present In Folder Are:
python Filename_java.py
set /p "input=Enter The File You Want To Execute:"
ECHO ===============================
javac %input%.java
ECHO ===============================
ECHO Name Of Java Executable Class Present In Folder Are:
python Filename_class.py
ECHO ===============================
javac %input%.java
ECHO ===============================
set /p "input=Enter The Class You Want To Run:"
color 0A
ECHO ===============================
ECHO OUTPUT:
ECHO ===============================
java %input%
ECHO ===============================
color 0F
pause
ECHO =======================================================
ECHO *******************************************************
ECHO =======================================================
goto first
</code>```

答:
```<code><Command name="Java Executor" Ctrl="no" Alt="no" Shift="no" Key="0">cmd /k cd /d "$(CURRENT_DIRECTORY)" && "D:\Projects\Java\Executor Java.bat"</Command>
</code>```

Third try seems almost there. You are changing directory from 'C:/Program Files/Notepad++ to D:\Projects\Java which will require /d after cd, else it will not change directory as to being on a different drive. Probably a good idea to enclose $(CURRENT_DIRECTORY) with double quotes as the current directory may have special characters with it's path i.e. "D:\dogs & cats". Executor Java.bat displays same issues with use of cd so it will behave similar.

Test script "D:\Projects\Java\Executor Java.bat" being:

```<code>@echo cd: "%cd%"
</code>```

Run Java Executor from Run menu of Notepad++ displays prompt window with:

```<code>cd: "D:\Projects\Java"

D:\Projects\Java>
</code>```

The prompt is ready for input as cmd /k was used.

In the batch-file in the question post is the line:

```<code>cd %cd%
</code>```

I would expect that to do nothing as %cd% is already the current directory.

Perhaps wanting to change directory to the script directory:

```<code>cd /d "%~dp0"
</code>```

View for /? or call /? about modifiers like dp.

Body:
I made a batch file that identifies java files kept in that particular folder and compiles them. But when I was running it from notepad++, the batch file was going to notepad++ working directory i.e. C:\Program Files\Notepad++, and then starting, so I was not getting desired output.

<Command name="Java_Executor" Ctrl="no" Alt="no" Shift="no" Key="0">"D:\Projects\Java\Executor Java.bat"</Command>

I tried to edit it many times but didn't got desired output.

<Command name="second try" Ctrl="no" Alt="no" Shift="no" Key="0">cmd /C "cd /d D:\Projects\Java\ && D:\Projects\Java\Executor Java.bat"</Command>

This was my second try.

This is the third try:

<Command name="Java_Executor" Ctrl="no" Alt="no" Shift="no" Key="0">cmd /k cd $(CURRENT_DIRECTORY) && "D:\Projects\Java\Executor_Java.bat"</Command>

What should I edit so that my batch file runs from the same folder where it is located?
Assuming my bat file is D:\Projects\Java\Executor Java.bat with the contents of:

@ECHO OFF
color F0
ECHO                                        WELCOME TO EXECUTOR
ECHO                                                         -Garvit Joshi(garvitjoshi9@gmail.com)
ECHO                                                          USER:%USERNAME%
cd %cd%
:first
ECHO LOOKING FOR FILES IN:%cd%
color F0
ECHO Name Of Java Executable Files Present In Folder Are:
python Filename_java.py
set /p "input=Enter The File You Want To Execute:"
ECHO ===============================
javac %input%.java
ECHO ===============================
ECHO Name Of Java Executable Class Present In Folder Are:
python Filename_class.py
ECHO ===============================
javac %input%.java
ECHO ===============================
set /p "input=Enter The Class You Want To Run:"
color 0A
ECHO ===============================
ECHO OUTPUT:
ECHO ===============================
java %input%
ECHO ===============================
color 0F
pause
ECHO =======================================================
ECHO *******************************************************
ECHO =======================================================
goto first

Body:
<Command name="Java Executor" Ctrl="no" Alt="no" Shift="no" Key="0">cmd /k cd /d &quot;$(CURRENT_DIRECTORY)&quot; &amp;&amp; &quot;D:\Projects\Java\Executor Java.bat&quot;</Command>

Third try seems almost there. You are changing directory from 'C:/Program Files/Notepad++ to D:\Projects\Java which will require /d after cd, else it will not change directory as to being on a different drive. Probably a good idea to enclose $(CURRENT_DIRECTORY) with double quotes as the current directory may have special characters with it's path i.e. "D:\dogs & cats". Executor Java.bat displays same issues with use of cd so it will behave similar.

Test script "D:\Projects\Java\Executor Java.bat" being:

@echo cd: "%cd%"

Run Java Executor from Run menu of Notepad++ displays prompt window with:

cd: "D:\Projects\Java"

D:\Projects\Java>

The prompt is ready for input as cmd /k was used.

In the batch-file in the question post is the line:

cd %cd%

I would expect that to do nothing as %cd% is already the current directory.

Perhaps wanting to change directory to the script directory:

cd /d "%~dp0"

View for /? or call /? about modifiers like dp.


问:
How to convert module.exports to json to use in gulp tasks?
I'm trying to pass some variables from my JS config file to SASS, by using this gulp plugin https://www.npmjs.com/package/gulp-json-data-to-sass, which accepts a JSON file as input.

My config file is the following

// config.js

module.exports = {
    use: {
        gallery: true,
        animations: true,
    },
}
```

how can I convert this to a valid JSON file, preferably with gulp itself, in order to be able to pass it to the plugin?

答:
You could store it as JSON:

config.json:

```<code>{
    "use": {
        "gallery": true,
        "animations": true,
    }
}
</code>```

That is how the example for the npm package does it. If you need to consume this from JS code elsewhere, you can require JSON.

```<code>const config = require('./config.json');
</code>```

Not sure how you add this to a gulp pipeline, but you can write a helper in your build pipeline that does this:

```<code>const config = require('./config')
const fs = require('fs')

fs.writeFileSync('./config.json', JSON.stringify(config), 'utf8')
</code>```

Body:
I'm trying to pass some variables from my JS config file to SASS, by using this gulp plugin https://www.npmjs.com/package/gulp-json-data-to-sass, which accepts a JSON file as input.

My config file is the following

// config.js

module.exports = {
    use: {
        gallery: true,
        animations: true,
    },
}

how can I convert this to a valid JSON file, preferably with gulp itself, in order to be able to pass it to the plugin?

Body:
You could store it as JSON:

config.json:

{
    "use": {
        "gallery": true,
        "animations": true,
    }
}

That is how the example for the npm package does it. If you need to consume this from JS code elsewhere, you can require JSON.

const config = require('./config.json');

Not sure how you add this to a gulp pipeline, but you can write a helper in your build pipeline that does this:

const config = require('./config')
const fs = require('fs')

fs.writeFileSync('./config.json', JSON.stringify(config), 'utf8')


问:
Django ModuleNotFoundError when making migrations
First of all: I am well aware that there are several questions with this exact error but I've read at least 20 of them and none helped me correct this error.

This being said, the problem is the following:

I created a directory called 'api' inside my Django project to store all the code related to the api. Inside this directory I created an app called 'profiles_app'. There, in the models.py file I defined a UserProfile class to override the default Django UserProfile class. I then added the app to the INSTALLED_APPS variable in the settings.py file and overrid the default UserProfile class with the following line:

```<code>AUTH_USER_MODEL = 'profiles_api.UserProfile'
</code>```

Finally I tried to make the migrations to see the new table in the database and this is when the error occurred.

This is the stack trace:

```<code>    (venv) C:\Users\Juan Pablo\Documents\backend\backend_django>python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute
    django.setup()
  File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\apps\registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\apps\config.py", line 90, in create
    module = import_module(entry)
  File "C:\Users\JUANPA~1\Envs\venv\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'api'
</code>```

As you can see in the trace I am working in a virtual environment and this is what I have installed:

```<code>asgiref==3.2.3
Django==3.0.3
djangorestframework==3.11.0
mysqlclient==1.4.6
pytz==2019.3
sqlparse==0.3.0
</code>```

This is the project's structure:

The init.py file inside the api directory wasn't there at first but after reading some answers I created a Python package instead of a directory and then that file appeared.

Finally, this is what the INSTALLED_APPS variable in the settings.py file looks like:

```<code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'api.profiles_api',
]
</code>```

I have tried the following:

'profiles_api' instead of 'api.profiles_api' in INSTALLED_APPS

AUTH_USER_MODEL = 'api.profiles_api.UserProfile' instead of 'profiles_api.UserProfile'

Creating a Python package named 'api' instead of a directory.

Any help is really appreciated. Sorry for the long question but I wanted to be as precise as possible.

答:
I made a new project and structured as follows:

Then in installed apps I added 'backend_project.Users' and it worked. Still don't know why the original question was wrong though.

Body:
First of all: I am well aware that there are several questions with this exact error but I've read at least 20 of them and none helped me correct this error.

This being said, the problem is the following:

I created a directory called 'api' inside my Django project to store all the code related to the api. Inside this directory I created an app called 'profiles_app'. There, in the models.py file I defined a UserProfile class to override the default Django UserProfile class. I then added the app to the INSTALLED_APPS variable in the settings.py file and overrid the default UserProfile class with the following line:

AUTH_USER_MODEL = 'profiles_api.UserProfile'

Finally I tried to make the migrations to see the new table in the database and this is when the error occurred.

This is the stack trace:

    (venv) C:\Users\Juan Pablo\Documents\backend\backend_django>python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute
    django.setup()
  File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\apps\registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\apps\config.py", line 90, in create
    module = import_module(entry)
  File "C:\Users\JUANPA~1\Envs\venv\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'api'

As you can see in the trace I am working in a virtual environment and this is what I have installed:

asgiref==3.2.3
Django==3.0.3
djangorestframework==3.11.0
mysqlclient==1.4.6
pytz==2019.3
sqlparse==0.3.0

This is the project's structure:

The init.py file inside the api directory wasn't there at first but after reading some answers I created a Python package instead of a directory and then that file appeared.

Finally, this is what the INSTALLED_APPS variable in the settings.py file looks like:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'api.profiles_api',
]

I have tried the following:

'profiles_api' instead of 'api.profiles_api' in INSTALLED_APPS

AUTH_USER_MODEL = 'api.profiles_api.UserProfile' instead of 'profiles_api.UserProfile'

Creating a Python package named 'api' instead of a directory.

Any help is really appreciated. Sorry for the long question but I wanted to be as precise as possible.