问:
How to display a simple abcjs sheet in an Angular application?
Using the abcjs library in an Angular 7 application, I have the following template:

```<code><div id="{{device.name}}"></div>
</code>```

with the controller:

```<code>@Component({
  selector: 'midi-sheet',
  templateUrl: './sheet.component.html',
  styleUrls: ['./sheet.component.css']
})
export class SheetComponent implements AfterViewInit, OnDestroy  {

  // devices$: Observable<Array<Device>>;
  @Input() device: Device;

  constructor(
    // private storeService: StoreService,
    private sheetService: SheetService
  ) { }

  ngAfterViewInit() {
    this.createSheet();
  }

  ngOnDestroy() {
  }

  private createSheet() {
    const sheet = this.sheetService.createSheet(this.device.name);
  }

}
</code>```

and its service:

```<code>export class SheetService {

  public createSheet(name: string) {
    const elementName: string = '#' + name;
    // tslint:disable-next-line: max-line-length
    const tune = 'X:1\nT: Cooley\'s\nM: 4/4\nL: 1/8\nR: reel\nK: Emin\nD2|:"Em"EB{c}BA B2 EB|~B2 AB dBAG|"D"FDAD BDAD|FDAD dAFD|\n"Em"EBBA B2 EB|B2 AB defg|"D"afe^c dBAF|1"Em"DEFD E2 D2:|2"Em"DEFD E2 gf||\n|:"Em"eB B2 efge|eB B2 gedB|"D"A2 FA DAFA|A2 FA defg|\n"Em"eB B2 eBgB|eB B2 defg|"D"afe^c dBAF|1"Em"DEFD E2 gf:|2"Em"DEFD E4|]\n';
    const sheet = abcjs.renderAbc(elementName, tune, {});
    console.log('Created a sheet for ' + name);
    return sheet;
  }

}
</code>```

The console log shows the sheet is being created:

```<code>Created a sheet for VMPKOutput
</code>```

and the Chrome browser console element tab shows:

```<code><midi-sheet _ngcontent-hvr-c2="" _nghost-hvr-c4="" ng-reflect-device="[object Object]"><div _ngcontent-hvr-c4="" id="MidiThroughPort-0"></div></midi-sheet>
</code>```

But there is no visible sheet in the page.

答:
I don't have a sample using Angular, but here is an example with Vue: https://github.com/paulrosen/vue-abcjs-basic-demo/blob/master/src/components/HelloWorld.vue

It looks very similar to what you're doing.

The first thing I notice is that you shouldn't have the '#' in the element id that you are passing in. Perhaps that's it. So const elementName: string = name;

Here's what I would debug:

1) At the time that abcjs.renderAbc(elementName, tune, {}); is called, is there a visible element with the id elementName?

2) Look at the value of sheet that is returned. It should be an array with one item. There should be reasonable data in it. For instance, sheet[0].lines[0].staff[0].voices[0] should return an array of notes.

Body:
Using the abcjs library in an Angular 7 application, I have the following template:

with the controller:

@Component({
  selector: 'midi-sheet',
  templateUrl: './sheet.component.html',
  styleUrls: ['./sheet.component.css']
})
export class SheetComponent implements AfterViewInit, OnDestroy  {

  // devices$: Observable<Array<Device>>;
  @Input() device: Device;

  constructor(
    // private storeService: StoreService,
    private sheetService: SheetService
  ) { }

  ngAfterViewInit() {
    this.createSheet();
  }

  ngOnDestroy() {
  }

  private createSheet() {
    const sheet = this.sheetService.createSheet(this.device.name);
  }

}

and its service:

export class SheetService {

  public createSheet(name: string) {
    const elementName: string = '#' + name;
    // tslint:disable-next-line: max-line-length
    const tune = 'X:1\nT: Cooley\'s\nM: 4/4\nL: 1/8\nR: reel\nK: Emin\nD2|:"Em"EB{c}BA B2 EB|~B2 AB dBAG|"D"FDAD BDAD|FDAD dAFD|\n"Em"EBBA B2 EB|B2 AB defg|"D"afe^c dBAF|1"Em"DEFD E2 D2:|2"Em"DEFD E2 gf||\n|:"Em"eB B2 efge|eB B2 gedB|"D"A2 FA DAFA|A2 FA defg|\n"Em"eB B2 eBgB|eB B2 defg|"D"afe^c dBAF|1"Em"DEFD E2 gf:|2"Em"DEFD E4|]\n';
    const sheet = abcjs.renderAbc(elementName, tune, {});
    console.log('Created a sheet for ' + name);
    return sheet;
  }

}

The console log shows the sheet is being created:

Created a sheet for VMPKOutput

and the Chrome browser console element tab shows:

<midi-sheet _ngcontent-hvr-c2="" _nghost-hvr-c4="" ng-reflect-device="[object Object]">

</midi-sheet>

But there is no visible sheet in the page.


来源: stackexchange

问:
How to filter items by a field in Firebase?
```<code>"Products" : {
    "DateTime" : {
      "category" : "Mobile Phones",
      "pid" : "",
      "pname" : "",
      "price" : "",
    }
  }
</code>```

Hello I am developing an android app using firebase. I am able to list all products in my firebase database. However, I would like to show products based on the category (ex: Mobile Phones, Tablets etc). How do I do this?

答:
you can use a compound query like:

```<code>Query products = db.collection("Products/DateTime").whereEqualTo("category", YOUR_CATEGORY);
</code>```

Check more here

ContentLicense: CC BY-SA 4.0

Body:
"Products" : {
    "DateTime" : {
      "category" : "Mobile Phones",
      "pid" : "",
      "pname" : "",
      "price" : "",
    }
  }

Hello I am developing an android app using firebase. I am able to list all products in my firebase database. However, I would like to show products based on the category (ex: Mobile Phones, Tablets etc). How do I do this?

Body:
you can use a compound query like:

Query products = db.collection("Products/DateTime").whereEqualTo("category", YOUR_CATEGORY);

Check more here


问:
Calculating duration of continuous events in Flink
I have a stream of some device state changes, for example: case class DeviceState(ts: Long, state: Int). The device sends its state only when it's changed. So, for example, it can be like this:

```<code>ts | state
----------
 0 | ONLINE
 3 | OFFLINE
11 | ONLINE
19 | OFFLINE
</code>```

(in real code ts is unix time milliseconds, I simplified it for example purpose)
I want to partition this stream by tumbling window of 10 ticks and calculate the total duration of each state, so for example if the punctuation was emitted at tick 45, the result should be like this:

```<code> window | state   | duration
-----------------------------
 0 - 10 | ONLINE  | 3
 0 - 10 | OFFLINE | 7
10 - 20 | OFFLINE | 2
10 - 20 | ONLINE  | 8
20 - 30 | OFFLINE | 10
30 - 40 | OFFLINE | 10
</code>```

Is it possible to do such duration calculations in Flink? I think it can be made by custom reduce function, but I can't figure out how to emit last state so it will appear in each window (in the example above the last state was at tick 19, but it still should be used in windows 20-30, 30-40 and so on).

答:
With Flink's window API, a window doesn't exist until an event is assigned to it, which makes what you are trying to do more difficult.

One solution might be to use a ProcessFunction with a timer to mix into your stream a third type of event that's only used to trigger the windows that would otherwise be empty.

Another solution would be to do all the work of computing the analytics with a ProcessFunction (with some state and timers), rather than windows.

Body:
I have a stream of some device state changes, for example: case class DeviceState(ts: Long, state: Int). The device sends its state only when it's changed. So, for example, it can be like this:

ts | state
----------
 0 | ONLINE
 3 | OFFLINE
11 | ONLINE
19 | OFFLINE

(in real code ts is unix time milliseconds, I simplified it for example purpose)
I want to partition this stream by tumbling window of 10 ticks and calculate the total duration of each state, so for example if the punctuation was emitted at tick 45, the result should be like this:

 window | state   | duration
-----------------------------
 0 - 10 | ONLINE  | 3
 0 - 10 | OFFLINE | 7
10 - 20 | OFFLINE | 2
10 - 20 | ONLINE  | 8
20 - 30 | OFFLINE | 10
30 - 40 | OFFLINE | 10

Is it possible to do such duration calculations in Flink? I think it can be made by custom reduce function, but I can't figure out how to emit last state so it will appear in each window (in the example above the last state was at tick 19, but it still should be used in windows 20-30, 30-40 and so on).


问:
Remove a tag using BeautifulSoup but keep its contents
Currently I have code that does something like this:

```<code>soup = BeautifulSoup(value)

for tag in soup.findAll(True):
    if tag.name not in VALID_TAGS:
        tag.extract()
soup.renderContents()
</code>```

Except I don't want to throw away the contents inside the invalid tag. How do I get rid of the tag but keep the contents inside when calling soup.renderContents()?

答:
Here is a python 3 friendly version of this function: </p>

```<code>from bs4 import BeautifulSoup, NavigableString
invalidTags = ['br','b','font']
def stripTags(html, invalid_tags):
    soup = BeautifulSoup(html, "lxml")
    for tag in soup.findAll(True):
        if tag.name in invalid_tags:
            s = ""
            for c in tag.contents:
                if not isinstance(c, NavigableString):
                    c = stripTags(str(c), invalid_tags)
                s += str(c)
            tag.replaceWith(s)
    return soup
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Currently I have code that does something like this:

soup = BeautifulSoup(value)

for tag in soup.findAll(True):
    if tag.name not in VALID_TAGS:
        tag.extract()
soup.renderContents()

Except I don't want to throw away the contents inside the invalid tag. How do I get rid of the tag but keep the contents inside when calling soup.renderContents()?

Body:
Here is a python 3 friendly version of this function:

from bs4 import BeautifulSoup, NavigableString
invalidTags = ['br','b','font']
def stripTags(html, invalid_tags):
    soup = BeautifulSoup(html, "lxml")
    for tag in soup.findAll(True):
        if tag.name in invalid_tags:
            s = ""
            for c in tag.contents:
                if not isinstance(c, NavigableString):
                    c = stripTags(str(c), invalid_tags)
                s += str(c)
            tag.replaceWith(s)
    return soup


问:
Progress bar in Swing (Java) for command tools
I have several C/C++ command line tools that I'm wrapping with Java.Swing as GUI. The command line tools can take minutes to hours. Progress bar seems like a good idea to keep users sane. I'm also thinking it might be nice to wrap a GUI for the progress bar, instead of just using system out.  But how?

I'm thinking the command line tools can write percents to stderr and I can somehow read it in java. Not exactly sure what the mechanics for this would be.  I'm also not clear on asynchronous display (learned a bit about invokeLater() ).  New to Java, and would appreciate general suggestions as well.  Thanks.

--- update ---

Thanks everyone for your suggestions.  Here's the resulting code.

```<code>private void redirectSystemStreams() {
    OutputStream out_stderr = new OutputStream() {
      @Override
      public void write(final int b) throws IOException {
        update(String.valueOf((char) b));
      }
      @Override
      public void write(byte[] b, int off, int len) throws IOException {
        update(new String(b, off, len));
      }
      @Override
      public void write(byte[] b) throws IOException {
        write(b, 0, b.length);
      }
    };
    System.setErr(new PrintStream(out_stderr, true));
}

private void update(final String inputText) {
    int value = 20; //parse inputText; make sure your executable calls fflush(stderr) after each fprintf().
    jProgressBar.setValue(value);

    /* Also one can redirect to a textpane
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        //update jTextPane with inputText
      }
    });
    */
}
</code>```

答:
That's seems very fragile, better would be to communicate via sockets in a well established protocol or with some sort of RCP ( perhaps Google's protobuf ) or even webservices.

If you still insists you can launch a process in Java with ProcessBuilder that will give you a Process reference of which you can get the InputStream to read the standard output, but again, that seems very fragile to me.

I hope this helps.

Body:
I have several C/C++ command line tools that I'm wrapping with Java.Swing as GUI. The command line tools can take minutes to hours. Progress bar seems like a good idea to keep users sane. I'm also thinking it might be nice to wrap a GUI for the progress bar, instead of just using system out.  But how?

I'm thinking the command line tools can write percents to stderr and I can somehow read it in java. Not exactly sure what the mechanics for this would be.  I'm also not clear on asynchronous display (learned a bit about invokeLater() ).  New to Java, and would appreciate general suggestions as well.  Thanks.

--- update ---

Thanks everyone for your suggestions.  Here's the resulting code.

private void redirectSystemStreams() {
    OutputStream out_stderr = new OutputStream() {
      @Override
      public void write(final int b) throws IOException {
        update(String.valueOf((char) b));
      }
      @Override
      public void write(byte[] b, int off, int len) throws IOException {
        update(new String(b, off, len));
      }
      @Override
      public void write(byte[] b) throws IOException {
        write(b, 0, b.length);
      }
    };
    System.setErr(new PrintStream(out_stderr, true));
}

private void update(final String inputText) {
    int value = 20; //parse inputText; make sure your executable calls fflush(stderr) after each fprintf().
    jProgressBar.setValue(value);

    /* Also one can redirect to a textpane
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        //update jTextPane with inputText
      }
    });
    */
}


问:
GeofencingClient take lot of time in adding the geofences
I have a feature that depends on GeoFencing Technology There is a weird problem. On adding a Geofence, the client takes a lot of time to add (Have a look at logs). This is weird as it works pretty well earlier (no code change related to location and all afaik) without any delay.

I am using the following dependency:

'com.google.android.gms:play-services-location:16.0.0'

```<code>@RequiresPermission(Manifest.permission.ACCESS_FINE_LOCATION)
    fun addGeoFences(
            geoFences: ArrayList<Geofence>,
            onSuccess: () -> Unit = {},
            onFailure: (Exception) -> Unit = {}
    ): Boolean {
        if (isAddingGeofence) {
            GlobalLoggerUtils.showLog(TAG, "isAddingGeofence: $isAddingGeofence")
            return false
        }
        GlobalLoggerUtils.showLog(TAG, "addGeoFences()")

        if (geoFences.size == 0) {
            return false
        }
        isAddingGeofence = true

        geoFencingClient
                .addGeofences(
                        getGeoFencingRequest(geoFences),
                        geoFencePendingIntent
                ).addOnSuccessListener { result ->
                    isAddingGeofence = false
                }
                .addOnFailureListener { exception ->
                    isAddingGeofence = false
                }
                .addOnCanceledListener {
                    isAddingGeofence = false
                }
        return true
    }

2019-05-30 12:43:29.716  I/: addGeoFences()
2019-05-30 12:44:00.602  I/: isAddingGeofence: true
2019-05-30 12:44:02.424  I/: isAddingGeofence: true
2019-05-30 12:44:03.525  I/: isAddingGeofence: true
2019-05-30 12:44:04.975  I/: isAddingGeofence: true
2019-05-30 12:44:06.541  I/: isAddingGeofence: true
2019-05-30 12:48:18.384  I/: add success >>> result: null
2019-05-30 12:48:18.393  I/: add success >>> requestIds: XYZ
</code>```

Let me know if there anything required to add in context to this problem. Adding the Geofence is as per the official Android documentation.

Edit #1: 05 June 2019

Looks like this happen in development build only. Works fine in
  release build installed from play store.

答: If it's Android 8.0+, be aware that there is a background location restriction that also applies to the Geofencing APIenter link description here</p>

Body:
I have a feature that depends on GeoFencing Technology There is a weird problem. On adding a Geofence, the client takes a lot of time to add (Have a look at logs). This is weird as it works pretty well earlier (no code change related to location and all afaik) without any delay.

I am using the following dependency:

'com.google.android.gms:play-services-location:16.0.0'

@RequiresPermission(Manifest.permission.ACCESS_FINE_LOCATION)
    fun addGeoFences(
            geoFences: ArrayList<Geofence>,
            onSuccess: () -> Unit = {},
            onFailure: (Exception) -> Unit = {}
    ): Boolean {
        if (isAddingGeofence) {
            GlobalLoggerUtils.showLog(TAG, "isAddingGeofence: $isAddingGeofence")
            return false
        }
        GlobalLoggerUtils.showLog(TAG, "addGeoFences()")

        if (geoFences.size == 0) {
            return false
        }
        isAddingGeofence = true

        geoFencingClient
                .addGeofences(
                        getGeoFencingRequest(geoFences),
                        geoFencePendingIntent
                ).addOnSuccessListener { result ->
                    isAddingGeofence = false
                }
                .addOnFailureListener { exception ->
                    isAddingGeofence = false
                }
                .addOnCanceledListener {
                    isAddingGeofence = false
                }
        return true
    }

2019-05-30 12:43:29.716  I/: addGeoFences()
2019-05-30 12:44:00.602  I/: isAddingGeofence: true
2019-05-30 12:44:02.424  I/: isAddingGeofence: true
2019-05-30 12:44:03.525  I/: isAddingGeofence: true
2019-05-30 12:44:04.975  I/: isAddingGeofence: true
2019-05-30 12:44:06.541  I/: isAddingGeofence: true
2019-05-30 12:48:18.384  I/: add success >>> result: null
2019-05-30 12:48:18.393  I/: add success >>> requestIds: XYZ

Let me know if there anything required to add in context to this problem. Adding the Geofence is as per the official Android documentation.

Edit #1: 05 June 2019

Looks like this happen in development build only. Works fine in
  release build installed from play store.


问:
Docker + Xdebug + VSCode Could not connect to client
PHP version: 7.1.20

XDebug version: 2.7.0

I'm using a Docker container on MacOS Mojave.
On pressing "F5", it shows debug options Pause, Restart, and Stop. But Step Over, Step Into, Step Out are disabled.

I'm kind of learner because I was used to code till 2012-13 on Windows OS. After that year, I am back to coding this month. :) Even after reviewing a lot of posts on Google about how to resolve this issue, I'm not sure how to finally make it work. Please help.

My launch.json file:

```<code>{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for XDebug",
            "type": "php",
            "request": "launch",
            "port": 9001,
            "log": true,
            "pathMappings": {
                "/var/www/html": "${workspaceFolder}/learn"
            }
        },
        {
            "name": "Launch currently open script",
            "type": "php",
            "request": "launch",
            "program": "${file}",
            "cwd": "${fileDirname}",
            "port": 9001
        }
    ]
}
</code>```

XDebug php.ini config:

```<code>xdebug.remote_host = 172.20.0.1
xdebug.remote_port = 9001
xdebug.scream = 1
xdebug.remote_enable = 1
xdebug.show_local_vars = 1
xdebug.remote_autostart = 1
xdebug.remote_connect_back = 1
xdebug.remote_log = "/var/www/html/xdebug.log"
xdebug.idekey = "VSCODE"
</code>```

XDebug logfile (from setting xdebug.remote_log in php.ini):

```<code>[12] Log opened at 2019-05-12 10:16:44
[12] I: Checking remote connect back address.
[12] I: Checking header 'HTTP_X_FORWARDED_FOR'.
[12] I: Checking header 'REMOTE_ADDR'.
[12] I: Remote address found, connecting to 172.20.0.1:9001.
[12] W: Creating socket for '172.20.0.1:9001', poll success, but error: Operation now in progress (29).
[12] E: Could not connect to client. :-(
[12] Log closed at 2019-05-12 10:16:44
</code>```

Debug console:

```<code><- launchResponse
Response {
  seq: 0,
  type: 'response',
  request_seq: 2,
  command: 'launch',
  success: true }
</code>```

Here's the dockerfile.

```<code>FROM php:7.1.20-apache

RUN apt-get -y update --fix-missing
RUN apt-get upgrade -y

# Install tools & libraries
RUN apt-get -y install apt-utils nano wget dialog \
    build-essential git curl libcurl3 libcurl3-dev zip

# Install important libraries
RUN apt-get -y install --fix-missing apt-utils build-essential git curl libcurl3 libcurl3-dev zip \
    libmcrypt-dev libsqlite3-dev libsqlite3-0 mysql-client zlib1g-dev \
    libicu-dev libfreetype6-dev libjpeg62-turbo-dev libpng-dev

# Composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

# PHP Extensions
RUN pecl install xdebug-2.7.0 \
    && docker-php-ext-enable xdebug \
    && docker-php-ext-install mcrypt \
    && docker-php-ext-install pdo_mysql \
    && docker-php-ext-install pdo_sqlite \
    && docker-php-ext-install mysqli \
    && docker-php-ext-install curl \
    && docker-php-ext-install tokenizer \
    && docker-php-ext-install json \
    && docker-php-ext-install zip \
    && docker-php-ext-install -j$(nproc) intl \
    && docker-php-ext-install mbstring \
    && docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ \
    && docker-php-ext-install -j$(nproc) gd \
    && pecl install redis \
    && docker-php-ext-enable redis

# Enable apache modules
RUN a2enmod rewrite headers

ENTRYPOINT ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]
</code>```

Here's the docker-compose.yml file.

```<code>version: "3"

services:
  webserver:
    build:
      context: ./bin/webserver
    container_name: '7.1.x-webserver'
    restart: 'always'
    ports:
      - "80:80"
      - "443:443"
    links:
      - mysql
    volumes:
      - ${DOCUMENT_ROOT-./www}:/var/www/html
      - ${PHP_INI-./config/php/php.ini}:/usr/local/etc/php/php.ini
      - ${VHOSTS_DIR-./config/vhosts}:/etc/apache2/sites-enabled
      - ${LOG_DIR-./logs/apache2}:/var/log/apache2
  mysql:
    build: ./bin/mysql
    container_name: '5.7-mysql'
    restart: 'always'
    ports:
      - "3306:3306"
    volumes:
      - ${MYSQL_DATA_DIR-./data/mysql}:/var/lib/mysql
      - ${MYSQL_LOG_DIR-./logs/mysql}:/var/log/mysql
    environment:
      MYSQL_ROOT_PASSWORD: tiger
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    container_name: 'sc-phpmyadmin'
    links:
      - mysql
    environment:
      PMA_HOST: mysql
      PMA_PORT: 3306
    ports:
      - '8080:80'
    volumes:
      - /sessions
  redis:
    container_name: 'sc-redis'
    image: redis:latest
    ports:
      - "6379:6379"
</code>```

Thank you in advance.

答:
You can have your docker container connect to your host by configuring PHP appropriately.

Note that I've used Docker's host.docker.internal domain, that always points to the host IP.

```<code>xdebug.remote_enable=1
xdebug.remote_port=9000
xdebug.idekey=docker
xdebug.profiler_enable=0
xdebug.profiler_enable_trigger=1
xdebug.remote_host=host.docker.internal
</code>```

There's no need to open ports to the docker container.
Just make sure that your debugging application can listen on the appointed port (9000 in my case) and that this port is not occupied.

Take for example this PhpStorm configuration:

Troubleshooting

Validate that xdebug is installed, run in the php container:

php -i | grep xdebug

Make sure that you're editing the appropriate .ini files, check:

php -i | grep \.ini

If you have idekey enabled, make sure to configure them in your IDE too:

There's a Debugger Config Validator in PhpStorm if you're exposing PHP scripts on a webserver:

Body:
PHP version: 7.1.20

XDebug version: 2.7.0

I'm using a Docker container on MacOS Mojave.
On pressing "F5", it shows debug options Pause, Restart, and Stop. But Step Over, Step Into, Step Out are disabled.

I'm kind of learner because I was used to code till 2012-13 on Windows OS. After that year, I am back to coding this month. :) Even after reviewing a lot of posts on Google about how to resolve this issue, I'm not sure how to finally make it work. Please help.

My launch.json file:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for XDebug",
            "type": "php",
            "request": "launch",
            "port": 9001,
            "log": true,
            "pathMappings": {
                "/var/www/html": "${workspaceFolder}/learn"
            }
        },
        {
            "name": "Launch currently open script",
            "type": "php",
            "request": "launch",
            "program": "${file}",
            "cwd": "${fileDirname}",
            "port": 9001
        }
    ]
}

XDebug php.ini config:

xdebug.remote_host = 172.20.0.1
xdebug.remote_port = 9001
xdebug.scream = 1
xdebug.remote_enable = 1
xdebug.show_local_vars = 1
xdebug.remote_autostart = 1
xdebug.remote_connect_back = 1
xdebug.remote_log = "/var/www/html/xdebug.log"
xdebug.idekey = "VSCODE"

XDebug logfile (from setting xdebug.remote_log in php.ini):

[12] Log opened at 2019-05-12 10:16:44
[12] I: Checking remote connect back address.
[12] I: Checking header 'HTTP_X_FORWARDED_FOR'.
[12] I: Checking header 'REMOTE_ADDR'.
[12] I: Remote address found, connecting to 172.20.0.1:9001.
[12] W: Creating socket for '172.20.0.1:9001', poll success, but error: Operation now in progress (29).
[12] E: Could not connect to client. :-(
[12] Log closed at 2019-05-12 10:16:44

Debug console:

<- launchResponse
Response {
  seq: 0,
  type: 'response',
  request_seq: 2,
  command: 'launch',
  success: true }

Here's the dockerfile.

FROM php:7.1.20-apache

RUN apt-get -y update --fix-missing
RUN apt-get upgrade -y

# Install tools & libraries
RUN apt-get -y install apt-utils nano wget dialog \
    build-essential git curl libcurl3 libcurl3-dev zip

# Install important libraries
RUN apt-get -y install --fix-missing apt-utils build-essential git curl libcurl3 libcurl3-dev zip \
    libmcrypt-dev libsqlite3-dev libsqlite3-0 mysql-client zlib1g-dev \
    libicu-dev libfreetype6-dev libjpeg62-turbo-dev libpng-dev

# Composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

# PHP Extensions
RUN pecl install xdebug-2.7.0 \
    && docker-php-ext-enable xdebug \
    && docker-php-ext-install mcrypt \
    && docker-php-ext-install pdo_mysql \
    && docker-php-ext-install pdo_sqlite \
    && docker-php-ext-install mysqli \
    && docker-php-ext-install curl \
    && docker-php-ext-install tokenizer \
    && docker-php-ext-install json \
    && docker-php-ext-install zip \
    && docker-php-ext-install -j$(nproc) intl \
    && docker-php-ext-install mbstring \
    && docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ \
    && docker-php-ext-install -j$(nproc) gd \
    && pecl install redis \
    && docker-php-ext-enable redis

# Enable apache modules
RUN a2enmod rewrite headers

ENTRYPOINT ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]

Here's the docker-compose.yml file.

version: "3"

services:
  webserver:
    build:
      context: ./bin/webserver
    container_name: '7.1.x-webserver'
    restart: 'always'
    ports:
      - "80:80"
      - "443:443"
    links:
      - mysql
    volumes:
      - ${DOCUMENT_ROOT-./www}:/var/www/html
      - ${PHP_INI-./config/php/php.ini}:/usr/local/etc/php/php.ini
      - ${VHOSTS_DIR-./config/vhosts}:/etc/apache2/sites-enabled
      - ${LOG_DIR-./logs/apache2}:/var/log/apache2
  mysql:
    build: ./bin/mysql
    container_name: '5.7-mysql'
    restart: 'always'
    ports:
      - "3306:3306"
    volumes:
      - ${MYSQL_DATA_DIR-./data/mysql}:/var/lib/mysql
      - ${MYSQL_LOG_DIR-./logs/mysql}:/var/log/mysql
    environment:
      MYSQL_ROOT_PASSWORD: tiger
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    container_name: 'sc-phpmyadmin'
    links:
      - mysql
    environment:
      PMA_HOST: mysql
      PMA_PORT: 3306
    ports:
      - '8080:80'
    volumes:
      - /sessions
  redis:
    container_name: 'sc-redis'
    image: redis:latest
    ports:
      - "6379:6379"

Thank you in advance.

Body:
You can have your docker container connect to your host by configuring PHP appropriately.

Note that I've used Docker's host.docker.internal domain, that always points to the host IP.

xdebug.remote_enable=1
xdebug.remote_port=9000
xdebug.idekey=docker
xdebug.profiler_enable=0
xdebug.profiler_enable_trigger=1
xdebug.remote_host=host.docker.internal

There's no need to open ports to the docker container.
Just make sure that your debugging application can listen on the appointed port (9000 in my case) and that this port is not occupied.

Take for example this PhpStorm configuration:

Troubleshooting

Validate that xdebug is installed, run in the php container:

php -i | grep xdebug

Make sure that you're editing the appropriate .ini files, check:

php -i | grep \.ini

If you have idekey enabled, make sure to configure them in your IDE too:

There's a Debugger Config Validator in PhpStorm if you're exposing PHP scripts on a webserver:


问:
How do I append the data or json received from this request to an empty array?
I am using a custom codable class Events. How do i append the resulting json from a request to an empty array so as to populate the table ?</p>

```<code>var events = [Events]()

let URL_GET_DATA = "http://192.168.100.4/PrototypeWebService/api/getevents.php"

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
        Alamofire.request(URL_GET_DATA).responseJSON{ response in
            if let json = response.result.value {
                print(json)
                do {
                    let decoder = JSONDecoder()

                    self.EventTable.reloadData()

                } catch {
        }

        }

 }
}
</code>```

答:
pass your array data from your model to the array you created, after doing this</p>

```<code>let jsonDecoder = JSONDecoder()
let genaricModel = try jsonDecoder.decode(EventModel.self, from: JSON.data(using: .utf8)!)
</code>```

Body:
I am using a custom codable class Events. How do i append the resulting json from a request to an empty array so as to populate the table ?

var events = [Events]()

let URL_GET_DATA = "http://192.168.100.4/PrototypeWebService/api/getevents.php"

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
        Alamofire.request(URL_GET_DATA).responseJSON{ response in
            if let json = response.result.value {
                print(json)
                do {
                    let decoder = JSONDecoder()

                    self.EventTable.reloadData()

                } catch {
        }

        }

 }
}

Body:
pass your array data from your model to the array you created, after doing this

let jsonDecoder = JSONDecoder()
let genaricModel = try jsonDecoder.decode(EventModel.self, from: JSON.data(using: .utf8)!)


问:
Populate pandas dataframe using column and row indices as variables

Overview

How do you populate a pandas dataframe using math which uses column and row indices as variables.

Setup

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame(index = range(5), columns = ['Combo_Class0', 'Combo_Class1', 'Combo_Class2', 'Combo_Class3', 'Combo_Class4'])
</code>```

Objective

Each cell in df = row index * (column index + 2)

Attempt 1

You can use this solution to produce the following code:

```<code>row = 0
for i in range(5):
    row = row + 1
    df.loc[i] = [(row)*(1+2), (row)*(2+2), (row)*(3+2), (row)*(4+2), (row)*(4+2), (row)*(5+2)]
</code>```

Attempt 2

This solution seemed relevant as well, although I believe I've read you're not supposed to loop through dataframes. Besides, I'm not seeing how to loop through rows and columns:

```<code>for i, j in df.iterrows():
    df.loc[i] = i
</code>```

答:
Using multiply outer

```<code>df[:]=np.multiply.outer((np.arange(5)+1),(np.arange(5)+3))
</code>```

Body:
Overview

How do you populate a pandas dataframe using math which uses column and row indices as variables.

Setup

import pandas as pd
import numpy as np

df = pd.DataFrame(index = range(5), columns = ['Combo_Class0', 'Combo_Class1', 'Combo_Class2', 'Combo_Class3', 'Combo_Class4'])

Objective

Each cell in df = row index * (column index + 2)

Attempt 1

You can use this solution to produce the following code:

row = 0
for i in range(5):
    row = row + 1
    df.loc[i] = [(row)*(1+2), (row)*(2+2), (row)*(3+2), (row)*(4+2), (row)*(4+2), (row)*(5+2)]

Attempt 2

This solution seemed relevant as well, although I believe I've read you're not supposed to loop through dataframes. Besides, I'm not seeing how to loop through rows and columns:

for i, j in df.iterrows():
    df.loc[i] = i

Body:
Using multiply outer

df[:]=np.multiply.outer((np.arange(5)+1),(np.arange(5)+3))


问:
What's the formula for Welford's Algorithm for Variance/Std with Batch Updates?
I want to extend Welford's online algorithm to be able to be updated with multiple numbers (in batch) instead of just one at a time: https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance

I tried to update the algorithm from the wiki page like this:

```<code># my attempt.
def update1(existingAggregate, newValues):
    (count, mean, M2) = existingAggregate
    count += len(newValues)
    delta = np.sum(np.subtract(newValues, [mean] * len(newValues)))
    mean += delta / count
    delta2 = np.sum(np.subtract(newValues, [mean] * len(newValues)))
    M2 += delta * delta2

    return (count, mean, M2)

# The original two functions from wikipedia.
def update(existingAggregate, newValue):
    (count, mean, M2) = existingAggregate
    count += 1
    delta = newValue - mean
    mean += delta / count
    delta2 = newValue - mean
    M2 += delta * delta2

def finalize(existingAggregate):
    (count, mean, M2) = existingAggregate
    (mean, variance, sampleVariance) = (mean, M2/count, M2/(count - 1))
    if count < 2:
        return float('nan')
    else:
        return (mean, variance, sampleVariance)
</code>```

However, I must not understand it correctly, because the result is wrong:

```<code># example x that might have led to an a = (2, 2.0, 2.0).
x = [1.0, 3.0]
mean = np.mean(x)
count = len(x)
m2 = np.sum(np.subtract(x, [mean] * count)**2)

a = (count, mean, m2)
print(a)
# new batch of values.
b = [5, 3]

</code>```

Note that a = (2, 2.0, 2.0) means that we had 2 observations, and their mean was 2.0.

```<code># update one at a time.
temp = update(a, newValues[0])
result_single = update(temp, newValues[1])
print(finalize(result_single))

# update with my faulty batch function.
result_batch = update1(a, newValues)
print(finalize(result_batch))

</code>```

The correct output should be the one from applying the single number update twice:

```<code>(3.0, 2.0, 2.6666666666666665)
(3.0, 2.5, 3.3333333333333335)
</code>```

What am I missing regarding the correct variance updates? Do I need to update the finalize function as well somehow?

The reason I need to do this, is because I am working with extremely large monthly files (with varying numbers of observations) and I need to get to yearly means and variances.

答:
Thanks to Nico's clarification's I figured it out!
The problem was that I summed for the deltas and then multiply to get M2, but instead have to sum over the product of the deltas.
Here is the correct batch function that is able to accept single numbers as well as batches:

```<code># https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
def update(existingAggregate, newValues):
    if isinstance(newValues, (int, float, complex)):
        # Handle single digits.
        newValues = [newValues]

    (count, mean, M2) = existingAggregate
    count += len(newValues)
    # newvalues - oldMean
    delta = np.subtract(newValues, [mean] * len(newValues))
    mean += np.sum(delta / count)
    # newvalues - newMeant
    delta2 = np.subtract(newValues, [mean] * len(newValues))
    M2 += np.sum(delta * delta2)

    return (count, mean, M2)

def finalize(existingAggregate):
    (count, mean, M2) = existingAggregate
    (mean, variance, sampleVariance) = (mean, M2/count, M2/(count - 1))
    if count < 2:
        return float('nan')
    else:
        return (mean, variance, sampleVariance)
</code>```

Sample Usage:

```<code>x = [1.0, 3.0]
mean = np.mean(x)
count = len(x)
m2 = np.sum(np.subtract(x, [mean] * count)**2)

a = (count, mean, m2)
print(a)
# new batch of values.
b = [5, 3]

result_batch = update(a, b)
result_batch1 = update(a, b[0])

print(finalize(result_batch))
print(finalize(result_batch1))
</code>```

And it is indeed faster:

```<code>import timeit
x = random.sample(range(1, 10000), 1000)
# ...
b = random.sample(range(1, 10000), 1000)

start_time = timeit.default_timer()
result_batch = update(a, b)
print(f'{timeit.default_timer() - start_time:.4f}')
print(*(f'{x:.2f}' for x in finalize(result_batch)))

start_time = timeit.default_timer()
for i in b:
    a  = update1(a, i)
print(f'{timeit.default_timer() - start_time:.4f}')
print(*(f'{x:.2f}' for x in finalize(result_batch)))
</code>```

Result:

```<code>0.0010
5008.36 8423224.68 8427438.40
0.0031
5008.36 8423224.68 8427438.40
</code>```

Body:
I want to extend Welford's online algorithm to be able to be updated with multiple numbers (in batch) instead of just one at a time: https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance

I tried to update the algorithm from the wiki page like this:

# my attempt.
def update1(existingAggregate, newValues):
    (count, mean, M2) = existingAggregate
    count += len(newValues)
    delta = np.sum(np.subtract(newValues, [mean] * len(newValues)))
    mean += delta / count
    delta2 = np.sum(np.subtract(newValues, [mean] * len(newValues)))
    M2 += delta * delta2

    return (count, mean, M2)

# The original two functions from wikipedia.
def update(existingAggregate, newValue):
    (count, mean, M2) = existingAggregate
    count += 1
    delta = newValue - mean
    mean += delta / count
    delta2 = newValue - mean
    M2 += delta * delta2

def finalize(existingAggregate):
    (count, mean, M2) = existingAggregate
    (mean, variance, sampleVariance) = (mean, M2/count, M2/(count - 1))
    if count < 2:
        return float('nan')
    else:
        return (mean, variance, sampleVariance)

However, I must not understand it correctly, because the result is wrong:

# example x that might have led to an a = (2, 2.0, 2.0).
x = [1.0, 3.0]
mean = np.mean(x)
count = len(x)
m2 = np.sum(np.subtract(x, [mean] * count)**2)

a = (count, mean, m2)
print(a)
# new batch of values.
b = [5, 3]

Note that a = (2, 2.0, 2.0) means that we had 2 observations, and their mean was 2.0.

# update one at a time.
temp = update(a, newValues[0])
result_single = update(temp, newValues[1])
print(finalize(result_single))

# update with my faulty batch function.
result_batch = update1(a, newValues)
print(finalize(result_batch))

The correct output should be the one from applying the single number update twice:

(3.0, 2.0, 2.6666666666666665)
(3.0, 2.5, 3.3333333333333335)

What am I missing regarding the correct variance updates? Do I need to update the finalize function as well somehow?

The reason I need to do this, is because I am working with extremely large monthly files (with varying numbers of observations) and I need to get to yearly means and variances.

Body:
Thanks to Nico's clarification's I figured it out!
The problem was that I summed for the deltas and then multiply to get M2, but instead have to sum over the product of the deltas.
Here is the correct batch function that is able to accept single numbers as well as batches:

# https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
def update(existingAggregate, newValues):
    if isinstance(newValues, (int, float, complex)):
        # Handle single digits.
        newValues = [newValues]

    (count, mean, M2) = existingAggregate
    count += len(newValues)
    # newvalues - oldMean
    delta = np.subtract(newValues, [mean] * len(newValues))
    mean += np.sum(delta / count)
    # newvalues - newMeant
    delta2 = np.subtract(newValues, [mean] * len(newValues))
    M2 += np.sum(delta * delta2)

    return (count, mean, M2)

def finalize(existingAggregate):
    (count, mean, M2) = existingAggregate
    (mean, variance, sampleVariance) = (mean, M2/count, M2/(count - 1))
    if count < 2:
        return float('nan')
    else:
        return (mean, variance, sampleVariance)

Sample Usage:

x = [1.0, 3.0]
mean = np.mean(x)
count = len(x)
m2 = np.sum(np.subtract(x, [mean] * count)**2)

a = (count, mean, m2)
print(a)
# new batch of values.
b = [5, 3]

result_batch = update(a, b)
result_batch1 = update(a, b[0])

print(finalize(result_batch))
print(finalize(result_batch1))

And it is indeed faster:

import timeit
x = random.sample(range(1, 10000), 1000)
# ...
b = random.sample(range(1, 10000), 1000)

start_time = timeit.default_timer()
result_batch = update(a, b)
print(f'{timeit.default_timer() - start_time:.4f}')
print(*(f'{x:.2f}' for x in finalize(result_batch)))

start_time = timeit.default_timer()
for i in b:
    a  = update1(a, i)
print(f'{timeit.default_timer() - start_time:.4f}')
print(*(f'{x:.2f}' for x in finalize(result_batch)))

Result:

0.0010
5008.36 8423224.68 8427438.40
0.0031
5008.36 8423224.68 8427438.40


问:
Does all releases of Durandal.js support responsive website development
I want to use Durandal.js to make single page responsive webapp. Can I use any version of Durandal.js or should I use some specific version?

答:
Durandal is a SPA (or a large website that's dynamic in nature). Sites build using Durandal are responsive in their speed but not directly responsive to different browsers, resolutions and devices. This is handled by our friends at Bootstrap.

If you are making just one page advert for your company, use Bootstrap. If you're making a large application with many forms, questions and layouts, use Aurelia. Aurelia is a new shift on Durnadal that's using the latest design practices.

https://aurelia.io/home

https://en.wikipedia.org/wiki/Responsive_web_design

https://getbootstrap.com/docs/4.3/getting-started/introduction/


问:
How can I instantiate a lambda closure type in C++11/14?
I'm aware that there's no default constructor for lambda closure type. But does that mean it's impossible to instantiate it after it being passed as a template parameter?

Consider the following minimal example:

```<code>#include <iostream>

template <typename FuncType>
std::pair<int,int> DoSomething() {
    return FuncType()(std::make_pair(1,1));
}

int main() {
    auto myLambda = [](std::pair<int,int> x) {
        return std::make_pair(x.first*2,x.second*2);
    };
    std::pair<int,int> res = DoSomething<decltype(myLambda)>();
    return 0;
}
</code>```

For performance reasons, I can't use std::function to avoid virtual pointer calls. Is there a way to do this? I need to instantiate that lambda once and use it many times inside that function.

How does the standard library make it work when decltype(myLambda) is passed to something like std::map comparators in the template parameter?

答:
Although this feature is coming in C++20 (see songyuanyao's answer), you don't actually need that in this case. You can just pass the lambda as a function parameter of type FuncType and call that multiple times:

```<code>template <typename FuncType>
std::pair<int,int> DoSomething(FuncType f)
{
    return f(std::make_pair(1,1));
}

int main()
{
    auto myLambda = [](std::pair<int,int> x) {
        return std::make_pair(x.first*2,x.second*2);
    };
    std::pair<int,int> res = DoSomething(myLambda);
}
</code>```

Body:
I'm aware that there's no default constructor for lambda closure type. But does that mean it's impossible to instantiate it after it being passed as a template parameter?

Consider the following minimal example:

#include <iostream>

template <typename FuncType>
std::pair<int,int> DoSomething() {
    return FuncType()(std::make_pair(1,1));
}

int main() {
    auto myLambda = [](std::pair<int,int> x) {
        return std::make_pair(x.first*2,x.second*2);
    };
    std::pair<int,int> res = DoSomething<decltype(myLambda)>();
    return 0;
}

For performance reasons, I can't use std::function to avoid virtual pointer calls. Is there a way to do this? I need to instantiate that lambda once and use it many times inside that function.

How does the standard library make it work when decltype(myLambda) is passed to something like std::map comparators in the template parameter?

Body:
Although this feature is coming in C++20 (see songyuanyao's answer), you don't actually need that in this case. You can just pass the lambda as a function parameter of type FuncType and call that multiple times:

template <typename FuncType>
std::pair<int,int> DoSomething(FuncType f)
{
    return f(std::make_pair(1,1));
}

int main()
{
    auto myLambda = [](std::pair<int,int> x) {
        return std::make_pair(x.first*2,x.second*2);
    };
    std::pair<int,int> res = DoSomething(myLambda);
}


问:
How to split a large Excel file into multiple small files in SSIS?
I want to read an Excel file which is 250 Mb large and has more than 300 000 rows. So when I try to process it in Excel source in SSIS it takes too much time and at last fails to process. Can anyone tell me how to split the big file into small ones or any other method that can help?</p>

答:
Best way is to read data by chunks, i have done this to read huge tables from SQL databases. But to read big excel files, i implemented this in a C# application not in SSIS since it is more complicated. I will provide some links for more info:

Reading Huge volume of data from Sqlite to SQL Server fails at pre-execute (SQLite)

SSIS failing to save packages and reboots Visual Studio (Oracle)

Optimizing SSIS package for millions of rows with Order by / sort in SQL command and Merge Join (MySQL)

Getting top n to n rows from db2 (DB2)

OutOfMemoryException while trying to read big Excel file into DataTable (Excel C#)

If you need to do this only using SSIS, i can provide a detailed answer later similar to what i provided in the first link above (SQLite).

SchemaMapper: C# schema mapping class library

Recently i started a new project on Git-Hub, which is a class library developed using C#. You can use it to import tabular data from excel, word , powerpoint, text, csv, html, json and xml into SQL server table with a different schema definition using schema mapping approach. It gives the ability to import big excel files. check it out at:

SchemaMapper: C# Schema mapping class library

You can follow this Wiki page for a step-by-step guide:

Import data from multiple files into one SQL table step by step guide


问:
Pass an additional counter as parameter to a callback
I have a $("").load call to get data and dump it into several divs. Each div has a unique ID that I track with an index variable inside a For loop. I do several ajax calls inside this loop. In the call back function I want to use the value of this index again. However by the time the callback executes, the for loop is already finished the index variable always has the top limit value for the loop.

How can I pass the value to this index to the callback function?

EDIT:

```<code>for (var i=1;i<=daysNum;i++)
{

    var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + i);

    var tmd=(tomorrow.getMonth()+1)+'/'+(tomorrow.getDate())+'/'+tomorrow.getFullYear();
    var tmdurl=(tomorrow.getMonth()+1)+'%2F'+(tomorrow.getDate())+'%2F'+tomorrow.getFullYear();

    $("#events").append("<div><div id='event"+i+"'></div><div id='date"+i+"'>"+tmd+"</div></div>");
    $("#event"+i).load(seicalendarurl+"/calendar.aspx?CalendarDate="+tmdurl+"&CalendarPeriod=Day .ms-cal-tdayitem, .ms-cal-alldayevent"

        ,  function (data){
             if($("event"+i).html()=="")
                $("date"+i).html("");

           }
    );

}
</code>```

答: You can pass the div unique index as either the div ID, the div's.data() or even in the metadata plugin. Another option is using closures.

Body:
I have a $("").load call to get data and dump it into several divs. Each div has a unique ID that I track with an index variable inside a For loop. I do several ajax calls inside this loop. In the call back function I want to use the value of this index again. However by the time the callback executes, the for loop is already finished the index variable always has the top limit value for the loop.

How can I pass the value to this index to the callback function?

EDIT:

for (var i=1;i<=daysNum;i++)
{

    var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + i);

    var tmd=(tomorrow.getMonth()+1)+'/'+(tomorrow.getDate())+'/'+tomorrow.getFullYear();
    var tmdurl=(tomorrow.getMonth()+1)+'%2F'+(tomorrow.getDate())+'%2F'+tomorrow.getFullYear();

    $("#events").append("

"+tmd+"

");
    $("#event"+i).load(seicalendarurl+"/calendar.aspx?CalendarDate="+tmdurl+"&CalendarPeriod=Day .ms-cal-tdayitem, .ms-cal-alldayevent"

        ,  function (data){
             if($("event"+i).html()=="")
                $("date"+i).html("");

           }
    );

}


问:
NotificationCompat.PRIORITY_DEFAULT doesn't make sound on older OS versions
I don't specify any sound (resource), I want to use the default sound

It works fine on Android 8 and 9

But on Android 4-7 it triggers notification without sound

How can I make the same behavior on all Android?

Notificaiton builder:

```<code>NotificationCompat.Builder(this, channelId)
    .setSmallIcon(R.drawable.notify_icon
    .setContentTitle(title)
    .setContentText(subtitle)
    .setPriority(if (Prefs.isNotificationSound) NotificationCompat.PRIORITY_DEFAULT else NotificationCompat.PRIORITY_LOW)
    .setCategory(NotificationCompat.CATEGORY_PROMO)
    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
    .setAutoCancel(true)
</code>```

答: Have you tried to use .setDefaults(Notification.DEFAULT_SOUND) ?

Body:
I don't specify any sound (resource), I want to use the default sound

It works fine on Android 8 and 9

But on Android 4-7 it triggers notification without sound

How can I make the same behavior on all Android?

Notificaiton builder:

NotificationCompat.Builder(this, channelId)
    .setSmallIcon(R.drawable.notify_icon
    .setContentTitle(title)
    .setContentText(subtitle)
    .setPriority(if (Prefs.isNotificationSound) NotificationCompat.PRIORITY_DEFAULT else NotificationCompat.PRIORITY_LOW)
    .setCategory(NotificationCompat.CATEGORY_PROMO)
    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
    .setAutoCancel(true)


问:
Graphics over a picturebox aren't showing and if they are they flicker before disappearing
I'm working on a windows forms application and when I'm using the System.Drawing.Graphics on top of a picturebox the graphics either don't appear or appear only momentarily before disappearing.

This is the code that I'm using to set the picturebox (it's a simplified version and still exhibits the behavior)

```<code>private void showGraphic()
{
    pictureBox1.Invalidate();
    System.Drawing.Graphics graphics = this.pictureBox1.CreateGraphics();
    SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(128, 0, 0, 255));
    System.Drawing.Rectangle rect = new System.Drawing.Rectangle(100,100, 50, 50);

    graphics.FillEllipse(semiTransBrush, rect);
}

private void button1_Click(object sender, EventArgs e)
{
    showGraphic();
}
</code>```

The settings for the picturebox are just the default settings with a picture from a file declared in the properties pane.

I was able to solve this problem by using a timer which was started by the button and then executed the graphic drawing before stopping itself, however this seemed a terrible solution and I wanted to do this a better way, if one exists as that could result in lack of portability to older computers.

Thanks in advance

答:
To make this (old and answered) question more complete I'm adding an alternative solution: sometimes you don't want to redraw your picture every refresh, for example if drawing is complicated and takes time. For these cases, you can try the following approach:

Create a new bitmap in the size of the picturebox.

Draw on bitmap.

Set bitmap as the picturebox Image.

For example:

```<code>// create a new bitmap and create graphics from it
var bitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height);
var graphics = System.Drawing.Graphics.FromImage(bitmap);

// draw on bitmap
SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(128, 0, 0, 255));
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(100,100, 50, 50);
graphics.FillEllipse(semiTransBrush, rect);

// set bitmap as the picturebox's image
pictureBox1.Image = bitmap;
</code>```

With the code above you can draw everything once and it will survive redraw events.

Body:
I'm working on a windows forms application and when I'm using the System.Drawing.Graphics on top of a picturebox the graphics either don't appear or appear only momentarily before disappearing.

This is the code that I'm using to set the picturebox (it's a simplified version and still exhibits the behavior)

private void showGraphic()
{
    pictureBox1.Invalidate();
    System.Drawing.Graphics graphics = this.pictureBox1.CreateGraphics();
    SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(128, 0, 0, 255));
    System.Drawing.Rectangle rect = new System.Drawing.Rectangle(100,100, 50, 50);

    graphics.FillEllipse(semiTransBrush, rect);
}

private void button1_Click(object sender, EventArgs e)
{
    showGraphic();
}

The settings for the picturebox are just the default settings with a picture from a file declared in the properties pane.

I was able to solve this problem by using a timer which was started by the button and then executed the graphic drawing before stopping itself, however this seemed a terrible solution and I wanted to do this a better way, if one exists as that could result in lack of portability to older computers.

Thanks in advance

Body:
To make this (old and answered) question more complete I'm adding an alternative solution: sometimes you don't want to redraw your picture every refresh, for example if drawing is complicated and takes time. For these cases, you can try the following approach:

Create a new bitmap in the size of the picturebox.

Draw on bitmap.

Set bitmap as the picturebox Image.

For example:

// create a new bitmap and create graphics from it
var bitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height);
var graphics = System.Drawing.Graphics.FromImage(bitmap);

// draw on bitmap
SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(128, 0, 0, 255));
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(100,100, 50, 50);
graphics.FillEllipse(semiTransBrush, rect);

// set bitmap as the picturebox's image
pictureBox1.Image = bitmap;

With the code above you can draw everything once and it will survive redraw events.


问:
How can I make Tomcat accept unescaped brackets in URLs?
I've never used Tomcat before, but I've recently inherited a JSP project and now I need to get it running. I've managed to install Tomcat 8.0 locally in Eclipse and everything works fine. I've also installed Tomcat 8.0 on an Ubuntu VPS. The app is running fine, except for a small issue with how it handles URLs.

The client-side application produces URLs with unescaped square and curly brackets in parameters, like this:

```<code>GET /saveItems.json?items=[{%22json%22:%22here%22}]
</code>```

As much as I would like to change the client-side app, I can't. I just need to get this backend running.

My local copy of the application handles this fine. On the server, however, I get this error:

```<code>java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
    at org.apache.coyote.http11.AbstractNioInputBuffer.parseRequestLine(AbstractNioInputBuffer.java:286)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1504)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1460)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
</code>```

I've been looking for a setting that might affect this, without any luck. What am I missing here?

答:
I was experiencing a similar problem, but using Spring boot too, the following solution resolved my issue:

```<code>@Bean
public ConfigurableServletWebServerFactory webServerFactory() {
    TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
    factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
        @Override
        public void customize(Connector connector) {
            connector.setProperty("relaxedQueryChars", "|{}[]");
        }
    });
return factory;
}
</code>```

Credited to Matthias-lohr - https://stackoverflow.com/questions/46251131/invalid-character-found-in-the-request-target-in-spring-boot

Body:
I've never used Tomcat before, but I've recently inherited a JSP project and now I need to get it running. I've managed to install Tomcat 8.0 locally in Eclipse and everything works fine. I've also installed Tomcat 8.0 on an Ubuntu VPS. The app is running fine, except for a small issue with how it handles URLs.

The client-side application produces URLs with unescaped square and curly brackets in parameters, like this:

GET /saveItems.json?items=[{%22json%22:%22here%22}]

As much as I would like to change the client-side app, I can't. I just need to get this backend running.

My local copy of the application handles this fine. On the server, however, I get this error:

java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
    at org.apache.coyote.http11.AbstractNioInputBuffer.parseRequestLine(AbstractNioInputBuffer.java:286)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1504)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1460)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

I've been looking for a setting that might affect this, without any luck. What am I missing here?

Body:
I was experiencing a similar problem, but using Spring boot too, the following solution resolved my issue:

@Bean
public ConfigurableServletWebServerFactory webServerFactory() {
    TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
    factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
        @Override
        public void customize(Connector connector) {
            connector.setProperty("relaxedQueryChars", "|{}[]");
        }
    });
return factory;
}

Credited to Matthias-lohr - https://stackoverflow.com/questions/46251131/invalid-character-found-in-the-request-target-in-spring-boot


问:
Django does not find Pillow though installed
Django struggles to find Pillow and I'm not quite sure why.

Environment

Linux Alpine based Docker image, Django 2.2. Here are the relevant parts of:

The Dockerfile

```<code>RUN apk update \
    && apk add --virtual build-deps gcc python3-dev musl-dev jpeg-dev zlib-dev \
    && apk add --no-cache mariadb-dev mariadb-client

# install dependencies
RUN pip install --upgrade pip
RUN pip install pipenv
RUN pip install mysqlclient
COPY ./Pipfile /usr/src/cms/Pipfile
RUN pipenv install --skip-lock --system --dev
RUN apk del build-deps
</code>```

The Pipfile

```<code>[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]

[packages]
django = "==2.2"
markdown = "==3.1.1"
pillow = "==5.0.0"

[requires]
python_version = "3.6"
</code>```

The issue

When I run python manage.py runserver 0.0.0.0:8000 from the container, I get the following error:

```<code>django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:

ERRORS:
website.Photo.photo: (fields.E210) Cannot use ImageField because Pillow is not installed.
    HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow".
</code>```

which is weird because pip install Pillow gives me

```<code>Requirement already satisfied: Pillow in /usr/local/lib/python3.7/site-packages (5.4.1)
</code>```

About Pillow's conflict with PIL

While having a look at /usr/local/lib/python3.7/site-packages, I noticed that I had both PIL and Pillow. Is this:

the source of a conflict (Pillow's documentation) is quite specific about the need to uninstall PIL

pillow's use of the very name PIL to maintain compatibility as suggested in this discussion?

From the facts that i) pip uninstall PIL -> not installed ii) print(PIL.PILLOW_VERSION) -> 5.0.0 in python's shell and that iii) Django uses from PIL import Image source, I would go for hypotheses 2. So if Pillow is installed in the container, why does not Django find it?

Current path

```<code>>>> from PIL import Image
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python3.7/site-packages/PIL/Image.py", line 58, in <module>
    from . import _imaging as core
ImportError: Error loading shared library libjpeg.so.8: No such file or directory (needed by /usr/local/lib/python3.7/site-packages/PIL/_imaging.cpython-37m-x86_64-linux-gnu.so)
</code>```

I added jpeg-dev to the Dockerfile but, somehow, it does not seem to be enough. Still digging. Thanks for any clue

答:
Turns out, jpeg-dev (required by the compilation) was not enough to satisfy all dependencies during execution. Adding libjpeg solved the issue. Updated Dockerfile

```<code># install mysqlclient
RUN apk update \
    && apk add --virtual build-deps gcc python3-dev musl-dev jpeg-dev zlib-dev \
    && apk add --no-cache mariadb-dev mariadb-client

# install dependencies
RUN pip install --upgrade pip
RUN pip install pipenv
RUN pip install mysqlclient
RUN apk add libjpeg      -------------> et voila
COPY ./Pipfile /usr/src/cms/Pipfile
RUN pipenv install --skip-lock --system --dev
RUN apk del build-deps
</code>```

Body:
Django struggles to find Pillow and I'm not quite sure why.

Environment

Linux Alpine based Docker image, Django 2.2. Here are the relevant parts of:

The Dockerfile

RUN apk update \
    && apk add --virtual build-deps gcc python3-dev musl-dev jpeg-dev zlib-dev \
    && apk add --no-cache mariadb-dev mariadb-client

# install dependencies
RUN pip install --upgrade pip
RUN pip install pipenv
RUN pip install mysqlclient
COPY ./Pipfile /usr/src/cms/Pipfile
RUN pipenv install --skip-lock --system --dev
RUN apk del build-deps

The Pipfile

[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]

[packages]
django = "==2.2"
markdown = "==3.1.1"
pillow = "==5.0.0"

[requires]
python_version = "3.6"

The issue

When I run python manage.py runserver 0.0.0.0:8000 from the container, I get the following error:

django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:

ERRORS:
website.Photo.photo: (fields.E210) Cannot use ImageField because Pillow is not installed.
    HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow".

which is weird because pip install Pillow gives me

Requirement already satisfied: Pillow in /usr/local/lib/python3.7/site-packages (5.4.1)

About Pillow's conflict with PIL

While having a look at /usr/local/lib/python3.7/site-packages, I noticed that I had both PIL and Pillow. Is this:

the source of a conflict (Pillow's documentation) is quite specific about the need to uninstall PIL

pillow's use of the very name PIL to maintain compatibility as suggested in this discussion?

From the facts that i) pip uninstall PIL -> not installed ii) print(PIL.PILLOW_VERSION) -> 5.0.0 in python's shell and that iii) Django uses from PIL import Image source, I would go for hypotheses 2. So if Pillow is installed in the container, why does not Django find it?

Current path

>>> from PIL import Image
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python3.7/site-packages/PIL/Image.py", line 58, in <module>
    from . import _imaging as core
ImportError: Error loading shared library libjpeg.so.8: No such file or directory (needed by /usr/local/lib/python3.7/site-packages/PIL/_imaging.cpython-37m-x86_64-linux-gnu.so)

I added jpeg-dev to the Dockerfile but, somehow, it does not seem to be enough. Still digging. Thanks for any clue

Body:
Turns out, jpeg-dev (required by the compilation) was not enough to satisfy all dependencies during execution. Adding libjpeg solved the issue. Updated Dockerfile

# install mysqlclient
RUN apk update \
    && apk add --virtual build-deps gcc python3-dev musl-dev jpeg-dev zlib-dev \
    && apk add --no-cache mariadb-dev mariadb-client

# install dependencies
RUN pip install --upgrade pip
RUN pip install pipenv
RUN pip install mysqlclient
RUN apk add libjpeg      -------------> et voila
COPY ./Pipfile /usr/src/cms/Pipfile
RUN pipenv install --skip-lock --system --dev
RUN apk del build-deps


问:
The variables I updated in my forEach, return to their original value
I am trying to query, that would get all of the earning and withdrawal amount and sum, but somehow after the forEach loop is done and exits, all of the updated values I placed in a variable return to their original values.</p>

```<code>  var withdrawbalance = 0;
  var totalearning = 0;

  userplans.forEach((up) => {
    DepositEarning.findOne({deposit: up.deposit._id})
      .then(depositearning => {
        withdrawbalance += parseInt(depositearning.WithdrawableBalance, 10);
      });
    Earning.findOne({deposit: up.deposit._id})
      .then(earnings => {
        totalearning += parseInt(earnings.Earning, 10);
    });
  })

  console.log(withdrawbalance);
  console.log(totalearning);
</code>```

答: forEach is asynchronous. So the console.log runs before your mutation loop. You can make it synchronous by using map, but even then - you have asynchronous calls inside it. You will need to flatten it further - probably by doing Promise.all on a map, then reducing the output of that.

Body:
I am trying to query, that would get all of the earning and withdrawal amount and sum, but somehow after the forEach loop is done and exits, all of the updated values I placed in a variable return to their original values.

  var withdrawbalance = 0;
  var totalearning = 0;

  userplans.forEach((up) => {
    DepositEarning.findOne({deposit: up.deposit._id})
      .then(depositearning => {
        withdrawbalance += parseInt(depositearning.WithdrawableBalance, 10);
      });
    Earning.findOne({deposit: up.deposit._id})
      .then(earnings => {
        totalearning += parseInt(earnings.Earning, 10);
    });
  })

  console.log(withdrawbalance);
  console.log(totalearning);


问:
Get message ID in Azure queue
Is there a way to get the message ID after insert it in a queue Azure ?</p>

```<code>CloudStorageAccount storageAccount =
    CloudStorageAccount.parse(storageConnectionString);

CloudQueueClient queueClient = storageAccount.createCloudQueueClient();

CloudQueue queue = queueClient.getQueueReference("myqueue");

queue.createIfNotExist();

CloudQueueMessage message = new CloudQueueMessage("Hello, World");
queue.addMessage(message);

// Get message ID here ?
</code>```

答:
I realize it has been 5 years since this was originally asked; however, it is now possible to achieve this.</p>

```<code>CloudQueueMessage message = new CloudQueueMessage("Hello, World");
queue.AddMessage(message);

// here's how you get the id
string id = message.Id;
</code>```

Title: Get message ID in Azure queue

Body:
Is there a way to get the message ID after insert it in a queue Azure ?

CloudStorageAccount storageAccount =
    CloudStorageAccount.parse(storageConnectionString);

CloudQueueClient queueClient = storageAccount.createCloudQueueClient();

CloudQueue queue = queueClient.getQueueReference("myqueue");

queue.createIfNotExist();

CloudQueueMessage message = new CloudQueueMessage("Hello, World");
queue.addMessage(message);

// Get message ID here ?

Body:
I realize it has been 5 years since this was originally asked; however, it is now possible to achieve this.

CloudQueueMessage message = new CloudQueueMessage("Hello, World");
queue.AddMessage(message);

// here's how you get the id
string id = message.Id;


问:
MaxListenersExceededWarning occurs when promise.all is used in while loop
I am using promise in while loop. When about 50 promises is executed, MaxListenersExceededWarning warning start to alert. So I wonder what relation is between EventEmitter and Promise. and How to fix my code to avoid this warning.

I tried to decrease number of items in contentList. and when number is lower than fifty there is no warning. but when number is over fifty, it start to warn.

```<code>async (req, res, next) => {
    let repository = new ContentRep();

    let contentList = (await repository.getContentList({category: 'allContent'})).contentList;

    while (contentList.length > 0) {
        let taskSize = contentList.length > 5 ? 5 : contentList.length;
        let subList = contentList.slice(0, taskSize);
        contentList = contentList.slice(taskSize, contentList.length);
        let contentPromises = [];

        subList.forEach(row => {
            contentPromises.push(new Promise(resolve => {
                repository.getTemplateInfo(row.category, row.content)
                    .then(templateInfo => {
                        resolve(templateInfo);
                    });
            }));

        })

        await Promise.all(contentPromises);
    }
    return contentList;
}
</code>```

error code

```<code>(node:63176) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit
</code>```

答:
This warning commonly occurs because of memory leakage and internal errors.
Increase the limit of maximum events that you can register will remove the warning

Add this code to your main file

```<code>require('events').EventEmitter.prototype._maxListeners = 100;
</code>```

Body:
I am using promise in while loop. When about 50 promises is executed, MaxListenersExceededWarning warning start to alert. So I wonder what relation is between EventEmitter and Promise. and How to fix my code to avoid this warning.

I tried to decrease number of items in contentList. and when number is lower than fifty there is no warning. but when number is over fifty, it start to warn.

async (req, res, next) => {
    let repository = new ContentRep();

    let contentList = (await repository.getContentList({category: 'allContent'})).contentList;

    while (contentList.length > 0) {
        let taskSize = contentList.length > 5 ? 5 : contentList.length;
        let subList = contentList.slice(0, taskSize);
        contentList = contentList.slice(taskSize, contentList.length);
        let contentPromises = [];

        subList.forEach(row => {
            contentPromises.push(new Promise(resolve => {
                repository.getTemplateInfo(row.category, row.content)
                    .then(templateInfo => {
                        resolve(templateInfo);
                    });
            }));

        })

        await Promise.all(contentPromises);
    }
    return contentList;
}

error code

(node:63176) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit

Body:
This warning commonly occurs because of memory leakage and internal errors.
Increase the limit of maximum events that you can register will remove the warning

Add this code to your main file

require('events').EventEmitter.prototype._maxListeners = 100;


问:
How to stop mysqld
To find out the start command for mysqld (using a mac) I can do:

```<code>ps aux|grep mysql
</code>```

I get the following output, which allows me to start mysql server.

```<code>/usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=...
</code>```

How would I find the necessary command to stop mysql from the command line?

答:
Try killing mysqld four times in a row.  It's the only thing that worked for me...

```<code>root@ubuntu:/etc/init# killall -KILL mysqld
root@ubuntu:/etc/init# killall -KILL mysqld
root@ubuntu:/etc/init# killall -KILL mysqld
root@ubuntu:/etc/init# killall -KILL mysqld
mysqld: no process found
</code>```

Just keep killing it over and over until you see "mysqld: no process found".

Title: How to stop mysqld

Body:
To find out the start command for mysqld (using a mac) I can do:

ps aux|grep mysql

I get the following output, which allows me to start mysql server.

/usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=...

How would I find the necessary command to stop mysql from the command line?

Body:
Try killing mysqld four times in a row.  It's the only thing that worked for me...

root@ubuntu:/etc/init# killall -KILL mysqld
root@ubuntu:/etc/init# killall -KILL mysqld
root@ubuntu:/etc/init# killall -KILL mysqld
root@ubuntu:/etc/init# killall -KILL mysqld
mysqld: no process found

Just keep killing it over and over until you see "mysqld: no process found".


问:
Calculate relative frequencies of factor levels in dataset
Let this be my data:

```<code>my.data<-data.frame(name=c("a","b","b","c","c","c"))
</code>```

What I need is a variable that indicates for each name, their respective relative frequency in the dataset. Essentially, this would look like that:

```<code>  name    target
1    a 0.1666667
2    b 0.3333333
3    b 0.3333333
4    c 0.5000000
5    c 0.5000000
6    c 0.5000000
</code>```

What I tried is that I computed dummy variables for each name, and then based on these dummies I calculated new variables that indicate the relative frequency of each name in the dataset. See below:

```<code>temp_dummies<-data.frame(spatstat::dummify(my.data$name))
my.data<-cbind.data.frame(my.data, temp_dummies)
rm(temp_dummies)

my.data %>%
  dplyr::mutate(a_per=mean(a),
                b_per=mean(b),
                c_per=mean(c)) -> my.data
</code>```

Now I need to extract the relative frequencies for each name and aggregate it back to get my target variable. I guess I should do something like this below but I don't know what to mutate.

```<code>my.data %>%
  dplyr::group_by(name) %>%
  dplyr::mutate(...) -> my.data
</code>```

Questions:

How would I get my target variable using dplyr? Am I on the right track?

Is there an easier way to achive the same result?

Might it be possible to write a function that does all of this stuff automatically? It seems like a pretty standard problem that we should be able to fix by simply applying a function(x) to name.

答:
We can use add_count to get count of each name and then divide it by number of rows using n().

```<code>library(dplyr)

my.data %>%
   add_count(name) %>%
   mutate(n = n/n())

#  name      n
#  <fct> <dbl>
#1 a     0.167
#2 b     0.333
#3 b     0.333
#4 c     0.5
#5 c     0.5
#6 c     0.5
</code>```

Body:
Let this be my data:

my.data<-data.frame(name=c("a","b","b","c","c","c"))

What I need is a variable that indicates for each name, their respective relative frequency in the dataset. Essentially, this would look like that:

  name    target
1    a 0.1666667
2    b 0.3333333
3    b 0.3333333
4    c 0.5000000
5    c 0.5000000
6    c 0.5000000

What I tried is that I computed dummy variables for each name, and then based on these dummies I calculated new variables that indicate the relative frequency of each name in the dataset. See below:

temp_dummies<-data.frame(spatstat::dummify(my.data$name))
my.data<-cbind.data.frame(my.data, temp_dummies)
rm(temp_dummies)

my.data %>%
  dplyr::mutate(a_per=mean(a),
                b_per=mean(b),
                c_per=mean(c)) -> my.data

Now I need to extract the relative frequencies for each name and aggregate it back to get my target variable. I guess I should do something like this below but I don't know what to mutate.

my.data %>%
  dplyr::group_by(name) %>%
  dplyr::mutate(...) -> my.data

Questions:

How would I get my target variable using dplyr? Am I on the right track?

Is there an easier way to achive the same result?

Might it be possible to write a function that does all of this stuff automatically? It seems like a pretty standard problem that we should be able to fix by simply applying a function(x) to name.

Body:
We can use add_count to get count of each name and then divide it by number of rows using n().

library(dplyr)

my.data %>%
   add_count(name) %>%
   mutate(n = n/n())

#  name      n
#  <fct> <dbl>
#1 a     0.167
#2 b     0.333
#3 b     0.333
#4 c     0.5
#5 c     0.5
#6 c     0.5


问:
Make a phrase column out of columns with value of 1 in Pandas Dataframe
Let's say I have this dataset, I want to create a phrase column that adds a word for each column with value of 1...

```<code>    SINNOUVEAU  PERTETOTAL  CHANGGARAN  SOCLOCATIO  SINISAMEDI  NOMASCONDU  SINIREPET
0            1           0           0           0           0           1          0
1            0           1           0           0           0           1          0
2            0           0           1           0           0           1          0
</code>```

This is the dataframe for the phrase values for each column if set to 1:

```<code>          col                  phr
0  SINNOUVEAU     sinistre nouveau
1  PERTETOTAL         perte totale
2  CHANGGARAN  changement garantie
3  SOCLOCATIO     societe location
4  SINISAMEDI               samedi
5  NOMASCONDU        nom different
6   SINIREPET   sinistre repetitif
</code>```

So, for the dataframe above, this is the result I expect:

```<code>    SINNOUVEAU  PERTETOTAL  CHANGGARAN  SOCLOCATIO  SINISAMEDI  NOMASCONDU  SINIREPET  Phrase
0            1           0           0           0           0           1          0  sinistre nouveau, nom different
1            0           1           0           0           0           1          0  perte totale, nom different
2            0           0           1           0           0           1          0  changement garantie, nom different
</code>```

答:
IIUC</p>

```<code>s=df.dot(df.columns.map(df1.set_index('col').phr)+',').str[:-1]
s
0       sinistrenouveau,nomdifferent
1           pertetotale,nomdifferent
2    changementgarantie,nomdifferent
dtype: object
df['Phr']=s
</code>```

Body:
Let's say I have this dataset, I want to create a phrase column that adds a word for each column with value of 1...

    SINNOUVEAU  PERTETOTAL  CHANGGARAN  SOCLOCATIO  SINISAMEDI  NOMASCONDU  SINIREPET
0            1           0           0           0           0           1          0
1            0           1           0           0           0           1          0
2            0           0           1           0           0           1          0

This is the dataframe for the phrase values for each column if set to 1:

          col                  phr
0  SINNOUVEAU     sinistre nouveau
1  PERTETOTAL         perte totale
2  CHANGGARAN  changement garantie
3  SOCLOCATIO     societe location
4  SINISAMEDI               samedi
5  NOMASCONDU        nom different
6   SINIREPET   sinistre repetitif

So, for the dataframe above, this is the result I expect:

    SINNOUVEAU  PERTETOTAL  CHANGGARAN  SOCLOCATIO  SINISAMEDI  NOMASCONDU  SINIREPET  Phrase
0            1           0           0           0           0           1          0  sinistre nouveau, nom different
1            0           1           0           0           0           1          0  perte totale, nom different
2            0           0           1           0           0           1          0  changement garantie, nom different

Body:
IIUC

s=df.dot(df.columns.map(df1.set_index('col').phr)+',').str[:-1]
s
0       sinistrenouveau,nomdifferent
1           pertetotale,nomdifferent
2    changementgarantie,nomdifferent
dtype: object
df['Phr']=s


问:
Where to save GoogleService-Info.plist in Flutter without Xcode?
I have my app already submited, reviewed and online in Google Play & iTunes, but recently I added the firebase_messaging plugin for notification feature.

While joining the Firebase Cloud Messaging, Google forced me to download two files:

google-services.json - Saved in the folder of my flutter App: MyApp\android\app

GoogleService-Info.plist - I don't know where to save it, but tried on MyApp\ios\Runner and MyApp\ios\Runner.xcodeworkspace without success

And all the tutorials point to the use of Xcode to set the file GoogleService-Info.plist properly, but I do not own a Mac and I've been using with success the windows application AppUploader to submit my iOS apps.

Is there any way to not use the Xcode and be able to attach the GoogleService-Info.plist to my project?

答:
Somewhere along the line, AppUploader must be using XCode to build an iOS app from your code. While I don't know how they do that (their documentation is scarce on details), the best you can hope for is to put the google-services-info.plist in the right place before uploading the app.

In my projects I always put the google-services-info.plist in the myappname/ios/Runner directory that the Flutter tooling auto-generates. That's where the build then picks it up from.


问:
HTML5 video not playing in Opera
Having some issues with this website...

All the browsers play HTML5 video but Opera. It played before, but I can't see anything that would affect it in the recent update I did...

Any ideas?

答:
Solution ...</p>

```<code>sudo ln -sf /usr/lib/chromium-browser/libffmpeg.so /usr/lib/x86_64-linux-gnu/opera/libffmpeg.so
</code>```

Title: HTML5 video not playing in Opera

Body:
Solution ...

sudo ln -sf /usr/lib/chromium-browser/libffmpeg.so /usr/lib/x86_64-linux-gnu/opera/libffmpeg.so


问:
PHP Downloaded file is 0 bytes in firefox puzzle
I've been running this test on my website for days now and it still baffles me.

I have a zip file on my server. Within the zip file is a single text file that contains the phrase "this is a test".

In my file api.php, I have the following code:

```<code><?php

$originalFileName = "test.zip";

header("content-encoding: none");
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=\"" . "test.zip" . "\"");
header("Content-Length: " . filesize($originalFileName));

readfile($originalFileName);

?>
</code>```

When I visit the api.php file in firefox. It prompts to download "test.zip" with a file size of 128 bytes.

When I click save. It creates the file on my desktop, but the file is 0 bytes in size and is empty.

If I visit the url using the direct IP address i.e. http://192.0.0.1/api.php

It downloads the zip file and contains the text file as its suppose to.

The domain is under cloudflare with the caching disabled and developer mode on so it shouldn't be that different.

I used firefox's dev tools to copy the responses from the domain request and the ip request

Domain request - This makes the 0 byte empty zip file

```<code>HTTP/1.1 200 OK
Date: Sat, 01 Jun 2019 10:15:22 GMT
content-disposition: attachment; filename="test.zip"
Content-Length: 128
Content-Type: application/zip
content-encoding: none
Connection: keep-alive
X-Powered-By: PHP/7.2.16
Vary: User-Agent
Alt-Svc: h2=":443"; ma=60
CF-RAY: 4e006d0d4e615629-ORD
Server: cloudflare

UEsDBBQAAAAAADEcwU7q5x4NDgAAAA4AAAAIAAAAdGVzdC50eHR0aGlzIGlzIGEgdGVzdFBLAQIUABQAAAAAADEcwU7q5x4NDgAAAA4AAAAIAAAAAAAAAAEAIAAAAAAAAAB0ZXN0LnR4dFBLBQYAAAAAAQABADYAAAA0AAAAAAA=
</code>```

Direct IP request - This makes the 128 byte zip file

```<code>HTTP/1.1 200 OK
Date: Sat, 01 Jun 2019 10:15:57 GMT
content-disposition: attachment; filename="test.zip"
content-length: 128
Content-Type: application/zip
content-encoding: none
Connection: Upgrade, Keep-Alive
X-Powered-By: PHP/7.2.16
Upgrade: h2,h2c
Vary: User-Agent
Keep-Alive: timeout=5
Server: Apache

UEsDBBQAAAAAADEcwU7q5x4NDgAAAA4AAAAIAAAAdGVzdC50eHR0aGlzIGlzIGEgdGVzdFBLAQIUABQAAAAAADEcwU7q5x4NDgAAAA4AAAAIAAAAAAAAAAEAIAAAAAAAAAB0ZXN0LnR4dFBLBQYAAAAAAQABADYAAAA0AAAAAAA=
</code>```

Both the response payloads are identical and besides a few tiny changes in the response headers.

Such as the letter casing and the cloudflare headers.

I don't see any reason why the zip file should be 0 bytes when trying to save the download prompt through the domain.

When I press ctrl+j to view the download history.
It looks fine for the direct ip download on the bottom and a weird message for the top domain one.

Does anyone have any suggestions on how to solve this?

答:
I tested your issue, maybe changing some headers this may solve the question, with my headers I can see the zip file downloaded and opening it's fine... let's me know if with my code your question is solved...

```<code><?php
  $file = basename("test.zip");
  $downloads_folder = "./";
  header('Content-Description: File Transfer');
  header('Content-Type: application/octet-stream');
  header('Content-Disposition: attachment; filename="' . $file . '"');
  header('Content-Transfer-Encoding: binary');
  header('Connection: Keep-Alive');
  header('Expires: 0');
  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  header('Pragma: public');
  header('Content-Length: ' . sprintf("%u", filesize($downloads_folder . $file)));
  // Open and output file contents
  set_time_limit(0);
  $fh = fopen($downloads_folder . $file, "rb");
  while (!feof($fh)) {
    echo fgets($fh);
    ob_flush();
    flush();
  }
  fclose($fh);
  exit;
?>
</code>```

EDIT: I discovered that the fault is due to HTTP/2, if you have a paid account you can disable it (source). Using my code and disabling HTTP/2 you should solve your issue or you can use SSL to solve this issue, seems that HTTP/2 without SSL is causing this issue...

You can read other threads that have the same Topic:

https://community.cloudflare.com/t/files-can-not-be-downloaded/5598

https://community.cloudflare.com/t/downloads-are-failing-timing-out/7588

https://community.cloudflare.com/t/file-download-from-website-failing/81700

https://community.cloudflare.com/t/unexpected-connection-errors/4366

Finally the assumption of fault:

https://blog.cloudflare.com/the-curious-case-of-slow-downloads/

I hope this helps.

Body:
I've been running this test on my website for days now and it still baffles me.

I have a zip file on my server. Within the zip file is a single text file that contains the phrase "this is a test".

In my file api.php, I have the following code:

<?php

$originalFileName = "test.zip";

header("content-encoding: none");
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=\"" . "test.zip" . "\"");
header("Content-Length: " . filesize($originalFileName));

readfile($originalFileName);

?>

When I visit the api.php file in firefox. It prompts to download "test.zip" with a file size of 128 bytes.

When I click save. It creates the file on my desktop, but the file is 0 bytes in size and is empty.

If I visit the url using the direct IP address i.e. http://192.0.0.1/api.php

It downloads the zip file and contains the text file as its suppose to.

The domain is under cloudflare with the caching disabled and developer mode on so it shouldn't be that different.

I used firefox's dev tools to copy the responses from the domain request and the ip request

Domain request - This makes the 0 byte empty zip file

HTTP/1.1 200 OK
Date: Sat, 01 Jun 2019 10:15:22 GMT
content-disposition: attachment; filename="test.zip"
Content-Length: 128
Content-Type: application/zip
content-encoding: none
Connection: keep-alive
X-Powered-By: PHP/7.2.16
Vary: User-Agent
Alt-Svc: h2=":443"; ma=60
CF-RAY: 4e006d0d4e615629-ORD
Server: cloudflare

UEsDBBQAAAAAADEcwU7q5x4NDgAAAA4AAAAIAAAAdGVzdC50eHR0aGlzIGlzIGEgdGVzdFBLAQIUABQAAAAAADEcwU7q5x4NDgAAAA4AAAAIAAAAAAAAAAEAIAAAAAAAAAB0ZXN0LnR4dFBLBQYAAAAAAQABADYAAAA0AAAAAAA=

Direct IP request - This makes the 128 byte zip file

HTTP/1.1 200 OK
Date: Sat, 01 Jun 2019 10:15:57 GMT
content-disposition: attachment; filename="test.zip"
content-length: 128
Content-Type: application/zip
content-encoding: none
Connection: Upgrade, Keep-Alive
X-Powered-By: PHP/7.2.16
Upgrade: h2,h2c
Vary: User-Agent
Keep-Alive: timeout=5
Server: Apache

UEsDBBQAAAAAADEcwU7q5x4NDgAAAA4AAAAIAAAAdGVzdC50eHR0aGlzIGlzIGEgdGVzdFBLAQIUABQAAAAAADEcwU7q5x4NDgAAAA4AAAAIAAAAAAAAAAEAIAAAAAAAAAB0ZXN0LnR4dFBLBQYAAAAAAQABADYAAAA0AAAAAAA=

Both the response payloads are identical and besides a few tiny changes in the response headers.

Such as the letter casing and the cloudflare headers.

I don't see any reason why the zip file should be 0 bytes when trying to save the download prompt through the domain.

When I press ctrl+j to view the download history.
It looks fine for the direct ip download on the bottom and a weird message for the top domain one.

Does anyone have any suggestions on how to solve this?

Body:
I tested your issue, maybe changing some headers this may solve the question, with my headers I can see the zip file downloaded and opening it's fine... let's me know if with my code your question is solved...

<?php
  $file = basename("test.zip");
  $downloads_folder = "./";
  header('Content-Description: File Transfer');
  header('Content-Type: application/octet-stream');
  header('Content-Disposition: attachment; filename="' . $file . '"');
  header('Content-Transfer-Encoding: binary');
  header('Connection: Keep-Alive');
  header('Expires: 0');
  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  header('Pragma: public');
  header('Content-Length: ' . sprintf("%u", filesize($downloads_folder . $file)));
  // Open and output file contents
  set_time_limit(0);
  $fh = fopen($downloads_folder . $file, "rb");
  while (!feof($fh)) {
    echo fgets($fh);
    ob_flush();
    flush();
  }
  fclose($fh);
  exit;
?>

EDIT: I discovered that the fault is due to HTTP/2, if you have a paid account you can disable it (source). Using my code and disabling HTTP/2 you should solve your issue or you can use SSL to solve this issue, seems that HTTP/2 without SSL is causing this issue...

You can read other threads that have the same Topic:

https://community.cloudflare.com/t/files-can-not-be-downloaded/5598

https://community.cloudflare.com/t/downloads-are-failing-timing-out/7588

https://community.cloudflare.com/t/file-download-from-website-failing/81700

https://community.cloudflare.com/t/unexpected-connection-errors/4366

Finally the assumption of fault:

https://blog.cloudflare.com/the-curious-case-of-slow-downloads/

I hope this helps.


问:
Importing a single function from a module in VB.Net
I was wondering if I can import a single function like python without importing all the other things like python does:</p>

```<code>from prog1 import func
</code>```

答:
In VB you need to do two things to able to use a function or anything else declared in another assembly or namespace.

Add a reference to the assembly (*.dll, *.exe).

Import the namespace. E.g. Imports System.Drawing.

Then you can use all the things in there.

Instead of using an Imports statement you can also specify the namespace directly. Example:

```<code>'Without Imports
Dim image As System.Drawing.Image
image = New System.Drawing.Bitmap(myImagefile)
</code>```

With Imports System.Drawing at the top of the code:

```<code>Dim image As Image
image = New Bitmap(myImagefile)
</code>```

The most important assemblies are already referenced and the most often used namespaces imported implicitly. These namespaces are list in the project properties under References.

Note that you cannot import single functions, you always have to reference a whole assembly. The Imports does not influence the resources used. It only makes it handier to access things. They reduce typing.

Note also, that the standard .NET libraries of the .NET Framework are installed on the system and are already compiled. They are not imported physically into your project, they are only referenced. I.e., using them does not make your application bigger.

Body:
I was wondering if I can import a single function like python without importing all the other things like python does:

from prog1 import func

Body:
In VB you need to do two things to able to use a function or anything else declared in another assembly or namespace.

Add a reference to the assembly (*.dll, *.exe).

Import the namespace. E.g. Imports System.Drawing.

Then you can use all the things in there.

Instead of using an Imports statement you can also specify the namespace directly. Example:

'Without Imports
Dim image As System.Drawing.Image
image = New System.Drawing.Bitmap(myImagefile)

With Imports System.Drawing at the top of the code:

Dim image As Image
image = New Bitmap(myImagefile)

The most important assemblies are already referenced and the most often used namespaces imported implicitly. These namespaces are list in the project properties under References.

Note that you cannot import single functions, you always have to reference a whole assembly. The Imports does not influence the resources used. It only makes it handier to access things. They reduce typing.

Note also, that the standard .NET libraries of the .NET Framework are installed on the system and are already compiled. They are not imported physically into your project, they are only referenced. I.e., using them does not make your application bigger.


问:
Error in making jar file: "No configuration setting found for key 'akka.remote.artery'"
I wrote a Flink program to parse streaming data. I can run it without any problem. But when I make a jar file of that, the jar file is not run.
To make jar file, I follow this path:

```<code> Flile ---> Project Structure ---> Artifacts ---> jar ---> From modules with dependencies
</code>```

I change the directory for META-INF to resources. After that I build the artifact. The jar file is built; even though, I can not run it. When I want to run it, I receive this error:

Exception in thread "main" java.lang.Exception: Could not create actor system
      at org.apache.flink.runtime.clusterframework.BootstrapTools.startActorSystem(BootstrapTools.java:276)
      at org.apache.flink.runtime.clusterframework.BootstrapTools.startActorSystem(BootstrapTools.java:162)
      at org.apache.flink.runtime.metrics.util.MetricUtils.startMetricsActorSystem(MetricUtils.java:126)
      at org.apache.flink.runtime.minicluster.MiniCluster.start(MiniCluster.java:260)
      at org.apache.flink.streaming.api.environment.LocalStreamEnvironment.execute(LocalStreamEnvironment.java:120)
      at org.apache.flink.streaming.api.environment.StreamExecutionEnvironment.execute(StreamExecutionEnvironment.java:1510)
      at PooyaCo.App.main(App.java:38)

Caused by: com.typesafe.config.ConfigException$Missing: No configuration setting found for key 'akka.remote.artery'

The strange things is that I follow above steps to make jar file for helloworld program and the jar file is run without any issues. I think the problem is because of flink dependencies.

Would you please guide me to solve the issue?

Any help would be very much appreciated.

答: Yes, getting this setup correctly is non-trivial. Your best bet is to follow the quickstart guide in the documentation -- https://ci.apache.org/projects/flink/flink-docs-release-1.8/dev/projectsetup/java_api_quickstart.html -- which shows how to do this with both maven and gradle.</p>

Body:
I wrote a Flink program to parse streaming data. I can run it without any problem. But when I make a jar file of that, the jar file is not run.
To make jar file, I follow this path:

 Flile ---> Project Structure ---> Artifacts ---> jar ---> From modules with dependencies

I change the directory for META-INF to resources. After that I build the artifact. The jar file is built; even though, I can not run it. When I want to run it, I receive this error:

Exception in thread "main" java.lang.Exception: Could not create actor system
      at org.apache.flink.runtime.clusterframework.BootstrapTools.startActorSystem(BootstrapTools.java:276)
      at org.apache.flink.runtime.clusterframework.BootstrapTools.startActorSystem(BootstrapTools.java:162)
      at org.apache.flink.runtime.metrics.util.MetricUtils.startMetricsActorSystem(MetricUtils.java:126)
      at org.apache.flink.runtime.minicluster.MiniCluster.start(MiniCluster.java:260)
      at org.apache.flink.streaming.api.environment.LocalStreamEnvironment.execute(LocalStreamEnvironment.java:120)
      at org.apache.flink.streaming.api.environment.StreamExecutionEnvironment.execute(StreamExecutionEnvironment.java:1510)
      at PooyaCo.App.main(App.java:38)

Caused by: com.typesafe.config.ConfigException$Missing: No configuration setting found for key 'akka.remote.artery'

The strange things is that I follow above steps to make jar file for helloworld program and the jar file is run without any issues. I think the problem is because of flink dependencies.

Would you please guide me to solve the issue?

Any help would be very much appreciated.