问:
Sorting Column Values in Flutter DataTable
I am having serious difficulty in sorting columns in my DataTable.

Here is my code

```<code>  SingleChildScrollView(
  scrollDirection: Axis.horizontal,
  child: DataTable(
    sortColumnIndex: 0,
    sortAscending: true,

    columnSpacing: 5.0,
      horizontalMargin: 10,
    columns: [
      DataColumn(label: Text('Col1'),
      DataColumn(label: Text('Col2'),numeric: false ),
      DataColumn(label: Text('Col3'),numeric: true ),
      DataColumn(label: Text('Col4'), numeric: true),
      DataColumn(label: Text('Col5'), numeric: true),
    ],
    rows: myList
        .map(
        ((element) => DataRow(
          cells: <DataCell>[
            DataCell(Text(element["Col1"]), placeholder: true,showEditIcon: false),
            DataCell(Text(element["Col2"].toString())),
            DataCell(Text(element["Col3"].toString())),
            DataCell(Text(element["Col4"].toString())),
            DataCell(Text(element["Col5"].toString())),
          ],
        )),
    ).toList(),
  ),
));
</code>```

What more am I meant to do? Ideally, I'd like to have the sort function on whichever column the user presses on, but for now, I'd be delighted with just 1 column working being sortable.

As you can see, I have added the constraints:

```<code>    sortColumnIndex: 0,
    sortAscending: true,
</code>```

But all I get is an arrow near 1st column (ColumnIndex = 0) - which really does nothing when you press it.

What am I doing wrong?

答:
You have to add an onSort property to the column that will be sorted, and call a sorting function.

bool sort = true; // or `false`...

DataTable(
  sortAscending: sort,
  sortColumnIndex: 0,
  columns: [
    DataColumn(
      label: Text("Col1"),
      onSort: (columnIndex, ascending) {
        setState(() {
          sort = !sort;
        });

        onSortColum(columnIndex, ascending);
      }),
      ...
```
<p>And the <code>onSortColum</code> function:</p>
<pre class="lang-dart prettyprint-override"><code>onSortColum(int columnIndex, bool ascending) {
  if (columnIndex == 0) {
    if (ascending) {
      yourDataList.sort((a, b) => a['name'].compareTo(b['name']));
    } else {
      yourDataList.sort((a, b) => b['name'].compareTo(a['name']));
    }
  }
}
</code>```

Body:
I am having serious difficulty in sorting columns in my DataTable.

Here is my code

  SingleChildScrollView(
  scrollDirection: Axis.horizontal,
  child: DataTable(
    sortColumnIndex: 0,
    sortAscending: true,

    columnSpacing: 5.0,
      horizontalMargin: 10,
    columns: [
      DataColumn(label: Text('Col1'),
      DataColumn(label: Text('Col2'),numeric: false ),
      DataColumn(label: Text('Col3'),numeric: true ),
      DataColumn(label: Text('Col4'), numeric: true),
      DataColumn(label: Text('Col5'), numeric: true),
    ],
    rows: myList
        .map(
        ((element) => DataRow(
          cells: <DataCell>[
            DataCell(Text(element["Col1"]), placeholder: true,showEditIcon: false),
            DataCell(Text(element["Col2"].toString())),
            DataCell(Text(element["Col3"].toString())),
            DataCell(Text(element["Col4"].toString())),
            DataCell(Text(element["Col5"].toString())),
          ],
        )),
    ).toList(),
  ),
));

What more am I meant to do? Ideally, I'd like to have the sort function on whichever column the user presses on, but for now, I'd be delighted with just 1 column working being sortable.

As you can see, I have added the constraints:

    sortColumnIndex: 0,
    sortAscending: true,

But all I get is an arrow near 1st column (ColumnIndex = 0) - which really does nothing when you press it.

What am I doing wrong?

Body:
You have to add an onSort property to the column that will be sorted, and call a sorting function.

bool sort = true; // or `false`...

DataTable(
  sortAscending: sort,
  sortColumnIndex: 0,
  columns: [
    DataColumn(
      label: Text("Col1"),
      onSort: (columnIndex, ascending) {
        setState(() {
          sort = !sort;
        });

        onSortColum(columnIndex, ascending);
      }),
      ...

And the onSortColum function:

onSortColum(int columnIndex, bool ascending) {
  if (columnIndex == 0) {
    if (ascending) {
      yourDataList.sort((a, b) => a['name'].compareTo(b['name']));
    } else {
      yourDataList.sort((a, b) => b['name'].compareTo(a['name']));
    }
  }
}


来源: stackexchange

问:
spring autowiring not working from a non-spring managed class
I have a class (Class ABC) that's instantiated by calling the constructor. Class ABC in turn has a helper class (Class XYZ) injected using auto-wired.

Ours is a Spring MVC based application and I don't see any exception while server start-up.

But I still see Class XYZ coming as null. Is it because of the fact that Class ABC is not instantiated by Spring Container?

In such scenarios, how do i make use of auto-wiring?

Thanks.

答:
Spring has util class

```<code> BeanUtils.instantiateClass(clazz)
 BeanUtils.instantiate(clazz)

 YouClass ins = BeanUtils.instantiate(YouClass.class)
</code>```

https://docs.spring.io/autorepo/docs/spring/4.0.2.RELEASE/javadoc-api/org/springframework/beans/BeanUtils.html

ContentLicense: CC BY-SA 3.0

Body:
Spring has util class

 BeanUtils.instantiateClass(clazz)
 BeanUtils.instantiate(clazz)

 YouClass ins = BeanUtils.instantiate(YouClass.class)

https://docs.spring.io/autorepo/docs/spring/4.0.2.RELEASE/javadoc-api/org/springframework/beans/BeanUtils.html

ContentLicense: CC BY-SA 4.0


问:
Can someone explain the parameter void(*pfn)(void*)?
I've come across this piece of code

```<code>inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
</code>```

I don't understand this part

```<code>void(*pfn)(void*)
</code>```

Can someone tell me what it means/is?

This is btw not listed in books for beginners so if you want to mention to read books, it's not there.

Afaik, void is datatype of a function meaning it will not return anything, however that part there...void is used on a pointer?

答:
This is a function pointer (or a pointer to a function).

```<code>void(*pfn)(void*)
</code>```

This is broken down as such:

*pfn (the name of the pointer i.e. pointer to a function)

(void *) (these are the parameters to the function ie. a simple pointer to anything)

void (this is return from the function)

So if you have a function like this:

```<code>void DoSomeThing(void *data) {
  ... does something....
}
</code>```

then you can pass it into the CreateThread function like so...

```<code>int i  = 99;
void * arg = (void*)&i;
pthread_t thread = CreateThread(DoSomeThing, arg, ... other parameters ...);
</code>```

So somewhere in CreateThread it will make a call:

```<code>pfn(parg);
</code>```

and your function DoSomeThing will be called and void * data you get will be the arg you passed in.

More info:

Remember that code is just a sequence of bytes in memory. It's just how the cpu interprets them that makes them different from the thing we call data.

So at any point in a program we can refer to another part of the code by it's memory address. Since the code is broken down into functions with in C, this is a useful unit of reuse that C understands and allows us to treat the address of the function as just another pointer to some data.

In the above example the CreateThread function needs the address of a function so it can execute that function in a new thread. So we pass it a pointer to that function. Hence we pass it a function pointer.

Body:
I've come across this piece of code

inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)

I don't understand this part

void(*pfn)(void*)

Can someone tell me what it means/is?

This is btw not listed in books for beginners so if you want to mention to read books, it's not there.

Afaik, void is datatype of a function meaning it will not return anything, however that part there...void is used on a pointer?

Body:
This is a function pointer (or a pointer to a function).

void(*pfn)(void*)

This is broken down as such:

*pfn (the name of the pointer i.e. pointer to a function)

(void *) (these are the parameters to the function ie. a simple pointer to anything)

void (this is return from the function)

So if you have a function like this:

void DoSomeThing(void *data) {
  ... does something....
}

then you can pass it into the CreateThread function like so...

int i  = 99;
void * arg = (void*)&i;
pthread_t thread = CreateThread(DoSomeThing, arg, ... other parameters ...);

So somewhere in CreateThread it will make a call:

pfn(parg);

and your function DoSomeThing will be called and void * data you get will be the arg you passed in.

More info:

Remember that code is just a sequence of bytes in memory. It's just how the cpu interprets them that makes them different from the thing we call data.

So at any point in a program we can refer to another part of the code by it's memory address. Since the code is broken down into functions with in C, this is a useful unit of reuse that C understands and allows us to treat the address of the function as just another pointer to some data.

In the above example the CreateThread function needs the address of a function so it can execute that function in a new thread. So we pass it a pointer to that function. Hence we pass it a function pointer.


问:
dplyr summarize with subtotals
One of the great things about pivot tables in excel is that they provide subtotals automatically.  First, I would like to know if there is anything already created within dplyr that can accomplish this.  If not, what is the easiest way to achieve it?

In the example below, I show the mean displacement by number of cylinders and carburetors.  For each group of cylinders (4,6,8), I'd like to see the mean displacement for the group (or total displacement, or any other summary statistic).

```<code>library(dplyr)
mtcars %>% group_by(cyl,carb) %>% summarize(mean(disp))

  cyl carb mean(disp)
1   4    1      91.38
2   4    2     116.60
3   6    1     241.50
4   6    4     163.80
5   6    6     145.00
6   8    2     345.50
7   8    3     275.80
8   8    4     405.50
9   8    8     301.00
</code>```

答:
Having tried long and hard for very similar issues, I have found that data.table offers the simplest and fastest solution which fits exactly this purpose

```<code>data.table::cube(
             data.table::as.data.table(mtcars),
             .(mean_disp = mean(disp)),
             by = c("cyl","carb"))

   cyl carb mean_disp
 1:   6    4  163.8000
 2:   4    1   91.3800
 3:   6    1  241.5000
 4:   8    2  345.5000
 5:   8    4  405.5000
 6:   4    2  116.6000
 7:   8    3  275.8000
 8:   6    6  145.0000
 9:   8    8  301.0000
10:   6   NA  183.3143
11:   4   NA  105.1364
12:   8   NA  353.1000
13:  NA    4  308.8200
14:  NA    1  134.2714
15:  NA    2  208.1600
16:  NA    3  275.8000
17:  NA    6  145.0000
18:  NA    8  301.0000
19:  NA   NA  230.7219
</code>```

The NA entries are the subtotals you are looking for; for instance in row 10 the 183.31 result is the mean for all 6 cylinders. The last row with double NA is the one with the overall mean.

From there, you can easily wrap the result with as_tibble() to jump back into the dplyr semantics world.

Title: dplyr summarize with subtotals

Body:
One of the great things about pivot tables in excel is that they provide subtotals automatically.  First, I would like to know if there is anything already created within dplyr that can accomplish this.  If not, what is the easiest way to achieve it?

In the example below, I show the mean displacement by number of cylinders and carburetors.  For each group of cylinders (4,6,8), I'd like to see the mean displacement for the group (or total displacement, or any other summary statistic).

library(dplyr)
mtcars %>% group_by(cyl,carb) %>% summarize(mean(disp))

  cyl carb mean(disp)
1   4    1      91.38
2   4    2     116.60
3   6    1     241.50
4   6    4     163.80
5   6    6     145.00
6   8    2     345.50
7   8    3     275.80
8   8    4     405.50
9   8    8     301.00

Body:
Having tried long and hard for very similar issues, I have found that data.table offers the simplest and fastest solution which fits exactly this purpose

data.table::cube(
             data.table::as.data.table(mtcars),
             .(mean_disp = mean(disp)),
             by = c("cyl","carb"))

   cyl carb mean_disp
 1:   6    4  163.8000
 2:   4    1   91.3800
 3:   6    1  241.5000
 4:   8    2  345.5000
 5:   8    4  405.5000
 6:   4    2  116.6000
 7:   8    3  275.8000
 8:   6    6  145.0000
 9:   8    8  301.0000
10:   6   NA  183.3143
11:   4   NA  105.1364
12:   8   NA  353.1000
13:  NA    4  308.8200
14:  NA    1  134.2714
15:  NA    2  208.1600
16:  NA    3  275.8000
17:  NA    6  145.0000
18:  NA    8  301.0000
19:  NA   NA  230.7219

The NA entries are the subtotals you are looking for; for instance in row 10 the 183.31 result is the mean for all 6 cylinders. The last row with double NA is the one with the overall mean.

From there, you can easily wrap the result with as_tibble() to jump back into the dplyr semantics world.


问:
Incorrect syntax near 'S' when passing string parameter
In c# I have the following lines of code:

```<code> string mySqlStmt = "SELECT CASE WHEN (SELECT COUNT(*)  FROM tlGenericName WHERE ( UPPER(ltrim(rtrim(genericName_str))) = '" + this.cmbGenericName.Text.Trim().ToUpper() + "' ) ) > 0 THEN"
   + " ( SELECT top(1) isnull(genericNameCode_str, '') FROM tlGenericName "
       + " WHERE ( UPPER(ltrim(rtrim(genericName_str))) = '" + this.cmbGenericName.Text.Trim().ToUpper() + "' )  ) ELSE '' END";
</code>```

Then I use an SqlCommand (in c#) for executeScalar.
However, I get the following error:

```<code>Incorrect syntax near 'S'
</code>```

I have noticed that this occurs for some records (a break in the parameter  value); for example:

'BANDAGE P.O.P.ROLL TYPE 1;200MMX2.7M 12's'

How can I safely pass the string parameter in Sql in the designer (c#) ?

答:
Try it using string interpolation :</p>

```<code>var number = 2;
var exampleString = $"Number is : {number}";
</code>```

Body:
In c# I have the following lines of code:

 string mySqlStmt = "SELECT CASE WHEN (SELECT COUNT(*)  FROM tlGenericName WHERE ( UPPER(ltrim(rtrim(genericName_str))) = '" + this.cmbGenericName.Text.Trim().ToUpper() + "' ) ) > 0 THEN"
   + " ( SELECT top(1) isnull(genericNameCode_str, '') FROM tlGenericName "
       + " WHERE ( UPPER(ltrim(rtrim(genericName_str))) = '" + this.cmbGenericName.Text.Trim().ToUpper() + "' )  ) ELSE '' END";

Then I use an SqlCommand (in c#) for executeScalar.
However, I get the following error:

Incorrect syntax near 'S'

I have noticed that this occurs for some records (a break in the parameter  value); for example:

'BANDAGE P.O.P.ROLL TYPE 1;200MMX2.7M 12's'

How can I safely pass the string parameter in Sql in the designer (c#) ?

Body:
Try it using string interpolation :

var number = 2;
var exampleString = $"Number is : {number}";


问:
The source of "close" are different from security('60',close) of 20m and close of 60m
the code on 20m chart

```<code>// © david03kimo

//@version=4
study("MTM close")
hclose=security(syminfo.ticker, '60',close)
plot(hclose)

</code>```

the code on 60m chart

```<code>// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © david03kimo

//@version=4
study("MTM close")

plot(close)
</code>```

and the result output to graph,I can check the close price is not consistency.

enter image description here

答:
Version 1

That's because the close you are seeing on the 60m chart at the 11:00 bar is the close at 12:00, which hasn't occurred yet [on bars earlier than at] 11:40 on the 20m bars, so that bar is showing the last confirmed close, i.e., the one of the 10:00 bar which closed at 11:00.

Version 2

While the edited version 1 of the answer is now correct, it wasn't the problem in your screenshot as it was showing an 11:40 bar. There is another issue, which is your use of syminfo.ticker (which used the generic ticker, in this case FX:GBPCHF rather than syminfo.tickerid which uses the chart's ticker).

This code shows the difference:

```<code>//@version=4
study("MTM close", "", true)
hclose=security(syminfo.ticker, '60',close)
hclose1=security("FX:GBPCHF", '60',close)
hclose2=security(syminfo.tickerid, '60',close)
plot(hclose)
plot(hclose1)
plot(hclose2)
</code>```

You'll see hclose and hclose1 being always equal, whereas hclose2 will show what you expect.

Body:
the code on 20m chart

// © david03kimo

//@version=4
study("MTM close")
hclose=security(syminfo.ticker, '60',close)
plot(hclose)

the code on 60m chart

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © david03kimo

//@version=4
study("MTM close")

plot(close)

and the result output to graph,I can check the close price is not consistency.

enter image description here

Body:
Version 1

That's because the close you are seeing on the 60m chart at the 11:00 bar is the close at 12:00, which hasn't occurred yet [on bars earlier than at] 11:40 on the 20m bars, so that bar is showing the last confirmed close, i.e., the one of the 10:00 bar which closed at 11:00.

Version 2

While the edited version 1 of the answer is now correct, it wasn't the problem in your screenshot as it was showing an 11:40 bar. There is another issue, which is your use of syminfo.ticker (which used the generic ticker, in this case FX:GBPCHF rather than syminfo.tickerid which uses the chart's ticker).

This code shows the difference:

//@version=4
study("MTM close", "", true)
hclose=security(syminfo.ticker, '60',close)
hclose1=security("FX:GBPCHF", '60',close)
hclose2=security(syminfo.tickerid, '60',close)
plot(hclose)
plot(hclose1)
plot(hclose2)

You'll see hclose and hclose1 being always equal, whereas hclose2 will show what you expect.


问:
remove rows from a certain dataframe by the values of a different data frame in R
I have these two data frames a and b
I want to remove what is in a from b

```<code>example a =
     X  Y
1    1  3
2    2  4
3    3  5

example b =
   X   Y   Z
1  3   5   4  --- want to remove this
2  4   6   2
3  1   3   2  --- want to remove this
4  2   3   4
5  5   3   4
6  2   4   2  ---  want to remove this
7  4   3   4
8  2   4   6 ----  want remove this
9  6   9   6
10 2   0   3

</code>```

So I'm only keeping the rows that dont have the combination of a
the final result would be this:

```<code>   X   Y   Z
1  4   6   2
2  2   3   4
3  5   3   4
4  4   3   4
5  6   9   6
6  2   0   3

</code>```

Thanks

Body:
I have these two data frames a and b
I want to remove what is in a from b

example a =
     X  Y
1    1  3
2    2  4
3    3  5

example b =
   X   Y   Z
1  3   5   4  --- want to remove this
2  4   6   2
3  1   3   2  --- want to remove this
4  2   3   4
5  5   3   4
6  2   4   2  ---  want to remove this
7  4   3   4
8  2   4   6 ----  want remove this
9  6   9   6
10 2   0   3

So I'm only keeping the rows that dont have the combination of a
the final result would be this:

   X   Y   Z
1  4   6   2
2  2   3   4
3  5   3   4
4  4   3   4
5  6   9   6
6  2   0   3

Thanks

Body:
anti-join from the dplyr package can be very helpful.

library(tidyverse)

a <- tibble(X=c(1, 2, 3), Y=c(3, 4, 5))

b <- tibble(X=c(3, 4, 1, 2, 5, 2, 4, 2, 6, 2),
            Y=c(5, 6, 3, 3, 3, 4, 3, 4, 9, 0),
            Z=c(4, 2, 2, 4, 4, 2, 4, 6, 6, 3))

c <- b %>% anti_join(a, by=c("X", "Y"))
c

Gives

# A tibble: 6 x 3
      X     Y     Z
  <dbl> <dbl> <dbl>
1     4     6     2
2     2     3     4
3     5     3     4
4     4     3     4
5     6     9     6
6     2     0     3


问:
Covert datetime64[ns, UTC] to datetime64 python
I have a column with datetime UTC date

```<code>2020-01-01 00:00:00+00:00
</code>```

Can someone help me to convert it to just datetime64 for eg:

```<code>2020-01-01
</code>```

答:
Try the datetime package with Python 3.2+.

```<code>import datetime
a='2020-01-01 00:00:00+00:00'
print (datetime.datetime.strptime(a,'%Y-%m-%d %H:%M:%S%z').strftime('%Y-%m-%d'))
</code>```

Body:
I have a column with datetime UTC date

2020-01-01 00:00:00+00:00

Can someone help me to convert it to just datetime64 for eg:

2020-01-01

Body:
Try the datetime package with Python 3.2+.

import datetime
a='2020-01-01 00:00:00+00:00'
print (datetime.datetime.strptime(a,'%Y-%m-%d %H:%M:%S%z').strftime('%Y-%m-%d'))


答:
Try to use cases.to_csv('E:\Corona\csv\confirmedglobal\casesGlobal.csv', header=False, index=True)
 instead header=None

Title: How to ignore the header rows in Pandas Python

Body:
I want my python script to automatically graph certain parts of a CSV file. I have managed to get the data I want by removing certain parts of the csv file through the .drop command, anyway the headers won't go away. I have used the header = none command. Please help someone!

import matplotlib.pyplot as plt
import urllib.request
import pandas as pd

url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv"
filename, headers = urllib.request.urlretrieve(url, filename="E:\Corona\csv\confirmedglobal/casesGlobal.csv")
print ("download file location: ", filename)
print ("download headers: ", headers)
print ("Download #1 Completed")

cases = pd.read_csv(r'E:\Corona\csv\confirmedglobal\casesGlobal.csv')

cases.drop('Province/State', axis=1, inplace=True)
cases.drop('Country/Region', axis=1, inplace=True)
cases.drop('Lat', axis=1, inplace=True)
cases.drop('Long', axis=1, inplace=True)

cases.to_csv('E:\Corona\csv\confirmedglobal\casesGlobal.csv', header=None, index=True)

#Australian Capital
cases.drop([0,1,2,3,4,5,6,7,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,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265] ,axis=0, inplace=True)

print(cases)


问:
Is there way to convert web application in python flask to mobile?
I know that there are ways to convert web site to mobile application using directories and platforms, but it seems like all the examples were on JavaScript. Does it also work with python flask web application?</p>

答:
You won’t be able to convert python django application into a native mobile application.

For web application, both the client side and server side code is rendered through web browser. For mobile, client side code sits in native inside the mobile and all the dynamic stuff gets loaded from server through http/https. Python django app is generally written in MVT format, UI is closely tied with server side backend code.

To convert your present app into mobile app requires:

Implement django rest framework to write rest apis
A native mobile app which can consume those apis (this is full mobile app development)
Workarounds:

There is a way where you write a small mobile app which loads your website. This can be done but only requirement is your site needs to be responsive UI and compatible on mobile browser


问:
How to set a variable and check it for null both in the "case when" conditions SQL
I have problem with this piece of code.

I need to do something like this:

```<code>DECLARE @UserID INT
...
    CASE
        WHEN (@UserID = (SELECT TOP 1 UserPk FROM Users WHERE Name= 'JoeDoe')) IS NULL
        THEN 0
        ELSE 1
    END
</code>```

I need set @UserID for some other next steps and at the same time need to check (SELECT TOP 1 UserPk FROM Users WHERE Name = 'JoeDoe') for null.

Thanks for help.

答:
Perhaps just an ISNULL?

```<code>SET @UserID = ISNULL(SELECT UserPk FROM Users WHERE Name= 'JoeDoe'),0);
</code>```

Body:
I have problem with this piece of code.

I need to do something like this:

DECLARE @UserID INT
...
    CASE
        WHEN (@UserID = (SELECT TOP 1 UserPk FROM Users WHERE Name= 'JoeDoe')) IS NULL
        THEN 0
        ELSE 1
    END

I need set @UserID for some other next steps and at the same time need to check (SELECT TOP 1 UserPk FROM Users WHERE Name = 'JoeDoe') for null.

Thanks for help.

Body:
Perhaps just an ISNULL?

SET @UserID = ISNULL(SELECT UserPk FROM Users WHERE Name= 'JoeDoe'),0);


问:
How to copy datas from one table into another one with all columns but not id in Laravel?
I use Laravel 6.x and I need to copy datas from one table to another. As usual both of tables has many columns and I'm looking for a solution where I don't depend on column names. In the future maybe columns will be change and I don't want to touch this part of software on every changes.

I want to do something like this:

INSERT INTO product_copys (SELECT * from products);
```

I want to copy all columns without the id from the products table.

I use Product and ProductCopy models to handle these datas.

Is there any handy solution for this in Laravel, Eloquent?

答:
You may use the following

In your App\Product Model

```<code>class Product extends Model
{

    protected $hidden = ['id'];
    //...
}
</code>```

Then in your Controller

```<code>$copy = Product::all()->toArray();

ProductCopy::insert($copy);
</code>```

If you need to process a lot (thousands) of Eloquent records, using
  the chunk command will allow you to do without eating all of your RAM:

```<code>Product::chunk(200, function($products)
{
    ProductCopy::insert($products->toArray());
});
</code>```

https://laravel.com/docs/7.x/eloquent#chunking-results

Body:
I use Laravel 6.x and I need to copy datas from one table to another. As usual both of tables has many columns and I'm looking for a solution where I don't depend on column names. In the future maybe columns will be change and I don't want to touch this part of software on every changes.

I want to do something like this:

INSERT INTO product_copys (SELECT * from products);

I want to copy all columns without the id from the products table.

I use Product and ProductCopy models to handle these datas.

Is there any handy solution for this in Laravel, Eloquent?

Body:
You may use the following

In your App\Product Model

class Product extends Model
{

    protected $hidden = ['id'];
    //...
}

Then in your Controller

$copy = Product::all()->toArray();

ProductCopy::insert($copy);

If you need to process a lot (thousands) of Eloquent records, using
  the chunk command will allow you to do without eating all of your RAM:

Product::chunk(200, function($products)
{
    ProductCopy::insert($products->toArray());
});

https://laravel.com/docs/7.x/eloquent#chunking-results


问:
Where do I find my youtube v3 data API quota limit?
on this page (https://developers.google.com/youtube/v3/getting-started) google says:

You can find the quota available to your application in the Developers Console.

I went to my Developer Console, and it shows me how many requests I made, but it does not show my exact quota (for my free account). Does anybody know how to access this information? The url for the developer console is https://console.developers.google.com/

Thanks!

答:
For server/web-based apps

The valid steps as of February 21, 2021:

Go to Console: https://console.developers.google.com/ & check if correct project is selected*

Click on the Library option on the left menu

Click on the YouTube Data API 3 option

Click on the Manage button on the Youtube Data API 3 page

Then click on Quotas on the left menu on the Manage page

Lastly, expand the Queries section to see the quota usage.

*Make sure the project/service is selected which is using the YouTube API


问:
How to use PM2 CLI on Heroku
I'm trying to use pm2 on Heroku. I did have a look at the documentation. It looks like the application works fine once deployed, and the logs indicates that multiple instances has started on a 2X dyno.

Yet when I run: heroku run bash and do a pm2 ls I get an empty list:

```<code>┌──────────┬────┬──────┬─────┬────────┬─────────┬────────┬────────┬──────────┐
│ App name │ id │ mode │ pid │ status │ restart │ uptime │ memory │ watching │
└──────────┴────┴──────┴─────┴────────┴─────────┴────────┴────────┴──────────┘
</code>```

And I can't use any pm2 CLI functions. I understand that when I do a heroku run command a one-off dyno is created on the fly and the pm2 instance running on this dyno does not run any process.

However I don't see how I can access pm2 on a specific dyno.

Is there any way to take advantage of the pm2 cli on Heroku?

答:
heroku run connects you to an additional temporary container.

To connect to a real running app container, use heroku ps:exec.

Title: How to use PM2 CLI on Heroku

Body:
I'm trying to use pm2 on Heroku. I did have a look at the documentation. It looks like the application works fine once deployed, and the logs indicates that multiple instances has started on a 2X dyno.

Yet when I run: heroku run bash and do a pm2 ls I get an empty list:

┌──────────┬────┬──────┬─────┬────────┬─────────┬────────┬────────┬──────────┐
│ App name │ id │ mode │ pid │ status │ restart │ uptime │ memory │ watching │
└──────────┴────┴──────┴─────┴────────┴─────────┴────────┴────────┴──────────┘

And I can't use any pm2 CLI functions. I understand that when I do a heroku run command a one-off dyno is created on the fly and the pm2 instance running on this dyno does not run any process.

However I don't see how I can access pm2 on a specific dyno.

Is there any way to take advantage of the pm2 cli on Heroku?


问:
Prevent Windows Error Reporting (DW20.exe) window for a particular process
I have an automated build system set up on a Windows box, but one of the compiling tools randomly fail to work. The whole system works as a service, so it has no interaction with users. I detect the failure by looking at the DW20.exe process. The failed process waits for a user to click a button, so it stops the whole build system.

Can I prevent Windows Error Reporting from waiting for user actions for a particular process (or a particular Windows user)?

The box has Windows Server 2008 R2 installed, and the process is Intel Fortran compiler (ifort.exe).

答: There are some relevant options in WER Settings, such as DefaultConsent, DontShowUI or (as a last resort) ExcludedApplications.


问:
Unpacking objects individually from a TCP stream
I would like to read one by one the objects coming from a TCP stream, preferably using the MessagePack library.

On one side I have a client that, at each iteration of a loop:

computes a point location (tuple)

packs that location and sends it through a socket

On the other side, a server that:

receive the data when client is detected

unpack that data

For now I am storing the data in a buffer on reception, then proceed to unpacking when the stream is over. My problem is that I need to unpack the tuples one by one as they are sent. In other words I would like to read the data in real time without putting it in a buffer.

Provided it is possible, how could I achieve this using MessagePack ?

-- client side --

```<code>#Python3.7
import socket
import msgpack
import math

HOST = "127.0.0.1"
PORT = 9000

den = 40
rad = 100
theta = math.tau / den

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.connect((HOST, PORT)) #connect to server

    for step in range(den):
        x = math.cos(i*theta) * rad
        y = math.sin(i*theta) * rad
        data = msgpack.packb((x, y), use_bin_type = True)
        sock.sendall(data)
</code>```

-- server side --

```<code>#Jython2.7 <-- Python 2.7 compatible only
from io import BytesIO
import msgpack
import socket

HOST = "127.0.0.1"
PORT = 9000

buf = BytesIO()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
connection, address = s.accept()

while True:
    try:
        data = connection.recv(1024)
        buf.write(data)

    except:
        buf.seek(0)
        unpacker = msgpack.Unpacker(buf, use_list=False, raw=False)
        for unpacked in unpacker:
            print(unpacked)
        buf = BytesIO()
</code>```

答:
See "Stream Unpacking" section in the README:
https://github.com/msgpack/msgpack-python#streaming-unpacking

You can do like this:

```<code>unpacker = msgpack.Unpacker(use_list=False, raw=False)

while True:
    data = connection.recv(1024)
    if not data:
        break
    unpacker.feed(data)
    for unpacked in unpacker:
        print(unpacked)
</code>```

Body:
I would like to read one by one the objects coming from a TCP stream, preferably using the MessagePack library.

On one side I have a client that, at each iteration of a loop:

computes a point location (tuple)

packs that location and sends it through a socket

On the other side, a server that:

receive the data when client is detected

unpack that data

For now I am storing the data in a buffer on reception, then proceed to unpacking when the stream is over. My problem is that I need to unpack the tuples one by one as they are sent. In other words I would like to read the data in real time without putting it in a buffer.

Provided it is possible, how could I achieve this using MessagePack ?

-- client side --

#Python3.7
import socket
import msgpack
import math

HOST = "127.0.0.1"
PORT = 9000

den = 40
rad = 100
theta = math.tau / den

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.connect((HOST, PORT)) #connect to server

    for step in range(den):
        x = math.cos(i*theta) * rad
        y = math.sin(i*theta) * rad
        data = msgpack.packb((x, y), use_bin_type = True)
        sock.sendall(data)

-- server side --

#Jython2.7 <-- Python 2.7 compatible only
from io import BytesIO
import msgpack
import socket

HOST = "127.0.0.1"
PORT = 9000

buf = BytesIO()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
connection, address = s.accept()

while True:
    try:
        data = connection.recv(1024)
        buf.write(data)

    except:
        buf.seek(0)
        unpacker = msgpack.Unpacker(buf, use_list=False, raw=False)
        for unpacked in unpacker:
            print(unpacked)
        buf = BytesIO()

Body:
See "Stream Unpacking" section in the README:
https://github.com/msgpack/msgpack-python#streaming-unpacking

You can do like this:

unpacker = msgpack.Unpacker(use_list=False, raw=False)

while True:
    data = connection.recv(1024)
    if not data:
        break
    unpacker.feed(data)
    for unpacked in unpacker:
        print(unpacked)


问:
Microsoft ACE DatabaseEngine 2010 driver (12.0) Problem, after Windows 10 1909 Cumulative Updates (and later)
since cumulative Windows 10 1909 Updates are installed, I get following exception when accessing MS Access accdb.
: An external component raised an exception.
After reinstalling Microsoft ACE DatabaseEngine 2010 (OLEDB.12.0 ..), all works fine again.
What can I do about it?</p>

```<code>Dim sel As String = "Select Notiz from T_TerminNotiz where ztrText=@ztrText and serNr=@serNr"
Using myConnection As New OleDbConnection(myConnStringX1)
    myConnection.Open()

    Using mySqlCmd As New OleDbCommand(sel, myConnection)
        mySqlCmd.CommandType = CommandType.Text
        mySqlCmd.CommandTimeout = myCmdTimeOut
        mySqlCmd.CommandText = sel
        mySqlCmd.Parameters.Clear()
        mySqlCmd.Parameters.Add(New OleDbParameter("@ztrText", OleDbType.VarChar)).Value = strKlient
        mySqlCmd.Parameters.Add(New OleDbParameter("@serNr", OleDbType.Integer)).Value = serNr
        oRet = mySqlCmd.ExecuteScalar()
    End Using

End Using
</code>```

答:
after some tests, I found following solution to my problem.

Installing Microsoft DatabaseEngine 2016.

I activated all OLE DB Services by adding it into configuration file xxx.config.
...
connectionString="Provider=Microsoft.ACE.OLEDB.16.0;Data Source=Table.accdb;Persist Security Info=True;OLE DB Services=-1;

Body:
since cumulative Windows 10 1909 Updates are installed, I get following exception when accessing MS Access accdb.
: An external component raised an exception.
After reinstalling Microsoft ACE DatabaseEngine 2010 (OLEDB.12.0 ..), all works fine again.
What can I do about it?

Dim sel As String = "Select Notiz from T_TerminNotiz where ztrText=@ztrText and serNr=@serNr"
Using myConnection As New OleDbConnection(myConnStringX1)
    myConnection.Open()

    Using mySqlCmd As New OleDbCommand(sel, myConnection)
        mySqlCmd.CommandType = CommandType.Text
        mySqlCmd.CommandTimeout = myCmdTimeOut
        mySqlCmd.CommandText = sel
        mySqlCmd.Parameters.Clear()
        mySqlCmd.Parameters.Add(New OleDbParameter("@ztrText", OleDbType.VarChar)).Value = strKlient
        mySqlCmd.Parameters.Add(New OleDbParameter("@serNr", OleDbType.Integer)).Value = serNr
        oRet = mySqlCmd.ExecuteScalar()
    End Using

End Using


问:
Get Row value as Column Header
I have two tables as below. I want to join these two tables and need to set the column values of second table as column header as shown  below. How can I achieve this?

Table1

```<code>ID       NAME
---------------
1        AAA
2        BBB
</code>```

table2

```<code>ID         QUESTION         ANSWER
----------------------------------
1              Q1             YES
1              Q2             NO
1              Q3             YES
1              Q4             NO
1              Q5             YES
2              Q1             YES
2              Q2             YES
2              Q3             YES
2              Q4             YES
2              Q5             YES
</code>```

The output table should be

```<code>   ID      NAME       Q1     Q2      Q3     Q4      Q5
   ----------------------------------------------------
   1       AAA        YES    NO     YES     NO      YES
   2       BBB        YES    YES    YES     YES     YES
</code>```

答:
You can use Dynamic Pivot as below-</p>

```<code>DECLARE @cols AS NVARCHAR(MAX),
@sqlCommand  AS NVARCHAR(MAX);

SELECT  @cols =
STUFF((SELECT   ( '],[' +  A.QUESTION)
    FROM (SELECT DISTINCT QUESTION FROM table2) A
    ORDER BY A.QUESTION
    FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)')
,1,1,'')+']'
FROM table2

SET @sqlCommand=
N'SELECT [ID],NAME,'+SUBSTRING(@cols,2,LEN(@cols))+'
FROM
(
    SELECT A.ID,A.NAME, B.QUESTION, B.ANSWER
    FROM table1 A
    INNER JOIN table2 B ON A.ID = B.ID
) AS P
PIVOT
(
    MAX(ANSWER)
    FOR QUESTION IN('+SUBSTRING(@cols,2,LEN(@cols))+')
) PVT'

--PRINT @sqlCommand
EXEC (@sqlCommand)
</code>```

Title: Get Row value as Column Header

Body:
I have two tables as below. I want to join these two tables and need to set the column values of second table as column header as shown  below. How can I achieve this?

Table1

ID       NAME
---------------
1        AAA
2        BBB

table2

ID         QUESTION         ANSWER
----------------------------------
1              Q1             YES
1              Q2             NO
1              Q3             YES
1              Q4             NO
1              Q5             YES
2              Q1             YES
2              Q2             YES
2              Q3             YES
2              Q4             YES
2              Q5             YES

The output table should be

   ID      NAME       Q1     Q2      Q3     Q4      Q5
   ----------------------------------------------------
   1       AAA        YES    NO     YES     NO      YES
   2       BBB        YES    YES    YES     YES     YES

Body:
You can use Dynamic Pivot as below-

DECLARE @cols AS NVARCHAR(MAX),
@sqlCommand  AS NVARCHAR(MAX);

SELECT  @cols =
STUFF((SELECT   ( '],[' +  A.QUESTION)
    FROM (SELECT DISTINCT QUESTION FROM table2) A
    ORDER BY A.QUESTION
    FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)')
,1,1,'')+']'
FROM table2

SET @sqlCommand=
N'SELECT [ID],NAME,'+SUBSTRING(@cols,2,LEN(@cols))+'
FROM
(
    SELECT A.ID,A.NAME, B.QUESTION, B.ANSWER
    FROM table1 A
    INNER JOIN table2 B ON A.ID = B.ID
) AS P
PIVOT
(
    MAX(ANSWER)
    FOR QUESTION IN('+SUBSTRING(@cols,2,LEN(@cols))+')
) PVT'

--PRINT @sqlCommand
EXEC (@sqlCommand)


问:
Angular reactive form and ngx-admin problem with error FormGroup isn't a known property of form
I need to use angular ReactiveFormsModule on my custom component with ngx-admin theme but I have the problem when compiling for error: "Can't bind to 'formGroup' since it isn't a known property of 'form'", on VisualStudioCode no error reported.

I have add "import { FormsModule, ReactiveFormsModule } from '@angular/forms';" on my module also on pages.module.ts and app.module.ts without success, I have always that error when compiling.

If I try to add reactive form on Register page of ngx-admin no error when compiling.

Can someone help me to find where I'm wrong?

答:
this is my pages.module.ts

```<code>import { NgModule } from '@angular/core';

import { PagesComponent } from './pages.component';
import { DashboardModule } from './dashboard/dashboard.module';
import { PagesRoutingModule } from './pages-routing.module';
import { ThemeModule } from '../@theme/theme.module';
import { MiscellaneousModule } from './miscellaneous/miscellaneous.module';
import { PagesMenu } from './pages-menu';
import { ECommerceModule } from './e-commerce/e-commerce.module';
import { NbMenuModule } from '@nebular/theme';
import { AuthModule } from '../@auth/auth.module';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

const PAGES_COMPONENTS = [
  PagesComponent,
];

@NgModule({
  imports: [
    FormsModule,
    ReactiveFormsModule,
    PagesRoutingModule,
    ThemeModule,
    DashboardModule,
    ECommerceModule,
    NbMenuModule,
    MiscellaneousModule,
    AuthModule.forRoot(),
  ],
  declarations: [
    ...PAGES_COMPONENTS,
  ],
  providers: [
    PagesMenu,
  ],
})
expo
</code>```

rt class PagesModule {
}

Body:
this is my pages.module.ts

import { NgModule } from '@angular/core';

import { PagesComponent } from './pages.component';
import { DashboardModule } from './dashboard/dashboard.module';
import { PagesRoutingModule } from './pages-routing.module';
import { ThemeModule } from '../@theme/theme.module';
import { MiscellaneousModule } from './miscellaneous/miscellaneous.module';
import { PagesMenu } from './pages-menu';
import { ECommerceModule } from './e-commerce/e-commerce.module';
import { NbMenuModule } from '@nebular/theme';
import { AuthModule } from '../@auth/auth.module';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

const PAGES_COMPONENTS = [
  PagesComponent,
];

@NgModule({
  imports: [
    FormsModule,
    ReactiveFormsModule,
    PagesRoutingModule,
    ThemeModule,
    DashboardModule,
    ECommerceModule,
    NbMenuModule,
    MiscellaneousModule,
    AuthModule.forRoot(),
  ],
  declarations: [
    ...PAGES_COMPONENTS,
  ],
  providers: [
    PagesMenu,
  ],
})
expo

rt class PagesModule {
}


问:
How to setup Azure DevOps Server 2019 with LDAP
I am trying to connect our Azure Devops Server 2019 to our external Active Directory. I have no experience with LDAP, connecting to an AD or similar.

It should be possible for users to log on to the Azure DevOps Server with their AD credentials.

Unfortunately I cannot find a way to do this. Is this possible with LDAP? And if so, how?
Are there any other possibilities besides integrating the Azure DevOps Server into the Active Directory domain (this will not be possible with us)?

I would be very grateful for any help!

答:
I am afraid that Azure DevOps Server/TFS only supports AD. You need to add your Azure DevOps Server/TFS to your corporate domain, and establish trust between your corporate domain and the external domain.

You may take a look at the blog below:

http://blogs.agorainc.com/post/External-User-in-Team-Foundation-Server-(TFS)-with-Active-Directory.aspx


问:
Spring MVC 3 and Ajax library advice
I'm developing a webapp with Hibernate+Spring 3 (Spring MVC, JSP): I'd like to create some divs with AJAX style (i.e. no need to refresh all the page, independent update of each div).

I'd like a good advice about which AJAX library to use (in conjunction with Spring 3 MVC + JSP) and, if possible, where to find some code snippets.

I know very little of AJAX libraries, JSONs and how to integrate them, but I have good knowledge of Javascript and Spring (and how callbacks work). I'd like to write as less code as possible, particularly in the jsps.

My Webapp will display an updated (every 5 minutes) POJO in a div and perform some operations between different domain objects in the other div when user press a button.

答:
This is correct use JQuery

Here
http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/

you can find working examples to use Jquery+JSON+Spring MVC.

and this question can help you with server side configuration:
JQuery, Spring MVC @RequestBody and JSON - making it work together

Title: Spring MVC 3 and Ajax library advice


问:
Corda - setting up multiple user accounts in a single node
Can you please suggest the workaround to set-up multiple user accounts in a single node. I have a Bank node where I need to set-up multiple accounts for the customers of the bank. Is this feature added in Corda</p>

答: Hi Sushil multiple user accounts in a single node can now be setup using the accounts-sdk feature released with Corda 4.3.</p>


问:
Angular8 node js and npm installation problems
I'm learning angular js. For this  I've install nodejs  and git. And I've run following command on CMD:

```<code>  npm install -g @angular/cli@latest
</code>```

After some time following error occurred

```<code>npm WARN rollback Rolling back @schematics/angular@8.3.21 failed (this is
probably harmless): EPERM: operation not permitted, lstat 'C:\Users\User
Name\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\@schematics'
npm ERR! code EEXIST
npm ERR! path C:\Users\User
Name\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng
npm ERR! dest C:\Users\User Name\AppData\Roaming\npm\ng.ps1
npm ERR! EEXIST: file already exists, cmd shim 'C:\Users\Chaitanya
Kulkarni\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng' ->
'C:\Users\Chaitanya Kulkarni\AppData\Roaming\npm\ng.ps1'
npm ERR! File exists: C:\Users\User Name\AppData\Roaming\npm\ng.ps1
npm ERR! Remove the existing file and try again, or run npm
npm ERR! with --force to overwrite files recklessly.
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\User Name\AppData\Roaming\npm-cache\_logs\2020-01-
04T12_12_30_922Z-debug.log
</code>```

Can you please explain what is that error and how I could solve this. I am using Window 10.

答:
In the terminal navigate to the following path:
C:\Users\UserName\AppData\Roaming\npm\node_modules
and delete angular file and reinstall cli.
That worked for me.

Also do check if you've set your path variables correctly.

Body:
I'm learning angular js. For this  I've install nodejs  and git. And I've run following command on CMD:

  npm install -g @angular/cli@latest

After some time following error occurred

npm WARN rollback Rolling back @schematics/angular@8.3.21 failed (this is
probably harmless): EPERM: operation not permitted, lstat 'C:\Users\User
Name\AppData\Roaming\npm\node_modules\@angular\cli\node_modules\@schematics'
npm ERR! code EEXIST
npm ERR! path C:\Users\User
Name\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng
npm ERR! dest C:\Users\User Name\AppData\Roaming\npm\ng.ps1
npm ERR! EEXIST: file already exists, cmd shim 'C:\Users\Chaitanya
Kulkarni\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng' ->
'C:\Users\Chaitanya Kulkarni\AppData\Roaming\npm\ng.ps1'
npm ERR! File exists: C:\Users\User Name\AppData\Roaming\npm\ng.ps1
npm ERR! Remove the existing file and try again, or run npm
npm ERR! with --force to overwrite files recklessly.
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\User Name\AppData\Roaming\npm-cache\_logs\2020-01-
04T12_12_30_922Z-debug.log

Can you please explain what is that error and how I could solve this. I am using Window 10.


问:
Does Smaato provides sdk of Symbian^3?
Currently, we are working on 3-D Game on Symbian^3 platform. Now I need to implement ads in my Game(preferably via Smaato). I have also checked out Smaato's website for SDK, but there I found SDKs for Symbian S60, WRT and Qt. There is no SDK specially for Symbian^3 on Smaato's website. I am a bit confused now.

Moreover, we are using Carbide C++ editor for writing our Symbian^3 Game application. What I should do, in order to implement ads via Smaato on Symbian^3 platform.

Thanks,

ATUL PRAKASH

答:
The Smaato website says about their Symbian support:

Key Facts

Easy integration

Compatible with Qt 4.6 and Qt 4.7

Allows ad display in QWidget and Qt Quick based applications

Multi platform: runs on Symbian S60 3rd & 5th edition Symbian ^3 and Maemo

Targeting: gender, age, keywords, search queries, carrier and location
  (GPS & ZIP)

Beacons support: required for ad networks to get high priced CPM
  campaigns

Asynchronous loading of display ad (no wait time for users)

Flexibility to set time controlled ad rotations

Supports banner and text ads

Low resource consumption

It has a picture of their ads running on a Nokia N8 too, a Symbian^3 phone. So you should be able to use the same SDK.

Title: Does Smaato provides sdk of Symbian^3?


问:
Python Unable to import 'nbt' even though it is installed
I ran into an issue trying to import a module, it says "Unable to import 'nbt'", I have re-installed it and made sure I have latest version of pylint. But I still get the error message.

When I try to do "pip install nbt" it says "requirement already satisfied", anyone know the issue?

Here is my code:

```<code>import io
import base64
from nbt import nbt
raw = "H4sIAAAAAAAAANWZ3XLbxhmGYSduJLWJnZn0Jz+TQVq7SSfdBFj8a6YHNEnRZAVAIiHRwIlngV0QAPGjgqAk8h56Bz1uTnrQg15BLqUX0ukHSnRki5KYWh6l9liigA/YNfA++77faovjNrl78RbHcZ/e5+7H9N5f73EPmsU0r+5tce9UZPQOt/kspmwnJaMJVP1ni9sajKdpap/krNzg7ncp9zgM1dAPqIYUUdKRpPoGIhINkBwomISSHmCBwnV7ZXHEyipmk01uo2Kn1bRkk3roexvcg0OSThn3TzbrCd7zSKDPe2kw66rwszMQUrubHGnd/HDmN7tqN4Pzzxrq7sy4UKtUZKikrtSLvHx/6meHwq7UT9mzvhhkB8dW62DmdazISqLE7riyO3RFc25lbhLMLexF3vAwcnEvteZtyU3G2G4FGI4npjOSzaQ/due9sTmnkTsPZHvoJdY8iMPnogGz3+Leo/HkKCWzTe7d3aJkG3Dw5xz//XfaoCpZPqqibfgh+Fqsv37VKWg6478W/8A9gYpmGVd8MyJ5wM6LnrxS9eRCWYtkZHRlGcc9hsJuXrE0jUfs/Ibk0qgc97v6hkWcT/hJRcqKJ0dHjJRxPuJJCW+e8rNiyv0WioogIJO4yEkK1xY5fzT10zjg40lKcjr5htuEmt1pMJ59AXf91fffhd9/lzZt07QtvtFstgcDu+9ucO9aJGPcJ3D6bBIOSeNJRnK+CPnFNOAJPmyfViVpVFUZ+9OKTTa4jaygcRizknswqi/b4DaLMh7FuUNG3C+b/caO07U6Lzr9butF097dbTedjVrA3PtNu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y5KoMl8hyh33X9a8F1m4n7iZK3lDK7KyLvYSdw6GI9pgGmZiSrYzPnVx+9RNRrLdaQte8hR4O5h7mau4jjkDJqH3epraTndmJmlqzq43l/dqrbCDPP7LlPHtMGRBtc3vFVUM+WMpmkX8+UH0iwA0LcmipghBqbMFFgHEnmkGDJxffpaA8CICnVnFJ+dWUWOwQCfOj1leFeXsm/OQBcA5UTzh44plfEDgJowvWViUI0a/uFn3v4aC1ybP9+N8tFLtayr7o359fA8eKASnxs5O1+o67kuBK7IsGcyHgBJqEpIlWUA+NXRY1TETJIMYWLvURGGtFri0LePb3F/AGiFYDRBYnAq4iTVkhopEBfyNyAr8u+v9BdCzsvCFzBt7ST/xnH5iZS6EqIZgDw8zdx4lrvM0NVtRbA+74Dm9zMTgKc6o3n8Ye9kOhC4r8loBBCwvARYk94bfSj1YeMpSvAvtLrR1FAdjfnrElySHB/9wsWzXcpVOz9fYW1AjLN/EJKOcVXFw/cK7phQ/NBsdq+10myuaeaKJRJQhLYc6RbIWaEhXdYwCggNB93Eo6fpVvxkV5Us6vPTnv0dPp71kIAAA"

def decode_inventory_data(raw):
    data = nbt.nbt.NBTFile(fileobj=io.BytesIO(base64.b64decode(raw)))
    print(data)
    return data
</code>```

Thanks

答:
The python executable cannot find the module.

I suggest these steps:

1) involuntary override

Check you have not saved any of your files with the filename nbt.py

2) Which is the interpreter? Where does it load the modules from?

Add this lines to your script:

import sys

print(sys.executable)

print(sys.path)

The ouput is

the python interpreter location

the directories where it is looking for to load the modules

If the module is installed, you can search it on the filesystem.
For example for linux

find / -name nbt.py

Its location shall be one of those listed before.

3) lookup in specific directories

You can suggest to Python to look for modules in other directories, adding the directories to this environment variable:

PYTHONPATH

See the Python docs, section 1.2 environmemt variables

https://docs.python.org/3/using/cmdline.html

Body:
I ran into an issue trying to import a module, it says "Unable to import 'nbt'", I have re-installed it and made sure I have latest version of pylint. But I still get the error message.

When I try to do "pip install nbt" it says "requirement already satisfied", anyone know the issue?

Here is my code:

import io
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8tFLtayr7o359fA8eKASnxs5O1+o67kuBK7IsGcyHgBJqEpIlWUA+NXRY1TETJIMYWLvURGGtFri0LePb3F/AGiFYDRBYnAq4iTVkhopEBfyNyAr8u+v9BdCzsvCFzBt7ST/xnH5iZS6EqIZgDw8zdx4lrvM0NVtRbA+74Dm9zMTgKc6o3n8Ye9kOhC4r8loBBCwvARYk94bfSj1YeMpSvAvtLrR1FAdjfnrElySHB/9wsWzXcpVOz9fYW1AjLN/EJKOcVXFw/cK7phQ/NBsdq+10myuaeaKJRJQhLYc6RbIWaEhXdYwCggNB93Eo6fpVvxkV5Us6vPTnv0dPp71kIAAA"

def decode_inventory_data(raw):
    data = nbt.nbt.NBTFile(fileobj=io.BytesIO(base64.b64decode(raw)))
    print(data)
    return data

Thanks


问:
Git Submodule not found by Bamboo
I am trying the continuous integration using bamboo, in my git folder i have a submodule project. While building the .SLN the log shows that he did not find the path of the submodule.

Here is the project folder :
git repo

and in my bamboo i made :

Task 1 : Source Code Checkout configuration from this folder

Task 2 : nuget restore

Task 3 : Build the .sln

...

Is there any Task should be added to build the submodule ?

答:
Did you init the submodule after checkout?
If you don't there will just be an epmty folder.

```<code>git clone https://REPOSITORY
cd SUMBMODULEFOLDER
git submodule init
</code>```

here's the documentation: Cloning a Project with Submodules

Title: Git Submodule not found by Bamboo

Body:
Did you init the submodule after checkout?
If you don't there will just be an epmty folder.

git clone https://REPOSITORY
cd SUMBMODULEFOLDER
git submodule init

here's the documentation: Cloning a Project with Submodules


问:
Django api testing for get request with parameters
I am testing.My code works for non parametric get request.But how to pass paremeters while testing in Rest api.

```<code>from rest_framework.test import RequestsClient
from rest_framework.test import APIRequestFactory
from configparser import ConfigParser
config = ConfigParser()
config.read('config.ini')
import django
django.setup()
from analyse.views_noquery import AverageTurnover

factory = APIRequestFactory()
request = factory.get('http://127.0.0.1:8000/average/turnover/start_date=2019-01-1/end_date=2019-01-1/')
view = AverageTurnover.as_view()(request)
#response = view(request)
print(view.data)

</code>```

My views.py file

```<code>class AverageTurnover(APIView):
    '''Average Turn Over'''
    #permission_classes = [IsAuthenticated]
    def get(self, request, start_date, end_date):
        dataset = requests.get(config['url']['API_FETCH_URL']).json()
        turnover_data = []
        for data in dataset:
            data_date = datetime.datetime.strptime(data['Date'], "%d-%b-%Y").strftime("%Y-%m-%d")
            if data_date > start_date and data_date < end_date and data['Open']>data['Close'] :
                turnover_data += [data['Turnover (Rs. Cr)']]
        return Response({"Average Turnover" : sum(turnover_data)/len(turnover_data)})
</code>```

答:
You can pass a dictionary arg with parameter: value pairs, for example:

```<code>response = factory.get('http://127.0.0.1:8000/my-endpoint', {"param1": "value1"})
</code>```

That would generate a GET request with to the url: http://127.0.0.1:8000/my-endpoint?param1=value1

Check the docs.

Body:
I am testing.My code works for non parametric get request.But how to pass paremeters while testing in Rest api.

from rest_framework.test import RequestsClient
from rest_framework.test import APIRequestFactory
from configparser import ConfigParser
config = ConfigParser()
config.read('config.ini')
import django
django.setup()
from analyse.views_noquery import AverageTurnover

factory = APIRequestFactory()
request = factory.get('http://127.0.0.1:8000/average/turnover/start_date=2019-01-1/end_date=2019-01-1/')
view = AverageTurnover.as_view()(request)
#response = view(request)
print(view.data)

My views.py file

class AverageTurnover(APIView):
    '''Average Turn Over'''
    #permission_classes = [IsAuthenticated]
    def get(self, request, start_date, end_date):
        dataset = requests.get(config['url']['API_FETCH_URL']).json()
        turnover_data = []
        for data in dataset:
            data_date = datetime.datetime.strptime(data['Date'], "%d-%b-%Y").strftime("%Y-%m-%d")
            if data_date > start_date and data_date < end_date and data['Open']>data['Close'] :
                turnover_data += [data['Turnover (Rs. Cr)']]
        return Response({"Average Turnover" : sum(turnover_data)/len(turnover_data)})

Body:
You can pass a dictionary arg with parameter: value pairs, for example:

response = factory.get('http://127.0.0.1:8000/my-endpoint', {"param1": "value1"})

That would generate a GET request with to the url: http://127.0.0.1:8000/my-endpoint?param1=value1

Check the docs.


问:
Flutter - how to trigger a RaisedButton Programmatically?
I have a RaisedButton.

```<code>  Widget build(BuildContext context) {
    print("MyHomePageState build");
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(title: Text("test")),
      body: Stack(
        children: <Widget>[
          RaisedButton(
            onPressed: () {
              Navigator.of(context).pushNamed("Page2");
            },
            child: Text("jump"),
          )
        ],
      )
    );
  }
</code>```

How can I trigger this button's onTap() method by code programmatically rather than click this button?

答:
You can just create a separate function and call this method programmatically:

```<code>void triggerButton() {
    Navigator.of(context).pushNamed("Page2");
}
</code>```

Then, call it like so:

```<code>  Widget build(BuildContext context) {
    print("MyHomePageState build");
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(title: Text("test")),
      body: Stack(
        children: <Widget>[
          RaisedButton(
            onPressed: () {
              triggerButton();
            },
            child: Text("jump"),
          )
        ],
      )
    );
  }
</code>```

Body:
I have a RaisedButton.

  Widget build(BuildContext context) {
    print("MyHomePageState build");
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(title: Text("test")),
      body: Stack(
        children: <Widget>[
          RaisedButton(
            onPressed: () {
              Navigator.of(context).pushNamed("Page2");
            },
            child: Text("jump"),
          )
        ],
      )
    );
  }

How can I trigger this button's onTap() method by code programmatically rather than click this button?

Body:
You can just create a separate function and call this method programmatically:

void triggerButton() {
    Navigator.of(context).pushNamed("Page2");
}

Then, call it like so:

  Widget build(BuildContext context) {
    print("MyHomePageState build");
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(title: Text("test")),
      body: Stack(
        children: <Widget>[
          RaisedButton(
            onPressed: () {
              triggerButton();
            },
            child: Text("jump"),
          )
        ],
      )
    );
  }


问:
Check dict from Json output (urllib2)
I am trying to pull specific data from json output using urllib2.
From the code and output below, I am trying to pull out specific value but i didn't manage to do that.

This is the URL itself:

```<code>baseURIs: [
{
service: "true",
location: "alex",
URL: "barcelonat",
},
{
service: "false",
location: "daniel",
URL: "RealMadrid",
},
</code>```

This is the output from the json (using my code):

```<code>{u'URL': u'barcelona', u'location': u'alex', u'service': u'true'}
{u'URL': u'RealMadrid', u'location': u'daniel', u'service': u'false'}
</code>```

I am trying to search this dict and print "found it" if the string 'RealMadrid' is there.
Here is code:

```<code>#!/usr/bin/env python
import time
from datetime import datetime
import json
import urllib2
req = urllib2.Request('http://admin/alex/0.json')
response = urllib2.urlopen(req)
page = response.read()
user_dict = json.loads(page)
count = 0

for k in user_dict['baseURIs']:
    if 'RealMadrid' in k:
        print("Found it!")
</code>```

答:
Your piece of code:

```<code>for k in user_dict['baseURIs']:
    if 'RealMadrid' in k:
        print("Found it!")
</code>```

Searches for 'RealMadrid' in the dictionary k, which means it looks for that string in the dictionary keys. However, in the dictionary you provided as input, 'RealMadrid' is not a key, but the value associated with the 'URL' key. You should replace the above with:

```<code>for k in user_dict['baseURIs']:
    if k['URL'] == 'RealMadrid':
        print("Found it!")
</code>```

Title: Check dict from Json output (urllib2)

Body:
I am trying to pull specific data from json output using urllib2.
From the code and output below, I am trying to pull out specific value but i didn't manage to do that.

This is the URL itself:

baseURIs: [
{
service: "true",
location: "alex",
URL: "barcelonat",
},
{
service: "false",
location: "daniel",
URL: "RealMadrid",
},

This is the output from the json (using my code):

{u'URL': u'barcelona', u'location': u'alex', u'service': u'true'}
{u'URL': u'RealMadrid', u'location': u'daniel', u'service': u'false'}

I am trying to search this dict and print "found it" if the string 'RealMadrid' is there.
Here is code:

#!/usr/bin/env python
import time
from datetime import datetime
import json
import urllib2
req = urllib2.Request('http://admin/alex/0.json')
response = urllib2.urlopen(req)
page = response.read()
user_dict = json.loads(page)
count = 0

for k in user_dict['baseURIs']:
    if 'RealMadrid' in k:
        print("Found it!")

Body:
Your piece of code:

for k in user_dict['baseURIs']:
    if 'RealMadrid' in k:
        print("Found it!")

Searches for 'RealMadrid' in the dictionary k, which means it looks for that string in the dictionary keys. However, in the dictionary you provided as input, 'RealMadrid' is not a key, but the value associated with the 'URL' key. You should replace the above with:

for k in user_dict['baseURIs']:
    if k['URL'] == 'RealMadrid':
        print("Found it!")


答:
Simply copy that onPressed() functions body and wrap it in a function as:

```<code>void onTapRaised(){
  Navigator.of(context).pushNamed("Page2");
}

RaisedButton(
  onPressed:onTapRaised,
  child:Text("Jump"),
)
</code>```

now you can call onTapRaised programmatically from anywhere in the same page.

Title: Flutter - how to trigger a RaisedButton Programmatically?

Body:
Simply copy that onPressed() functions body and wrap it in a function as:

void onTapRaised(){
  Navigator.of(context).pushNamed("Page2");
}

RaisedButton(
  onPressed:onTapRaised,
  child:Text("Jump"),
)

now you can call onTapRaised programmatically from anywhere in the same page.


问:
Access an NSUserDefault from multiple views
I am trying to access an NSUserDefault called prefs from multiple views. I am allocating prefs in one view but I don't know how to access it without just reallocating a new NSUserDefault in the second view.

Also, my operating system is ios.

Here is my FlipSideViewController Function:

The function in my FlipSideViewController: 'NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

```<code>- (IBAction) changeRate:(id)sender {

if (rate.selectedSegmentIndex == 1){
    [prefs setInteger:1 forKey:@"myRate"];//save

}
else if (rate.selectedSegmentIndex == 2){
    [prefs setInteger:2 forKey:@"myRate"];//save
}
[[NSUserDefaults standardUserDefaults] synchronize];
};
</code>```

And this is the MainViewController function:

```<code> NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// [prefs setValue: @"0" forKey: @"myRate"];

if (!([prefs valueForKey: @"myRate"])){
    [prefs setInteger:0 forKey: @"myRate"];
}

[prefs setInteger:2 forKey: @"myRate"];

int rateOption = [[prefs valueForKey: @"myRate"] intValue];

if (rateOption == 1)
{
    dayOrHourly.text = @"% of Day:";
    percentOrHours.hidden = YES;
    hours.hidden = YES;
    dayPercentage.hidden = NO;
}
else if (rateOption == 2)
{
    dayOrHourly.text = @"# of Hours:";
    percentOrHours.hidden = NO;
    dayPercentage.hidden = YES;
}
</code>```

答:
Having more than one prefs for different views shouldn't be a problem. Just call

```<code>[prefObject synchronize];
</code>```

when you modify one of the instances of NSUserDefaults in one view or try to access them from another view and you'll be fine.

But if you really want to keep a single object shared across all your view controllers, put it in your App Delegate.  [I must say, I don't see the point...]

Body:
I am trying to access an NSUserDefault called prefs from multiple views. I am allocating prefs in one view but I don't know how to access it without just reallocating a new NSUserDefault in the second view.

Also, my operating system is ios.

Here is my FlipSideViewController Function:

The function in my FlipSideViewController: 'NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

- (IBAction) changeRate:(id)sender {

if (rate.selectedSegmentIndex == 1){
    [prefs setInteger:1 forKey:@"myRate"];//save

}
else if (rate.selectedSegmentIndex == 2){
    [prefs setInteger:2 forKey:@"myRate"];//save
}
[[NSUserDefaults standardUserDefaults] synchronize];
};

And this is the MainViewController function:

 NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// [prefs setValue: @"0" forKey: @"myRate"];

if (!([prefs valueForKey: @"myRate"])){
    [prefs setInteger:0 forKey: @"myRate"];
}

[prefs setInteger:2 forKey: @"myRate"];

int rateOption = [[prefs valueForKey: @"myRate"] intValue];

if (rateOption == 1)
{
    dayOrHourly.text = @"% of Day:";
    percentOrHours.hidden = YES;
    hours.hidden = YES;
    dayPercentage.hidden = NO;
}
else if (rateOption == 2)
{
    dayOrHourly.text = @"# of Hours:";
    percentOrHours.hidden = NO;
    dayPercentage.hidden = YES;
}

Body:
Having more than one prefs for different views shouldn't be a problem. Just call

[prefObject synchronize];

when you modify one of the instances of NSUserDefaults in one view or try to access them from another view and you'll be fine.

But if you really want to keep a single object shared across all your view controllers, put it in your App Delegate.  [I must say, I don't see the point...]


问:
WPF Overlay does not activate until after button has finished
I have a small sample WPF application using Caliburn Micro. In it, I have a rectangle overlay that says loading. I want this to appear whenever a large task is loading however it doesn't appear until after the method is finished. I have tried using Dispatch as well as other suggestions howver nothing works until after the button method is finished. Below is my current example

```<code>  public async void TheActionButton()
        {
            //Application.Current.Dispatcher.Invoke(new System.Action(() => { IsLoadingMessageVisible = true; NotifyOfPropertyChange(() => IsLoadingMessageVisible); }));
            Execute.OnUIThread(new System.Action(() => { IsLoadingMessageVisible = true; NotifyOfPropertyChange(() => IsLoadingMessageVisible); }));
            await LongMethod();
        }

</code>```

The overlay shows up only after LongMethod() is finished running. Is there a way to get it to show before the method runs?

答:
You should use the TAP (Task-based Asynchronous Programming), it integrates well with such use cases.

```<code>async void TheActionButton()
{
    IsLoadingMessageVisible = true;
    NotifyOfPropertyChange(() => IsLoadingMessageVisible);

    await LongMethod();

    IsLoadingMessageVisible = false;
    NotifyOfPropertyChange(() => IsLoadingMessageVisible);
}
</code>```

Note: implement your IsLoadingMessageVisible in the way so that you don't need to call NotifyOfPropertyChange() each time you set the property.

Body:
I have a small sample WPF application using Caliburn Micro. In it, I have a rectangle overlay that says loading. I want this to appear whenever a large task is loading however it doesn't appear until after the method is finished. I have tried using Dispatch as well as other suggestions howver nothing works until after the button method is finished. Below is my current example

  public async void TheActionButton()
        {
            //Application.Current.Dispatcher.Invoke(new System.Action(() => { IsLoadingMessageVisible = true; NotifyOfPropertyChange(() => IsLoadingMessageVisible); }));
            Execute.OnUIThread(new System.Action(() => { IsLoadingMessageVisible = true; NotifyOfPropertyChange(() => IsLoadingMessageVisible); }));
            await LongMethod();
        }

The overlay shows up only after LongMethod() is finished running. Is there a way to get it to show before the method runs?

Body:
You should use the TAP (Task-based Asynchronous Programming), it integrates well with such use cases.

async void TheActionButton()
{
    IsLoadingMessageVisible = true;
    NotifyOfPropertyChange(() => IsLoadingMessageVisible);

    await LongMethod();

    IsLoadingMessageVisible = false;
    NotifyOfPropertyChange(() => IsLoadingMessageVisible);
}

Note: implement your IsLoadingMessageVisible in the way so that you don't need to call NotifyOfPropertyChange() each time you set the property.


问:
Can't able to get location of moblie in flutter of moblie
I am trying to get location of mobile by flutter and i can't able to get the dimensions.
wheni am pressing the button op services null is getting.there are so many friends are getting this error and we can't able to solve it.please anyone one help me out of these trouble   </p>

```<code>import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';

class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {

  void getLocation() async{
  Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
  print(position);
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          onPressed: () {
            getLocation();
          },
          child: Text('Get Location'),
        ),
      ),
    );
  }
}

    Error i get is like:-
    I/Surface (24964): opservice is null false
    I/Surface (24964): opservice is null false
    I/Surface (24964): opservice is null false
    D/DecorView(24964): onWindowFocusChangedFromViewRoot hasFocus: true, DecorView@936a7df[MainActivity]
    I/Surface (24964): opservice is null false
</code>```

答: In Android put FINE_LOCATION instead of COARSE_LOCATION, I had the same issue but after changing that I got the location printed and the permission dialog box doesn't appear if you have already given the permission for the location for this app in your phone, but if you changed then permission dialog box also would appear.

Body:
I am trying to get location of mobile by flutter and i can't able to get the dimensions.
wheni am pressing the button op services null is getting.there are so many friends are getting this error and we can't able to solve it.please anyone one help me out of these trouble

import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';

class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {

  void getLocation() async{
  Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
  print(position);
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          onPressed: () {
            getLocation();
          },
          child: Text('Get Location'),
        ),
      ),
    );
  }
}

    Error i get is like:-
    I/Surface (24964): opservice is null false
    I/Surface (24964): opservice is null false
    I/Surface (24964): opservice is null false
    D/DecorView(24964): onWindowFocusChangedFromViewRoot hasFocus: true, DecorView@936a7df[MainActivity]
    I/Surface (24964): opservice is null false


问:
Button that moves box with text - JavaScript Jquery
I have to make this first button called "натисни" make box "кутийка с текст" move to right by 10px when i click the button. Any suggestions ?

Here is the code.

http://jsfiddle.net/08y7rqf5/

// find elements
var banner = $("#banner-message")
var button = $("button")

// handle click and add class
button.on("click", () => {
  banner.toggleClass("alt")
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.min.css">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

кутийка с текст

            <input type="button" class="btn btn-info float-right" value="Натисни">

```

答:
where is your banner-message id in your html code ???
And you're using input with type button, not button tag so you cannot use

```<code>var button = $("button")
</code>```

You need to use

```<code>var button = $("input[type=button]")
</code>```

But the best way is defined the class for it. Example

```<code><input type="button" class="btn btn-info float-right myButtonClass" value="Натисни">
</code>```

and then call it as

```<code>var button = $(".myButtonClass");
</code>```

Body:
I have to make this first button called "натисни" make box "кутийка с текст" move to right by 10px when i click the button. Any suggestions ?

Here is the code.

http://jsfiddle.net/08y7rqf5/

// find elements
var banner = $("#banner-message")
var button = $("button")

// handle click and add class
button.on("click", () => {
  banner.toggleClass("alt")
})

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.min.css">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

кутийка с текст

            <input type="button" class="btn btn-info float-right" value="Натисни">

Body:
where is your banner-message id in your html code ???
And you're using input with type button, not button tag so you cannot use

var button = $("button")

You need to use

var button = $("input[type=button]")

But the best way is defined the class for it. Example

<input type="button" class="btn btn-info float-right myButtonClass" value="Натисни">

and then call it as

var button = $(".myButtonClass");


问:
Is it possibile to access ( not copy ) files in my remote from my local machine?
I want to access a random forest estimator that I trained and saved on the remote machine. The pickled estimator is 2.4 gigs and my local machine is low on space so i can't use scp to download the file in my local. Is it possible that python can access (read) the file kept in the remote and load it in its RAM ?

答:
Yes. The paramiko module allows to open a file like object to a remote file. From the Paramiko SFTP doc page:

class paramiko.sftp_client.SFTPClient(sock)

SFTP client object.

Used to open an SFTP session across an open SSH Transport and perform remote file operations.

Instances of this class may be used as context managers.

...

file(filename, mode='r', bufsize=-1)

Open a file on the remote server. The arguments are the same as for Python’s built-in file (aka open). A file-like object is returned, which closely mimics the behavior of a normal Python file object, including the ability to be used as a context manager.


答:
You are searching inside the dict keys instead of values. Try:</p>

```<code>for k in user_dict['baseURIs']:
    if 'RealMadrid' in k.values():
        print("Found it!")
</code>```

Title: Check dict from Json output (urllib2)

Body:
You are searching inside the dict keys instead of values. Try:

for k in user_dict['baseURIs']:
    if 'RealMadrid' in k.values():
        print("Found it!")


问:
"Uncaught TypeError: history.push is not a function" error occurs
I have been developing a navigation bar. I wrote a function to switch screens and call it in button onClick. I wrapped the component in withRouter also. But the following error occurs:

Uncaught TypeError: history.push is not a function" error.

This is my code:

```<code>import { withRouter } from 'react-router-dom';

function Navigation(history) {
  const abc = path => {
    history.push(path);
  };

return(
<button onClick={() => abc('/user')}>User</button>
);}

export default withRouter(Navigation);
</code>```

Thank you

答:
You have wrapped the Navigation component with withRouter, thus you will need to access the history object via the component's props. You may choose to destructure your props as shown below:

```<code>function Navigation({ history }) {
  const abc = path => {
    history.push(path);
  };

  return (
    <button onClick={() => abc('/user')}>User</button>
  );
}

export default withRouter(Navigation);
</code>```

Since you are working with functional components, an alternative way of doing things would be to make use of the useHistory hook, which spares you the need to wrap your component with withRouter:

```<code>import { useHistory } from 'react-router-dom';

function Navigation(props) {
  const history = useHistory();

  const abc = path => {
    history.push(path);
  };

  return (
    <button onClick={() => abc('/user')}>User</button>
  );
}

export default Navigation;
</code>```

Body:
I have been developing a navigation bar. I wrote a function to switch screens and call it in button onClick. I wrapped the component in withRouter also. But the following error occurs:

Uncaught TypeError: history.push is not a function" error.

This is my code:

import { withRouter } from 'react-router-dom';

function Navigation(history) {
  const abc = path => {
    history.push(path);
  };

return(
<button onClick={() => abc('/user')}>User</button>
);}

export default withRouter(Navigation);

Thank you

Body:
You have wrapped the Navigation component with withRouter, thus you will need to access the history object via the component's props. You may choose to destructure your props as shown below:

function Navigation({ history }) {
  const abc = path => {
    history.push(path);
  };

  return (
    <button onClick={() => abc('/user')}>User</button>
  );
}

export default withRouter(Navigation);

Since you are working with functional components, an alternative way of doing things would be to make use of the useHistory hook, which spares you the need to wrap your component with withRouter:

import { useHistory } from 'react-router-dom';

function Navigation(props) {
  const history = useHistory();

  const abc = path => {
    history.push(path);
  };

  return (
    <button onClick={() => abc('/user')}>User</button>
  );
}

export default Navigation;


问:
Can I exclude some files from git-lfs?
I created a repo with some image files. I have .gitignore and .gitattributes that I want to exclude from lfs. So I need to track all files by lfs but not .gitignore and .gitattributes.

I' m using Sourcetree and I tried that in .gitattributes:

```<code>.gitignore      text
.gitattributes  text
*               filter=lfs diff=lfs merge=lfs -text
</code>```

But all of my files getting tracked by lfs.

答:
I was looking for the same.  I am using git version 2.26.2 and rkedge's answer did not work for me.  I found this thread and ended up using:

```<code>*.dat         filter=lfs diff=lfs merge=lfs -text
excluded.dat  !filter !diff !merge text
</code>```

For files already commited, I had to untrack and re-commit them after modifying .gitattributes.

Title: Can I exclude some files from git-lfs?

Body:
I created a repo with some image files. I have .gitignore and .gitattributes that I want to exclude from lfs. So I need to track all files by lfs but not .gitignore and .gitattributes.

I' m using Sourcetree and I tried that in .gitattributes:

.gitignore      text
.gitattributes  text
*               filter=lfs diff=lfs merge=lfs -text

But all of my files getting tracked by lfs.

Body:
I was looking for the same.  I am using git version 2.26.2 and rkedge's answer did not work for me.  I found this thread and ended up using:

*.dat         filter=lfs diff=lfs merge=lfs -text
excluded.dat  !filter !diff !merge text

For files already commited, I had to untrack and re-commit them after modifying .gitattributes.


问:
Placing 3 div's Side by Side
I want to place 3 divs side by side using CSS. I have gone through many posts on SO, but not getting the thing working for my project.

```<code>#quotescointainer{
    width: 100%;
    font-size: 12px;
}
#quotesleft{
    float:left;
    width: 33%;
    background-color: white;
}
#quotescenter{
    background-color:white;
    width: 33%;
}
#quotesright{
    float:left;
    width: 33%;
}
</code>```

The above does not place the div's in the correct place. I cannot seem to figure out the mistake I am making.

答:
You could float: left all the inner divs:

http://jsfiddle.net/W8dyy/

You should fix the spelling of quotescointainer to quotescontainer.

```<code>#quotescointainer{
    width: 100%;
    font-size: 12px;
    overflow: hidden; /* contain floated elements */
    background: #ccc
}
#quotesleft {
    float: left;
    width: 33%;
    background-color: #bbb;
}
#quotescenter {
    float: left;
    background-color: #eee;
    width: 33%;
}
#quotesright{
    float: left;
    width: 33%;
    background-color: #bbb;
}
</code>```

Title: Placing 3 div's Side by Side

Body:
I want to place 3 divs side by side using CSS. I have gone through many posts on SO, but not getting the thing working for my project.

#quotescointainer{
    width: 100%;
    font-size: 12px;
}
#quotesleft{
    float:left;
    width: 33%;
    background-color: white;
}
#quotescenter{
    background-color:white;
    width: 33%;
}
#quotesright{
    float:left;
    width: 33%;
}

The above does not place the div's in the correct place. I cannot seem to figure out the mistake I am making.

Body:
You could float: left all the inner divs:

http://jsfiddle.net/W8dyy/

You should fix the spelling of quotescointainer to quotescontainer.

#quotescointainer{
    width: 100%;
    font-size: 12px;
    overflow: hidden; /* contain floated elements */
    background: #ccc
}
#quotesleft {
    float: left;
    width: 33%;
    background-color: #bbb;
}
#quotescenter {
    float: left;
    background-color: #eee;
    width: 33%;
}
#quotesright{
    float: left;
    width: 33%;
    background-color: #bbb;
}


答: You have to destruct all the props like Navigation({ history })

Title: "Uncaught TypeError: history.push is not a function" error occurs


问:
Azure function proxy - required request header
I would like to use an Azure function proxy to restrict access to an API by requiring that a specified request header X-MY-HEADER is present. I don't want to actually check the value of the header here, just that it is present.

I can't find any examples of this and some trial and error hasn't worked. The proxy configuration is working properly before adding the additional for the header.

I have tried something like:

```<code>{
  "proxies": {
    "Mock API - POST": {
      "matchCondition": {
        "methods": [ "POST" ],
        "route": "/api",
        "request.headers.X-MY-HEADER": "{*}"
      },
      "responseOverrides": {
        "response.headers.Location": "https://REAL/API/ADDRESS/ETC"
      }
    }
  }
}
</code>```

also "request.headers": "X-MY-HEADER" but neither appear to work.

Is this possible to do and I just have the syntax wrong?

If the header is missing I'm happy for it to simply 404.

答:
You can do the autherize like this:

```<code>using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace FunctionApp62
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            if (req.Headers.Keys.Contains("X-MY-HEADER"))
            {
                log.LogInformation("has header X-MY-HEADER!");
                //put your process logic here.
            }

            return new OkObjectResult("!!!!!!!!!!!!!!!!!!!!!!");
        }
    }
}
</code>```

(do the autherize in the logic of your function, if the request has the header, then do something.)

Body:
I would like to use an Azure function proxy to restrict access to an API by requiring that a specified request header X-MY-HEADER is present. I don't want to actually check the value of the header here, just that it is present.

I can't find any examples of this and some trial and error hasn't worked. The proxy configuration is working properly before adding the additional for the header.

I have tried something like:

{
  "proxies": {
    "Mock API - POST": {
      "matchCondition": {
        "methods": [ "POST" ],
        "route": "/api",
        "request.headers.X-MY-HEADER": "{*}"
      },
      "responseOverrides": {
        "response.headers.Location": "https://REAL/API/ADDRESS/ETC"
      }
    }
  }
}

also "request.headers": "X-MY-HEADER" but neither appear to work.

Is this possible to do and I just have the syntax wrong?

If the header is missing I'm happy for it to simply 404.

Body:
You can do the autherize like this:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace FunctionApp62
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            if (req.Headers.Keys.Contains("X-MY-HEADER"))
            {
                log.LogInformation("has header X-MY-HEADER!");
                //put your process logic here.
            }

            return new OkObjectResult("!!!!!!!!!!!!!!!!!!!!!!");
        }
    }
}

(do the autherize in the logic of your function, if the request has the header, then do something.)


问:
Read only replica on a different server using SQL Server 2019
What options exist through SQL Server or vendor tools including AWS that would allow me to take an existing SQL Server with multiple databases and create a read only replica of a different very large (multiple terabyte) database on that same server?

Our requirement is the databases need to live on the same server and we want to stay on SQL Server.

Linked Servers cause performance concerns when executing complex joins and distributed always on appears to require all databases on source database to be replicated.

Example:

```<code>**Server A**
DB1
DB2
DB3
DB4
DB5 *(replicated read only version)*

**Server B**
DB5 *(source, 1tb+)*
</code>```

What option am I missing?

答:
I wouldn't use Transactional Replication as the database won't be Read-Only

Seems like a classic use case for creating an AlwaysOn Availability group between Server B (Primary) and Server A. In this case I think you will want to use a Availability Group without a Cluster - see the article at - https://www.sqlshack.com/read-scale-availability-group-in-a-clusterless-availability-group/ for an introduction.

Server A will then have a read only copy of DB5

Of course this is based on my understanding of your scenario from the few words you gave above, for detailed pros and cons you could look at the article below although note it is getting a little old and a lot of things have been updated especially for availability groups. Of course if you only require a subset of the data from DB5 suddenly transactional replication looks like a much better fit - moving 10% of 1TB has a lot of advantages.

https://www.sqlskills.com/blogs/jonathan/availability-group-readable-secondaries-just-say-no/

Body:
What options exist through SQL Server or vendor tools including AWS that would allow me to take an existing SQL Server with multiple databases and create a read only replica of a different very large (multiple terabyte) database on that same server?

Our requirement is the databases need to live on the same server and we want to stay on SQL Server.

Linked Servers cause performance concerns when executing complex joins and distributed always on appears to require all databases on source database to be replicated.

Example:

**Server A**
DB1
DB2
DB3
DB4
DB5 *(replicated read only version)*

**Server B**
DB5 *(source, 1tb+)*

What option am I missing?