问:
c - cannot take address of bit-field
Why cannot take address of bit-field?

How do I make a pointer to bit-field?

Here is the code...

```<code>struct bitfield {
    unsigned int a: 1;
    unsigned int b: 1;
    unsigned int c: 1;
    unsigned int d: 1;
};

int main(void)
{
    struct bitfield pipe = {
        .a = 1, .b = 0,
        .c = 0, .d = 0
    };
    printf("%d %d %d %d\n", pipe.a,
            pipe.b, pipe.c, pipe.d);
    printf("%p\n", &pipe.a); /* OPPS HERE */
    // error: cannot take address of bit-field ...
    return 0;
}
</code>```

答:
You can't print the address of the bit field but you can assigned to some local variable of required size type(typecasting from one bit memory to 2 bytes(for integer type size will be compiler dependent) memory),that can be used for printing the address.

unsigned int x=pipe.a;
printf("x=%d",&x);

Title: c - cannot take address of bit-field

Body:
Why cannot take address of bit-field?

How do I make a pointer to bit-field?

Here is the code...

struct bitfield {
    unsigned int a: 1;
    unsigned int b: 1;
    unsigned int c: 1;
    unsigned int d: 1;
};

int main(void)
{
    struct bitfield pipe = {
        .a = 1, .b = 0,
        .c = 0, .d = 0
    };
    printf("%d %d %d %d\n", pipe.a,
            pipe.b, pipe.c, pipe.d);
    printf("%p\n", &pipe.a); /* OPPS HERE */
    // error: cannot take address of bit-field ...
    return 0;
}


来源: stackexchange

问:
Getting the y axis value(amplitude) on FFT
I am working on a FFT program, and I would like to get the frequency which has the largest amplitude or intensity in a sound. I checked out some codes on internet, but I couldn't find how to get the amplitude on a python program.</p>

答:
Check librosa.core.stft This gives magnitude of each frequency bin at given time. More details here:

https://librosa.github.io/librosa/generated/librosa.core.stft.html?highlight=stft#librosa.core.stft

ContentLicense: CC BY-SA 4.0


问:
Laravel query by date and time
Query by date and time.

I have table with field and sample data

```<code>Schedule
 --date_start     = 2019-05-01
 --date_end       = 2019-06-30
 --time_start     = 08:00:00
 --time_end       = 10:00:00
</code>```

My question is can I query it by doing select date by (current_date) if current_date is in range or in between the date_start and date end. the same also in time if time is in range

thanks in advance.

答:
You can do it with something like this

```<code>$current = Schedule::whereDate('start_date', '<=', today())
    ->whereDate('end_date', '>=', today())
    ->whereTime('start_time', '<=', now())
    ->whereTime('end_time', '>=', now())
    ->get();
</code>```

$current will be the DB records that are for now.

More information at the Docs

Title: Laravel query by date and time

Body:
Query by date and time.

I have table with field and sample data

Schedule
 --date_start     = 2019-05-01
 --date_end       = 2019-06-30
 --time_start     = 08:00:00
 --time_end       = 10:00:00

My question is can I query it by doing select date by (current_date) if current_date is in range or in between the date_start and date end. the same also in time if time is in range

thanks in advance.

Body:
You can do it with something like this

$current = Schedule::whereDate('start_date', '<=', today())
    ->whereDate('end_date', '>=', today())
    ->whereTime('start_time', '<=', now())
    ->whereTime('end_time', '>=', now())
    ->get();

$current will be the DB records that are for now.

More information at the Docs


问:
How to reply back a user with his/her name using Dialogflow?
I want to know how to reply back a user with his/ her name?
For example:

AppName: Hello, may I ask your name?

User: My name is John

AppName: Welcome John to $appname

I want to do this without webhook or fulfillment. I just want to do with Dialogflow.

答: If you want to use it in other intents taking this context as an input, you have to refer to it as #context_name.parameter_name like this :

ContentLicense: CC BY-SA 3.0


问:
Display substring seperated by / in Hive
I have a column in my table with entries like:

```<code>this/is/my/dir/file
this/is/my/another/dir/file
</code>```

I want to display the string without the filename:

```<code>this/is/my/dir/
</code>```

This is the query which I am using:

```<code>select regexp_replace('this/is/my/another/dir/file','[^/]+','');
</code>```

答:
OK, you can use regexp_replace to remove the file and only reserve the dir path, as we know the file name does not contain the character '/' and is always located at the end of the dir path, so the regexp can be written as '[^/]+$', the examples as below, it means that replace the substring with regexp '[^/]+$' to an empty ''.

```<code>select regexp_replace('/this/is/my/dir/file','[^/]+$','') as dir;
+-------------------+
|        dir        |
+-------------------+
| /this/is/my/dir/  |
+-------------------+

select regexp_replace('this/is/my/another/dir/file','[^/]+$','') as dir;
+--------------------------+
|           dir            |
+--------------------------+
| this/is/my/another/dir/  |
+--------------------------+
</code>```

Body:
I have a column in my table with entries like:

this/is/my/dir/file
this/is/my/another/dir/file

I want to display the string without the filename:

this/is/my/dir/

This is the query which I am using:

select regexp_replace('this/is/my/another/dir/file','[^/]+','');

Body:
OK, you can use regexp_replace to remove the file and only reserve the dir path, as we know the file name does not contain the character '/' and is always located at the end of the dir path, so the regexp can be written as '[^/]+$', the examples as below, it means that replace the substring with regexp '[^/]+$' to an empty ''.

select regexp_replace('/this/is/my/dir/file','[^/]+$','') as dir;
+-------------------+
|        dir        |
+-------------------+
| /this/is/my/dir/  |
+-------------------+

select regexp_replace('this/is/my/another/dir/file','[^/]+$','') as dir;
+--------------------------+
|           dir            |
+--------------------------+
| this/is/my/another/dir/  |
+--------------------------+


问:
How to hash a filename down to a small number or digit for output processing
I am not a Perl programmer but I've inherited existing code that is going to a directory, finding all files iren that folder and subfolder (usually JPG or Office files) and then converting this into a single file to use to load into a SQL Server database. The customer has about 500,000 of these files.

It takes about 45 mins to create the file and then another 45 mins for SQL to load the data. Crudely, it's doing about 150 per second which is reasonable but time is the issue for the job. There are many reasons I don't want to use other techniques so please don't suggest other options unless closely aligned to this process.

What I was considering is to improve speed by running something like 10 processes concurrent. Each process would get passed another argument (0-9). Each process would go to the directory and find all files as it is currently doing but for each file found, it would hash or kludge the filename down to a single digit (0-9) and if that matched the supplied argument, the process would process that file and write it out to it's unique file stream.

Then I would have 10 output files at the end. I doubt that the SQL Server side could be improved as I would have to load to separate tables and then merge in the database and as these are BLOB objects, will not be fast.

So I am looking for some basic code or clues on what functions to use in Perl to take a variable (the file name $File) and generate a single 0 to 9 value based on that. It is probably done by getting the ascii value of each char, then adding these together to get a long number, then add these individual numbers together and eventually you'll get an answer.

Any clues or suggested techniques?

答:
Here's an easy one to implement suggested in the unpack function documentation:

```<code>sub string_to_code {
    # convert an arbitrary string to a digit from 0-9
    my ($string) = @_;
    return unpack("%32W*",$string) % 10;
}
</code>```

Body:
Here's an easy one to implement suggested in the unpack function documentation:

sub string_to_code {
    # convert an arbitrary string to a digit from 0-9
    my ($string) = @_;
    return unpack("%32W*",$string) % 10;
}


问:
Layout with 2 columns and 2 rows
I have a .container
with 2 columns and in the second column .right I want to have 2 rows
but the first row .content should use the remaining space

this is the HTML markup

```<code><div class="container">
    <div class="left">left</div>
    <div class="right">
        <div class="content">content</div>
        <div class="footer">footer</div>
    </div>
</div>
</code>```

this is the CSS

```<code>.container {
    display: flex;
    flex-direction: row;
    height: 400px; /* the remaining space  in the screen will be nice */
}

.left {
    width: 300px;
}

.right {
    flex-grow: 1;
}

.content {
    align-self: stretch; /* this is not doing anything*/
}

.footer {

}
</code>```

and this is how it should look

```<code>+--------+----------------------+
|        |                      |
|        |                      |
|        |       content        |
|  left  |                      |
|        |                      |
|        +----------------------+
|        |       footer         |
+--------+----------------------+
</code>```

答:
You can use a full height flexbox container:

nest a column flexbox inside for the right element,

use flex-grow: 1 on content to occupy remaining space.

See demo below:

body {
  margin: 0;
}
.container {
  display: flex;
  /* flex-direction: row; <-- omit this, its default */
  height: 100vh; /* full height */
}

.left {
  width: 300px;
  border: 1px solid;
}

.right {
  flex-grow: 1; /* occupy remaining space */
  display: flex;
  flex-direction: column; /* column flexbox */
  border: 1px solid;
}

.content {
  flex-grow: 1; /* occupy remaining space */
  border-bottom: 1px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="left">left</div>
  <div class="right">
    <div class="content">content</div>
    <div class="footer">footer</div>
  </div>
</div></code>```

Title: Layout with 2 columns and 2 rows

Body:
I have a .container
with 2 columns and in the second column .right I want to have 2 rows
but the first row .content should use the remaining space

this is the HTML markup

left

content

footer

this is the CSS

.container {
    display: flex;
    flex-direction: row;
    height: 400px; /* the remaining space  in the screen will be nice */
}

.left {
    width: 300px;
}

.right {
    flex-grow: 1;
}

.content {
    align-self: stretch; /* this is not doing anything*/
}

.footer {

}

and this is how it should look

+--------+----------------------+
|        |                      |
|        |                      |
|        |       content        |
|  left  |                      |
|        |                      |
|        +----------------------+
|        |       footer         |
+--------+----------------------+

Body:
You can use a full height flexbox container:

nest a column flexbox inside for the right element,

use flex-grow: 1 on content to occupy remaining space.

See demo below:

body {
  margin: 0;
}
.container {
  display: flex;
  /* flex-direction: row; <-- omit this, its default */
  height: 100vh; /* full height */
}

.left {
  width: 300px;
  border: 1px solid;
}

.right {
  flex-grow: 1; /* occupy remaining space */
  display: flex;
  flex-direction: column; /* column flexbox */
  border: 1px solid;
}

.content {
  flex-grow: 1; /* occupy remaining space */
  border-bottom: 1px solid;
}

<div class="container">
  <div class="left">left</div>
  <div class="right">
    <div class="content">content</div>
    <div class="footer">footer</div>
  </div>
</div>


问:
Counting number of sequences of particular value for multiple columns in a data frame
I would like to create a table or a new data frame that displays, for each column in the original data frame (of which there are many), how many times a sequence of a specific value occurs. For example, if I have the following data frame:

```<code>x <- data.frame("Red" = c("a", "b", "a", "a", "c", "d"), "Blue" = c("b", "a", "a", "a", "a", "a"), "Green" = c("a", "a", "b", "a", "b", "a"))
</code>```

and I want to know, for each color (Red, Blue, and Green) how many times a run of the value "a" occurs (i.e., before it is interrupted by another value like b or c)

The correct answer would look something like this:

```<code>     Color a_sequences
1   Red  2
2  Blue  1
3 Green  3
</code>```

I have found solutions on this site using the rle function on single vectors but I don't know how to scale this up for an entire data frame with multiple columns and obtain a new table or data frame with the sequence counts, as in the above table. Thank you!

答:
```<code>f = function(v, ch) sum(rle(as.character(v))$values == ch)
sapply(x, f, 'a')
# Red  Blue Green
# 2     1     3
</code>```

Body:
I would like to create a table or a new data frame that displays, for each column in the original data frame (of which there are many), how many times a sequence of a specific value occurs. For example, if I have the following data frame:

x <- data.frame("Red" = c("a", "b", "a", "a", "c", "d"), "Blue" = c("b", "a", "a", "a", "a", "a"), "Green" = c("a", "a", "b", "a", "b", "a"))

and I want to know, for each color (Red, Blue, and Green) how many times a run of the value "a" occurs (i.e., before it is interrupted by another value like b or c)

The correct answer would look something like this:

     Color a_sequences
1   Red  2
2  Blue  1
3 Green  3

I have found solutions on this site using the rle function on single vectors but I don't know how to scale this up for an entire data frame with multiple columns and obtain a new table or data frame with the sequence counts, as in the above table. Thank you!


问:
How to remove a TextField from ListView when onPressed button?
How to remove the TextField when user click on "clear icon" button ? (not just clear the Text of TextField)

User Story

The user click on a button to add player. (Technically this button add TextField)

The user can write the name of player on TextField.

The user click on a "clear icon" button to remove current TextField (opposite of add function).

```<code>new ListView.builder(
                     padding: EdgeInsets.all(0),
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      itemCount: 5,
                      itemBuilder: (context, index) {
                        print(index);
                        return TextField(
                          maxLength: 20,
                          decoration: InputDecoration(
                            labelText: "Player ${index+1}",
                            counterText: "",
                            prefixIcon: const Icon(Icons.person),
                            suffixIcon: new IconButton(
                                icon: Icon(Icons.clear),
                                onPressed: () =>
                                  setState(() {
                                    this.dispose(); // -----Doesn't work----
                                  })
                                ),
                          ),
                        );
                      }
                    ),
</code>```

For example, user set "John" on Player 4 if user click on "clear button" then Player 4 TextField is deleted. It will remain only 4 TextField

答:
Facts I assume:

you want to be able to delete (or add) a field from (to) the list

you want the values of the remaining fields to remain when you delete the field

the list can be larger than 5

Solution:

If you want all the above to be true, then you actually need to track the TextEditingControllers of the TextFields, instead of the text fields themselves. This is because the value of the TextField is actually stored in the TextEditingController (which is created anew on the fly if you do not supply it for each widget). Check this out:

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

// needs to be StatefulWidget, so we can keep track of the count of the fields internally
class PlayerList extends StatefulWidget {
  const PlayerList({
    this.initialCount = 5,
  });

  // also allow for a dynamic number of starting players
  final int initialCount;

  @override
  _PlayerListState createState() => _PlayerListState();
}

class _PlayerListState extends State<PlayerList> {
  int fieldCount = 0;
  int nextIndex = 0;
  // you must keep track of the TextEditingControllers if you want the values to persist correctly
  List<TextEditingController> controllers = <TextEditingController>[];

  // create the list of TextFields, based off the list of TextControllers
  List<Widget> _buildList() {
    int i;
    // fill in keys if the list is not long enough (in case we added one)
    if (controllers.length < fieldCount) {
      for (i = controllers.length; i < fieldCount; i++) {
        controllers.add(TextEditingController());
      }
    }

    i = 0;
    // cycle through the controllers, and recreate each, one per available controller
    return controllers.map<Widget>((TextEditingController controller) {
      int displayNumber = i + 1;
      i++;
      return TextField(
        controller: controller,
        maxLength: 20,
        decoration: InputDecoration(
          labelText: "Player $displayNumber",
          counterText: "",
          prefixIcon: const Icon(Icons.person),
          suffixIcon: IconButton(
            icon: Icon(Icons.clear),
            onPressed: () {
              // when removing a TextField, you must do two things:
              // 1. decrement the number of controllers you should have (fieldCount)
              // 2. actually remove this field's controller from the list of controllers
              setState(() {
                fieldCount--;
                controllers.remove(controller);
              });
            },
          ),
        ),
      );
    }).toList(); // convert to a list
  }

  @override
  Widget build(BuildContext context) {
    // generate the list of TextFields
    final List<Widget> children = _buildList();

    // append an 'add player' button to the end of the list
    children.add(
      GestureDetector(
        onTap: () {
          // when adding a player, we only need to inc the fieldCount, because the _buildList()
          // will handle the creation of the new TextEditingController
          setState(() {
            fieldCount++;
          });
        },
        child: Container(
          color: Colors.blue,
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Text(
              'add player',
              style: TextStyle(
                color: Colors.white,
              ),
            ),
          ),
        ),
      ),
    );

    // build the ListView
    return ListView(
      padding: EdgeInsets.all(0),
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      children: children,
    );
  }

  @override
  void initState() {
    super.initState();

    // upon creation, copy the starting count to the current count
    fieldCount = widget.initialCount;
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void didUpdateWidget(PlayerList oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}
</code>```

With the above, you can:

start the app

change player 2 to 'bob'

change player 3 to 'steve'

change player 4 to 'charles'

delete player 3

observe that player 2 is 'bob' and the new player 3 is 'charles'

I think this is what you are looking for here.

Body:
How to remove the TextField when user click on "clear icon" button ? (not just clear the Text of TextField)

User Story

The user click on a button to add player. (Technically this button add TextField)

The user can write the name of player on TextField.

The user click on a "clear icon" button to remove current TextField (opposite of add function).

new ListView.builder(
                     padding: EdgeInsets.all(0),
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      itemCount: 5,
                      itemBuilder: (context, index) {
                        print(index);
                        return TextField(
                          maxLength: 20,
                          decoration: InputDecoration(
                            labelText: "Player ${index+1}",
                            counterText: "",
                            prefixIcon: const Icon(Icons.person),
                            suffixIcon: new IconButton(
                                icon: Icon(Icons.clear),
                                onPressed: () =>
                                  setState(() {
                                    this.dispose(); // -----Doesn't work----
                                  })
                                ),
                          ),
                        );
                      }
                    ),

For example, user set "John" on Player 4 if user click on "clear button" then Player 4 TextField is deleted. It will remain only 4 TextField

Body:
Facts I assume:

you want to be able to delete (or add) a field from (to) the list

you want the values of the remaining fields to remain when you delete the field

the list can be larger than 5

Solution:

If you want all the above to be true, then you actually need to track the TextEditingControllers of the TextFields, instead of the text fields themselves. This is because the value of the TextField is actually stored in the TextEditingController (which is created anew on the fly if you do not supply it for each widget). Check this out:

import 'package:flutter/material.dart';

// needs to be StatefulWidget, so we can keep track of the count of the fields internally
class PlayerList extends StatefulWidget {
  const PlayerList({
    this.initialCount = 5,
  });

  // also allow for a dynamic number of starting players
  final int initialCount;

  @override
  _PlayerListState createState() => _PlayerListState();
}

class _PlayerListState extends State<PlayerList> {
  int fieldCount = 0;
  int nextIndex = 0;
  // you must keep track of the TextEditingControllers if you want the values to persist correctly
  List<TextEditingController> controllers = <TextEditingController>[];

  // create the list of TextFields, based off the list of TextControllers
  List<Widget> _buildList() {
    int i;
    // fill in keys if the list is not long enough (in case we added one)
    if (controllers.length < fieldCount) {
      for (i = controllers.length; i < fieldCount; i++) {
        controllers.add(TextEditingController());
      }
    }

    i = 0;
    // cycle through the controllers, and recreate each, one per available controller
    return controllers.map<Widget>((TextEditingController controller) {
      int displayNumber = i + 1;
      i++;
      return TextField(
        controller: controller,
        maxLength: 20,
        decoration: InputDecoration(
          labelText: "Player $displayNumber",
          counterText: "",
          prefixIcon: const Icon(Icons.person),
          suffixIcon: IconButton(
            icon: Icon(Icons.clear),
            onPressed: () {
              // when removing a TextField, you must do two things:
              // 1. decrement the number of controllers you should have (fieldCount)
              // 2. actually remove this field's controller from the list of controllers
              setState(() {
                fieldCount--;
                controllers.remove(controller);
              });
            },
          ),
        ),
      );
    }).toList(); // convert to a list
  }

  @override
  Widget build(BuildContext context) {
    // generate the list of TextFields
    final List<Widget> children = _buildList();

    // append an 'add player' button to the end of the list
    children.add(
      GestureDetector(
        onTap: () {
          // when adding a player, we only need to inc the fieldCount, because the _buildList()
          // will handle the creation of the new TextEditingController
          setState(() {
            fieldCount++;
          });
        },
        child: Container(
          color: Colors.blue,
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Text(
              'add player',
              style: TextStyle(
                color: Colors.white,
              ),
            ),
          ),
        ),
      ),
    );

    // build the ListView
    return ListView(
      padding: EdgeInsets.all(0),
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      children: children,
    );
  }

  @override
  void initState() {
    super.initState();

    // upon creation, copy the starting count to the current count
    fieldCount = widget.initialCount;
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void didUpdateWidget(PlayerList oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}

With the above, you can:

start the app

change player 2 to 'bob'

change player 3 to 'steve'

change player 4 to 'charles'

delete player 3

observe that player 2 is 'bob' and the new player 3 is 'charles'

I think this is what you are looking for here.


问:
Regex Expression working in Notepad++ but not Java
Okay, so i'm working on a problem I'd rather solve with regex, I test most of my regex expressions in Notepad++, This has worked fine after a few tweaks such as double escaping some things for java, However this regex expression throws an exception when run in java, however it runs in Notepad++ just fine, the idea if this code is to be able to mention a different player in the game with a highlighted name.

tldr; I'm trying to replace the first occurrence of a specific name in a message

I've tried looking around for a while but i haven't found a solution, so i thought i might as well ask here.

p.getName() simply returns a string (the players name)

String newmessage = message.replaceFirst("(?i)" + Pattern.quote(p.getName()) + "((?(?=\\s)|('|,|!))|$)", color + p.getName() + Color.toString(Color.getLastColorOf(message)));
```

<p>However executing the code throws this exception
<code>...at java.lang.Thread.run(Unknown Source) [?:1.8.0_202]
Caused by: java.util.regex.PatternSyntaxException: Unknown inline modifier near index 15
(?i)\QTauCubed\E((?(?=\s)|('|,))|$)
               ^
at java.util.regex.Pattern.error(Unknown Source) ~[?:1.8.0_202]...</code></p>

<p>And I'm not sure  what it wants me to do, I don't see how this is not valid regex</p>

<p>This is the regex for Notepad++</p>

```(?i)Name((?(?=\s)|('|,|!))|$)
```

<p>The above will match</p>

```Name's r
Name
Name test
Name,
Name!
```

<p>But will not match</p>

```Nametest
```

That is what I intended it to do.

答:
I vote for just using the pattern \bName\b along with String#replaceFirst:

```<code>String input = "Rename here is a Name and here is the same Name again.";
input = input.replaceFirst("\\bName\\b", "blah");
System.out.println(input);
</code>```

This prints:

```<code>Rename here is a blah and here is the same Name again.
</code>```

Body:
Okay, so i'm working on a problem I'd rather solve with regex, I test most of my regex expressions in Notepad++, This has worked fine after a few tweaks such as double escaping some things for java, However this regex expression throws an exception when run in java, however it runs in Notepad++ just fine, the idea if this code is to be able to mention a different player in the game with a highlighted name.

tldr; I'm trying to replace the first occurrence of a specific name in a message

I've tried looking around for a while but i haven't found a solution, so i thought i might as well ask here.

p.getName() simply returns a string (the players name)

String newmessage = message.replaceFirst("(?i)" + Pattern.quote(p.getName()) + "((?(?=\\s)|('|,|!))|$)", color + p.getName() + Color.toString(Color.getLastColorOf(message)));

However executing the code throws this exception
...at java.lang.Thread.run(Unknown Source) [?:1.8.0_202]
Caused by: java.util.regex.PatternSyntaxException: Unknown inline modifier near index 15
(?i)\QTauCubed\E((?(?=\s)|('|,))|$)
               ^
at java.util.regex.Pattern.error(Unknown Source) ~[?:1.8.0_202]...

And I'm not sure  what it wants me to do, I don't see how this is not valid regex

This is the regex for Notepad++

(?i)Name((?(?=\s)|('|,|!))|$)

The above will match

Name's r
Name
Name test
Name,
Name!

But will not match

Nametest

That is what I intended it to do.

Body:
I vote for just using the pattern \bName\b along with String#replaceFirst:

String input = "Rename here is a Name and here is the same Name again.";
input = input.replaceFirst("\\bName\\b", "blah");
System.out.println(input);

This prints:

Rename here is a blah and here is the same Name again.


问:
Android How to print image with TSC Alpha-3R printer?
I want to print an image with android bluetooth TSC Alpha-3R printer ?

Any one to work with this device? How can I print bitmap with this device ?

Code sample or Any idea please ?

答:
You might wanna use an end user solution like Hammer Print, so far one of the only and best support, but still not perfect.

I just got the device, but is not like ESC/POS that you'll find a lot of apps with support.

If you have any recomendation, I'll love to hear it.

Cheers!


问:
ggplot facetting using group_by
Say I have measured some values in two experiments, a toy example in R being:

```<code>set.seed(9)
df <- data.frame(
    exp=c(rep(1,10), rep(2,10)),
    value=runif(20,0,3))
</code>```

I then assign the categorial variable level based on value:

```<code>require("dplyr")
df <- df %>% mutate(level = ifelse(value<1, "low", ifelse(value>2, "high", "intermediate")))
</code>```

I can display a geom_point() geom (ggplot2 package) of valuefor the two exp groups:

```<code>require("ggplot2")
ggplot(df, aes(x=factor(exp), y=value))+geom_point()
</code>```

My problem is:
How can I break down the display with facet_wrap() by level so that I get a 3x3 graph of geom_point()'s with the nine combinations of levelfor the two exp (e.g. "high", "intermediate" and "low" vertically for experimment 1 and horizontally for experiment 2. In other words, the upper left graph are those valuewhich are "high" in experiment 1 and 2; first row second column graph are those that are "high" in experiment 1 and "intermediate" in experiment 2 etc). Can I somehow use group_by() in the ggplot2 call, or will I have to make level.exp1 and level.exp2variables to facet around  ?

UPDATE:
Seems I didnt explain it properly, so to clarify what I need: I would like to facet_wrap() instead of repeating this code 9 times with different filter() conditions (i.e. for all 9 combinations of levelin experiment 1 and 2):

```<code>df  %>% filter((exp==1 & level=="high") | (exp==2 & level=="high")) %>%
  ggplot(aes(x=factor(exp), y=value))+geom_point()
</code>```

A handmade madeup and not related to dfabove and with fake legends may give an impression of what I want:

There must be a gentle solution - I could not figure out a a dcast() solution.

答:
See if this works for you. I think the key is that there should be some id that observations share between experiment 1 and experiment 2.

set.seed(9)
df <-
  data.frame(
    id = rep(1:100, 2),
    # adding exp_ bc this will be the column name in the next step
    exp = paste0("exp_", rep(1:2, each = 100)),
    value = runif(200, 0, 3)
  ) %>%
  # this will pivot the data into a column for exp_1 and exp_2
  spread(exp, value) %>%
  mutate(
    level_1 = case_when(exp_1 < 1 ~ "low", exp_1 > 2 ~ "high", TRUE ~ "intermediate"),
    level_2 = case_when(exp_2 < 1 ~ "low", exp_2 > 2 ~ "high", TRUE ~ "intermediate"),
    # reorder the high med low categories
    level_1 = fct_relevel(level_1, "high", "intermediate", "low"),
    level_2 = fct_relevel(level_2, "high", "intermediate", "low")
  )

# plot it
ggplot(df, aes(x = exp_1, y = exp_2)) +
  geom_point() +
  facet_grid(level_1~level_2) +
  labs(
    x = "Experiment 1",
    y = "Experiment 2"
  )
```

There is a new function in the works that will allow you to create the labels and pivot both the values and the labels together but it's not out yet
https://www.r-bloggers.com/pivoting-data-frames-just-got-easier-thanks-to-pivot_wide-and-pivot_long/

Title: ggplot facetting using group_by

Body:
Say I have measured some values in two experiments, a toy example in R being:

set.seed(9)
df <- data.frame(
    exp=c(rep(1,10), rep(2,10)),
    value=runif(20,0,3))

I then assign the categorial variable level based on value:

require("dplyr")
df <- df %>% mutate(level = ifelse(value<1, "low", ifelse(value>2, "high", "intermediate")))

I can display a geom_point() geom (ggplot2 package) of valuefor the two exp groups:

require("ggplot2")
ggplot(df, aes(x=factor(exp), y=value))+geom_point()

My problem is:
How can I break down the display with facet_wrap() by level so that I get a 3x3 graph of geom_point()'s with the nine combinations of levelfor the two exp (e.g. "high", "intermediate" and "low" vertically for experimment 1 and horizontally for experiment 2. In other words, the upper left graph are those valuewhich are "high" in experiment 1 and 2; first row second column graph are those that are "high" in experiment 1 and "intermediate" in experiment 2 etc). Can I somehow use group_by() in the ggplot2 call, or will I have to make level.exp1 and level.exp2variables to facet around  ?

UPDATE:
Seems I didnt explain it properly, so to clarify what I need: I would like to facet_wrap() instead of repeating this code 9 times with different filter() conditions (i.e. for all 9 combinations of levelin experiment 1 and 2):

df  %>% filter((exp==1 & level=="high") | (exp==2 & level=="high")) %>%
  ggplot(aes(x=factor(exp), y=value))+geom_point()

A handmade madeup and not related to dfabove and with fake legends may give an impression of what I want:

There must be a gentle solution - I could not figure out a a dcast() solution.

Body:
See if this works for you. I think the key is that there should be some id that observations share between experiment 1 and experiment 2.

set.seed(9)
df <-
  data.frame(
    id = rep(1:100, 2),
    # adding exp_ bc this will be the column name in the next step
    exp = paste0("exp_", rep(1:2, each = 100)),
    value = runif(200, 0, 3)
  ) %>%
  # this will pivot the data into a column for exp_1 and exp_2
  spread(exp, value) %>%
  mutate(
    level_1 = case_when(exp_1 < 1 ~ "low", exp_1 > 2 ~ "high", TRUE ~ "intermediate"),
    level_2 = case_when(exp_2 < 1 ~ "low", exp_2 > 2 ~ "high", TRUE ~ "intermediate"),
    # reorder the high med low categories
    level_1 = fct_relevel(level_1, "high", "intermediate", "low"),
    level_2 = fct_relevel(level_2, "high", "intermediate", "low")
  )

# plot it
ggplot(df, aes(x = exp_1, y = exp_2)) +
  geom_point() +
  facet_grid(level_1~level_2) +
  labs(
    x = "Experiment 1",
    y = "Experiment 2"
  )

There is a new function in the works that will allow you to create the labels and pivot both the values and the labels together but it's not out yet
https://www.r-bloggers.com/pivoting-data-frames-just-got-easier-thanks-to-pivot_wide-and-pivot_long/


问:
Why is my database field 'not updateable'?
I am developing a program which allows the user to take tests and receive a score, percentage and grade for this. These will be stored in a data table, named 'tblStudentScores'. The SQL code below aims to update the relevant record when a user completes a test, so that their latest score for that test is stored.

```<code>UPDATE tblStudentScores
SET Score = @Score, Percentage = @Perc, Grade = @Grade, CompletedTask = True
WHERE SpecificTaskID = @SpecID AND StudentID = @StudID;
</code>```

When testing this SQL in MS Access, it works perfectly. However, when I attempt to use the same query as an OleDBCommand in VB.NET, nothing happens. There is no error message, but the code does not update the table either.

I thought this may be due to parameters so I explicitly declared these at the top of the query:

```<code>PARAMETERS @SpecID Number, @StudID Number, @Score Number, @Perc Number, @Grade Text;
</code>```

Now, rather than nothing happening, I receive the following error message:

```<code>An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Cannot update 'Score'; field not updateable.
</code>```

As I have previously said, the query succeeded in MS Access's query designer, so the field must be updateable. What could be going wrong here?

EDIT: After further testing, I have found that the query does work in VB when using fixed inputs, rather than parameters. The problem is clearly therefore with the parameters, but what could the problem be?

EDIT: The entire piece of code in which I create and use the query is below:

```<code> Dim cmd As New OleDbCommand("PARAMETERS @Score Number, @Perc Number, @Grade Text, @SpecID Number, @StudID Number; UPDATE tblStudentScores " & _
                                    "SET Score = @Score, Percentage = @Perc, Grade = @Grade, CompletedTask = True " & _
                                    "WHERE SpecificTaskID = @SpecID AND StudentID = @StudID;", connection)

        With cmd.Parameters
            .AddWithValue("@Score", score)
            .AddWithValue("@Perc", percentage)
            .AddWithValue("@Grade", grade)
            .AddWithValue("@SpecID", specificIDorder(cbxCurrentTasks.SelectedIndex))
            .AddWithValue("@StudID", id)
        End With

        connection.Open()
        cmd.ExecuteReader()
        connection.Close()
</code>```

答:
Keep your data objects local so you can be sure they closed and disposed. The Using...End Using blocks do this for you even if there is an error.

Don't use .AddWithValue. See http://www.dbdelta.com/addwithvalue-is-evil/  and https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/#comment-8442  to see the reason why. You will have to check the database for the datatypes of the fields. I just guessed.

In Access the names of parameters do not matter. The order that they appear in the sql statement must match the order that they are added to the Parameters collection.

.ExecuteReader is used to retrieve records. You want to execute an Update statement so use .ExecuteNonQuery.

I am not sure what you are doing with specificIDorder(cbxCurrentTasks.SelectedIndex
Is specificIDorder a Function that returns some value based on the index that is selected in the combo box? If not you need to rethink the value for that parameter.

```<code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Using cn As New OleDbConnection("Your connection string")
        Using cmd As New OleDbCommand("Update tblStudentScores
                                Set Score = @Score,
                                Percentage = @Perc,
                                Grade = @Grade,
                                CompletedTask = True
                                WHERE
                                SpecificTaskID = @SpecID
                                And
                                StudentID = @StudID;", cn)
            With cmd.Parameters
                .Add("@Score", OleDbType.Integer).Value = score
                .Add("@Perc", OleDbType.Integer).Value = percentage
                .Add("@Grade", OleDbType.VarChar).Value = grade
                .Add("@SpecID", OleDbType.Integer).Value = CInt(specificIDorder(cbxCurrentTasks.SelectedIndex))
                .Add("@StudID", OleDbType.Integer).Value = id
            End With
            cn.Open()
            cmd.ExecuteNonQuery()
        End Using
    End Using
End Sub
</code>```

Body:
I am developing a program which allows the user to take tests and receive a score, percentage and grade for this. These will be stored in a data table, named 'tblStudentScores'. The SQL code below aims to update the relevant record when a user completes a test, so that their latest score for that test is stored.

UPDATE tblStudentScores
SET Score = @Score, Percentage = @Perc, Grade = @Grade, CompletedTask = True
WHERE SpecificTaskID = @SpecID AND StudentID = @StudID;

When testing this SQL in MS Access, it works perfectly. However, when I attempt to use the same query as an OleDBCommand in VB.NET, nothing happens. There is no error message, but the code does not update the table either.

I thought this may be due to parameters so I explicitly declared these at the top of the query:

PARAMETERS @SpecID Number, @StudID Number, @Score Number, @Perc Number, @Grade Text;

Now, rather than nothing happening, I receive the following error message:

An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Cannot update 'Score'; field not updateable.

As I have previously said, the query succeeded in MS Access's query designer, so the field must be updateable. What could be going wrong here?

EDIT: After further testing, I have found that the query does work in VB when using fixed inputs, rather than parameters. The problem is clearly therefore with the parameters, but what could the problem be?

EDIT: The entire piece of code in which I create and use the query is below:

 Dim cmd As New OleDbCommand("PARAMETERS @Score Number, @Perc Number, @Grade Text, @SpecID Number, @StudID Number; UPDATE tblStudentScores " & _
                                    "SET Score = @Score, Percentage = @Perc, Grade = @Grade, CompletedTask = True " & _
                                    "WHERE SpecificTaskID = @SpecID AND StudentID = @StudID;", connection)

        With cmd.Parameters
            .AddWithValue("@Score", score)
            .AddWithValue("@Perc", percentage)
            .AddWithValue("@Grade", grade)
            .AddWithValue("@SpecID", specificIDorder(cbxCurrentTasks.SelectedIndex))
            .AddWithValue("@StudID", id)
        End With

        connection.Open()
        cmd.ExecuteReader()
        connection.Close()

Body:
Keep your data objects local so you can be sure they closed and disposed. The Using...End Using blocks do this for you even if there is an error.

Don't use .AddWithValue. See http://www.dbdelta.com/addwithvalue-is-evil/  and https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/#comment-8442  to see the reason why. You will have to check the database for the datatypes of the fields. I just guessed.

In Access the names of parameters do not matter. The order that they appear in the sql statement must match the order that they are added to the Parameters collection.

.ExecuteReader is used to retrieve records. You want to execute an Update statement so use .ExecuteNonQuery.

I am not sure what you are doing with specificIDorder(cbxCurrentTasks.SelectedIndex
Is specificIDorder a Function that returns some value based on the index that is selected in the combo box? If not you need to rethink the value for that parameter.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Using cn As New OleDbConnection("Your connection string")
        Using cmd As New OleDbCommand("Update tblStudentScores
                                Set Score = @Score,
                                Percentage = @Perc,
                                Grade = @Grade,
                                CompletedTask = True
                                WHERE
                                SpecificTaskID = @SpecID
                                And
                                StudentID = @StudID;", cn)
            With cmd.Parameters
                .Add("@Score", OleDbType.Integer).Value = score
                .Add("@Perc", OleDbType.Integer).Value = percentage
                .Add("@Grade", OleDbType.VarChar).Value = grade
                .Add("@SpecID", OleDbType.Integer).Value = CInt(specificIDorder(cbxCurrentTasks.SelectedIndex))
                .Add("@StudID", OleDbType.Integer).Value = id
            End With
            cn.Open()
            cmd.ExecuteNonQuery()
        End Using
    End Using
End Sub


问:
How to Dock a bottom panel in NativeScript

The Problem

I have a page that is a slider, simply displays an image, and you slide left or right to get to the next/previous.

What I am trying to do, is at the bottom of the screen overlay a panel where I can enter some text describing the image.

Here is my XML:

```<code>
<Page xmlns="http://schemas.nativescript.org/tns.xsd" xmlns:ns="nativescript-carousel">

  <Page.actionBar>
    <ActionBar title="Customer On Boarding" icon="" class="action-bar">
    </ActionBar>
  </Page.actionBar>

  <StackLayout class="">
    <ns:Carousel height="100%" width="100%" pageChanged="myChangeEvent" pageTapped="mySelectedEvent" indicatorColor="#fff000" finite="true" bounce="false" showIndicator="true" verticalAlignment="top" android:indicatorAnimation="swap" color="white">
      <ns:CarouselItem class="slides slides-1" id="slide1" backgroundColor="#b3cde0" verticalAlignment="middle">
        <Label backgroundRepeat="no-repeat" text="Step 1" backgroundColor="#50000000" horizontalAlignment="center" />
        <!-- Dock Bottom -->
      </ns:CarouselItem>
      <ns:CarouselItem class="slides slides-2" id="slide2" backgroundColor="#6497b1" verticalAlignment="middle">
        <Label text="Slide 2" backgroundColor="#50000000" horizontalAlignment="center" />
      </ns:CarouselItem>
      <ns:CarouselItem class="slides slides-3" id="slide3" backgroundColor="#005b96" verticalAlignment="middle">
        <Label text="Slide 3" backgroundColor="#50000000" horizontalAlignment="center" />
      </ns:CarouselItem>
      <ns:CarouselItem class="slides slides-4" id="slide4" backgroundColor="#03396c" verticalAlignment="middle">
        <Label text="Slide 4" backgroundColor="#50000000" horizontalAlignment="center" />
      </ns:CarouselItem>
    </ns:Carousel>
  </StackLayout>

</Page>
</code>```

and here is a screenshot:

At the bottom I would like a 100% width, roughly 100px high, bordered 'panel' I can add some text.

Does anyone have any ideas? I tried Dock Failed miserably. Ugh.

Thank You for looking.

John

答:
You can use the GridLayout like the example below</p>

```<code><GridLayout columns="*" rows=auto, * " backgroundColor="lightgray ">
            <StackLayout class=" row=" 0">
  <ns:Carousel height="100%" width="100%" pageChanged="myChangeEvent" pageTapped="mySelectedEvent" indicatorColor="#fff000" finite="true" bounce="false" showIndicator="true" verticalAlignment="top" android:indicatorAnimation="swap" color="white">
    <ns:CarouselItem class="slides slides-1" id="slide1" backgroundColor="#b3cde0" verticalAlignment="middle">
      <Label backgroundRepeat="no-repeat" text="Step 1" backgroundColor="#50000000" horizontalAlignment="center" />
      <!-- Dock Bottom -->
    </ns:CarouselItem>
    <ns:CarouselItem class="slides slides-2" id="slide2" backgroundColor="#6497b1" verticalAlignment="middle">
      <Label text="Slide 2" backgroundColor="#50000000" horizontalAlignment="center" />
    </ns:CarouselItem>
    <ns:CarouselItem class="slides slides-3" id="slide3" backgroundColor="#005b96" verticalAlignment="middle">
      <Label text="Slide 3" backgroundColor="#50000000" horizontalAlignment="center" />
    </ns:CarouselItem>
    <ns:CarouselItem class="slides slides-4" id="slide4" backgroundColor="#03396c" verticalAlignment="middle">
      <Label text="Slide 4" backgroundColor="#50000000" horizontalAlignment="center" />
    </ns:CarouselItem>
  </ns:Carousel>
  </StackLayout>
  <StackLayout row="1">
    // add text panel here
  </StackLayout>
</GridLayout>
</code>```

Body:
The Problem

I have a page that is a slider, simply displays an image, and you slide left or right to get to the next/previous.

What I am trying to do, is at the bottom of the screen overlay a panel where I can enter some text describing the image.

Here is my XML:

<Page xmlns="http://schemas.nativescript.org/tns.xsd" xmlns:ns="nativescript-carousel">

  <Page.actionBar>
    <ActionBar title="Customer On Boarding" icon="" class="action-bar">
    </ActionBar>
  </Page.actionBar>

  <StackLayout class="">
    <ns:Carousel height="100%" width="100%" pageChanged="myChangeEvent" pageTapped="mySelectedEvent" indicatorColor="#fff000" finite="true" bounce="false" showIndicator="true" verticalAlignment="top" android:indicatorAnimation="swap" color="white">
      <ns:CarouselItem class="slides slides-1" id="slide1" backgroundColor="#b3cde0" verticalAlignment="middle">

      </ns:CarouselItem>
      <ns:CarouselItem class="slides slides-2" id="slide2" backgroundColor="#6497b1" verticalAlignment="middle">

      </ns:CarouselItem>
      <ns:CarouselItem class="slides slides-3" id="slide3" backgroundColor="#005b96" verticalAlignment="middle">

      </ns:CarouselItem>
      <ns:CarouselItem class="slides slides-4" id="slide4" backgroundColor="#03396c" verticalAlignment="middle">

      </ns:CarouselItem>
    </ns:Carousel>
  </StackLayout>

</Page>

and here is a screenshot:

At the bottom I would like a 100% width, roughly 100px high, bordered 'panel' I can add some text.

Does anyone have any ideas? I tried Dock Failed miserably. Ugh.

Thank You for looking.

John

Body:
You can use the GridLayout like the example below

<GridLayout columns="*" rows=auto, * " backgroundColor="lightgray ">
            <StackLayout class=" row=" 0">
  <ns:Carousel height="100%" width="100%" pageChanged="myChangeEvent" pageTapped="mySelectedEvent" indicatorColor="#fff000" finite="true" bounce="false" showIndicator="true" verticalAlignment="top" android:indicatorAnimation="swap" color="white">
    <ns:CarouselItem class="slides slides-1" id="slide1" backgroundColor="#b3cde0" verticalAlignment="middle">
      <Label backgroundRepeat="no-repeat" text="Step 1" backgroundColor="#50000000" horizontalAlignment="center" />
      <!-- Dock Bottom -->
    </ns:CarouselItem>
    <ns:CarouselItem class="slides slides-2" id="slide2" backgroundColor="#6497b1" verticalAlignment="middle">
      <Label text="Slide 2" backgroundColor="#50000000" horizontalAlignment="center" />
    </ns:CarouselItem>
    <ns:CarouselItem class="slides slides-3" id="slide3" backgroundColor="#005b96" verticalAlignment="middle">
      <Label text="Slide 3" backgroundColor="#50000000" horizontalAlignment="center" />
    </ns:CarouselItem>
    <ns:CarouselItem class="slides slides-4" id="slide4" backgroundColor="#03396c" verticalAlignment="middle">
      <Label text="Slide 4" backgroundColor="#50000000" horizontalAlignment="center" />
    </ns:CarouselItem>
  </ns:Carousel>
  </StackLayout>
  <StackLayout row="1">
    // add text panel here
  </StackLayout>
</GridLayout>


问:
PHP 5 second countdown (CLI, not JavaScript)
I am writing a PHP CLI (command line) script that will do some irreversible damage if it is run by accident. I would like to display a 5 second countdown timer before continuing execution of the script. How can I do this with PHP?</p>

答:
You should be able to use sleep

http://php.net/manual/en/function.sleep.php

Something like this should do the trick:

```<code>for($i = 5; $i > 0; $i--) {
    echo "$i\n";
    sleep(1);
}
echo "Doing dangerous stuff now...\n";
</code>```

Body:
You should be able to use sleep

http://php.net/manual/en/function.sleep.php

Something like this should do the trick:

for($i = 5; $i > 0; $i--) {
    echo "$i\n";
    sleep(1);
}
echo "Doing dangerous stuff now...\n";


问:
Calculating the green colour percentage in an image
I want to calculate the green colour percentage in an image

I have calculated by iterating through each pixel in an image and check the color of each pixel. Finally, I keep the count of the number of green pixels and find the total percentage in whole image.

def green_color_optimized(screenpath):
    start_time = time.time()
    img = image.load_img(screenpath,target_size=(300,300,3))
    x = image.img_to_array(img)
    print("Image size: ", x.shape)
    count_green = 0
    for i in range(0,x.shape[0]):
      for j in range(0,x.shape[1]):
        pixel = list(map(int, x[i,j].tolist()))
        if sum(pixel) != 0:
          green_pixel = 100*(pixel[1]/sum(pixel))
          blue_pixel = 100*(pixel[2]/sum(pixel))
          red_pixel = 100*(pixel[0]/sum(pixel))
          if green_pixel > red_pixel and green_pixel > blue_pixel:
            if green_pixel > 35:
              count_green += 1
    green_percent = round(100*(count_green/(x.shape[0]*x.shape[1])),2)
```

With this code, each image takes around 200ms to process; and I want to process 1 million images. How can I optimise the code?

答:
Presuming that x is a numpy array, you should always vectorize your matrix operations. The following runs ~200 times faster:

```<code># Your original function, with the file i/o removed for timing comparison
def green_original(x):
    count_green = 0
    for i in range(0,x.shape[0]):
      for j in range(0,x.shape[1]):
        pixel = list(map(int, x[i,j].tolist()))
        if sum(pixel) != 0:
          green_pixel = 100*(pixel[1]/sum(pixel))
          blue_pixel = 100*(pixel[2]/sum(pixel))
          red_pixel = 100*(pixel[0]/sum(pixel))
          if green_pixel > red_pixel and green_pixel > blue_pixel:
            if green_pixel > 35:
              count_green += 1
    green_percent = round(100*(count_green/(x.shape[0]*x.shape[1])),2)
    return green_percent

def green_vectorized(x):
    mask = (img[:,:,1] > img[:,:,0]) & (img[:,:,1] > img[:,:,2]) & ((img[:,:,1]/np.sum(img, axis=2)) > .35)
    round(100 * np.sum(mask)/(x.shape[0]*x.shape[1]), 2)

img = np.ones(shape=(300,300,3))
img[0:150,0:150, 1] = 134
%timeit green_original(img)
%timeit green_vectorized(img)
</code>```

Your Version

81.7 ms ± 6.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Vectorized Version

461 µs ± 78.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Body:
I want to calculate the green colour percentage in an image

I have calculated by iterating through each pixel in an image and check the color of each pixel. Finally, I keep the count of the number of green pixels and find the total percentage in whole image.

def green_color_optimized(screenpath):
    start_time = time.time()
    img = image.load_img(screenpath,target_size=(300,300,3))
    x = image.img_to_array(img)
    print("Image size: ", x.shape)
    count_green = 0
    for i in range(0,x.shape[0]):
      for j in range(0,x.shape[1]):
        pixel = list(map(int, x[i,j].tolist()))
        if sum(pixel) != 0:
          green_pixel = 100*(pixel[1]/sum(pixel))
          blue_pixel = 100*(pixel[2]/sum(pixel))
          red_pixel = 100*(pixel[0]/sum(pixel))
          if green_pixel > red_pixel and green_pixel > blue_pixel:
            if green_pixel > 35:
              count_green += 1
    green_percent = round(100*(count_green/(x.shape[0]*x.shape[1])),2)

With this code, each image takes around 200ms to process; and I want to process 1 million images. How can I optimise the code?

Body:
Presuming that x is a numpy array, you should always vectorize your matrix operations. The following runs ~200 times faster:

# Your original function, with the file i/o removed for timing comparison
def green_original(x):
    count_green = 0
    for i in range(0,x.shape[0]):
      for j in range(0,x.shape[1]):
        pixel = list(map(int, x[i,j].tolist()))
        if sum(pixel) != 0:
          green_pixel = 100*(pixel[1]/sum(pixel))
          blue_pixel = 100*(pixel[2]/sum(pixel))
          red_pixel = 100*(pixel[0]/sum(pixel))
          if green_pixel > red_pixel and green_pixel > blue_pixel:
            if green_pixel > 35:
              count_green += 1
    green_percent = round(100*(count_green/(x.shape[0]*x.shape[1])),2)
    return green_percent

def green_vectorized(x):
    mask = (img[:,:,1] > img[:,:,0]) & (img[:,:,1] > img[:,:,2]) & ((img[:,:,1]/np.sum(img, axis=2)) > .35)
    round(100 * np.sum(mask)/(x.shape[0]*x.shape[1]), 2)

img = np.ones(shape=(300,300,3))
img[0:150,0:150, 1] = 134
%timeit green_original(img)
%timeit green_vectorized(img)

Your Version

81.7 ms ± 6.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Vectorized Version

461 µs ± 78.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)


问:
SignalR Core, not getting response from server when client is connected
I am working on a SignalR Clinet-Server connection. My server is WebApi Core 2.1 and my client is WPF .NET Framework 4.7.2.

On the client side I have a singleton hub service with one Instance to recive messages from server:

```<code>using System.Collections.ObjectModel;
using Microsoft.AspNetCore.SignalR.Client;

public class HubService
{
    //singleton
    public static HubService Instance { get; } = new HubService();

    public ObservableCollection<string> Notifications { get; set; }

    public async void Initialize()
    {
        this.Notifications = new ObservableCollection<string>();

        var hubConnection = new HubConnectionBuilder()
            .WithUrl(UrlBuilder.BuildEndpoint("Notifications"))
            .Build();

        hubConnection.On<string>("ReciveServerUpdate", update =>
        {
            //todo
        });

        await hubConnection.StartAsync();
    }
}
</code>```

i initialize it as singleton:

```<code>    public MainWindowViewModel()
    {
        HubService.Instance.Initialize();
    }
</code>```

While I'm debugging, on MainWindowViewModel im hitting that HubService.

On Server side its look like this.

Hub:

```<code>using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;

public class NotificationsHub : Hub
{
    public async Task GetUpdateForServer(string call)
    {
        await this.Clients.Caller.SendAsync("ReciveServerUpdate", call);
    }
}
</code>```

Im trigering send message in this way in my controller's methods:

```<code>    [HttpPost]
    public async Task<IActionResult> PostTask([FromBody] Task task)
    {
        if (!this.ModelState.IsValid)
        {
            return this.BadRequest(this.ModelState);
        }

        this.taskService.Add(task);

        //here im calling sending message. When im debugging
        //i see one connection from my WPF with unique ConnectionId
        await this.notificationsHub.Clients.All.SendAsync("ReciveServerUpdate", "New Task in database!");

        return this.Ok(task);
    }
</code>```

As I wrote before, while I'm debugging my WebApi, in Clients I have exactly one connection from my WPF. When I turn off WPF, connection count = 0 so connections works perfectly.

But when I call SendAsync(), I'm not reciving any information in WPF in hubConnection.On. Funny thing, yesterday it works perfectly.

So, is my thinking about making HubService as static singleton is right? If its, why i cant recive messages from WebApi by SignalR when my WPF is connected to it?

I asked something similiar yesterday but i found a solution for it. Yesterday, my methods works, i could hit hubConnection.On when i get any message from WebApi. My question from yestarday.

EDIT

Injection of HUb to controller:

```<code>    private readonly ITaskService taskService;

    private readonly IHubContext<NotificationsHub> notificationsHub;

    public TaskController(ITaskService taskService, IHubContext<NotificationsHub> notificationsHub)
    {
        this.taskService = taskService;
        this.notificationsHub = notificationsHub;
    }
</code>```

And Startup.cs only SignalR things (i deleted other things not related to signal):

```<code>    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHttpContextAccessor();
        services.AddSignalR();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseSignalR(routes => routes.MapHub<NotificationsHub>("/Notifications"));
    }
</code>```

EDIT2

Here is connection that i can get it, when my client WPF will register his connection:

答:
I tried your code with all kinds of clients (wpf/console/even with a browser), it always works fine for me. The hubConnection.On<string>("ReciveServerUpdate", update => {//todo}); always be invoked when I send a request to PostTask.

I'm not sure why (sometimes) it doesn't work for you somehow . However, when SignalR client has connected to server but gets no message from server, there're possible two reasons:

Your PostTask([FromBody] Task task) action method is not executed. Let's say this is an ApiController method, if the browser posts a request with a Content-Type of application/www-x-form-urlencoded by accident, the invocation of Clients.All.SendAsync(..., ...); won't be executed at all.

The handler of SigalR client (hubConnection.On<>(method,handler)) must has exactly the same argument list as the invocation in order to receive messages. We must be very careful when dealing with this.

Finally, it's better to add a reference to Microsoft.Extensions.Logging.Console

```<code><PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.2.*" />
</code>```

so that we could enable logging to troubleshoot :

```<code>var hubConnection = new HubConnectionBuilder()
    .WithUrl(UrlBuilder.BuildEndpoint("Notifications"))
    .ConfigureLogging(logging =>{
        logging.AddConsole();        // enable logging
    })
    .Build();
</code>```

Body:
I am working on a SignalR Clinet-Server connection. My server is WebApi Core 2.1 and my client is WPF .NET Framework 4.7.2.

On the client side I have a singleton hub service with one Instance to recive messages from server:

using System.Collections.ObjectModel;
using Microsoft.AspNetCore.SignalR.Client;

public class HubService
{
    //singleton
    public static HubService Instance { get; } = new HubService();

    public ObservableCollection<string> Notifications { get; set; }

    public async void Initialize()
    {
        this.Notifications = new ObservableCollection<string>();

        var hubConnection = new HubConnectionBuilder()
            .WithUrl(UrlBuilder.BuildEndpoint("Notifications"))
            .Build();

        hubConnection.On<string>("ReciveServerUpdate", update =>
        {
            //todo
        });

        await hubConnection.StartAsync();
    }
}

i initialize it as singleton:

    public MainWindowViewModel()
    {
        HubService.Instance.Initialize();
    }

While I'm debugging, on MainWindowViewModel im hitting that HubService.

On Server side its look like this.

Hub:

using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;

public class NotificationsHub : Hub
{
    public async Task GetUpdateForServer(string call)
    {
        await this.Clients.Caller.SendAsync("ReciveServerUpdate", call);
    }
}

Im trigering send message in this way in my controller's methods:

    [HttpPost]
    public async Task<IActionResult> PostTask([FromBody] Task task)
    {
        if (!this.ModelState.IsValid)
        {
            return this.BadRequest(this.ModelState);
        }

        this.taskService.Add(task);

        //here im calling sending message. When im debugging
        //i see one connection from my WPF with unique ConnectionId
        await this.notificationsHub.Clients.All.SendAsync("ReciveServerUpdate", "New Task in database!");

        return this.Ok(task);
    }

As I wrote before, while I'm debugging my WebApi, in Clients I have exactly one connection from my WPF. When I turn off WPF, connection count = 0 so connections works perfectly.

But when I call SendAsync(), I'm not reciving any information in WPF in hubConnection.On. Funny thing, yesterday it works perfectly.

So, is my thinking about making HubService as static singleton is right? If its, why i cant recive messages from WebApi by SignalR when my WPF is connected to it?

I asked something similiar yesterday but i found a solution for it. Yesterday, my methods works, i could hit hubConnection.On when i get any message from WebApi. My question from yestarday.

EDIT

Injection of HUb to controller:

    private readonly ITaskService taskService;

    private readonly IHubContext<NotificationsHub> notificationsHub;

    public TaskController(ITaskService taskService, IHubContext<NotificationsHub> notificationsHub)
    {
        this.taskService = taskService;
        this.notificationsHub = notificationsHub;
    }

And Startup.cs only SignalR things (i deleted other things not related to signal):

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHttpContextAccessor();
        services.AddSignalR();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseSignalR(routes => routes.MapHub<NotificationsHub>("/Notifications"));
    }

EDIT2

Here is connection that i can get it, when my client WPF will register his connection:

Body:
I tried your code with all kinds of clients (wpf/console/even with a browser), it always works fine for me. The hubConnection.On<string>("ReciveServerUpdate", update => {//todo}); always be invoked when I send a request to PostTask.

I'm not sure why (sometimes) it doesn't work for you somehow . However, when SignalR client has connected to server but gets no message from server, there're possible two reasons:

Your PostTask([FromBody] Task task) action method is not executed. Let's say this is an ApiController method, if the browser posts a request with a Content-Type of application/www-x-form-urlencoded by accident, the invocation of Clients.All.SendAsync(..., ...); won't be executed at all.

The handler of SigalR client (hubConnection.On<>(method,handler)) must has exactly the same argument list as the invocation in order to receive messages. We must be very careful when dealing with this.

Finally, it's better to add a reference to Microsoft.Extensions.Logging.Console

<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.2.*" />

so that we could enable logging to troubleshoot :

var hubConnection = new HubConnectionBuilder()
    .WithUrl(UrlBuilder.BuildEndpoint("Notifications"))
    .ConfigureLogging(logging =>{
        logging.AddConsole();        // enable logging
    })
    .Build();


问:
virtual function with user-defined-type vector
I want to define an abstract base class with a vector of struct variables, and a virtual function to be implemented by derived classes:

```<code>class TestFather {

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    virtual vector<myStruct> get_myStructVect() = 0;
};
</code>```

but when I write the derived class:

```<code>#include "TestFather.h"

class TestSon : public TestFather{

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    vector<myStruct> get_myStructVect();
};
</code>```

I get this error:

```<code>invalid covariant return type for ‘virtual std::vector<ProvaSon::myStruct, std::allocator<ProvaSon::myStruct> > ProvaSon::get_myStructVect()’
</code>```

Am I doing something wrong or maybe I'm trying to do something that is forbidden by the language?

答:
It says vector<myStruct> but since you changed myStruct in the child class it's actually two distinct types so each of the two functions thinks its returning a different type. This is only allowed for covariant types where the type is related to the actual type of the class containing the function.

Note that you probably shouldn't be returning a class attribute vector by value here anyway.

I can't tell what you really are intending to do, but the nested structures really shouldn't have the same name if they're two different things (and if they're the same, don't redefine it). My first gut reaction is that maybe the parent-child relationship isn't appropriate here. Have you considered other options? If you really need to return a different type in the child and the parent doesn't know about that, then you can't use a virtual interface to do this. You should just give the functions different names so you know what the return type should be.

With more details about your goals a better answer could be provided.

Body:
I want to define an abstract base class with a vector of struct variables, and a virtual function to be implemented by derived classes:

class TestFather {

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    virtual vector<myStruct> get_myStructVect() = 0;
};

but when I write the derived class:

#include "TestFather.h"

class TestSon : public TestFather{

private:
    struct myStruct
    {
        // struct definition
    };
    vector<myStruct> myStructVect;

public:
    vector<myStruct> get_myStructVect();
};

I get this error:

invalid covariant return type for ‘virtual std::vector<ProvaSon::myStruct, std::allocator<ProvaSon::myStruct> > ProvaSon::get_myStructVect()’

Am I doing something wrong or maybe I'm trying to do something that is forbidden by the language?


问:
AssertJ: make assertion that all Assert objects were asserted upon
When using the AssertJ library, I'm interested in being able to assert that all org.assertj.core.api.Assert objects had an actual assertion made on them. That is, a test such as the following should fail because it is clearly a mistake:

```<code>import static org.assertj.core.api.Assertions.assertThat;

// ... elided ...

@Test
public void unfinishedAssertion() {
    assertThat("str");
}
</code>```

Is there a way to configure this with AssertJ, or to make this assertion in a JUnit @After method?

My only thought is to provide a static factory like assertThat that returns a proxy, delegating all method invocations to the underlying Assert, and using an After method to assert that the proxy had at least one invocation with a method that was not Assert#as or Assert#withFailMessage, etc., but this seems cumbersome and unnecessary as the library should provide this functionality itself.

答:
At the moment, the best way is to use findbugs/spotbugs to warn you about this kind of misuse, see https://assertj.github.io/doc/#assertj-core-incorrect-usage for details.

Hope it helps.

Body:
When using the AssertJ library, I'm interested in being able to assert that all org.assertj.core.api.Assert objects had an actual assertion made on them. That is, a test such as the following should fail because it is clearly a mistake:

import static org.assertj.core.api.Assertions.assertThat;

// ... elided ...

@Test
public void unfinishedAssertion() {
    assertThat("str");
}

Is there a way to configure this with AssertJ, or to make this assertion in a JUnit @After method?

My only thought is to provide a static factory like assertThat that returns a proxy, delegating all method invocations to the underlying Assert, and using an After method to assert that the proxy had at least one invocation with a method that was not Assert#as or Assert#withFailMessage, etc., but this seems cumbersome and unnecessary as the library should provide this functionality itself.


问:
Confusion over JavaScript implementations of MessagePack
The official MessagePack page links to the page:

https://github.com/msgpack/msgpack-javascript

but its last update is three years ago. On the other hand, there are other implementations of MessagePack in JavaScript such as:

https://github.com/cuzic/MessagePack-JS

https://github.com/creationix/msgpack-js

What are the differences among them? Which one is the most authentic one? Which one should I use?

答:
I have restarted to maintain https://github.com/msgpack/msgpack-javascript
 , released as @msgpack/msgpack, with completely new codebase in TypeScript, optimized for browsers or pure ECMA-262 JavaScript engines, employing new ES features like whatwg-stream, AsyncIterator, and so on.

I wish it clear the confusions.


问:
How to notify View from ViewModel without breaking MVVM?
I recently started trying out MVVM pattern in school and was wondering what the best way (if any) is to notify View from the ViewModel, letting the view know to run a method without breaking MVVM? Basically letting the view know if something was successful, like a login attempt or trying to connect to a database?

An example could be a login page, where the mainwindow should change content to a new page only if the login was successful, if not, a messagebox should show up

Edit:

I'm using .NET

What I have tried so far:

View:

<Page
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:local="clr-namespace:View.Pages" xmlns:ViewModels="clr-namespace:ViewModel.ViewModels;assembly=ViewModel" x:Class="View.Pages.Start_Page"
      mc:Ignorable="d"
      d:DesignHeight="720" d:DesignWidth="1280"
      Title="Start_Page">

    <Page.DataContext>
        <ViewModels:Start_Page_ViewModel/>
    </Page.DataContext>
```

<p>Code behind it:</p>

<pre class="lang-cs prettyprint-override"><code>public Start_Page()
        {
            InitializeComponent();

            Start_Page_ViewModel currentDataContext = DataContext as Start_Page_ViewModel;

            currentDataContext.CurrentUserIDGotten += GoToMenu;
        }

        private void GoToMenu(int result)
        {
            if (result == -1)
            {
                MessageBox.Show("User credentials incorrect");
            }
            else if (result == -2)
            {
                MessageBox.Show("Connection failed");
            }
            else
            {
                Application.Current.MainWindow.Content = new Menu_Page();
            }
        }
</code>```

ViewModel:

public class Start_Page_ViewModel
    {

        private string userName;
        private string userPassword;

        public string UserName { get => userName; set => userName = value; }

        public string UserPassword { get => userPassword; set => userPassword = value; }

        private RelayCommand logIn;

        public RelayCommand LogIn => logIn;

        public delegate void CurrentUserIDGottenEventHandler(int result);
        public event CurrentUserIDGottenEventHandler CurrentUserIDGotten;

        public Start_Page_ViewModel()
        {
            logIn = new RelayCommand(LogInToProgram, CanLogIn);
        }

        public void LogInToProgram(object o)
        {
            PasswordBox passwordBox = o as PasswordBox;

            ViewModelController.Instance.CurrentUserID = Database_Controller.Instance.SignIn(userName, passwordBox.Password);

            OnUserIDGotten(ViewModelController.Instance.CurrentUserID);
        }

        public bool CanLogIn(object o)
        {
            if (userName != null)
            {
                return true;
            }
            return false;
        }

        protected virtual void OnUserIDGotten(int result)
        {
            if (CurrentUserIDGotten != null)
            {
                CurrentUserIDGotten(result);
            }
        }
    }
```

答:
In pure way, without specified framework.

Create a event delegate (or listener interface), associate with view model

Register the event handler on view

Fire the event when view model is changed

Likes this

```<code>using System;

public class MainClass {
  public static void Main (string[] args) {
    ViewModel m = new ViewModel();
    View v = new View();
    v.Model = m;
    m.MakeSomeChange();
  }
}

public class View {
  private IViewModel _model;
  public IViewModel Model {
    get {
      return _model;
    }
    set {
      if(_model != null) {
        _model.OnChanged -= OnChanged;
      }
      if(value != null) {
        value.OnChanged += OnChanged;
      }
      _model = value;
    }
  }
  private void OnChanged(){
    //update view
    Console.WriteLine ("View Updated");
  }
}

public delegate void ViewChangeDelegate();

public interface IViewModel {
  event ViewChangeDelegate OnChanged;
}

public class ViewModel: IViewModel {
  public event ViewChangeDelegate OnChanged;

  public void MakeSomeChange() {
    //make some change in the view Model
    OnChanged.Invoke();
  }
}
</code>```

Body:
I recently started trying out MVVM pattern in school and was wondering what the best way (if any) is to notify View from the ViewModel, letting the view know to run a method without breaking MVVM? Basically letting the view know if something was successful, like a login attempt or trying to connect to a database?

An example could be a login page, where the mainwindow should change content to a new page only if the login was successful, if not, a messagebox should show up

Edit:

I'm using .NET

What I have tried so far:

View:

<Page
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:local="clr-namespace:View.Pages" xmlns:ViewModels="clr-namespace:ViewModel.ViewModels;assembly=ViewModel" x:Class="View.Pages.Start_Page"
      mc:Ignorable="d"
      d:DesignHeight="720" d:DesignWidth="1280"
      Title="Start_Page">

    <Page.DataContext>
        <ViewModels:Start_Page_ViewModel/>
    </Page.DataContext>

Code behind it:

public Start_Page()
        {
            InitializeComponent();

            Start_Page_ViewModel currentDataContext = DataContext as Start_Page_ViewModel;

            currentDataContext.CurrentUserIDGotten += GoToMenu;
        }

        private void GoToMenu(int result)
        {
            if (result == -1)
            {
                MessageBox.Show("User credentials incorrect");
            }
            else if (result == -2)
            {
                MessageBox.Show("Connection failed");
            }
            else
            {
                Application.Current.MainWindow.Content = new Menu_Page();
            }
        }

ViewModel:

public class Start_Page_ViewModel
    {

        private string userName;
        private string userPassword;

        public string UserName { get => userName; set => userName = value; }

        public string UserPassword { get => userPassword; set => userPassword = value; }

        private RelayCommand logIn;

        public RelayCommand LogIn => logIn;

        public delegate void CurrentUserIDGottenEventHandler(int result);
        public event CurrentUserIDGottenEventHandler CurrentUserIDGotten;

        public Start_Page_ViewModel()
        {
            logIn = new RelayCommand(LogInToProgram, CanLogIn);
        }

        public void LogInToProgram(object o)
        {
            PasswordBox passwordBox = o as PasswordBox;

            ViewModelController.Instance.CurrentUserID = Database_Controller.Instance.SignIn(userName, passwordBox.Password);

            OnUserIDGotten(ViewModelController.Instance.CurrentUserID);
        }

        public bool CanLogIn(object o)
        {
            if (userName != null)
            {
                return true;
            }
            return false;
        }

        protected virtual void OnUserIDGotten(int result)
        {
            if (CurrentUserIDGotten != null)
            {
                CurrentUserIDGotten(result);
            }
        }
    }

Body:
In pure way, without specified framework.

Create a event delegate (or listener interface), associate with view model

Register the event handler on view

Fire the event when view model is changed

Likes this

using System;

public class MainClass {
  public static void Main (string[] args) {
    ViewModel m = new ViewModel();
    View v = new View();
    v.Model = m;
    m.MakeSomeChange();
  }
}

public class View {
  private IViewModel _model;
  public IViewModel Model {
    get {
      return _model;
    }
    set {
      if(_model != null) {
        _model.OnChanged -= OnChanged;
      }
      if(value != null) {
        value.OnChanged += OnChanged;
      }
      _model = value;
    }
  }
  private void OnChanged(){
    //update view
    Console.WriteLine ("View Updated");
  }
}

public delegate void ViewChangeDelegate();

public interface IViewModel {
  event ViewChangeDelegate OnChanged;
}

public class ViewModel: IViewModel {
  public event ViewChangeDelegate OnChanged;

  public void MakeSomeChange() {
    //make some change in the view Model
    OnChanged.Invoke();
  }
}


问:
Use Python pymssql from Ubuntu bash
I have installed Ubuntu bash on my Windows 10

I can access python3 from there, and everything seems ok

the problem i am facing at the moment is connect to MS SQL Server through Python pymssql.

I can connect from my Spyder perfectly but when I use the same script in Ubuntu bash I get this error

```<code>>>> conn = pymssql.connect(server="MyServer", database="MyDB")
Traceback (most recent call last):
  File "src/pymssql.pyx", line 636, in pymssql.connect
  File "src/_mssql.pyx", line 1957, in _mssql.connect
  File "src/_mssql.pyx", line 676, in _mssql.MSSQLConnection.__init__
  File "src/_mssql.pyx", line 1683, in _mssql.maybe_raise_MSSQLDatabaseException
_mssql.MSSQLDatabaseException: (20002, b'DB-Lib error message 20002, severity 9:\nAdaptive Server connection failed (MyServer:1433)\n')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "src/pymssql.pyx", line 642, in pymssql.connect
pymssql.OperationalError: (20002, b'DB-Lib error message 20002, severity 9:\nAdaptive Server connection failed (MyServer:1433)\n')
</code>```

Anyone has an idea how to fix that?

答:
It look like problem with libraries for Unix ( this happend to me in Debian ) .I'm not sure you can try some similar this :

install openssl

sudo apt-get update

sudo apt-get install openssl

sudo apt-get install libssl-dev

install FreeTDS with ssl

wget ftp://ftp.freetds.org/pub/freetds/stable/freetds-1.00.9.tar.gz

gunzip freetds-1.00.9.tar.gz

tar -xvf freetds-1.00.9.tar

cd freetds-1.00.9.tar

sudo ./configure --with-openssl='/usr/lib/ssl'

sudo make

sudo make install

Install pymssql from source with a flag to not use bundled FreeTDS

export PYMSSQL_DONT_BUILD_WITH_BUNDLED_FREETDS=1

sudo -H pip install git+https://github.com/pymssql/pymssql.git

Install pymssql

export PYMSSQL_DONT_BUILD_WITH_BUNDLED_FREETDS=1

sudo -H pip install git+https://github.com/pymssql/pymssql.git

Good luck

Title: Use Python pymssql from Ubuntu bash

Body:
I have installed Ubuntu bash on my Windows 10

I can access python3 from there, and everything seems ok

the problem i am facing at the moment is connect to MS SQL Server through Python pymssql.

I can connect from my Spyder perfectly but when I use the same script in Ubuntu bash I get this error

>>> conn = pymssql.connect(server="MyServer", database="MyDB")
Traceback (most recent call last):
  File "src/pymssql.pyx", line 636, in pymssql.connect
  File "src/_mssql.pyx", line 1957, in _mssql.connect
  File "src/_mssql.pyx", line 676, in _mssql.MSSQLConnection.__init__
  File "src/_mssql.pyx", line 1683, in _mssql.maybe_raise_MSSQLDatabaseException
_mssql.MSSQLDatabaseException: (20002, b'DB-Lib error message 20002, severity 9:\nAdaptive Server connection failed (MyServer:1433)\n')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "src/pymssql.pyx", line 642, in pymssql.connect
pymssql.OperationalError: (20002, b'DB-Lib error message 20002, severity 9:\nAdaptive Server connection failed (MyServer:1433)\n')

Anyone has an idea how to fix that?


问:
Can't Build Container Optimized OS | sed: -e expression #2, char 60: unknown option to `s'
When following their documentation and running ./build_packages --board=lakitu, I get the following error.

Using ubuntu 16.0.4. Looks like a sed syntax error? Am I missing a variable? Does sed work differently in different operating systems or is something wrong with their documentation/scripts? Followed their documentation to the t and didn't add or configure anything. Waiting for a successful run first.

Looking at similar questions, they all appear to be syntax errors...

```<code> * Package:    sys-boot/shim-14.0.20180308-r4
 * Repository: lakitu
 * USE:        abi_x86_64 amd64 elibc_glibc kernel_linux userland_GNU
 * FEATURES:   network-sandbox sandbox splitdebug userpriv usersandbox
 * Running stacked hooks for pre_pkg_setup
 *    sysroot_build_bin_dir ...                                          [ ok ]
 * Running stacked hooks for post_pkg_setup
 *    python_eclass_hack ...                                             [ ok ]
 * Running stacked hooks for pre_src_unpack
 *    python_multilib_setup ...                                          [ ok ]
>>> Unpacking source...
>>> Unpacking shim-14.0.20180308.tar.gz to /build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/work
>>> Source unpacked in /build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/work
 * Running stacked hooks for post_src_unpack
 *    asan_init ...                                                      [ ok ]
>>> Preparing source in /build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/work/shim-79cdb2a215de2ace7d1bf0a294165a04b726c70a ...
>>> Source prepared.
>>> Configuring source in /build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/work/shim-79cdb2a215de2ace7d1bf0a294165a04b726c70a ...
>>> Source configured.
>>> Compiling source in /build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/work/shim-79cdb2a215de2ace7d1bf0a294165a04b726c70a ...
make -j8 ARCH=x86_64 CROSS_COMPILE=x86_64-cros-linux-gnu- EFI_INCLUDE=/build/lakitu//usr/include/efi EFI_PATH=/build/lakitu//usr/lib64 ARCH_LDFLAGS=--no-experimental-use-relr COMMITID=79cdb2a215de2ace7d1bf0a294165a04b726c70a DEFAULT_LOADER=\\\\grub-lakitu.efi shimx64.efi
sed     -e "s,@@VERSION@@,14," \
        -e "s,@@UNAME@@,Linux x86_64 Intel Xeon E312xx (Sandy Bridge, IBRS update) GenuineIntel GNU/Linux," \
        -e "s,@@COMMIT@@,79cdb2a215de2ace7d1bf0a294165a04b726c70a," \
        < /build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/work/shim-79cdb2a215de2ace7d1bf0a294165a04b726c70a/version.c.in > version.c
sed: -e expression #2, char 60: unknown option to `s'
make: *** [Makefile:183: version.c] Error 1
 * ERROR: sys-boot/shim-14.0.20180308-r4::lakitu failed (compile phase):
 *   emake failed
 *
 * If you need support, post the output of `emerge --info '=sys-boot/shim-14.0.20180308-r4::lakitu'`,
 * the complete build log and the output of `emerge -pqv '=sys-boot/shim-14.0.20180308-r4::lakitu'`.
 * The complete build log is located at '/build/lakitu/tmp/portage/logs/sys-boot:shim-14.0.20180308-r4:20190531-002217.log'.
 * For convenience, a symlink to the build log is located at '/build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/temp/build.log'.
 * The ebuild environment file is located at '/build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/temp/environment'.
 * Working directory: '/build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/work/shim-79cdb2a215de2ace7d1bf0a294165a04b726c70a'
 * S: '/build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/work/shim-79cdb2a215de2ace7d1bf0a294165a04b726c70a'
</code>```

答:
There's a , after Bridge

```<code>    -e "s,@@UNAME@@,Linux x86_64 Intel Xeon E312xx (Sandy Bridge, IBRS update) GenuineIntel GNU/Linux," \
</code>```

Change to

```<code>    -e "s#@@UNAME@@#Linux x86_64 Intel Xeon E312xx (Sandy Bridge, IBRS update) GenuineIntel GNU/Linux#" \
</code>```

Body:
When following their documentation and running ./build_packages --board=lakitu, I get the following error.

Using ubuntu 16.0.4. Looks like a sed syntax error? Am I missing a variable? Does sed work differently in different operating systems or is something wrong with their documentation/scripts? Followed their documentation to the t and didn't add or configure anything. Waiting for a successful run first.

Looking at similar questions, they all appear to be syntax errors...

 * Package:    sys-boot/shim-14.0.20180308-r4
 * Repository: lakitu
 * USE:        abi_x86_64 amd64 elibc_glibc kernel_linux userland_GNU
 * FEATURES:   network-sandbox sandbox splitdebug userpriv usersandbox
 * Running stacked hooks for pre_pkg_setup
 *    sysroot_build_bin_dir ...                                          [ ok ]
 * Running stacked hooks for post_pkg_setup
 *    python_eclass_hack ...                                             [ ok ]
 * Running stacked hooks for pre_src_unpack
 *    python_multilib_setup ...                                          [ ok ]
>>> Unpacking source...
>>> Unpacking shim-14.0.20180308.tar.gz to /build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/work
>>> Source unpacked in /build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/work
 * Running stacked hooks for post_src_unpack
 *    asan_init ...                                                      [ ok ]
>>> Preparing source in /build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/work/shim-79cdb2a215de2ace7d1bf0a294165a04b726c70a ...
>>> Source prepared.
>>> Configuring source in /build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/work/shim-79cdb2a215de2ace7d1bf0a294165a04b726c70a ...
>>> Source configured.
>>> Compiling source in /build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/work/shim-79cdb2a215de2ace7d1bf0a294165a04b726c70a ...
make -j8 ARCH=x86_64 CROSS_COMPILE=x86_64-cros-linux-gnu- EFI_INCLUDE=/build/lakitu//usr/include/efi EFI_PATH=/build/lakitu//usr/lib64 ARCH_LDFLAGS=--no-experimental-use-relr COMMITID=79cdb2a215de2ace7d1bf0a294165a04b726c70a DEFAULT_LOADER=\\\\grub-lakitu.efi shimx64.efi
sed     -e "s,@@VERSION@@,14," \
        -e "s,@@UNAME@@,Linux x86_64 Intel Xeon E312xx (Sandy Bridge, IBRS update) GenuineIntel GNU/Linux," \
        -e "s,@@COMMIT@@,79cdb2a215de2ace7d1bf0a294165a04b726c70a," \
        < /build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/work/shim-79cdb2a215de2ace7d1bf0a294165a04b726c70a/version.c.in > version.c
sed: -e expression #2, char 60: unknown option to `s'
make: *** [Makefile:183: version.c] Error 1
 * ERROR: sys-boot/shim-14.0.20180308-r4::lakitu failed (compile phase):
 *   emake failed
 *
 * If you need support, post the output of `emerge --info '=sys-boot/shim-14.0.20180308-r4::lakitu'`,
 * the complete build log and the output of `emerge -pqv '=sys-boot/shim-14.0.20180308-r4::lakitu'`.
 * The complete build log is located at '/build/lakitu/tmp/portage/logs/sys-boot:shim-14.0.20180308-r4:20190531-002217.log'.
 * For convenience, a symlink to the build log is located at '/build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/temp/build.log'.
 * The ebuild environment file is located at '/build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/temp/environment'.
 * Working directory: '/build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/work/shim-79cdb2a215de2ace7d1bf0a294165a04b726c70a'
 * S: '/build/lakitu/tmp/portage/sys-boot/shim-14.0.20180308-r4/work/shim-79cdb2a215de2ace7d1bf0a294165a04b726c70a'

Body:
There's a , after Bridge

    -e "s,@@UNAME@@,Linux x86_64 Intel Xeon E312xx (Sandy Bridge, IBRS update) GenuineIntel GNU/Linux," \

Change to

    -e "s#@@UNAME@@#Linux x86_64 Intel Xeon E312xx (Sandy Bridge, IBRS update) GenuineIntel GNU/Linux#" \


问:
How to create a python module as a single callable function?
I'd like to write the module as a function and not a class.

Is there a way to make this work as intended?

greet.py

def main(x):
    print(f'Hello {x}!')
```

<p>Now how do I write the module so that when <code>greet</code> is executed, <code>main</code> runs.</p>

<strong><code>main.py</code></strong>

<pre class="lang-py prettyprint-override"><code>import greet

greet('Foo') # output: Hello Foo!
</code>```

答:
Unfortunately, this isn't possible.

An object, class, or function can be callable, but a module cannot.

You can, however, name things conveniently:

```<code>[greet.py]
def greet(x):
     ...

[main.py]
    from greet import greet
    greet('foo')
</code>```

Body:
I'd like to write the module as a function and not a class.

Is there a way to make this work as intended?

greet.py

def main(x):
    print(f'Hello {x}!')

Now how do I write the module so that when greet is executed, main runs.

main.py

import greet

greet('Foo') # output: Hello Foo!

Body:
Unfortunately, this isn't possible.

An object, class, or function can be callable, but a module cannot.

You can, however, name things conveniently:

[greet.py]
def greet(x):
     ...

[main.py]
    from greet import greet
    greet('foo')


问:
I have a query that does 2 sums, and then the first will subtract the second, but in some cases the second is null
I have a query (in MS-Query, MSQRY32.EXE) that does 2 sums, and then the first will subtract the second, but in some cases the second is null, how do I go over this?

```<code>(Sum(CASE WHEN m.mcdmv=11 THEN m.mqtd END)-
Sum(CASE WHEN m.mcdmv=12 THEN m.mqtd END))
</code>```

This is the part of the query, but sometimes one of them or both are null, so how do I do this?

答:
(IIf(Sum1 Is Null,0,Sum1) -
IIf(Sum2 Is Null,0,Sum2))

Body:
I have a query (in MS-Query, MSQRY32.EXE) that does 2 sums, and then the first will subtract the second, but in some cases the second is null, how do I go over this?

(Sum(CASE WHEN m.mcdmv=11 THEN m.mqtd END)-
Sum(CASE WHEN m.mcdmv=12 THEN m.mqtd END))

This is the part of the query, but sometimes one of them or both are null, so how do I do this?


问:
image = vision_client.image( AttributeError: 'ImageAnnotatorClient' object has no attribute 'image'
```<code>import io,os

# Imports the Google Cloud client library
from google.cloud import vision
# Instantiates a client (Change the line below******)
vision_client = vision.ImageAnnotatorClient('my-key.json')

# The name of the image file to annotate (Change the line below 'image_path.jpg' ******)
file_name = os.path.join(
    os.path.dirname(__file__),
    'image_path.jpg')

# Loads the image into memory
with io.open(file_name, 'rb') as image_file:
    content = image_file.read()
    image = vision_client.image(
        content=content)

# Performs label detection on the image file
labels = image.detect_labels()

print('Labels:')
for label in labels:
    print(label.description)

</code>```

python 3.6.5 on windows

this code example gives me the error mention in the title, is anyone knows how to fix that?

答:
This worked for me:</p>

```<code>import io
import os
# Imports the Google Cloud client library
from google.cloud import vision
from google.cloud.vision import types
# Instantiates a client
client = vision.ImageAnnotatorClient()
# The name of the image file to annotate
file_name = os.path.join(
    os.path.dirname(__file__),
    'resources/wakeupcat.jpg')

# Loads the image into memory
with io.open(file_name, 'rb') as image_file:
    content = image_file.read()
image = types.Image(content=content)
# Performs label detection on the image file
response = client.label_detection(image=image)
labels = response.label_annotations
print('Labels:')
for label in labels:
    print(label.description)
</code>```

Body:
import io,os

# Imports the Google Cloud client library
from google.cloud import vision
# Instantiates a client (Change the line below******)
vision_client = vision.ImageAnnotatorClient('my-key.json')

# The name of the image file to annotate (Change the line below 'image_path.jpg' ******)
file_name = os.path.join(
    os.path.dirname(__file__),
    'image_path.jpg')

# Loads the image into memory
with io.open(file_name, 'rb') as image_file:
    content = image_file.read()
    image = vision_client.image(
        content=content)

# Performs label detection on the image file
labels = image.detect_labels()

print('Labels:')
for label in labels:
    print(label.description)

python 3.6.5 on windows

this code example gives me the error mention in the title, is anyone knows how to fix that?

Body:
This worked for me:

import io
import os
# Imports the Google Cloud client library
from google.cloud import vision
from google.cloud.vision import types
# Instantiates a client
client = vision.ImageAnnotatorClient()
# The name of the image file to annotate
file_name = os.path.join(
    os.path.dirname(__file__),
    'resources/wakeupcat.jpg')

# Loads the image into memory
with io.open(file_name, 'rb') as image_file:
    content = image_file.read()
image = types.Image(content=content)
# Performs label detection on the image file
response = client.label_detection(image=image)
labels = response.label_annotations
print('Labels:')
for label in labels:
    print(label.description)