问:
How do I get a full path to a node js file if its not known
The issue
I have an array of files which are as follows

```<code>[video.mp4, image.jgpeg, hello.png]
</code>```

my issue is trying to find the complete path to every file, I have looked at other answers, most of them point me to use

```<code>path.dirname(fileName)
</code>```

using the path module from Node JS, however I only get a relative and not the complete path to the file

Path Returned

```<code>/folder/video.mp4
</code>```

Path Needed

```<code>/folder/subdirectory/video.mp4
</code>```

I need to be able to see the full path including the directory its actually in and not just the relative path to it, if anyone can help me out it will be much appreciated!

Note I am not trying to find out if the path of the file exists, I am trying to find the actual path, this is not a duplicate of

How to check if a file (given by full path) exists? node js

答:
Give the glob package a try. (link)

Get all the files in your directory, and check if your file is in there. If it is, you'll have your full path as well.

You can find how to recursively get all the files in a directory using Glob here:

https://stackoverflow.com/a/41462807/11568997

Body:
The issue
I have an array of files which are as follows

[video.mp4, image.jgpeg, hello.png]

my issue is trying to find the complete path to every file, I have looked at other answers, most of them point me to use

path.dirname(fileName)

using the path module from Node JS, however I only get a relative and not the complete path to the file

Path Returned

/folder/video.mp4

Path Needed

/folder/subdirectory/video.mp4

I need to be able to see the full path including the directory its actually in and not just the relative path to it, if anyone can help me out it will be much appreciated!

Note I am not trying to find out if the path of the file exists, I am trying to find the actual path, this is not a duplicate of

How to check if a file (given by full path) exists? node js


来源: stackexchange

问:
How can I read (from disk) and resize an image, in Flutter/Dart
In Flutter/Dart, how can I perform the following 3 steps:

Read an image from disk,

Read its original dimensions (width and height),

Resize it.

Note: I must be able to display the final result with a regular Flutter Image widget.

CLARIFICATION: I don't want to save the image, but I do want to actually resize it in memory.

答:
Here's an example Thumbnail widget which does this on the flight

It uses Isolate to offload CPU-intensive work to background thread and have UI thread jank-free

import 'dart:io';
import 'dart:isolate';
import 'package:flutter/material.dart';
import 'package:image/image.dart' as IMG;
import 'package:path/path.dart';

class Thumbnail extends StatefulWidget {
  final Size size;
  final File image;

  const Thumbnail({Key key, this.size, this.image}) : super(key: key);
  @override
  _ThumbnailState createState() => _ThumbnailState();
}

class _ThumbnailState extends State<Thumbnail> {
  List<int> imgBytes;
  Isolate isolate;

  @override
  void initState() {
    _asyncInit();

    super.initState();
  }

  static _isolateEntry(dynamic d) async {
    final ReceivePort receivePort = ReceivePort();
    d.send(receivePort.sendPort);

    final config = await receivePort.first;

    print(config);

    final file = File(config['path']);
    final bytes = await file.readAsBytes();

    IMG.Image image = IMG.decodeImage(bytes);
    IMG.Image thumbnail = IMG.copyResize(
      image,
      width: config['size'].width.toInt(),
    );

    d.send(IMG.encodeNamedImage(thumbnail, basename(config['path'])));
  }

  _asyncInit() async {
    final ReceivePort receivePort = ReceivePort();
    isolate = await Isolate.spawn(_isolateEntry, receivePort.sendPort);

    receivePort.listen((dynamic data) {
      if (data is SendPort) {
        if (mounted) {
          data.send({
            'path': widget.image.path,
            'size': widget.size,
          });
        }
      } else {
        if (mounted) {
          setState(() {
            imgBytes = data;
          });
        }
      }
    });
  }

  @override
  void dispose() {
    if (isolate != null) {
      isolate.kill();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: widget.size.height,
      width: widget.size.width,
      child: imgBytes != null
          ? Image.memory(
              imgBytes,
              fit: BoxFit.cover,
            )
          : Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Colors.grey[100], Colors.grey[300]],
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                ),
              ),
            ),
    );
  }
}
```

ContentLicense: CC BY-SA 4.0


问:
Hitting a nullPointerExecption in my android project
Hi Iam trying to make a chat app. In this process Iam trying to retrieve messages stored in database but Iam getting a Null Object reference exception.

The code I used to add messages to database is:

```<code>    img_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String msg = text_send.getText().toString();
            if(!msg.equals(""))
                sendMessage(fuser.getUid(), currUserId, msg);
            else
                Toast.makeText(MessageActivity.this, "Enter Something",
            Toast.LENGTH_SHORT).show();
         }
       });

  private void sendMessage(String sender,String receiver,String message)
  {
    DatabaseReference reference =
    FirebaseDatabase.getInstance().getReference();
    HashMap<String,Object>hashMap = new HashMap<>();
    hashMap.put("sender",sender);
    hashMap.put("receiver",receiver);
    hashMap.put("message",message);

    reference.child("Chats").push().setValue(hashMap);

}
</code>```

NOTE:The above part of code is working fine. My database is getting updated correctly every time I send message.

After this part I tried to display messages of users, using the following code

```<code>     DatabaseReference chatref =
     FirebaseDatabase.getInstance().getReference().child("Chats");
     ArrayList<String> userchats = new ArrayList<>();

     listView = findViewById(R.id.listView);
     final ArrayAdapter <String> arrayAdapter = new ArrayAdapter<String>
     (this,android.R.layout.simple_list_item_1,userchats);
     listView.setAdapter(arrayAdapter);

     chatref.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot,
        @Nullable String s) {

            String value = dataSnapshot.getValue().toString();
            try {
                JSONObject object = new JSONObject(value);
                message = object.getString("message");
            }
            catch (JSONException e) {
                e.printStackTrace();
            }
            userchats.add(message);
            arrayAdapter.notifyDataSetChanged();
        }

        @Override
        public void onChildChanged(@NonNull DataSnapshot dataSnapshot,
         @Nullable String s) {

        }

        @Override
        public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(@NonNull DataSnapshot dataSnapshot,
        @Nullable String s) {

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
        });
</code>```

When I ran the app at this moment Iam getting error and my stacktrace is as follows:

```<code>         Process: com.kcw.firebasebasics, PID: 10943
         java.lang.NullPointerException: Attempt to invoke virtual method
         'java.lang.String java.lang.Object.toString()' on a null object
         reference at android.widget.ArrayAdapter.
         createViewFromResource(ArrayAdapter.java:401)
         at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369)
         at android.widget.AbsListView.obtainView(AbsListView.java:2346)
         at android.widget.ListView.makeAndAddView(ListView.java:1875)
</code>```

Finally a picture of my database:

答:
Change this:

```<code>String value = dataSnapshot.getValue().toString();
</code>```

into this:

```<code>String value = dataSnapshot.child("message").getValue(String.class);
</code>```

Body:
Hi Iam trying to make a chat app. In this process Iam trying to retrieve messages stored in database but Iam getting a Null Object reference exception.

The code I used to add messages to database is:

    img_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String msg = text_send.getText().toString();
            if(!msg.equals(""))
                sendMessage(fuser.getUid(), currUserId, msg);
            else
                Toast.makeText(MessageActivity.this, "Enter Something",
            Toast.LENGTH_SHORT).show();
         }
       });

  private void sendMessage(String sender,String receiver,String message)
  {
    DatabaseReference reference =
    FirebaseDatabase.getInstance().getReference();
    HashMap<String,Object>hashMap = new HashMap<>();
    hashMap.put("sender",sender);
    hashMap.put("receiver",receiver);
    hashMap.put("message",message);

    reference.child("Chats").push().setValue(hashMap);

}

NOTE:The above part of code is working fine. My database is getting updated correctly every time I send message.

After this part I tried to display messages of users, using the following code

     DatabaseReference chatref =
     FirebaseDatabase.getInstance().getReference().child("Chats");
     ArrayList<String> userchats = new ArrayList<>();

     listView = findViewById(R.id.listView);
     final ArrayAdapter <String> arrayAdapter = new ArrayAdapter<String>
     (this,android.R.layout.simple_list_item_1,userchats);
     listView.setAdapter(arrayAdapter);

     chatref.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot,
        @Nullable String s) {

            String value = dataSnapshot.getValue().toString();
            try {
                JSONObject object = new JSONObject(value);
                message = object.getString("message");
            }
            catch (JSONException e) {
                e.printStackTrace();
            }
            userchats.add(message);
            arrayAdapter.notifyDataSetChanged();
        }

        @Override
        public void onChildChanged(@NonNull DataSnapshot dataSnapshot,
         @Nullable String s) {

        }

        @Override
        public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(@NonNull DataSnapshot dataSnapshot,
        @Nullable String s) {

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
        });

When I ran the app at this moment Iam getting error and my stacktrace is as follows:

         Process: com.kcw.firebasebasics, PID: 10943
         java.lang.NullPointerException: Attempt to invoke virtual method
         'java.lang.String java.lang.Object.toString()' on a null object
         reference at android.widget.ArrayAdapter.
         createViewFromResource(ArrayAdapter.java:401)
         at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369)
         at android.widget.AbsListView.obtainView(AbsListView.java:2346)
         at android.widget.ListView.makeAndAddView(ListView.java:1875)

Finally a picture of my database:

Body:
Change this:

String value = dataSnapshot.getValue().toString();

into this:

String value = dataSnapshot.child("message").getValue(String.class);


问:
Starting OpenShift cluster never ends when starting minishift or takes to much memory
Whenever I run the command to start Minishift with the virtualbox driver to the OS host it takes a crazy time and it never ends. Sometimes I even get an error message on storage limit being reached.

I wonder if it is an error of Persistent storage volume configuration and usage that is described here

```<code>mike@mike-thinks:~$ minishift start --vm-driver=virtualbox
-- Starting profile 'minishift'
-- Check if depereccated options are used ... OK
-- Checking if https://github.com is reachable ... OK
-- Checking if requested OpenShift version 'v3.9.0' is valid ... OK
-- Checking if requested OpenShift version 'v3.9.0' is supported ... OK
-- Checking if requested hypervisor 'virtualbox' is supported on this platform ... OK
-- Checking if VirtualBox is installed ... OK
-- Checking the ISO URL ... OK
-- Checking if provided oc flags are supported ... OK
-- Starting local OpenShift cluster using 'virtualbox' hypervisor ...
-- Starting Minishift VM ........................ OK
-- Checking for IP address ... OK
-- Checking for nameservers ... OK
-- Checking if external host is reachable from the Minishift VM ...
   Pinging 8.8.8.8 ... OK
-- Checking HTTP connectivity from the VM ...
   Retrieving http://minishift.io/index.html ... OK
-- Checking if persistent storage volume is mounted ... OK
-- Checking available disk space ... 8% used OK
-- OpenShift cluster will be configured with ...
   Version: v3.9.0
-- Copying oc binary from the OpenShift container image to VM .... OK
-- Starting OpenShift cluster ..............................................
</code>```

What I can do ? I'm following this tutorial and I just want to get to the stage that allows me to add oc to the PATH

Update: new error during openshift cluster start

```<code>-- Starting OpenShift cluster ...........Error during 'cluster up' execution: Error starting the cluster. ssh command error:
command : /var/lib/minishift/bin/oc cluster up --use-existing-config --host-volumes-dir /var/lib/minishift/openshift.local.volumes --host-pv-dir /var/lib/minishift/openshift.local.pv --host-config-dir /var/lib/minishift/openshift.local.config --host-data-dir /var/lib/minishift/hostdata --public-hostname 192.168.99.100 --routing-suffix 192.168.99.100.nip.io
err     : exit status 1
output  : Deleted existing OpenShift container
Using nsenter mounter for OpenShift volumes
Using public hostname IP 192.168.99.100 as the host IP
Using 192.168.99.100 as the server IP
Starting OpenShift using openshift/origin:v3.9.0 ...
-- Starting OpenShift container ...
   Starting OpenShift using container 'origin'
   Waiting for API server to start listening
FAIL
   Error: cannot access master readiness URL https://192.168.99.100:8443/healthz/ready
   Details:
     Last 10 lines of "origin" container log:
     E0625 14:47:40.905680    2341 proxier.go:252] Error removing userspace rule: error checking rule: fork/exec /usr/sbin/iptables: exec format error:
     E0625 14:47:40.908353    2341 proxier.go:259] Error removing userspace rule: error checking rule: fork/exec /usr/sbin/iptables: exec format error:
     E0625 14:47:40.910681    2341 proxier.go:274] Error flushing userspace chain: error flushing chain "KUBE-PORTALS-CONTAINER": fork/exec /usr/sbin/iptables: exec format error:
     E0625 14:47:40.913452    2341 proxier.go:274] Error flushing userspace chain: error flushing chain "KUBE-PORTALS-HOST": fork/exec /usr/sbin/iptables: exec format error:
     E0625 14:47:40.919209    2341 proxier.go:274] Error flushing userspace chain: error flushing chain "KUBE-NODEPORT-HOST": fork/exec /usr/sbin/iptables: exec format error:
     W0625 14:47:40.931698    2341 cni.go:171] Unable to update cni config: No networks found in /etc/cni/net.d
     E0625 14:47:40.932412    2341 proxier.go:274] Error flushing userspace chain: error flushing chain "KUBE-NODEPORT-CONTAINER": fork/exec /usr/sbin/iptables: exec format error:
     E0625 14:47:40.938345    2341 proxier.go:274] Error flushing userspace chain: error flushing chain "KUBE-NODEPORT-NON-LOCAL": fork/exec /usr/sbin/iptables: exec format error:
     W0625 14:47:40.941639    2341 iptables.go:151] Error checking iptables version, assuming version at least 1.4.11: fork/exec /usr/sbin/iptables: exec format error
     F0625 14:47:40.949329    2341 network.go:177] error: Could not initialize Kubernetes Proxy. You must run this process as root (and if containerized, in the host network namespace as privileged) to use the service proxy: failed to initialize iptables: error creating chain "KUBE-PORTALS-CONTAINER": fork/exec /usr/sbin/iptables: exec format error:

   Caused By:
     Error: Get https://192.168.99.100:8443/healthz/ready: dial tcp 192.168.99.100:8443: getsockopt: connection refused
</code>```

答:
If this should anyhow help, the first time it did not finish for me at all too. However the image was in a state "running" in VirtualBox.

The second time I run it via elevated command prompt - and it finalized successfully. But perhaps running inside elevated user did not help, but the fact that I run it the second time.

Body:
Whenever I run the command to start Minishift with the virtualbox driver to the OS host it takes a crazy time and it never ends. Sometimes I even get an error message on storage limit being reached.

I wonder if it is an error of Persistent storage volume configuration and usage that is described here

mike@mike-thinks:~$ minishift start --vm-driver=virtualbox
-- Starting profile 'minishift'
-- Check if depereccated options are used ... OK
-- Checking if https://github.com is reachable ... OK
-- Checking if requested OpenShift version 'v3.9.0' is valid ... OK
-- Checking if requested OpenShift version 'v3.9.0' is supported ... OK
-- Checking if requested hypervisor 'virtualbox' is supported on this platform ... OK
-- Checking if VirtualBox is installed ... OK
-- Checking the ISO URL ... OK
-- Checking if provided oc flags are supported ... OK
-- Starting local OpenShift cluster using 'virtualbox' hypervisor ...
-- Starting Minishift VM ........................ OK
-- Checking for IP address ... OK
-- Checking for nameservers ... OK
-- Checking if external host is reachable from the Minishift VM ...
   Pinging 8.8.8.8 ... OK
-- Checking HTTP connectivity from the VM ...
   Retrieving http://minishift.io/index.html ... OK
-- Checking if persistent storage volume is mounted ... OK
-- Checking available disk space ... 8% used OK
-- OpenShift cluster will be configured with ...
   Version: v3.9.0
-- Copying oc binary from the OpenShift container image to VM .... OK
-- Starting OpenShift cluster ..............................................

What I can do ? I'm following this tutorial and I just want to get to the stage that allows me to add oc to the PATH

Update: new error during openshift cluster start

-- Starting OpenShift cluster ...........Error during 'cluster up' execution: Error starting the cluster. ssh command error:
command : /var/lib/minishift/bin/oc cluster up --use-existing-config --host-volumes-dir /var/lib/minishift/openshift.local.volumes --host-pv-dir /var/lib/minishift/openshift.local.pv --host-config-dir /var/lib/minishift/openshift.local.config --host-data-dir /var/lib/minishift/hostdata --public-hostname 192.168.99.100 --routing-suffix 192.168.99.100.nip.io
err     : exit status 1
output  : Deleted existing OpenShift container
Using nsenter mounter for OpenShift volumes
Using public hostname IP 192.168.99.100 as the host IP
Using 192.168.99.100 as the server IP
Starting OpenShift using openshift/origin:v3.9.0 ...
-- Starting OpenShift container ...
   Starting OpenShift using container 'origin'
   Waiting for API server to start listening
FAIL
   Error: cannot access master readiness URL https://192.168.99.100:8443/healthz/ready
   Details:
     Last 10 lines of "origin" container log:
     E0625 14:47:40.905680    2341 proxier.go:252] Error removing userspace rule: error checking rule: fork/exec /usr/sbin/iptables: exec format error:
     E0625 14:47:40.908353    2341 proxier.go:259] Error removing userspace rule: error checking rule: fork/exec /usr/sbin/iptables: exec format error:
     E0625 14:47:40.910681    2341 proxier.go:274] Error flushing userspace chain: error flushing chain "KUBE-PORTALS-CONTAINER": fork/exec /usr/sbin/iptables: exec format error:
     E0625 14:47:40.913452    2341 proxier.go:274] Error flushing userspace chain: error flushing chain "KUBE-PORTALS-HOST": fork/exec /usr/sbin/iptables: exec format error:
     E0625 14:47:40.919209    2341 proxier.go:274] Error flushing userspace chain: error flushing chain "KUBE-NODEPORT-HOST": fork/exec /usr/sbin/iptables: exec format error:
     W0625 14:47:40.931698    2341 cni.go:171] Unable to update cni config: No networks found in /etc/cni/net.d
     E0625 14:47:40.932412    2341 proxier.go:274] Error flushing userspace chain: error flushing chain "KUBE-NODEPORT-CONTAINER": fork/exec /usr/sbin/iptables: exec format error:
     E0625 14:47:40.938345    2341 proxier.go:274] Error flushing userspace chain: error flushing chain "KUBE-NODEPORT-NON-LOCAL": fork/exec /usr/sbin/iptables: exec format error:
     W0625 14:47:40.941639    2341 iptables.go:151] Error checking iptables version, assuming version at least 1.4.11: fork/exec /usr/sbin/iptables: exec format error
     F0625 14:47:40.949329    2341 network.go:177] error: Could not initialize Kubernetes Proxy. You must run this process as root (and if containerized, in the host network namespace as privileged) to use the service proxy: failed to initialize iptables: error creating chain "KUBE-PORTALS-CONTAINER": fork/exec /usr/sbin/iptables: exec format error:

   Caused By:
     Error: Get https://192.168.99.100:8443/healthz/ready: dial tcp 192.168.99.100:8443: getsockopt: connection refused


问:
foreach not assigning value to variable after mysql query
I'm attempting to create a PHP function that will allow me to convert a user_id to username from my MySQL database (as the assignment i'm working on requires this to be done a lot so i'd rather just call a function to quickly do this instead of repeating myself)

The issue i'm having is I can't assign the value returned from my query to a variable which is causing an undefined variable error.

The function is being called from a different .php script so I need the value to be returned. The user_id is passed along as a parameter when the function is called.

I've attempted already declaring the variable before the query and assigning the value during the foreach loop but I cannot get the values to save and return.

```<code>//Convert user_id to Username
function usernameConvert($userid)
{
    //Connection to DB
    include '../dbconnect.php';

    $results = $pdo->prepare('SELECT username FROM users WHERE
    user_id="$userid"');
    $results -> execute();

    foreach ($results as $row)
    {
        $username = $row["username"];
    }

    //comes back undefined
    return $username;
}
</code>```

The main error i'm getting is it's an undefined variable.

Thanks in advance.

答:
You can't directly use variables within string with single quotes ':

```<code>$foo = 'bar';
echo "hello $foo"; // hello bar
echo 'hello $foo'; // hello $foo
</code>```

Which lead to your query searching for a user id equalling the string $suserid, as there is no possible result, your foreach loop runs 0 laps and $username is never defined.

But using double quotes " would make your query vulnerable to SQL injection. You are already using a prepared statement but in a wrong way.

Working solution with named parameters:

```<code>$results = $pdo->prepare('SELECT username FROM users WHERE user_id = :id');
$results->bindParam(':id', $userid, PDO::PARAM_INT);
$results->execute();
</code>```

See PDOStatement::bindParam().

You also forgot to use fetch() (not fetchAll() as you're searching a username based on a primary key. As a primary key is unique, you can only get 1 row maximum. Therefore, no need for a loop):

```<code>$results->execute();

$username = $results->fetch();

return $username;
</code>```

Body:
I'm attempting to create a PHP function that will allow me to convert a user_id to username from my MySQL database (as the assignment i'm working on requires this to be done a lot so i'd rather just call a function to quickly do this instead of repeating myself)

The issue i'm having is I can't assign the value returned from my query to a variable which is causing an undefined variable error.

The function is being called from a different .php script so I need the value to be returned. The user_id is passed along as a parameter when the function is called.

I've attempted already declaring the variable before the query and assigning the value during the foreach loop but I cannot get the values to save and return.

//Convert user_id to Username
function usernameConvert($userid)
{
    //Connection to DB
    include '../dbconnect.php';

    $results = $pdo->prepare('SELECT username FROM users WHERE
    user_id="$userid"');
    $results -> execute();

    foreach ($results as $row)
    {
        $username = $row["username"];
    }

    //comes back undefined
    return $username;
}

The main error i'm getting is it's an undefined variable.

Thanks in advance.

Body:
You can't directly use variables within string with single quotes ':

$foo = 'bar';
echo "hello $foo"; // hello bar
echo 'hello $foo'; // hello $foo

Which lead to your query searching for a user id equalling the string $suserid, as there is no possible result, your foreach loop runs 0 laps and $username is never defined.

But using double quotes " would make your query vulnerable to SQL injection. You are already using a prepared statement but in a wrong way.

Working solution with named parameters:

$results = $pdo->prepare('SELECT username FROM users WHERE user_id = :id');
$results->bindParam(':id', $userid, PDO::PARAM_INT);
$results->execute();

See PDOStatement::bindParam().

You also forgot to use fetch() (not fetchAll() as you're searching a username based on a primary key. As a primary key is unique, you can only get 1 row maximum. Therefore, no need for a loop):

$results->execute();

$username = $results->fetch();

return $username;


问:
docker-compose "No such file or directory" for sh-command
I am setting up docker-for-windows on my private pc.

When I set it up a while ago on my office laptop I had the same issue but it just stopped happening.

So I am stuck with this:

I have a docker-working project (on my other computer) with a docker-compose.yml like this:

```<code>version: '2'

services:
  web:
    depends_on:
      - db
    build: .
    env_file: ./docker-compose.env
    command: bash ./run_web_local.sh
    volumes:
      - .:/srv/project
    ports:
      - 8001:8001
    links:
      - db
      - rabbit
    restart: always
</code>```

Dockerfile:

```<code>### STAGE 1: Build ###

# We label our stage as 'builder'
FROM node:8-alpine as builder

RUN npm set progress=false && npm config set depth 0 && npm cache clean --force

# build backend
ADD package.json /tmp/package.json
ADD package-lock.json /tmp/package-lock.json
RUN cd /tmp && npm install
RUN mkdir -p /backend-app && cp -a /tmp/node_modules /backend-app

### STAGE 2: Setup ###
FROM python:3

# Install Python dependencies
COPY requirements.txt /tmp/requirements.txt
RUN pip3 install -U pip
RUN pip3 install --no-cache-dir -r /tmp/requirements.txt

# Set env variables used in this Dockerfile (add a unique prefix, such as DOCKYARD)
# Local directory with project source
ENV PROJECT_SRC=.
# Directory in container for all project files
ENV PROJECT_SRVHOME=/srv
# Directory in container for project source files
ENV PROJECT_SRVPROJ=/srv/project

# Create application subdirectories
WORKDIR $PROJECT_SRVPROJ
RUN mkdir media static staticfiles logs

# make folders available for other containers
VOLUME ["$PROJECT_SRVHOME/media/", "$PROJECT_SRVHOME/logs/"]

# Copy application source code to SRCDIR
COPY $PROJECT_SRC $PROJECT_SRVPROJ

COPY --from=builder /backend-app/node_modules $PROJECT_SRVPROJ/node_modules

# Copy entrypoint script into the image
WORKDIR $PROJECT_SRVPROJ

# EXPOSE port 8000 to allow communication to/from server
EXPOSE 8000

CMD ["./run_web.sh"]
</code>```

docker-compose.env:

```<code>C_FORCE_ROOT=True
DJANGO_CELERY_BROKER_URL=amqp://admin:mypass@rabbit:5672//
DJANGO_DATABASE_ENGINE=django.db.backends.mysql
DJANGO_DATABASE_NAME=project-db
DJANGO_DATABASE_USER=project-user
DJANGO_DATABASE_PASSWORD=mypassword
DJANGO_DATABASE_HOST=db
DJANGO_ALLOWED_HOSTS=127.0.0.1,localhost
DJANGO_DEBUG=True
DJANGO_USE_DEBUG_TOOLBAR=off
DJANGO_TEST_RUN=off
PYTHONUNBUFFERED=0
</code>```

run_web_local.sh:

```<code>#!/bin/bash
echo django shell commands
python ./manage.py migrate
echo Starting django server on 127.0.0.1:8000
python ./manage.py runserver 127.0.0.1:8000
</code>```

When I call docker-compose up web I get the following error:

web_1          | bash: ./run_web_local.sh: No such file or directory

I checked the line endings, they are UNIX

the file exists on the file system as well as inside the container

I can call bash run_web_local.sh from my windows powershell and inside the container

I changed the UNIX permissions inside the container

I left out the bash in the command in the docker-compose command. And tried with backslash, no dot etc.

I reinstalled docker

I tried switching to version 3

docker claims to have a connection to my shared drive C

And: The exact same setup works on my other laptop.

Any ideas? All the two million github posts didn't solve the problem for me.

Thanks!

Update

Removing volumes: from the docker-compose makes it work like stated here but I don't have an instant mapping. That's kind of important for me...

答:
I had same issue recently and the problems goes away using any advanced editor and changing line ending to unix style on sh entrypoint scripts.

In my case, not sure why, because git handle it very well depending on linux or windows host I ended up in same situation.
If you have files mounted in container and host(in windows)
it dependes on how you edit them may be changed to linux from inside container but that affects outside windows host.
After that git stated file .sh changed but no additions no deletions.
a graphical compare tool showed up that only new line where changed.

Another workaround to trouble shooting you can start your container overriden entrypoint script by sh for example and then from there you can check on the started container how linux sees the entrypoint script, even  you can test it and will see exact same error.

Body:
I am setting up docker-for-windows on my private pc.

When I set it up a while ago on my office laptop I had the same issue but it just stopped happening.

So I am stuck with this:

I have a docker-working project (on my other computer) with a docker-compose.yml like this:

version: '2'

services:
  web:
    depends_on:
      - db
    build: .
    env_file: ./docker-compose.env
    command: bash ./run_web_local.sh
    volumes:
      - .:/srv/project
    ports:
      - 8001:8001
    links:
      - db
      - rabbit
    restart: always

Dockerfile:

### STAGE 1: Build ###

# We label our stage as 'builder'
FROM node:8-alpine as builder

RUN npm set progress=false && npm config set depth 0 && npm cache clean --force

# build backend
ADD package.json /tmp/package.json
ADD package-lock.json /tmp/package-lock.json
RUN cd /tmp && npm install
RUN mkdir -p /backend-app && cp -a /tmp/node_modules /backend-app

### STAGE 2: Setup ###
FROM python:3

# Install Python dependencies
COPY requirements.txt /tmp/requirements.txt
RUN pip3 install -U pip
RUN pip3 install --no-cache-dir -r /tmp/requirements.txt

# Set env variables used in this Dockerfile (add a unique prefix, such as DOCKYARD)
# Local directory with project source
ENV PROJECT_SRC=.
# Directory in container for all project files
ENV PROJECT_SRVHOME=/srv
# Directory in container for project source files
ENV PROJECT_SRVPROJ=/srv/project

# Create application subdirectories
WORKDIR $PROJECT_SRVPROJ
RUN mkdir media static staticfiles logs

# make folders available for other containers
VOLUME ["$PROJECT_SRVHOME/media/", "$PROJECT_SRVHOME/logs/"]

# Copy application source code to SRCDIR
COPY $PROJECT_SRC $PROJECT_SRVPROJ

COPY --from=builder /backend-app/node_modules $PROJECT_SRVPROJ/node_modules

# Copy entrypoint script into the image
WORKDIR $PROJECT_SRVPROJ

# EXPOSE port 8000 to allow communication to/from server
EXPOSE 8000

CMD ["./run_web.sh"]

docker-compose.env:

C_FORCE_ROOT=True
DJANGO_CELERY_BROKER_URL=amqp://admin:mypass@rabbit:5672//
DJANGO_DATABASE_ENGINE=django.db.backends.mysql
DJANGO_DATABASE_NAME=project-db
DJANGO_DATABASE_USER=project-user
DJANGO_DATABASE_PASSWORD=mypassword
DJANGO_DATABASE_HOST=db
DJANGO_ALLOWED_HOSTS=127.0.0.1,localhost
DJANGO_DEBUG=True
DJANGO_USE_DEBUG_TOOLBAR=off
DJANGO_TEST_RUN=off
PYTHONUNBUFFERED=0

run_web_local.sh:

#!/bin/bash
echo django shell commands
python ./manage.py migrate
echo Starting django server on 127.0.0.1:8000
python ./manage.py runserver 127.0.0.1:8000

When I call docker-compose up web I get the following error:

web_1          | bash: ./run_web_local.sh: No such file or directory

I checked the line endings, they are UNIX

the file exists on the file system as well as inside the container

I can call bash run_web_local.sh from my windows powershell and inside the container

I changed the UNIX permissions inside the container

I left out the bash in the command in the docker-compose command. And tried with backslash, no dot etc.

I reinstalled docker

I tried switching to version 3

docker claims to have a connection to my shared drive C

And: The exact same setup works on my other laptop.

Any ideas? All the two million github posts didn't solve the problem for me.

Thanks!

Update

Removing volumes: from the docker-compose makes it work like stated here but I don't have an instant mapping. That's kind of important for me...


问:
Why Excel Services does not keep pivot chart style when date changes?
I'm experiencing a problem with Excel Services and charts:

If in my excel pivot chart I use the default style, when publishing the excel to sharepoint all goes well. When I try to make some customization on the pivot chart (e.g. add data labels) they are kept unless the pivot data is updated adding a new row.

Specifically, I have pivot data with dates as rows and the filter is saved on "Today". When the day change, my chart style is lost (reverted to the default one).

Does anyone know about this odd behavior? Is there some setting in excel or Excel Service I'm missing?

Thanks

答: In client Excel, refreshing the pivot table often reverts formatting of the table and related chart to the default. Microsoft doesn't quite admit it's a bug, but suggests recording a macro when you reformat your chart, so you can rerun the macro. I suppose this doesn't help in Excel Services.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Truncate text in flex item
I have a header with a left and right side. The left side contains some text which I want to keep on a single line, truncating with ellipsis if needed. However, when I apply white-space: nowrap to it then the whole header goes outside its container. Here's what I mean:

.container {
  width: 300px;
  height: 400px;
  border: 1px solid black;
}

.header {
  height: 80px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 1px solid red;
}

.header-right,
.header-left {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid blue;
}

.title {
  text-overflow: ellipsis;
  white-space: nowrap;
}

img {
  height: 20px;
  width: 20px;
  margin: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="header">
    <div class="header-left">
      <img src="https://image.flaticon.com/icons/png/128/181/181548.png">
      <span class="title">Title: Keep me on a single line</span>
    </div>
    <div class="header-right">
      <img src="https://image.flaticon.com/icons/png/128/181/181548.png">
      <img src="https://image.flaticon.com/icons/png/128/181/181548.png">
      <img src="https://image.flaticon.com/icons/png/128/181/181548.png">
    </div>
  </div>
</div></code>```

Does anyone know how to keep the title on a single line but truncate it so the header doesn't go outside the bounds?

答:
You need to disable the default minimun width by adding min-width:0 and disable the shriking for the images and their container by adding flex-shrink:0; and add overflow:hidden

.container {
  width: 300px;
  height: 400px;
  border: 1px solid black;
}

.header {
  height: 80px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 1px solid red;
}

.header-right,
.header-left {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid blue;
  min-width:0; /* Added */
}

.title {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow:hidden; /* Added */
}

img {
  height: 20px;
  width: 20px;
  margin: 10px;
  flex-shrink:0; /* Added */
}

.header-right {
  flex-shrink:0; /* Added */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="header">
    <div class="header-left">
      <img src="https://image.flaticon.com/icons/png/128/181/181548.png">
      <span class="title">Title: Keep me on a single line</span>
    </div>
    <div class="header-right">
      <img src="https://image.flaticon.com/icons/png/128/181/181548.png">
      <img src="https://image.flaticon.com/icons/png/128/181/181548.png">
      <img src="https://image.flaticon.com/icons/png/128/181/181548.png">
    </div>
  </div>
</div></code>```

Related:

Why don't flex items shrink past content size? (To understand the min-width)

Why is a flex-child limited to parent size? (To understand the flex-shrink)

Title: Truncate text in flex item

Body:
I have a header with a left and right side. The left side contains some text which I want to keep on a single line, truncating with ellipsis if needed. However, when I apply white-space: nowrap to it then the whole header goes outside its container. Here's what I mean:

.container {
  width: 300px;
  height: 400px;
  border: 1px solid black;
}

.header {
  height: 80px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 1px solid red;
}

.header-right,
.header-left {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid blue;
}

.title {
  text-overflow: ellipsis;
  white-space: nowrap;
}

img {
  height: 20px;
  width: 20px;
  margin: 10px;
}

      Title: Keep me on a single line

Does anyone know how to keep the title on a single line but truncate it so the header doesn't go outside the bounds?

Body:
You need to disable the default minimun width by adding min-width:0 and disable the shriking for the images and their container by adding flex-shrink:0; and add overflow:hidden

.container {
  width: 300px;
  height: 400px;
  border: 1px solid black;
}

.header {
  height: 80px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 1px solid red;
}

.header-right,
.header-left {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid blue;
  min-width:0; /* Added */
}

.title {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow:hidden; /* Added */
}

img {
  height: 20px;
  width: 20px;
  margin: 10px;
  flex-shrink:0; /* Added */
}

.header-right {
  flex-shrink:0; /* Added */
}

<div class="container">
  <div class="header">
    <div class="header-left">
      <img src="https://image.flaticon.com/icons/png/128/181/181548.png">
      <span class="title">Title: Keep me on a single line</span>
    </div>
    <div class="header-right">
      <img src="https://image.flaticon.com/icons/png/128/181/181548.png">
      <img src="https://image.flaticon.com/icons/png/128/181/181548.png">
      <img src="https://image.flaticon.com/icons/png/128/181/181548.png">
    </div>
  </div>
</div>

Related:

Why don't flex items shrink past content size? (To understand the min-width)

Why is a flex-child limited to parent size? (To understand the flex-shrink)


Title: find all label and product in json python

Body:
I'm trying to find all label and product in text/javascript, but I don't have any idea to how do it. I'm trying to parse label, id  and products.

    var spConfigDisabledProducts = [-1
    , '290058', '290060', '290061', '290062', '290063', '290065', '290071', '290073', '290075', '290076', '290077', '290078'        ];
    var spConfig = new Product.Config({"attributes":{"959":{"id":"959","code":"aw_taglia","label":"Taglia","options":[{"id":"730","label":"36 ½","price":"0","oldPrice":"0","products":["290058"]},{"id":"731","label":"37 ½","price":"0","oldPrice":"0","products":["290060"]},{"id":"732","label":"38","price":"0","oldPrice":"0","products":["290061"]},{"id":"733","label":"38 ½","price":"0","oldPrice":"0","products":["290062"]},{"id":"734","label":"39","price":"0","oldPrice":"0","products":["290063"]},{"id":"735","label":"40","price":"0","oldPrice":"0","products":["290064"]},{"id":"736","label":"40 ½","price":"0","oldPrice":"0","products":["290065"]},{"id":"737","label":"41","price":"0","oldPrice":"0","products":["290066"]},{"id":"738","label":"42","price":"0","oldPrice":"0","products":["290067"]},{"id":"739","label":"42 ½","price":"0","oldPrice":"0","products":["290068"]},{"id":"740","label":"43","price":"0","oldPrice":"0","products":["290069"]},{"id":"741","label":"44","price":"0","oldPrice":"0","products":["290070"]},{"id":"742","label":"44 ½","price":"0","oldPrice":"0","products":["290071"]},{"id":"743","label":"45","price":"0","oldPrice":"0","products":["290072"]},{"id":"744","label":"45 ½","price":"0","oldPrice":"0","products":["290073"]},{"id":"745","label":"46","price":"0","oldPrice":"0","products":["290074"]},{"id":"746","label":"47","price":"0","oldPrice":"0","products":["290075"]},{"id":"747","label":"47 ½","price":"0","oldPrice":"0","products":["290076"]},{"id":"748","label":"13.5","price":"0","oldPrice":"0","products":["290077"]},{"id":"749","label":"48 ½","price":"0","oldPrice":"0","products":["290078"]}]}},"template":"#{price}\u00a0\u20ac","basePrice":"130","oldPrice":"130","productId":"290059","chooseText":"Seleziona","taxConfig":{"includeTax":true,"showIncludeTax":true,"showBothPrices":false,"defaultTax":0,"currentTax":0,"inclTaxTitle":"Incl. Tasse"}});
    jQuery("#attribute959 option").each(function () {
        var option = jQuery(this);
        var id = option.attr('value');
        jQuery.each(spConfig.config.attributes, function () {
            jQuery.each(this.options, function () {
                if (this.id == id) {
                    if (spConfigDisabledProducts.indexOf(this.products[0]) >= 0) {
                        option.data('disabled', true);
                    }
                }
            });
        });
    });

Body:
You can regex out javascript object and pass to json then parse out info

import re
import json

#html = response.content from requests
html = '''
var spConfigDisabledProducts = [-1
    , '290058', '290060', '290061', '290062', '290063', '290065', '290071', '290073', '290075', '290076', '290077', '290078'        ];
    var spConfig = new Product.Config({"attributes":{"959":{"id":"959","code":"aw_taglia","label":"Taglia","options":[{"id":"730","label":"36 &frac12;","price":"0","oldPrice":"0","products":["290058"]},{"id":"731","label":"37 &frac12;","price":"0","oldPrice":"0","products":["290060"]},{"id":"732","label":"38","price":"0","oldPrice":"0","products":["290061"]},{"id":"733","label":"38 &frac12;","price":"0","oldPrice":"0","products":["290062"]},{"id":"734","label":"39","price":"0","oldPrice":"0","products":["290063"]},{"id":"735","label":"40","price":"0","oldPrice":"0","products":["290064"]},{"id":"736","label":"40 &frac12;","price":"0","oldPrice":"0","products":["290065"]},{"id":"737","label":"41","price":"0","oldPrice":"0","products":["290066"]},{"id":"738","label":"42","price":"0","oldPrice":"0","products":["290067"]},{"id":"739","label":"42 &frac12;","price":"0","oldPrice":"0","products":["290068"]},{"id":"740","label":"43","price":"0","oldPrice":"0","products":["290069"]},{"id":"741","label":"44","price":"0","oldPrice":"0","products":["290070"]},{"id":"742","label":"44 &frac12;","price":"0","oldPrice":"0","products":["290071"]},{"id":"743","label":"45","price":"0","oldPrice":"0","products":["290072"]},{"id":"744","label":"45 &frac12;","price":"0","oldPrice":"0","products":["290073"]},{"id":"745","label":"46","price":"0","oldPrice":"0","products":["290074"]},{"id":"746","label":"47","price":"0","oldPrice":"0","products":["290075"]},{"id":"747","label":"47 &frac12;","price":"0","oldPrice":"0","products":["290076"]},{"id":"748","label":"13.5","price":"0","oldPrice":"0","products":["290077"]},{"id":"749","label":"48 &frac12;","price":"0","oldPrice":"0","products":["290078"]}]}},"template":"#{price}\u00a0\u20ac","basePrice":"130","oldPrice":"130","productId":"290059","chooseText":"Seleziona","taxConfig":{"includeTax":true,"showIncludeTax":true,"showBothPrices":false,"defaultTax":0,"currentTax":0,"inclTaxTitle":"Incl. Tasse"}});
    jQuery("#attribute959 option").each(function () {
        var option = jQuery(this);
        var id = option.attr('value');
        jQuery.each(spConfig.config.attributes, function () {
            jQuery.each(this.options, function () {
                if (this.id == id) {
                    if (spConfigDisabledProducts.indexOf(this.products[0]) >= 0) {
                        option.data('disabled', true);
                    }
                }
            });
        });
    });'''

p = re.compile(r'Product\.Config\((.*?)\)', re.DOTALL)
data = json.loads(p.findall(html)[0])

for attribute in data['attributes']:
    print('-----------------attribute--------------')
    print('label = ' + data['attributes'][attribute]['label'], 'id = ' + data['attributes'][attribute]['id'])
    print('-----------------options----------------')
    for product in data['attributes'][attribute]['options']:
        print('label = ' + product['label'], 'id = ' + product['id'], 'product = ' + product['products'][0])


问:
OpenVINO + HDDL plugin - Cannot run openvino samples - "HDDL hardware initialization failed"
I'm trying to get OpenVINO samples working on an mPCIe Myriad X card (with 2 MA2485 chips).

My goal is to get the samples working using the HDDL plugin, as from my understanding it should allow for working with multiple chips in parallel.

Using the "MYRIAD" plugin, the benchmarks run successfully every single time:
sudo -E ./demo_squeezenet_download_convert_run.sh -d MYRIAD

however, when switching to -d HDDL I get the following:

```<code>Run ./classification_sample -d HDDL -i /opt/intel/openvino_2019.1.144/deployment_tools/demo/car.png -m /home/vino/openvino_models/ir/FP16//classification/squeezenet/1.1/caffe/squeezenet1.1.xml

[ INFO ] InferenceEngine:
    API version ............ 1.6
    Build .................. custom_releases/2019/R1.1_28dfbfdd28954c4dfd2f94403dd8dfc1f411038b
[ INFO ] Parsing input parameters
[ INFO ] Files were added: 1
[ INFO ]     /opt/intel/openvino_2019.1.144/deployment_tools/demo/car.png
[ INFO ] Loading plugin

    API version ............ 1.6
    Build .................. 23780
    Description ....... HDDLPlugin
[ INFO ] Loading network files:
    /home/vino/openvino_models/ir/FP16//classification/squeezenet/1.1/caffe/squeezenet1.1.xml
    /home/vino/openvino_models/ir/FP16//classification/squeezenet/1.1/caffe/squeezenet1.1.bin
[ INFO ] Preparing input blobs
[ WARNING ] Image is resized from (787, 259) to (227, 227)
[ INFO ] Batch size is 1
[ INFO ] Preparing output blobs
[ INFO ] Loading model to the plugin
[16:52:27.5232][31126]I[ServiceStarter.cpp:93] Info: Found HDDL Service is not running. To start HDDL Service ...
[16:52:27.5241][31126]I[ServiceStarter.cpp:40] Info: Waiting for HDDL Service getting ready ...
Config file detected at /opt/intel/openvino_2019.1.144/deployment_tools/inference_engine/external/hddl/config/bsl.json
scan F75114 device...
found 0 F75114 device
hid-f75114 init returned status BSL_ERROR_NO_HID_DEVICE_FOUND
ioexpander is disabled by config, skipping
mcu is disabled by config, skipping
Auto-scan is disabled by config, aborting
bsl init failed for:    BSL_ERROR_NO_HID_DEVICE_FOUND
[ion_close][69]close ion_fd = 3
Config file detected at /opt/intel/openvino_2019.1.144/deployment_tools/inference_engine/external/hddl/config/bsl.json
scan F75114 device...
found 0 F75114 device
hid-f75114 init returned status BSL_ERROR_NO_HID_DEVICE_FOUND
ioexpander is disabled by config, skipping
mcu is disabled by config, skipping
Auto-scan is disabled by config, aborting
bsl init failed for:    BSL_ERROR_NO_HID_DEVICE_FOUND
## HDDL_INSTALL_DIR: /opt/intel/openvino_2019.1.144/deployment_tools/inference_engine/external/hddl
[16:52:27.5367][31131]I[ConfigParser.cpp:176] Config file '/opt/intel/openvino_2019.1.144/deployment_tools/inference_engine/external/hddl/config/hddl_service.config' has been loaded
[16:52:27.5372][31131]I[FileHelper.cpp:272] Set file:/var/tmp/hddl_service_alive.mutex owner: user-'no_change', group-'users', mode-'0660'
[16:52:27.5372][31131]I[FileHelper.cpp:272] Set file:/var/tmp/hddl_service_ready.mutex owner: user-'no_change', group-'users', mode-'0660'
[16:52:27.5373][31131]I[FileHelper.cpp:272] Set file:/var/tmp/hddl_start_exit.mutex owner: user-'no_change', group-'users', mode-'0660'
[16:52:27.5374][31131]I[AutobootStarter.cpp:150] Info: No running autoboot process. Start autoboot daemon...
Config file detected at /opt/intel/openvino_2019.1.144/deployment_tools/inference_engine/external/hddl/config/bsl.json
scan F75114 device...
found 0 F75114 device
hid-f75114 init returned status BSL_ERROR_NO_HID_DEVICE_FOUND
ioexpander is disabled by config, skipping
mcu is disabled by config, skipping
Auto-scan is disabled by config, aborting
bsl init failed for:    BSL_ERROR_NO_HID_DEVICE_FOUND
[16:52:27.5457][31133]I[ConfigParser.cpp:176] Config file '/opt/intel/openvino_2019.1.144/deployment_tools/inference_engine/external/hddl/config/hddl_autoboot.config' has been loaded
[16:52:27.5462][31133]I[FileHelper.cpp:272] Set file:/var/tmp/hddl_autoboot_alive.mutex owner: user-'no_change', group-'users', mode-'0660'
[16:52:27.5463][31133]I[FileHelper.cpp:272] Set file:/var/tmp/hddl_autoboot_ready.mutex owner: user-'no_change', group-'users', mode-'0660'
[16:52:27.5463][31133]I[FileHelper.cpp:272] Set file:/var/tmp/hddl_autoboot_start_exit.mutex owner: user-'no_change', group-'users', mode-'0660'
[16:52:27.5463][31133]I[FileHelper.cpp:272] Set file:/tmp/hddl_autoboot_device.map owner: user-'no_change', group-'users', mode-'0660'
[16:52:27.5464][31133]I[AutoBoot.cpp:282] [Firmware Config] deviceName=default deviceNum=0 firmwarePath=/opt/intel/openvino_2019.1.144/deployment_tools/inference_engine/external/hddl/lib/mvnc/MvNCAPI-ma2480.mvcmd
Reset all devices with device type 3
[16:52:27.5468][31133]ERROR[AutoBoot.cpp:444] Error: HDDL hardware initialization failed, exits now.
[ion_close][69]close ion_fd = 3
</code>```

I've tried messing with various configuration options but to no avail.
I've also tried reinstalling Ubuntu, which did not work either.

Using Ubuntu 16.04.6, kernel 4.4.0-148-generic.

lshw entry:

```<code>       *-pci
             description: PCI bridge
             product: 7 Series/C216 Chipset Family PCI Express Root Port 1
             vendor: Intel Corporation
             physical id: 1c
             bus info: pci@0000:00:1c.0
             version: c4
             width: 32 bits
             clock: 33MHz
             capabilities: pci pciexpress msi pm normal_decode bus_master cap_list
             configuration: driver=pcieport
             resources: irq:16 memory:f7c00000-f7cfffff
           *-usb
                description: USB controller
                product: ASM1042A USB 3.0 Host Controller
                vendor: ASMedia Technology Inc.
                physical id: 0
                bus info: pci@0000:01:00.0
                version: 00
                width: 64 bits
                clock: 33MHz
                capabilities: msi msix pm pciexpress xhci bus_master cap_list
                configuration: driver=xhci_hcd latency=0
                resources: irq:16 memory:f7c00000-f7c07fff
              *-usbhost:0
                   product: xHCI Host Controller
                   vendor: Linux 4.4.0-148-generic xhci-hcd
                   physical id: 0
                   bus info: usb@6
                   logical name: usb6
                   version: 4.04
                   capabilities: usb-3.00
                   configuration: driver=hub slots=2 speed=5000Mbit/s
              *-usbhost:1
                   product: xHCI Host Controller
                   vendor: Linux 4.4.0-148-generic xhci-hcd
                   physical id: 1
                   bus info: usb@5
                   logical name: usb5
                   version: 4.04
                   capabilities: usb-2.00
                   configuration: driver=hub slots=2 speed=480Mbit/s
                 *-usb UNCLAIMED
                      description: Generic USB device
                      product: Movidius MyriadX
                      vendor: Movidius Ltd.
                      physical id: 1
                      bus info: usb@5:1
                      version: 0.01
                      serial: 03e72485
                      capabilities: usb-2.00
                      configuration: maxpower=500mA speed=480Mbit/s
</code>```

${HDDL_INSTALL_DIR}/config/bsl.json (tried multiple configurations here, nothing worked):

```<code>{
  "autoscan": false,
  "comment_on_autoscan": "auto-scan can be true or false",
  "hid-f75114": {
    "enabled": true,
    "Linux_comment": "You can use setup_tools/path_detaction.sh to get the suggested paths",
    "Linux_path_example": "/sys/devices/pci0000:00/0000:00:01.1/0000:02:00.0/0000:03:04.0/0000:07:00.0/usb9/9-2/9-2.2/9-2.2:1.0",
    "Windows_comment": "HID\\VID_2C42&PID_5114\\6&A471F67&0&0000 is for Windows",
    "Comment": "Leave empty to pass all paths",
    "hid_paths": [
        "/sys/devices/pci0000:00/0000:00:1c.0/0000:01:00.0/usb5/5-1/5-1:1.0"
    ]
  },
  "ioexpander": {
    "enabled": false,
    "i2c_addr": [
      37,
      39
    ]
  },
  "mcu": {
    "enabled": false,
    "i2c_addr": [
      31
    ]
  }
}
</code>```

答: Turned out to be a hardware issue.</p>

Body:
I'm trying to get OpenVINO samples working on an mPCIe Myriad X card (with 2 MA2485 chips).

My goal is to get the samples working using the HDDL plugin, as from my understanding it should allow for working with multiple chips in parallel.

Using the "MYRIAD" plugin, the benchmarks run successfully every single time:
sudo -E ./demo_squeezenet_download_convert_run.sh -d MYRIAD

however, when switching to -d HDDL I get the following:

Run ./classification_sample -d HDDL -i /opt/intel/openvino_2019.1.144/deployment_tools/demo/car.png -m /home/vino/openvino_models/ir/FP16//classification/squeezenet/1.1/caffe/squeezenet1.1.xml

[ INFO ] InferenceEngine:
    API version ............ 1.6
    Build .................. custom_releases/2019/R1.1_28dfbfdd28954c4dfd2f94403dd8dfc1f411038b
[ INFO ] Parsing input parameters
[ INFO ] Files were added: 1
[ INFO ]     /opt/intel/openvino_2019.1.144/deployment_tools/demo/car.png
[ INFO ] Loading plugin

    API version ............ 1.6
    Build .................. 23780
    Description ....... HDDLPlugin
[ INFO ] Loading network files:
    /home/vino/openvino_models/ir/FP16//classification/squeezenet/1.1/caffe/squeezenet1.1.xml
    /home/vino/openvino_models/ir/FP16//classification/squeezenet/1.1/caffe/squeezenet1.1.bin
[ INFO ] Preparing input blobs
[ WARNING ] Image is resized from (787, 259) to (227, 227)
[ INFO ] Batch size is 1
[ INFO ] Preparing output blobs
[ INFO ] Loading model to the plugin
[16:52:27.5232][31126]I[ServiceStarter.cpp:93] Info: Found HDDL Service is not running. To start HDDL Service ...
[16:52:27.5241][31126]I[ServiceStarter.cpp:40] Info: Waiting for HDDL Service getting ready ...
Config file detected at /opt/intel/openvino_2019.1.144/deployment_tools/inference_engine/external/hddl/config/bsl.json
scan F75114 device...
found 0 F75114 device
hid-f75114 init returned status BSL_ERROR_NO_HID_DEVICE_FOUND
ioexpander is disabled by config, skipping
mcu is disabled by config, skipping
Auto-scan is disabled by config, aborting
bsl init failed for:    BSL_ERROR_NO_HID_DEVICE_FOUND
[ion_close][69]close ion_fd = 3
Config file detected at /opt/intel/openvino_2019.1.144/deployment_tools/inference_engine/external/hddl/config/bsl.json
scan F75114 device...
found 0 F75114 device
hid-f75114 init returned status BSL_ERROR_NO_HID_DEVICE_FOUND
ioexpander is disabled by config, skipping
mcu is disabled by config, skipping
Auto-scan is disabled by config, aborting
bsl init failed for:    BSL_ERROR_NO_HID_DEVICE_FOUND
## HDDL_INSTALL_DIR: /opt/intel/openvino_2019.1.144/deployment_tools/inference_engine/external/hddl
[16:52:27.5367][31131]I[ConfigParser.cpp:176] Config file '/opt/intel/openvino_2019.1.144/deployment_tools/inference_engine/external/hddl/config/hddl_service.config' has been loaded
[16:52:27.5372][31131]I[FileHelper.cpp:272] Set file:/var/tmp/hddl_service_alive.mutex owner: user-'no_change', group-'users', mode-'0660'
[16:52:27.5372][31131]I[FileHelper.cpp:272] Set file:/var/tmp/hddl_service_ready.mutex owner: user-'no_change', group-'users', mode-'0660'
[16:52:27.5373][31131]I[FileHelper.cpp:272] Set file:/var/tmp/hddl_start_exit.mutex owner: user-'no_change', group-'users', mode-'0660'
[16:52:27.5374][31131]I[AutobootStarter.cpp:150] Info: No running autoboot process. Start autoboot daemon...
Config file detected at /opt/intel/openvino_2019.1.144/deployment_tools/inference_engine/external/hddl/config/bsl.json
scan F75114 device...
found 0 F75114 device
hid-f75114 init returned status BSL_ERROR_NO_HID_DEVICE_FOUND
ioexpander is disabled by config, skipping
mcu is disabled by config, skipping
Auto-scan is disabled by config, aborting
bsl init failed for:    BSL_ERROR_NO_HID_DEVICE_FOUND
[16:52:27.5457][31133]I[ConfigParser.cpp:176] Config file '/opt/intel/openvino_2019.1.144/deployment_tools/inference_engine/external/hddl/config/hddl_autoboot.config' has been loaded
[16:52:27.5462][31133]I[FileHelper.cpp:272] Set file:/var/tmp/hddl_autoboot_alive.mutex owner: user-'no_change', group-'users', mode-'0660'
[16:52:27.5463][31133]I[FileHelper.cpp:272] Set file:/var/tmp/hddl_autoboot_ready.mutex owner: user-'no_change', group-'users', mode-'0660'
[16:52:27.5463][31133]I[FileHelper.cpp:272] Set file:/var/tmp/hddl_autoboot_start_exit.mutex owner: user-'no_change', group-'users', mode-'0660'
[16:52:27.5463][31133]I[FileHelper.cpp:272] Set file:/tmp/hddl_autoboot_device.map owner: user-'no_change', group-'users', mode-'0660'
[16:52:27.5464][31133]I[AutoBoot.cpp:282] [Firmware Config] deviceName=default deviceNum=0 firmwarePath=/opt/intel/openvino_2019.1.144/deployment_tools/inference_engine/external/hddl/lib/mvnc/MvNCAPI-ma2480.mvcmd
Reset all devices with device type 3
[16:52:27.5468][31133]ERROR[AutoBoot.cpp:444] Error: HDDL hardware initialization failed, exits now.
[ion_close][69]close ion_fd = 3

I've tried messing with various configuration options but to no avail.
I've also tried reinstalling Ubuntu, which did not work either.

Using Ubuntu 16.04.6, kernel 4.4.0-148-generic.

lshw entry:

       *-pci
             description: PCI bridge
             product: 7 Series/C216 Chipset Family PCI Express Root Port 1
             vendor: Intel Corporation
             physical id: 1c
             bus info: pci@0000:00:1c.0
             version: c4
             width: 32 bits
             clock: 33MHz
             capabilities: pci pciexpress msi pm normal_decode bus_master cap_list
             configuration: driver=pcieport
             resources: irq:16 memory:f7c00000-f7cfffff
           *-usb
                description: USB controller
                product: ASM1042A USB 3.0 Host Controller
                vendor: ASMedia Technology Inc.
                physical id: 0
                bus info: pci@0000:01:00.0
                version: 00
                width: 64 bits
                clock: 33MHz
                capabilities: msi msix pm pciexpress xhci bus_master cap_list
                configuration: driver=xhci_hcd latency=0
                resources: irq:16 memory:f7c00000-f7c07fff
              *-usbhost:0
                   product: xHCI Host Controller
                   vendor: Linux 4.4.0-148-generic xhci-hcd
                   physical id: 0
                   bus info: usb@6
                   logical name: usb6
                   version: 4.04
                   capabilities: usb-3.00
                   configuration: driver=hub slots=2 speed=5000Mbit/s
              *-usbhost:1
                   product: xHCI Host Controller
                   vendor: Linux 4.4.0-148-generic xhci-hcd
                   physical id: 1
                   bus info: usb@5
                   logical name: usb5
                   version: 4.04
                   capabilities: usb-2.00
                   configuration: driver=hub slots=2 speed=480Mbit/s
                 *-usb UNCLAIMED
                      description: Generic USB device
                      product: Movidius MyriadX
                      vendor: Movidius Ltd.
                      physical id: 1
                      bus info: usb@5:1
                      version: 0.01
                      serial: 03e72485
                      capabilities: usb-2.00
                      configuration: maxpower=500mA speed=480Mbit/s

${HDDL_INSTALL_DIR}/config/bsl.json (tried multiple configurations here, nothing worked):

{
  "autoscan": false,
  "comment_on_autoscan": "auto-scan can be true or false",
  "hid-f75114": {
    "enabled": true,
    "Linux_comment": "You can use setup_tools/path_detaction.sh to get the suggested paths",
    "Linux_path_example": "/sys/devices/pci0000:00/0000:00:01.1/0000:02:00.0/0000:03:04.0/0000:07:00.0/usb9/9-2/9-2.2/9-2.2:1.0",
    "Windows_comment": "HID\\VID_2C42&PID_5114\\6&A471F67&0&0000 is for Windows",
    "Comment": "Leave empty to pass all paths",
    "hid_paths": [
        "/sys/devices/pci0000:00/0000:00:1c.0/0000:01:00.0/usb5/5-1/5-1:1.0"
    ]
  },
  "ioexpander": {
    "enabled": false,
    "i2c_addr": [
      37,
      39
    ]
  },
  "mcu": {
    "enabled": false,
    "i2c_addr": [
      31
    ]
  }
}

Body: Turned out to be a hardware issue.


问:
Is there a way to isolate 'localStorage' between different tabs?
I am currently using window.localStorage to store some client side data on browser. But I'd like to isolate this storage to individual tabs.

Is there a way to achieve this?

答:
You should consider using sessionStorage instead:

sessionStorage is similar to localStorage; the only difference is while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated with the value of the top-level browsing context [...]


问:
Python vs Bash - In which kind of tasks each one outruns the other performance-wise?
Obviously Python is more user friendly, a quick search on google shows many results that say that, as Python is byte-compiled is usually faster. I even found this that claims that you can see an improvement of over 2000% on dictionary-based operations.

What is your experience on this matter? In which kind of task each one is a clear winner?

答:
I'm posting this late answer primarily because Google likes this question.

I believe the issue and context really should be about the workflow, not the tools.  The overall philosophy is always "Use the right tool for the job."  But before this comes one that many often forget when they get lost in the tools: "Get the job done."

When I have a problem that isn't completely defined, I almost always start with Bash.  I have solved some gnarly problems in large Bash scripts that are both readable and maintainable.

But when does the problem start to exceed what Bash should be asked to do?  I have some checks I use to give me warnings:

Am I wishing Bash had 2D (or higher) arrays?  If yes, it's time to realize that Bash is not a great data processing language.

Am I doing more work preparing data for other utilities than I am actually running those utilities?  If yes, time again to realize Bash is not a great data processing language.

Is my script simply getting too large to manage?  If yes, it is important to realize that while Bash can import script libraries, it lacks a package system like other languages.  It's really a "roll your own" language compared to most others.  Then again, it has a enormous amount of functionality built-in (some say too much...)

The list goes on.  Bottom-line, when you are working harder to keep your scripts running that you do adding features, it's time to leave Bash.

Let's assume you've decided to move your work to Python.  If your Bash scripts are clean, the initial conversion is quite straightforward.  There are even several converters / translators that will do the first pass for you.

The next question is: What do you give up moving to Python?

All calls to external utilities must be wrapped in something from the subprocess module (or equivalent).  There are multiple ways to do this, and until 3.7 it took some effort to get it right (3.7 improved subprocess.run() to handle all common cases on its own).

Surprisingly, Python has no standard platform-independent non-blocking utility (with timeout) for polling the keyboard (stdin).  The Bash read command is an awesome tool for simple user interaction.  My most common use is to show a spinner until the user presses a key, while also running a polling function (with each spinner step) to make sure things are still running well.  This is a harder problem than it would appear at first, so I often simply make a call to Bash: Expensive, but it does precisely what I need.

If you are developing on an embedded or memory-constrained system, Python's memory footprint can be many times larger than Bash's (depending on the task at hand).  Plus, there is almost always an instance of Bash already in memory, which may not be the case for Python.

For scripts that run once and exit quickly, Python's startup time can be much longer than Bash's.  But if the script contains significant calculations, Python quickly pulls ahead.

Python has the most comprehensive package system on the planet.  When Bash gets even slightly complex, Python probably has a package that makes whole chunks of Bash become a single call.  However, finding the right package(s) to use is the biggest and most daunting part of becoming a Pythonista.  Fortunately, Google and StackExchange are your friends.


问:
Handle Spring data source being temporarily unavailable during Hibernate initialisation
Part of my Spring (4.3.23) / Hibernate (5.0.12) application "A" uses a data source that is exposed be a second application "B" (the data source is an in-memory database). Both A and B are deployed in Tomcat and I don't control start order. Once both A and B have started both behave as expected, however if A starts before B an error is thrown during initialisation when Hibernate tries to query the data source:

```<code>org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator - HHH000342: Could not obtain connection to query metadata : Cannot create PoolableConnectionFactory (Connection is broken: "java.net.ConnectException: Connection refused: 127.0.1.1:5521" [90067-199])
</code>```

Is there any way I can suppress this error, delay this part of initialisation, or tell Hibernate that the data source may not be immediately available?

Here are the relevant parts of my configuration:

```<code><bean id="memDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
  <property name="jndiName" value="java:comp/env/jdbc/memdb" />
</bean>

<bean
  id="memSessionFactory"
  class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
  <property name="dataSource" ref="memDataSource" />
  <property name="packagesToScan" value="com.company" />
  <property name="hibernateProperties">
    <props>
      <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
      </props>
  </property>
</bean>

<bean id="memTransactionManager"class="org.springframework.orm.hibernate5.HibernateTransactionManager">
  <property name="sessionFactory" ref="memSessionFactory" />
  <qualifier value="memTransactions"/>
</bean>
<tx:annotation-driven transaction-manager="memTransactionManager" />
</code>```

答:
I would wind up scripting the deployment overall.  Bring up tomcat with application A in the webapps directory, and periodically ping for successful deployment of application A before copying/moving over application B into the webapps directory for deployment.

This entire solution would likely work best if you used a staging directory to move your war files onto that server, and then let the script clear the webapps directory and move/copy the new war(s) into webapps for fresh deployment.

SideNote: I've found that deployment of applications seems to be in a constant order, but I'm not sure as it is alphabetical, oldest first, or something else.

Body:
Part of my Spring (4.3.23) / Hibernate (5.0.12) application "A" uses a data source that is exposed be a second application "B" (the data source is an in-memory database). Both A and B are deployed in Tomcat and I don't control start order. Once both A and B have started both behave as expected, however if A starts before B an error is thrown during initialisation when Hibernate tries to query the data source:

org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator - HHH000342: Could not obtain connection to query metadata : Cannot create PoolableConnectionFactory (Connection is broken: "java.net.ConnectException: Connection refused: 127.0.1.1:5521" [90067-199])

Is there any way I can suppress this error, delay this part of initialisation, or tell Hibernate that the data source may not be immediately available?

Here are the relevant parts of my configuration:

<bean id="memDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
  <property name="jndiName" value="java:comp/env/jdbc/memdb" />
</bean>

<bean
  id="memSessionFactory"
  class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
  <property name="dataSource" ref="memDataSource" />
  <property name="packagesToScan" value="com.company" />
  <property name="hibernateProperties">
    <props>
      <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
      </props>
  </property>
</bean>

<bean id="memTransactionManager"class="org.springframework.orm.hibernate5.HibernateTransactionManager">
  <property name="sessionFactory" ref="memSessionFactory" />
  <qualifier value="memTransactions"/>
</bean>
<tx:annotation-driven transaction-manager="memTransactionManager" />


问:
How to rotate arbitrary degree an image
I want to rotate an image N degree
I write this code but it does not work what should I do?

```<code>var N=20
    function rotateImage() {
        var img = document.getElementById('myimage');
        img.style.transform = 'rotate(Ndeg)';

    }
</code>```

and

```<code>img.style.transform = 'rotate(${N}deg)';
</code>```

does not work but
    img.style.transform = 'rotate(20deg)';
works

答:
You need to actually place the variable into the string. You can either use a template literal (note the backticks,not single quotes), like so:

```<code>img.style.transform = `rotate(${N}deg)`;
</code>```

Or, concatenate strings:

```<code>img.style.transform = 'rotate(' + N + 'deg)';
</code>```

Also, I would refactor your code to take N as an argument:

```<code>function rotateImage(N) {
    var img = document.getElementById('myimage');
    img.style.transform = 'rotate(' + N + ')';

}
rotateImage(20);
</code>```

Or, if it is really always by 20 degrees:

```<code>function rotateImage() {
    document.getElementById('myimage').style.transform = 'rotate(20deg)';
}
</code>```

Title: How to rotate arbitrary degree an image

Body:
I want to rotate an image N degree
I write this code but it does not work what should I do?

var N=20
    function rotateImage() {
        var img = document.getElementById('myimage');
        img.style.transform = 'rotate(Ndeg)';

    }

and

img.style.transform = 'rotate(${N}deg)';

does not work but
    img.style.transform = 'rotate(20deg)';
works

Body:
You need to actually place the variable into the string. You can either use a template literal (note the backticks,not single quotes), like so:

img.style.transform = `rotate(${N}deg)`;

Or, concatenate strings:

img.style.transform = 'rotate(' + N + 'deg)';

Also, I would refactor your code to take N as an argument:

function rotateImage(N) {
    var img = document.getElementById('myimage');
    img.style.transform = 'rotate(' + N + ')';

}
rotateImage(20);

Or, if it is really always by 20 degrees:

function rotateImage() {
    document.getElementById('myimage').style.transform = 'rotate(20deg)';
}


问:
How to avoid org.springframework.transaction.UnexpectedRollbackException?
When a method is annotated with @Transactional and there is an runtime exception, spring eats the exception and throws:

```<code>org.springframework.transaction.UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only
</code>```

How do I avoid this "general" exception and propagate the original exception, but keeping the rollback?

Thanks.

答:
org.springframework.transaction.UnexpectedRollbackException:
  Transaction silently rolled back because it has been marked as
  rollback-only

It mostly happens if you have an outer @Transactional method calls an inner @Transactional method. When the inner method throws an exception , but the outer method catches this exception and return normally, Spring is confused and don't know if it should rollback or commit the transaction  since both methods contradict with each other. (Inner method says it wants to rollback but the outer method says it want to commit)

So , check if there are any outer @Transactional methods that catch the exception. If yes , re-throw that exception from the outer method such that the whole transaction will rollback.

Body:
When a method is annotated with @Transactional and there is an runtime exception, spring eats the exception and throws:

org.springframework.transaction.UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only

How do I avoid this "general" exception and propagate the original exception, but keeping the rollback?

Thanks.


问:
How do you run a .bat file from PHP?
Can anyone tell me how to execute a .bat file from a PHP script?

I have tried:

```<code>exec("C:\[path to file]");
system("C:\[path to file]");
</code>```

Nothing is working. I've checked the PHP manuals and googled around but can't find a good answer. Anyone know where I'm going wrong?

I'm running Windows 2003 Server and have successfully manually run the .bat file and it does what I need it to; I just need to be able to launch it programatically.

答:
This snippet is from working code.

You can trigger bat file not only from Windows GUI or Task Scheduler, but directly from PHP script when you need it. But in most cases it will have execution for 30-60 sec. depending from your PHP configuration. If job in BAT file is long and you don't want to freeze your PHP scripts, you need to fork BAT job as another process using php.exe and not be dependable from Apache.

This runs in background mode in Windows, seen as separate processes cmd.exe and php.exe from Task Manager not halting your Apache PHP scripts. The messages produced by your script may be stored and retrieved back via log files.

In my case in file_scanner.php I do some heavy calculations in loop for big array of files which may last for few hours with php function sleep() not to overload CPU.

The success poiner result from file  $r which you can query via ajax if you want to know success or fauty start. In my case file_scanner.php writes log file with messages  somefile.jpg - OK wich you can load to your UI with AJAX every few seconds to show progress.

PHP

```<code>/**
 * Runs bat file in background mode
 *
 */
 function run_scanner() {

    $c='start /b D:\Web\example.com\tasks\file_scanner.bat';
    $r=pclose(popen($c, 'r'));
    return json_encode(array('result'=>$r));

 }
</code>```

BAT

```<code>@echo Off
D:\PHP\php.exe D:\Web\example.com\tasks\file_scanner.php > D:\Web\example.com\tasks\file_scanner.log
exit
</code>```

Title: How do you run a .bat file from PHP?

Body:
Can anyone tell me how to execute a .bat file from a PHP script?

I have tried:

exec("C:\[path to file]");
system("C:\[path to file]");

Nothing is working. I've checked the PHP manuals and googled around but can't find a good answer. Anyone know where I'm going wrong?

I'm running Windows 2003 Server and have successfully manually run the .bat file and it does what I need it to; I just need to be able to launch it programatically.

Body:
This snippet is from working code.

You can trigger bat file not only from Windows GUI or Task Scheduler, but directly from PHP script when you need it. But in most cases it will have execution for 30-60 sec. depending from your PHP configuration. If job in BAT file is long and you don't want to freeze your PHP scripts, you need to fork BAT job as another process using php.exe and not be dependable from Apache.

This runs in background mode in Windows, seen as separate processes cmd.exe and php.exe from Task Manager not halting your Apache PHP scripts. The messages produced by your script may be stored and retrieved back via log files.

In my case in file_scanner.php I do some heavy calculations in loop for big array of files which may last for few hours with php function sleep() not to overload CPU.

The success poiner result from file  $r which you can query via ajax if you want to know success or fauty start. In my case file_scanner.php writes log file with messages  somefile.jpg - OK wich you can load to your UI with AJAX every few seconds to show progress.

PHP

/**
 * Runs bat file in background mode
 *
 */
 function run_scanner() {

    $c='start /b D:\Web\example.com\tasks\file_scanner.bat';
    $r=pclose(popen($c, 'r'));
    return json_encode(array('result'=>$r));

 }

BAT

@echo Off
D:\PHP\php.exe D:\Web\example.com\tasks\file_scanner.php > D:\Web\example.com\tasks\file_scanner.log
exit


问:
Powershell Select-String to include a wildcard
I need to use Select-String to find something is a known string of characters, followed by either a / or $ followed by another known string of characters.

So suppose literal string 1 is X and literal string 2 is Y, how do I look for the string X/Y or X$Y in powershell?

答:
I'd compound the RegEx even if strings are simple here:

```<code>## Q:\Test\2019\05\28\SO_56349782.ps1

$String1 = [regex]::Escape("X")
$String2 = [regex]::Escape("Y")
$RegEx   = [regex]"$String1(\/|\$)$String2"

$Text = @'
foo X/Y
foo X$Y baz
foo X/Y bar X$Y baz
'@ -split '\r?\n'

$Text | Select-String -Pattern $RegEx -AllMatches

($Text | Select-String -Pattern $RegEx -AllMatches).Matches.Value
</code>```

Sample output:

```<code>foo X/Y
foo X$Y baz
foo X/Y bar X$Y baz
</code>```

```<code>X/Y
X$Y
X/Y
X$Y
</code>```

Body:
I'd compound the RegEx even if strings are simple here:

## Q:\Test\2019\05\28\SO_56349782.ps1

$String1 = [regex]::Escape("X")
$String2 = [regex]::Escape("Y")
$RegEx   = [regex]"$String1(\/|\$)$String2"

$Text = @'
foo X/Y
foo X$Y baz
foo X/Y bar X$Y baz
'@ -split '\r?\n'

$Text | Select-String -Pattern $RegEx -AllMatches

($Text | Select-String -Pattern $RegEx -AllMatches).Matches.Value

Sample output:

foo X/Y
foo X$Y baz
foo X/Y bar X$Y baz

X/Y
X$Y
X/Y
X$Y


问:
What is the difference between setsockopt and ioctl with SIOCSIFFLAGS?
To set a network interface to promiscuous mode, for example, one can use setsockopt as

struct packet_mreq opt;
opt.mr_ifindex = the_very_interface_index;
setsockopt(socket_fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP, (void*)&opt, sizeof(opt));
```

<p>On the other hand, as packet(7) suggested, one can also use <code>ioctl</code> with SIOCSIFFLAGS option, like</p>

<pre class="lang-c prettyprint-override"><code>struct ifreq req;
strcpy(req.ifr_name, the_very_interface_name);
ioctl(socket_fd, SIOCGIFFLAGS, &req);
req.ifr_flags |= IFF_PROMISC;
ioctl(socket_fd, SIOCSIFFLAGS, &req);
</code>```

I understand these two ways are completely equivalent, but is there any difference? Otherwise, why is there two ways to do the same thing?

答:
There is very little difference between the two, as can be seen by perusing the source. Specifically, consider callers of __dev_set_promiscuity.

The setsockopt interface eventually calls dev_set_promiscuity.

The ioctl interface ends up calling dev_change_flags.

There has always been some duplication of mechanisms due to the file descriptor interface to devices. For example send() vs write(). To be honest, I have never thought too deeply about it. I imagine ioctl interfaces are a natural thing to add for generic devices, and setsockopt interfaces are natural to add for sockets, so both end up existing. You could think of sockets as a higher level abstraction over the network device, so a higher level interface to modify options would not be an unreasonable addition.

Body:
To set a network interface to promiscuous mode, for example, one can use setsockopt as

struct packet_mreq opt;
opt.mr_ifindex = the_very_interface_index;
setsockopt(socket_fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP, (void*)&opt, sizeof(opt));

On the other hand, as packet(7) suggested, one can also use ioctl with SIOCSIFFLAGS option, like

struct ifreq req;
strcpy(req.ifr_name, the_very_interface_name);
ioctl(socket_fd, SIOCGIFFLAGS, &req);
req.ifr_flags |= IFF_PROMISC;
ioctl(socket_fd, SIOCSIFFLAGS, &req);

I understand these two ways are completely equivalent, but is there any difference? Otherwise, why is there two ways to do the same thing?


问:
TCL problem: imported function get bracket({}) added around the "text"
I have a "library" type file that where I define a namespace and export some functions to "print" debug info or "trace" info in TCL.

```<code>proc cputs  { args } {
    puts "Test= $args"
}
</code>```

I import this function in multiple other files.  When I use it everything is fine except it add bracket to the output.

Like if I call cputs "Hi there" it will output {Hi there} instead of Hi there.

Can't find anything to explain that.  I would like to get ride of those brackets.

Any help would be appreciated.

Thanks

答:
If you do not want to pass an arbitrary, unknown numbers of arguments to your cproc, do not use args (which has a special meaning as a parameter name), but msg, for instance.

```<code>proc cputs  {msg} {
    puts "Test= $msg"
}
</code>```

See also proc documentation:

If the last formal argument has the name “args”, then a call to the
  procedure may contain more actual arguments than the procedure has
  formal arguments. In this case, all of the actual arguments starting
  at the one that would be assigned to args are combined into a list (as
  if the list command had been used); this combined value is assigned to
  the local variable args.

Body:
I have a "library" type file that where I define a namespace and export some functions to "print" debug info or "trace" info in TCL.

proc cputs  { args } {
    puts "Test= $args"
}

I import this function in multiple other files.  When I use it everything is fine except it add bracket to the output.

Like if I call cputs "Hi there" it will output {Hi there} instead of Hi there.

Can't find anything to explain that.  I would like to get ride of those brackets.

Any help would be appreciated.

Thanks

Body:
If you do not want to pass an arbitrary, unknown numbers of arguments to your cproc, do not use args (which has a special meaning as a parameter name), but msg, for instance.

proc cputs  {msg} {
    puts "Test= $msg"
}

See also proc documentation:

If the last formal argument has the name “args”, then a call to the
  procedure may contain more actual arguments than the procedure has
  formal arguments. In this case, all of the actual arguments starting
  at the one that would be assigned to args are combined into a list (as
  if the list command had been used); this combined value is assigned to
  the local variable args.


问:
How can i make this custom Stepper?
I want to make the Stepper with two circle (one inside other), linked to other circle, but that circle inside other is hard to do, i can i do it?

I try using this https://jsfiddle.net/dedi_wibisono17/c69e374r/2/  and change it to look like that i want to do, but i fail!

```<code><div class="row">
  <div class="col-xs-12 col-md-8 offset-md-2 block border">
    <div class="wrapper-progressBar">
      <ul class="progressBar">
        <li class="active">Beong Processed</li>
        <li class="active">Waiting for payment</li>
        <li>Paid</li>
      </ul>
    </div>
  </div>
</div>

.wrapper-progressBar {
    width: 100%
}

.progressBar {
}

.progressBar li {
    list-style-type: none;
    float: left;
    width: 33%;
    position: relative;
    text-align: center;
}

.progressBar li:before {
    content: " ";
    line-height: 30px;
    border-radius: 50%;
    width: 30px;
    height: 30px;
    border: 1px solid #ddd;
    display: block;
    text-align: center;
    margin: 0 auto 10px;
    background-color: white
}

.progressBar li:after {
    content: "";
    position: absolute;
    width: 100%;
    height: 2px;
    background-color: #ddd;
    top: 15px;
    left: -50%;
    z-index: -1;
}

.progressBar li:first-child:after {
    content: none;
}

.progressBar li.active {
    color: dodgerblue;
}

.progressBar li.active:before {
    border-color: dodgerblue;
    background-color: dodgerblue
}

.progressBar li.active + li:after {
    background-color: dodgerblue;
}
</code>```

there was an error, the linked line with z-index=-1 it stay behind the section background, how can i put it in front ( i try change z-index but it not look well, it stay in front of the circle)

答:
This should get you closer to what you're going for.

```<code>.wrapper-progressBar {
    width: 100%;
}

.progressBar {
}

.progressBar li {
    list-style-type: none;
    float: left;
    width: 33%;
    position: relative;
    text-align: center;
    color:white
}

.progressBar li:before {
    content: " ";
    line-height: 30px;
    border-radius: 50%;
    width: 10px;
    height: 10px;
    display: block;
    text-align: center;
    padding:5px;
    margin: 15px auto 25px;
    background-color: white;

}

.progressBar li:after {
    content: "";
    position: absolute;
    width: 94%;
    height: 2px;
    background-color: #19C1D5;
    top: 18px;
    left: -47%;
}

.progressBar li:first-child:after {
    content: none;
}

.progressBar li.active:before {
  margin:0 auto 10px;
  border:15px solid #19C1D5;
}
</code>```

The main changes were changing the margin of the li:before so it acts as a transparent border for the top and bottom, and changing li.active:before to revert the margin/add the border.

Title: How can i make this custom Stepper?

Body:
I want to make the Stepper with two circle (one inside other), linked to other circle, but that circle inside other is hard to do, i can i do it?

I try using this https://jsfiddle.net/dedi_wibisono17/c69e374r/2/  and change it to look like that i want to do, but i fail!

Beong Processed

Waiting for payment

Paid

.wrapper-progressBar {
    width: 100%
}

.progressBar {
}

.progressBar li {
    list-style-type: none;
    float: left;
    width: 33%;
    position: relative;
    text-align: center;
}

.progressBar li:before {
    content: " ";
    line-height: 30px;
    border-radius: 50%;
    width: 30px;
    height: 30px;
    border: 1px solid #ddd;
    display: block;
    text-align: center;
    margin: 0 auto 10px;
    background-color: white
}

.progressBar li:after {
    content: "";
    position: absolute;
    width: 100%;
    height: 2px;
    background-color: #ddd;
    top: 15px;
    left: -50%;
    z-index: -1;
}

.progressBar li:first-child:after {
    content: none;
}

.progressBar li.active {
    color: dodgerblue;
}

.progressBar li.active:before {
    border-color: dodgerblue;
    background-color: dodgerblue
}

.progressBar li.active + li:after {
    background-color: dodgerblue;
}

there was an error, the linked line with z-index=-1 it stay behind the section background, how can i put it in front ( i try change z-index but it not look well, it stay in front of the circle)

Body:
This should get you closer to what you're going for.

.wrapper-progressBar {
    width: 100%;
}

.progressBar {
}

.progressBar li {
    list-style-type: none;
    float: left;
    width: 33%;
    position: relative;
    text-align: center;
    color:white
}

.progressBar li:before {
    content: " ";
    line-height: 30px;
    border-radius: 50%;
    width: 10px;
    height: 10px;
    display: block;
    text-align: center;
    padding:5px;
    margin: 15px auto 25px;
    background-color: white;

}

.progressBar li:after {
    content: "";
    position: absolute;
    width: 94%;
    height: 2px;
    background-color: #19C1D5;
    top: 18px;
    left: -47%;
}

.progressBar li:first-child:after {
    content: none;
}

.progressBar li.active:before {
  margin:0 auto 10px;
  border:15px solid #19C1D5;
}

The main changes were changing the margin of the li:before so it acts as a transparent border for the top and bottom, and changing li.active:before to revert the margin/add the border.


问:
How is this animation implemented
Can you take a look at JWT and suggest what library was used to create the animation of DIV transition from one place to another?
Also, any suggestions about the overall algorithm used to load the RSS and the construct columns/rows out of it?

Thank you.

答:
This effect can be achieved using jquery.take a look here
Try the options in the dropdown like scale,size,fold etc</p>

Title: How is this animation implemented


问:
how to integrate Camunda workflow engine with jhipster generated application?
I want to use Camunda workflow engine to manual approval process with multilevel approval and dynamic forms for different users in Jhipster generate application</p>

答: Camunda can be run easily within a Spring Boot application; see this tutorial for more information. Beyond that, I think all of us would need a little more information regarding your additional requirements before we would be able to fully address your question.</p>


问:
Getting os.environ to work with Python run via NSSM
I am stuck on an environment variables mismatch.

I run a Python script on Windows 10 via a program called NSSM.

At runtime, I do the following:

Load in parameters from a text file

Put its contents into the environment using os.environ.setdefault(name, value).

Try to load in environment variables using os.environ[name]

Result:any variables I added do not show up.

I am not sure why the variables I add aren't available.  Can you please tell me what I am doing wrong?

A starting point is that NSSM uses environment variables from Windows HKLM registry: source (see bottom).  I am not sure if this is the reason os.environ cannot see relevant variables.

答:
Well it turns out that my problem was outside of the scope of this question.  @Recessive and @eryksun thank you both for answering, it put me "onto the scent".

It turns out my problem was using Python pathlib's Path.home().

When running via command prompt, it pulled HOMEPATH environment variable.

When running via NSSM, it pulled USERPROFILE environment variable.

This discrepancy in Path.home() was the real problem.  It wasn't finding the environment variables because NSSM was looking in a totally different folder.