问:
React-native: Super expression must either be null or a function, not undefined
I have seen similar questions asked but I can't seem to indentify the problem.
I am using react native v 0.27
I have changed all my require methods into imports.

Here's the error I receive:

I don't know if its relevant, but the first position of the error points to my LoginComp.js file which contains the following code:

```<code>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';
import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View,
  Image,
  TextInput,
  Button,
  TouchableHighlight
} from 'react-native';

class LoginComp extends Component {
  constructor(){
    super(props);
  }
  render() {
    return (
      <View style={{flex: 1}}>
        <View style={this.props.styles.loginLogoContainer}>
          <Image style={this.props.styles.view1logo} source={require('../imgs/Logo.png')} />
        </View>
        <View style={this.props.styles.loginContainer}>
          <Text>Użytkownik:</Text>
          <TextInput
            style={this.props.styles.defaultInput}
            placeholder="Użytkownik"
            stretch={true}
            autoComplete={false}
            autoCorrect={false}
          />
          <Text>Hasło:</Text>
          <TextInput
            style={this.props.styles.defaultInput}
            placeholder="Hasło"
            stretch={true}
            autoComplete={false}
            autoCorrect={false}
            secureTextEntry={true}
          />
        <TouchableHighlight onPress={this.props.LoginPress}>
            <Text style={this.props.styles.loginButton}>Login</Text>
          </TouchableHighlight>
        </View>
        <View style={this.props.styles.registrationWrapper}>
          <Text>- lub -</Text>
          <TouchableHighlight onPress={this.props.t_Registration}>
            <Text style={this.props.styles.registration}>Załóż nowe konto</Text>
          </TouchableHighlight>
        </View>
      </View>
    );
  }
}

module.exports = LoginComp;
</code>```

答:
I hit this error when attempting to use:

```<code>class Leaderboard extends React.component {

}
</code>```

It should have been Component with a capital C!

Body:
I have seen similar questions asked but I can't seem to indentify the problem.
I am using react native v 0.27
I have changed all my require methods into imports.

Here's the error I receive:

I don't know if its relevant, but the first position of the error points to my LoginComp.js file which contains the following code:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';
import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View,
  Image,
  TextInput,
  Button,
  TouchableHighlight
} from 'react-native';

class LoginComp extends Component {
  constructor(){
    super(props);
  }
  render() {
    return (
      <View style={{flex: 1}}>
        <View style={this.props.styles.loginLogoContainer}>
          <Image style={this.props.styles.view1logo} source={require('../imgs/Logo.png')} />
        </View>
        <View style={this.props.styles.loginContainer}>
          <Text>Użytkownik:</Text>
          <TextInput
            style={this.props.styles.defaultInput}
            placeholder="Użytkownik"
            stretch={true}
            autoComplete={false}
            autoCorrect={false}
          />
          <Text>Hasło:</Text>
          <TextInput
            style={this.props.styles.defaultInput}
            placeholder="Hasło"
            stretch={true}
            autoComplete={false}
            autoCorrect={false}
            secureTextEntry={true}
          />
        <TouchableHighlight onPress={this.props.LoginPress}>
            <Text style={this.props.styles.loginButton}>Login</Text>
          </TouchableHighlight>
        </View>
        <View style={this.props.styles.registrationWrapper}>
          <Text>- lub -</Text>
          <TouchableHighlight onPress={this.props.t_Registration}>
            <Text style={this.props.styles.registration}>Załóż nowe konto</Text>
          </TouchableHighlight>
        </View>
      </View>
    );
  }
}

module.exports = LoginComp;

Body:
I hit this error when attempting to use:

class Leaderboard extends React.component {

}

It should have been Component with a capital C!


来源: stackexchange

问:
How to archive multiple isolated instances of a micro service app in kubernetes?
We developed an application which consist out of a few go/java services, a mongoDB and a reverse proxy which forwards REST-calls to the specific service. Each service runs in an own docker container.
The whole app is deployable with a single docker-compose file.

We successfully managed to deploy the app in a kubernetes cluster.

Now the "tricky" part: We want to deploy one isolated instance of the app for each customer. (remember one instance consists of approximately 10 containers)

In the past we reached this goal by deploying multiple instances of the docker-compose file.

What is the recommended way in Kubernetes to reach this?

Thank you very much.

答:
In kuberenetes, you can package all your resources into a helm chart (https://helm.sh/docs/topics/charts/) so that you deploy different instances of each and can manage its lifecycle. You can also pass parameters for each of the instances if required.

Another method is by deploying your application instance using kubernetes operators (https://kubernetes.io/docs/concepts/extend-kubernetes/operator/). This also helps in managing your application components.

ContentLicense: CC BY-SA 4.0


问:
Tensorflow2 not working on Ubuntu 18.04. Probably incorrect installation, but what?
I installed Tensorflow2.1 on Ubuntu 18.04.3 with cuda 10.1, cudnn7.6.5.32, Nvidia driver 430.5.

I could not follow the instructions on the tensorflow site properly as many parts do not work, but, after many hours, I did finally get all the components installed.  When I try to run a 20 line mnist example I get:

```<code>2020-02-19 03:02:24.915143: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1555] Found device 0 with properties:
pciBusID: 0000:01:00.0 name: GeForce GTX 1080 Ti computeCapability: 6.1
coreClock: 1.683GHz coreCount: 28 deviceMemorySize: 10.91GiB deviceMemoryBandwidth: 451.17GiB/s
2020-02-19 03:02:24.915194: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1
2020-02-19 03:02:24.915216: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10
2020-02-19 03:02:24.915234: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10
2020-02-19 03:02:24.915253: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10
2020-02-19 03:02:24.915271: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10
2020-02-19 03:02:24.915289: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10
2020-02-19 03:02:24.915308: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7
2020-02-19 03:02:24.917997: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1697] Adding visible gpu devices: 0
2020-02-19 03:02:24.918060: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1
2020-02-19 03:02:24.920974: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1096] Device interconnect StreamExecutor with strength 1 edge matrix:
2020-02-19 03:02:24.921000: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1102]      0
2020-02-19 03:02:24.921013: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] 0:   N
2020-02-19 03:02:24.924091: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1241] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10258 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:01:00.0, compute capability: 6.1)
Train on 60000 samples
Epoch 1/5
2020-02-19 03:02:26.155747: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10
2020-02-19 03:02:26.156063: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED
2020-02-19 03:02:26.156110: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED
2020-02-19 03:02:26.156225: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED
2020-02-19 03:02:26.156253: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED
2020-02-19 03:02:26.156483: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED
2020-02-19 03:02:26.158110: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED
2020-02-19 03:02:26.158133: W tensorflow/stream_executor/stream.cc:2041] attempting to perform BLAS operation using StreamExecutor without BLAS support
2020-02-19 03:02:26.158158: W tensorflow/core/common_runtime/base_collective_executor.cc:217] BaseCollectiveExecutor::StartAbort Internal: Blas GEMM launch failed : a.shape=(32, 784), b.shape=(784, 128), m=32, n=128, k=784
     [[{{node sequential/dense/MatMul}}]]
</code>```

I understand that this error probably means there is an error in the installation, but how can I determine what ?  Is there ANY way to determine which version of cudnn is used ?

I have googled extensively and there are loads of people with the same problem, but no solutions.

答:
I spent 2 days trying to get this rubbish to work.  In the end I'll never know why it finally started to work.  I now know that everything I did was correct in principle but, although the install apparently worked, a simple mnist example failed with CUBLAS_STATUS_NOT_INITIALIZED.

When I finally got it to work, I:

Removed every Cuda related package before I started.

Followed the procedure here.  It is way clearer than the official docs.

At step 4) installing cuda 10.1 I executed:

sudo apt-get install cuda-10-1

instead of:

sudo apt-get install cuda

This ensures that cuda is not automatically upgrade to the most recent version (10.2) at time of writing.

Body:
I installed Tensorflow2.1 on Ubuntu 18.04.3 with cuda 10.1, cudnn7.6.5.32, Nvidia driver 430.5.

I could not follow the instructions on the tensorflow site properly as many parts do not work, but, after many hours, I did finally get all the components installed.  When I try to run a 20 line mnist example I get:

2020-02-19 03:02:24.915143: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1555] Found device 0 with properties:
pciBusID: 0000:01:00.0 name: GeForce GTX 1080 Ti computeCapability: 6.1
coreClock: 1.683GHz coreCount: 28 deviceMemorySize: 10.91GiB deviceMemoryBandwidth: 451.17GiB/s
2020-02-19 03:02:24.915194: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1
2020-02-19 03:02:24.915216: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10
2020-02-19 03:02:24.915234: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10
2020-02-19 03:02:24.915253: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10
2020-02-19 03:02:24.915271: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10
2020-02-19 03:02:24.915289: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10
2020-02-19 03:02:24.915308: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7
2020-02-19 03:02:24.917997: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1697] Adding visible gpu devices: 0
2020-02-19 03:02:24.918060: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1
2020-02-19 03:02:24.920974: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1096] Device interconnect StreamExecutor with strength 1 edge matrix:
2020-02-19 03:02:24.921000: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1102]      0
2020-02-19 03:02:24.921013: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] 0:   N
2020-02-19 03:02:24.924091: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1241] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10258 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:01:00.0, compute capability: 6.1)
Train on 60000 samples
Epoch 1/5
2020-02-19 03:02:26.155747: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10
2020-02-19 03:02:26.156063: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED
2020-02-19 03:02:26.156110: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED
2020-02-19 03:02:26.156225: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED
2020-02-19 03:02:26.156253: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED
2020-02-19 03:02:26.156483: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED
2020-02-19 03:02:26.158110: E tensorflow/stream_executor/cuda/cuda_blas.cc:238] failed to create cublas handle: CUBLAS_STATUS_NOT_INITIALIZED
2020-02-19 03:02:26.158133: W tensorflow/stream_executor/stream.cc:2041] attempting to perform BLAS operation using StreamExecutor without BLAS support
2020-02-19 03:02:26.158158: W tensorflow/core/common_runtime/base_collective_executor.cc:217] BaseCollectiveExecutor::StartAbort Internal: Blas GEMM launch failed : a.shape=(32, 784), b.shape=(784, 128), m=32, n=128, k=784
     [[{{node sequential/dense/MatMul}}]]

I understand that this error probably means there is an error in the installation, but how can I determine what ?  Is there ANY way to determine which version of cudnn is used ?

I have googled extensively and there are loads of people with the same problem, but no solutions.


问:
Create ReadStream from api request having audio gzip audio buffer in express js
How we can create read stream from file uploaded buffer something like below</p>

```<code>const express = require('express');

const router = express.Router();
const multer = require('multer');
const multer = require('zlib');
const fs= require('fs')
router.post('/upload/:recordId', upload.single('file'), async (req, res, next) => {
  try {
    const buffer=req.file.buffer // this is test.gz file buffer
    let write;
    var r = fs.createReadStream(buffer);// this line is not working
    var z = zlib.createGunzip();
    var w = fs.createWriteStream(write); // this line is not working
    r.pipe(z).pipe(w);
    res.status(204).json({ statusDescription: '204 No Content' });
  } catch (ex) {
    next(ex);
  }
});
</code>```

答:
How about this answer? Please think of this as just one of several possible answers.

In this answer, stream module is used.

Modified script:

When your script is modified, please modify as follows.

From:

```<code>var r = fs.createReadStream(buffer);
</code>```

To:

```<code>const stream = require("stream");
var r = new stream.PassThrough().end(buffer);
</code>```

And also, please modify as follows.

From:

```<code>const multer = require('zlib');
</code>```

To:

```<code>const zlib = require('zlib');
</code>```

Reference:

Class: stream.PassThrough

If I misunderstood your question and this was not the direction you want, I apologize.

Body:
How we can create read stream from file uploaded buffer something like below

const express = require('express');

const router = express.Router();
const multer = require('multer');
const multer = require('zlib');
const fs= require('fs')
router.post('/upload/:recordId', upload.single('file'), async (req, res, next) => {
  try {
    const buffer=req.file.buffer // this is test.gz file buffer
    let write;
    var r = fs.createReadStream(buffer);// this line is not working
    var z = zlib.createGunzip();
    var w = fs.createWriteStream(write); // this line is not working
    r.pipe(z).pipe(w);
    res.status(204).json({ statusDescription: '204 No Content' });
  } catch (ex) {
    next(ex);
  }
});

Body:
How about this answer? Please think of this as just one of several possible answers.

In this answer, stream module is used.

Modified script:

When your script is modified, please modify as follows.

From:

var r = fs.createReadStream(buffer);

To:

const stream = require("stream");
var r = new stream.PassThrough().end(buffer);

And also, please modify as follows.

From:

const multer = require('zlib');

To:

const zlib = require('zlib');

Reference:

Class: stream.PassThrough

If I misunderstood your question and this was not the direction you want, I apologize.


问:
How do I slowly migrate topics out of a Kafka node?
Imagine I have a kafka node that holds a lot of topics, the disk is degraded so I have to start moving topics out of it to the other nodes in the cluster. Kafka manager allows me to do that but the process is cumersome and requires a lot of clicks.

The simplest solution to prevent most clicking would be to just click on all topics but this is obviously not ideal as there will be a lot of disruption from all consumers all at once (and a lot of disk and network stuff changing all at the same time).

Is there a tool or something I could use (or an API I could call) that would allow me to slowly move topics one by one instead?

Kind of like running the reassign and getting the plans but programatically, I'd rather not do bash magic for this.

答:
Found a couple tools that can do it:

https://github.com/Yelp/kafka-utils

https://github.com/linkedin/cruise-control

https://github.com/DataDog/kafka-kit


问:
Binding method to a slot property
I am using VUE 2.6.11 and class components. I am trying to wrap components that can be displayed as modal inside a component that will manage the modal state.

As per docs I can access my child props/methods in a parent component with Scoped Slots
For some reasons my method does not bind to a template:

Modal.vue:

@Component
export default class Modal extends Vue {

  @Prop(String) icon !: string
  @Prop({ default: 'Open popup' }) tooltip !: string

  isVisible = false

  toggleModal() {
    console.log('toggleModal from Modal')
    this.isVisible = !this.isVisible
  }

  toggleModalFactory = 'simple property'
}
```
<p>Template:</p>
<pre class="lang-html prettyprint-override"><code><div >
  <div v-if="isVisible" class="page overlay" >
    <div class="page-content" >
      <div class="dialog-content" >
        <div class="row col" >
          <slot :toggle-modal="toggleModal" />
        </div >
      </div >
    </div >
  </div >
  <button class="btn-primary btn-icon"
          :title="$t(tooltip)"
          @click="toggleModal()" >
    <i :class="icon" />
  </button >
</div >
</code>```

Then in my Parent I do the following:

<modal icon="plus-icon" v-slot:default="modal" >
  <test-component :toggle-modal="modal.toggleModal" ></test-component >
</modal >
```
<p>Dev tools claim my method is bound
<img src="https://i.stack.imgur.com/QmQNr.png" alt="dev-tools" /></p>
<p>But when I execute the prop function in my nested modal content:</p>
<pre class="lang-typescript prettyprint-override"><code>export default class TestComponent extends Vue {

  @Prop() toggleModal !: Function

  @Emit()
  dismiss() {
    this.toggleModal()
    console.log('dismiss from TestComponent')
  }

  @Emit()
  accept() {
    this.toggleModal()
    console.log('accept from TestComponent')
    return 'close-success'
  }
}
</code>```

I get following errors:

[Vue warn]: Property or method "toggleModal" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

and:

TypeError: this.toggleModal is not a function

I have found this post (which actually points to docs I mentioned at the begining but I don't see a difference that breaks my code

答:
A story of a developer loosing his life:

My TestComponent was missing the @Component annotation ...

```

Title: Binding method to a slot property

Body:
I am using VUE 2.6.11 and class components. I am trying to wrap components that can be displayed as modal inside a component that will manage the modal state.

As per docs I can access my child props/methods in a parent component with Scoped Slots
For some reasons my method does not bind to a template:

Modal.vue:

@Component
export default class Modal extends Vue {

  @Prop(String) icon !: string
  @Prop({ default: 'Open popup' }) tooltip !: string

  isVisible = false

  toggleModal() {
    console.log('toggleModal from Modal')
    this.isVisible = !this.isVisible
  }

  toggleModalFactory = 'simple property'
}

Template:

          <slot :toggle-modal="toggleModal" />

  <button class="btn-primary btn-icon"
          :title="$t(tooltip)"
          @click="toggleModal()" >

  </button >

Then in my Parent I do the following:

<modal icon="plus-icon" v-slot:default="modal" >
  <test-component :toggle-modal="modal.toggleModal" ></test-component >
</modal >

Dev tools claim my method is bound

But when I execute the prop function in my nested modal content:

export default class TestComponent extends Vue {

  @Prop() toggleModal !: Function

  @Emit()
  dismiss() {
    this.toggleModal()
    console.log('dismiss from TestComponent')
  }

  @Emit()
  accept() {
    this.toggleModal()
    console.log('accept from TestComponent')
    return 'close-success'
  }
}

I get following errors:

[Vue warn]: Property or method "toggleModal" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

and:

TypeError: this.toggleModal is not a function

I have found this post (which actually points to docs I mentioned at the begining but I don't see a difference that breaks my code

Body:
A story of a developer loosing his life:

My TestComponent was missing the @Component annotation ...

<script lang="ts" >
import { Emit, Prop, Vue, Component } from 'vue-property-decorator'

@Component
export default class TestComponent extends Vue {

  @Prop(Function) close !: Function

  @Emit()
  dismiss() {
    this.close()
    console.log('dismiss from TestComponent')
  }

  @Emit()
  accept() {
    console.log('close', this.close, this)
    this.close()
    console.log('accept from TestComponent')
    return 'close-success'
  }
}
</script >


问:
Android dex2oat build:ERROR: Dex2oat failed to compile a boot image
Build Android 9.0

ERROR: Dex2oat failed to compile a boot image. The boot classpath is likely inconsistent. Rebuild with ART_BOOT_IMAGE_EXTRA_ARGS=–runtime-arg -verbose: verifier to see verification errors.

答:
now we use the below workaround method
export WITH_DEXPREOPT=falsee to disable dex2oat</p>


问:
Confusion as to what this is exactly returning (WinNT in VB.net)
```<code>'get list of all users on domain

     Dim de As New DirectoryEntry()
     de.Path = "WinNT://Domain.mydomain/JohnDoe2-1"
     For Each d As DirectoryEntry In de.Children()
        Console.WriteLine(d.Name)
        Console.ReadLine()
    Next
</code>```

When I run WintNT://Domain.mydomain it lists the users on the domain.
When I run it with /JOhnDoe2-1 I get a list of something. Are these files and is there a way to expand to search within them?

Any hints toward searching domain users for a specific file would be helpful.
Thanks folks

答:
What that returns depends on what JohnDoe2-1 is... is it a user?  a computer name?  something else?  We don't know...

For hints on solving your problem, look at
http://msdn.microsoft.com/en-us/library/aa772211(v=VS.85).aspx
and
http://msdn.microsoft.com/en-us/library/aa746534(v=vs.85).aspx

ContentLicense: CC BY-SA 3.0

Body:
'get list of all users on domain

     Dim de As New DirectoryEntry()
     de.Path = "WinNT://Domain.mydomain/JohnDoe2-1"
     For Each d As DirectoryEntry In de.Children()
        Console.WriteLine(d.Name)
        Console.ReadLine()
    Next

When I run WintNT://Domain.mydomain it lists the users on the domain.
When I run it with /JOhnDoe2-1 I get a list of something. Are these files and is there a way to expand to search within them?

Any hints toward searching domain users for a specific file would be helpful.
Thanks folks


问:
No such file while indicating application properties using Dockerfile for a Spring Boot jar
I'm using Docker Compose to create a container for a Spring Boot application.

I'm receiving the following errors when I do docker-compose up:

Recreating backend_springboot ... error

ERROR: for backend_springboot  Cannot start service service: OCI
  runtime create failed: container_linux.go:346: starting container
  process caused "exec: \"sh -c java
  -Dspring.config.location=/application.properties -Djava.security.egd=file:/dev/./urandom $JAVA_OPTS -jar /app.jar\": stat sh -c java -Dspring.config.location=/application.properties
  -Djava.security.egd=file:/dev/./urandom $JAVA_OPTS -jar /app.jar: no such file or directory": unknown

ERROR: for service  Cannot start service service: OCI runtime create
  failed: container_linux.go:346: starting container process caused
  "exec: \"sh -c java -Dspring.config.location=/application.properties
  -Djava.security.egd=file:/dev/./urandom $JAVA_OPTS -jar /app.jar\": stat sh -c java -Dspring.config.location=/application.properties
  -Djava.security.egd=file:/dev/./urandom $JAVA_OPTS -jar /app.jar: no such file or directory": unknown

My structure:

```<code>├── docker-compose.yml
├── spring-boot
│   ├── Dockerfile
│   ├── application.properties
│   └── backofficeservices-0.0.1.jar
</code>```

docker-compose.yml

```<code>version: '3'
services:
  service:
    container_name: backend_springboot
    build: ./spring-boot
    ports:
      - "80:8080"
    restart: always
</code>```

spring-boot/Dockerfile

```<code>FROM openjdk:8-jre-alpine as gradle

COPY backofficeservices-0.0.1.jar /app.jar

COPY application.properties /application.properties

ENV JAVA_OPTS=""

ENTRYPOINT ["sh -c java -Dspring.config.location=/application.properties -Djava.security.egd=file:/dev/./urandom $JAVA_OPTS -jar /app.jar"]

EXPOSE 8080
</code>```

As far as I know, the application.properties is not found. I will appreciate any help to detect my error.

My goal is to run my Spring Boot app applying the application.properties I have there.

答:
You have specified an ENTRYPOINT using a single "word".  When you launch the container, it is trying to run that as a single "word" – it is looking for a binary named sh -c java ..., with spaces and all as part of the filename.  If your command has multiple "words" and you're using the JSON-array form, you have to correctly manually split it up into words yourself.

```<code>ENTRYPOINT ["sh", "-c", "java -Dspring.config.location=..."]
</code>```

A Dockerfile CMD and ENTRYPOINT are fairly similar; both provide part of the command the container ultimately runs.  If you only need one of them I'd recommend using CMD instead, for two reasons: it makes it easier to get a debugging shell on the built image docker run --rm -it myimage /bin/sh, and there's a fairly standard pattern of using an ENTRYPOINT script to do some initial setup and then exec "$@" to run the CMD.

```<code>CMD ["sh", "-c", "java -Dspring.config.location=..."]
</code>```

If you have this form, Docker can provide the sh -c ... wrapper for you.

```<code>CMD java -Dspring.config.location=...
</code>```

With a little bit more cleanup, that would leave the final Dockerfile something like

FROM openjdk:8-jre-alpine
COPY backofficeservices-0.0.1.jar /app.jar
COPY application.properties /application.properties
ENV JAVA_OPTS=""
CMD java \
      -Dspring.config.location=/application.properties \
      -Djava.security.egd=file:/dev/./urandom \
      $JAVA_OPTS \
      -jar /app.jar
EXPOSE 8080
```

Body:
I'm using Docker Compose to create a container for a Spring Boot application.

I'm receiving the following errors when I do docker-compose up:

Recreating backend_springboot ... error

ERROR: for backend_springboot  Cannot start service service: OCI
  runtime create failed: container_linux.go:346: starting container
  process caused "exec: \"sh -c java
  -Dspring.config.location=/application.properties -Djava.security.egd=file:/dev/./urandom $JAVA_OPTS -jar /app.jar\": stat sh -c java -Dspring.config.location=/application.properties
  -Djava.security.egd=file:/dev/./urandom $JAVA_OPTS -jar /app.jar: no such file or directory": unknown

ERROR: for service  Cannot start service service: OCI runtime create
  failed: container_linux.go:346: starting container process caused
  "exec: \"sh -c java -Dspring.config.location=/application.properties
  -Djava.security.egd=file:/dev/./urandom $JAVA_OPTS -jar /app.jar\": stat sh -c java -Dspring.config.location=/application.properties
  -Djava.security.egd=file:/dev/./urandom $JAVA_OPTS -jar /app.jar: no such file or directory": unknown

My structure:

├── docker-compose.yml
├── spring-boot
│   ├── Dockerfile
│   ├── application.properties
│   └── backofficeservices-0.0.1.jar

docker-compose.yml

version: '3'
services:
  service:
    container_name: backend_springboot
    build: ./spring-boot
    ports:
      - "80:8080"
    restart: always

spring-boot/Dockerfile

FROM openjdk:8-jre-alpine as gradle

COPY backofficeservices-0.0.1.jar /app.jar

COPY application.properties /application.properties

ENV JAVA_OPTS=""

ENTRYPOINT ["sh -c java -Dspring.config.location=/application.properties -Djava.security.egd=file:/dev/./urandom $JAVA_OPTS -jar /app.jar"]

EXPOSE 8080

As far as I know, the application.properties is not found. I will appreciate any help to detect my error.

My goal is to run my Spring Boot app applying the application.properties I have there.

Body:
You have specified an ENTRYPOINT using a single "word".  When you launch the container, it is trying to run that as a single "word" – it is looking for a binary named sh -c java ..., with spaces and all as part of the filename.  If your command has multiple "words" and you're using the JSON-array form, you have to correctly manually split it up into words yourself.

ENTRYPOINT ["sh", "-c", "java -Dspring.config.location=..."]

A Dockerfile CMD and ENTRYPOINT are fairly similar; both provide part of the command the container ultimately runs.  If you only need one of them I'd recommend using CMD instead, for two reasons: it makes it easier to get a debugging shell on the built image docker run --rm -it myimage /bin/sh, and there's a fairly standard pattern of using an ENTRYPOINT script to do some initial setup and then exec "$@" to run the CMD.

CMD ["sh", "-c", "java -Dspring.config.location=..."]

If you have this form, Docker can provide the sh -c ... wrapper for you.

CMD java -Dspring.config.location=...

With a little bit more cleanup, that would leave the final Dockerfile something like

FROM openjdk:8-jre-alpine
COPY backofficeservices-0.0.1.jar /app.jar
COPY application.properties /application.properties
ENV JAVA_OPTS=""
CMD java \
      -Dspring.config.location=/application.properties \
      -Djava.security.egd=file:/dev/./urandom \
      $JAVA_OPTS \
      -jar /app.jar
EXPOSE 8080


问:
How can I use SQL's YEAR(), MONTH() and DAY() in Doctrine2?
I want to perform a query which would look like this in native SQL:

```<code>SELECT
    AVG(t.column) AS average_value
FROM
    table t
WHERE
    YEAR(t.timestamp) = 2013 AND
    MONTH(t.timestamp) = 09 AND
    DAY(t.timestamp) = 16 AND
    t.somethingelse LIKE 'somethingelse'
GROUP BY
    t.somethingelse;
</code>```

If I am trying to implement this in Doctrine's query builder like this:

```<code>$qb = $this->getDoctrine()->createQueryBuilder();
$qb->select('e.column AS average_value')
   ->from('MyBundle:MyEntity', 'e')
   ->where('YEAR(e.timestamp) = 2013')
   ->andWhere('MONTH(e.timestamp) = 09')
   ->andWhere('DAY(e.timestamp) = 16')
   ->andWhere('u.somethingelse LIKE somethingelse')
   ->groupBy('somethingelse');
</code>```

I get the error exception

[Syntax Error] line 0, col 63: Error: Expected known function, got 'YEAR'

How can I implement my query with Doctrines query builder?

Notes:

I know about Doctrine's Native SQL. I've tried this, but it leads to the problem that my productive and my development database tables have different names. I want to work database agnostic, so this is no option.

Although I want to work db agnostic: FYI, I am using MySQL.

There is way to extend Doctrine to "learn" the YEAR() etc. statements, e.g. as seen here. But I am looking for a way to avoid including third party plugins.

答:
go to this page and choose your database systeme and pick up functions thats you want </p>

<p>...
I too had the same problem as you... then I modified my doctrine.yaml file using exactly the same names as in the github file and it worked.</p>

Body:
I want to perform a query which would look like this in native SQL:

SELECT
    AVG(t.column) AS average_value
FROM
    table t
WHERE
    YEAR(t.timestamp) = 2013 AND
    MONTH(t.timestamp) = 09 AND
    DAY(t.timestamp) = 16 AND
    t.somethingelse LIKE 'somethingelse'
GROUP BY
    t.somethingelse;

If I am trying to implement this in Doctrine's query builder like this:

$qb = $this->getDoctrine()->createQueryBuilder();
$qb->select('e.column AS average_value')
   ->from('MyBundle:MyEntity', 'e')
   ->where('YEAR(e.timestamp) = 2013')
   ->andWhere('MONTH(e.timestamp) = 09')
   ->andWhere('DAY(e.timestamp) = 16')
   ->andWhere('u.somethingelse LIKE somethingelse')
   ->groupBy('somethingelse');

I get the error exception

[Syntax Error] line 0, col 63: Error: Expected known function, got 'YEAR'

How can I implement my query with Doctrines query builder?

Notes:

I know about Doctrine's Native SQL. I've tried this, but it leads to the problem that my productive and my development database tables have different names. I want to work database agnostic, so this is no option.

Although I want to work db agnostic: FYI, I am using MySQL.

There is way to extend Doctrine to "learn" the YEAR() etc. statements, e.g. as seen here. But I am looking for a way to avoid including third party plugins.

Body:
go to this page and choose your database systeme and pick up functions thats you want

...
I too had the same problem as you... then I modified my doctrine.yaml file using exactly the same names as in the github file and it worked.


问:
Trying to use single Angular component as template for multiple HTML content
I'm an Angular rookie trying to use the single component @comic-story as a template multiple comics, ultimately to make individual comic URLs (local for dev):

http://localhost:4200/bottle-of-red

http://localhost:4200/franks-next-mission

http://localhost:4200/i-did-nothing

Each comic is a single page with a carousel with elaborate HTML:

Bottle of Red

...

Bottle of Red: Page 1 of 7

       Previous
       Next

About This Page

...

      ...

      ...

Story Notes

...

```

My current directory tree from app:

comic-story/

|- comic-story.component.html

|- comic-story.component.scss

|- comic-story.component.spec.ts

|- comic-story.component.ts

|- comics/

|- |- bottle-of-red.component.html

|- |- bottle-of-red.component.scss

|- |- bottle-of-red.component.spec.ts

|- |- bottle-of-red.component.ts

|- |- franks-next-mission.component.html

|- |- franks-next-mission.component.scss

|- |- franks-next-mission.component.spec.ts

|- |- franks-next-mission.component.ts

|- |- i-did-nothing.component.html

|- |- i-did-nothing.component.scss

|- |- i-did-nothing.component.spec.ts

|- |- i-did-nothing.component.ts

my directory tree

What's the best way of hooking this up?

答:
Here is a stackblitz link showing how I do it using Angular Router,
stackblitz

Hope this helps

Body:
I'm an Angular rookie trying to use the single component @comic-story as a template multiple comics, ultimately to make individual comic URLs (local for dev):

http://localhost:4200/bottle-of-red

http://localhost:4200/franks-next-mission

http://localhost:4200/i-did-nothing

Each comic is a single page with a carousel with elaborate HTML:

Bottle of Red

...

Bottle of Red: Page 1 of 7

       Previous
       Next

About This Page

...

      ...

      ...

Story Notes

...

My current directory tree from app:

comic-story/

|- comic-story.component.html

|- comic-story.component.scss

|- comic-story.component.spec.ts

|- comic-story.component.ts

|- comics/

|- |- bottle-of-red.component.html

|- |- bottle-of-red.component.scss

|- |- bottle-of-red.component.spec.ts

|- |- bottle-of-red.component.ts

|- |- franks-next-mission.component.html

|- |- franks-next-mission.component.scss

|- |- franks-next-mission.component.spec.ts

|- |- franks-next-mission.component.ts

|- |- i-did-nothing.component.html

|- |- i-did-nothing.component.scss

|- |- i-did-nothing.component.spec.ts

|- |- i-did-nothing.component.ts

my directory tree

What's the best way of hooking this up?


问:
Count total number of words in a corpus using NLTK's Conditional Frequency Distribution in Python (newbie)
I need to count the number of words (word appearances) in some corpus using NLTK package.

Here is my corpus:

```<code>corpus = PlaintextCorpusReader('C:\DeCorpus', '.*')
</code>```

Here is how I try to get the total number of words for each document:

```<code>cfd_appr = nltk.ConditionalFreqDist(
    (textname, num_appr)
    for textname in corpus.fileids()
    for num_appr in [len(w) for w in corpus.raw(fileids=textname).replace("\r", " ").replace("\n", " ").split()])
</code>```

(I split strings into words manually, somehow it works better then using corpus.words(), but the problem remains the same, so it's irrelevant). Generally, this does the same (wrong) job:

```<code>cfd_appr = nltk.ConditionalFreqDist(
    (textname, num_appr)
    for textname in corpus.fileids()
    for num_appr in [len(w) for w in corpus.words(fileids=textname)])
</code>```

This is what I get by typing cfd.appr.tabulate():

```<code>                        1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21
2022.12.06_Bild 2.txt   3  36 109  40  47  43  29  29  33  23  24  12   8   6   4   2   2   0   0   0   0
2022.12.06_Bild 3.txt   2  42 129  59  57  46  46  35  22  24  17  21  13   5   6   6   2   2   2   0   0
2022.12.06_Bild 4.txt   3  36 106  48  43  32  38  30  19  39  15  14  16   6   5   8   3   2   3   1   0
2022.12.06_Bild 5.txt   1  55 162  83  68  72  46  24  34  38  27  16  12   8   8   5   9   3   1   5   1
2022.12.06_Bild 6.txt   7  69 216  76 113  83  73  52  49  42  37  20  19   9   7   5   3   6   3   0   1
2022.12.06_Bild 8.txt   0   2   0   1   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
</code>```

But these are numbers of words of different length. What I need is just this (only one type of item (text) should be counted by number of words):

```<code>2022.12.06_Bild 2.txt    451.0
2022.12.06_Bild 3.txt    538.0
2022.12.06_Bild 4.txt    471.0
2022.12.06_Bild 5.txt    679.0
2022.12.06_Bild 6.txt    890.0
2022.12.06_Bild 8.txt      3.0
dtype: float64
</code>```

I.e. the sum of all words of different length (or sum of columns that was composed using DataFrame(cfd_appr).transpose().sum(axis=1). (By the way, if there is some way to set up a name for this column that would also a solution, but .rename({None: 'W. appear.'}, axis='columns') is not working, and the solution would be generally not clear enough.

So, what I need is:

```<code>                             1
2022.12.06_Bild 2.txt    451.0
2022.12.06_Bild 3.txt    538.0
2022.12.06_Bild 4.txt    471.0
2022.12.06_Bild 5.txt    679.0
2022.12.06_Bild 6.txt    890.0
2022.12.06_Bild 8.txt      3.0
</code>```

Would be grateful for help!

答:
Well, here is what was actually needed:

First, get the numbers of words of different length (just as I did before):

```<code>cfd_appr = nltk.ConditionalFreqDist(
    (textname, num_appr)
    for textname in corpus.fileids()
    for num_appr in [len(w) for w in corpus.raw(fileids=textname).replace("\r", " ").replace("\n", " ").split()])
</code>```

Then add import DataFrame as pd and add to_frame(1) to the dtype: float64 Series that I got by summing the columns:

```<code>pd.DataFrame(cfd_appr).transpose().sum(axis=1).to_frame(1)
</code>```

That's it. However, if somebody knows how to sum them uo in the definition of cfd_appr, that would be some more elegant solution.

Body:
I need to count the number of words (word appearances) in some corpus using NLTK package.

Here is my corpus:

corpus = PlaintextCorpusReader('C:\DeCorpus', '.*')

Here is how I try to get the total number of words for each document:

cfd_appr = nltk.ConditionalFreqDist(
    (textname, num_appr)
    for textname in corpus.fileids()
    for num_appr in [len(w) for w in corpus.raw(fileids=textname).replace("\r", " ").replace("\n", " ").split()])

(I split strings into words manually, somehow it works better then using corpus.words(), but the problem remains the same, so it's irrelevant). Generally, this does the same (wrong) job:

cfd_appr = nltk.ConditionalFreqDist(
    (textname, num_appr)
    for textname in corpus.fileids()
    for num_appr in [len(w) for w in corpus.words(fileids=textname)])

This is what I get by typing cfd.appr.tabulate():

                        1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21
2022.12.06_Bild 2.txt   3  36 109  40  47  43  29  29  33  23  24  12   8   6   4   2   2   0   0   0   0
2022.12.06_Bild 3.txt   2  42 129  59  57  46  46  35  22  24  17  21  13   5   6   6   2   2   2   0   0
2022.12.06_Bild 4.txt   3  36 106  48  43  32  38  30  19  39  15  14  16   6   5   8   3   2   3   1   0
2022.12.06_Bild 5.txt   1  55 162  83  68  72  46  24  34  38  27  16  12   8   8   5   9   3   1   5   1
2022.12.06_Bild 6.txt   7  69 216  76 113  83  73  52  49  42  37  20  19   9   7   5   3   6   3   0   1
2022.12.06_Bild 8.txt   0   2   0   1   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

But these are numbers of words of different length. What I need is just this (only one type of item (text) should be counted by number of words):

2022.12.06_Bild 2.txt    451.0
2022.12.06_Bild 3.txt    538.0
2022.12.06_Bild 4.txt    471.0
2022.12.06_Bild 5.txt    679.0
2022.12.06_Bild 6.txt    890.0
2022.12.06_Bild 8.txt      3.0
dtype: float64

I.e. the sum of all words of different length (or sum of columns that was composed using DataFrame(cfd_appr).transpose().sum(axis=1). (By the way, if there is some way to set up a name for this column that would also a solution, but .rename({None: 'W. appear.'}, axis='columns') is not working, and the solution would be generally not clear enough.

So, what I need is:

                             1
2022.12.06_Bild 2.txt    451.0
2022.12.06_Bild 3.txt    538.0
2022.12.06_Bild 4.txt    471.0
2022.12.06_Bild 5.txt    679.0
2022.12.06_Bild 6.txt    890.0
2022.12.06_Bild 8.txt      3.0

Would be grateful for help!

Body:
Well, here is what was actually needed:

First, get the numbers of words of different length (just as I did before):

cfd_appr = nltk.ConditionalFreqDist(
    (textname, num_appr)
    for textname in corpus.fileids()
    for num_appr in [len(w) for w in corpus.raw(fileids=textname).replace("\r", " ").replace("\n", " ").split()])

Then add import DataFrame as pd and add to_frame(1) to the dtype: float64 Series that I got by summing the columns:

pd.DataFrame(cfd_appr).transpose().sum(axis=1).to_frame(1)

That's it. However, if somebody knows how to sum them uo in the definition of cfd_appr, that would be some more elegant solution.


问:
Wordpress - Retrieve all Posts by 'post_type' then filter by taxonomy

I have a Wordpress installation with ACF (Advanced Custom Fields) installed. I created the Class post type and each Class has it's on Location value.

How can I retrieve every Class and get the location I have chosen for that Class?
I'm currently using this function to retrieve the name of the 'Programs':

```<code>```
    $args = array(
        'post_type' => 'class',
        'posts_per_page' => -1,
    );
    $query = new WP_Query($args);
    if ($query->have_posts() ) :
        while ( $query->have_posts() ) : $query->the_post();
            echo get_the_ID();
            echo get_the_title();
        endwhile;
    endif;
```
</code>```

I'm trying to populate a dropdown list 'Location' which filters the next dropdown with the classes available for that location.

Any help or advice would be greatly appreciated. Thanks

答:
Not sure if this is what you're asking for, but here's how you can pull each posts locations inside of your query loop. Just update locations in the get_the_terms function with what you named the taxonomy.

```<code>if ($query->have_posts() ) :
    while ( $query->have_posts() ) : $query->the_post();
        $locations = get_the_terms($post->ID, 'locations');

        echo get_the_ID();
        echo get_the_title();

        foreach ($locations as $location) :
          echo '<p>' . $location->name . '</p>';
        endforeach;
    endwhile;
endif;
</code>```

Body:
I have a Wordpress installation with ACF (Advanced Custom Fields) installed. I created the Class post type and each Class has it's on Location value.

How can I retrieve every Class and get the location I have chosen for that Class?
I'm currently using this function to retrieve the name of the 'Programs':

    $args = array(
        'post_type' => 'class',
        'posts_per_page' => -1,
    );
    $query = new WP_Query($args);
    if ($query->have_posts() ) :
        while ( $query->have_posts() ) : $query->the_post();
            echo get_the_ID();
            echo get_the_title();
        endwhile;
    endif;

I'm trying to populate a dropdown list 'Location' which filters the next dropdown with the classes available for that location.

Any help or advice would be greatly appreciated. Thanks

Body:
Not sure if this is what you're asking for, but here's how you can pull each posts locations inside of your query loop. Just update locations in the get_the_terms function with what you named the taxonomy.

if ($query->have_posts() ) :
    while ( $query->have_posts() ) : $query->the_post();
        $locations = get_the_terms($post->ID, 'locations');

        echo get_the_ID();
        echo get_the_title();

        foreach ($locations as $location) :
          echo '<p>' . $location->name . '</p>';
        endforeach;
    endwhile;
endif;


问:
How must I print a value inside a nested dictionary without being too broad
I have a nested dictionary that was created through iteration, the values of the dictionary that HAS BEEN nested in another dictionary are unknown to me. So, without the keys/values being hardcoded in, how can I iterate through the dictionaries to pick a specific value to print?

Here's what I have in pseudocode (copying and pasting even chunks of the code would be nightmarish):

dataDict is my main dictionary

a loop runs however many times I have columns of data (that was a gross-sounding sentence, ex: runs 15 times if I have 15 columns of data)

this loop creates another dictionary first, called rowInfo. rowInfo is then hardcoded with different calculation values (rowInfo['Min'] = calculations.getMin(data[n]), etc.)

I then make dataDict[headers[n]] = rowInfo, thus taking the dictionary I just created and making it equal to one value of the main dictionary

Then, here is my code to print the data (if any variables don't make sense I can explain):

```<code>n = 0
  while n < len(headers):
    print("{:>11}".format(headers[n]),"|", "{:>10.2f}".format(dataDict[n].rowInfo['Min']), "|", "{:>10.2f}".format(dataDict[n].rowInfo['Max']), "|",
      "{:>10.2f}".format(dataDict[n].rowInfo['Mean']))
    n = n + 1
</code>```

I am aware this is not the correct way to print nested dictionaries, but I haven't found anything in my research that gives an answer to my more specific request.

An example of the data I am trying to process is as follows:

Mom, Dad, Son, Daughter

  2, 3, 4, 5

  6, 7, 8, 9

  1, 3, 5, 7

The first row is the headers, which I have put into a list, and the remaining rows are the data at a certain point. However, I need the data from each column that corresponds to each header.

答:
Ok, let's assume we have a nested dictionary like so.
Using recursion we can print each value that itself is not a dictionary.

```<code>data = {
    'outer_dictionary_key_1' : {
        'inner_dictionary_key_1' : 'some_val_1_1',
        'inner_dictionary_key_2' : 'some_val_1_2',
    },
    'outer_dictionary_key_2' : {
        'inner_dictionary_key_1' : {
            'level_3_key' : 'level_3_value',
        },
        'inner_dictionary_key_2' : 'some_val_2_2',
    }
}

def PrintInnerValues(data):

    # check if given element is a dictionary:
    if type(data) is dict:

        # iterate over every key value pair in dictionary:
        for key, value in data.items():

            # recursively call function:
            PrintInnerValues(data[key])

    # otherwise print the value:
    else:
        print(data)

PrintInnerValues(data)
</code>```

This will result in:

```<code>some_val_1_1
some_val_1_2
level_3_value
some_val_2_2
</code>```

Body:
I have a nested dictionary that was created through iteration, the values of the dictionary that HAS BEEN nested in another dictionary are unknown to me. So, without the keys/values being hardcoded in, how can I iterate through the dictionaries to pick a specific value to print?

Here's what I have in pseudocode (copying and pasting even chunks of the code would be nightmarish):

dataDict is my main dictionary

a loop runs however many times I have columns of data (that was a gross-sounding sentence, ex: runs 15 times if I have 15 columns of data)

this loop creates another dictionary first, called rowInfo. rowInfo is then hardcoded with different calculation values (rowInfo['Min'] = calculations.getMin(data[n]), etc.)

I then make dataDict[headers[n]] = rowInfo, thus taking the dictionary I just created and making it equal to one value of the main dictionary

Then, here is my code to print the data (if any variables don't make sense I can explain):

n = 0
  while n < len(headers):
    print("{:>11}".format(headers[n]),"|", "{:>10.2f}".format(dataDict[n].rowInfo['Min']), "|", "{:>10.2f}".format(dataDict[n].rowInfo['Max']), "|",
      "{:>10.2f}".format(dataDict[n].rowInfo['Mean']))
    n = n + 1

I am aware this is not the correct way to print nested dictionaries, but I haven't found anything in my research that gives an answer to my more specific request.

An example of the data I am trying to process is as follows:

Mom, Dad, Son, Daughter

  2, 3, 4, 5

  6, 7, 8, 9

  1, 3, 5, 7

The first row is the headers, which I have put into a list, and the remaining rows are the data at a certain point. However, I need the data from each column that corresponds to each header.

Body:
Ok, let's assume we have a nested dictionary like so.
Using recursion we can print each value that itself is not a dictionary.

data = {
    'outer_dictionary_key_1' : {
        'inner_dictionary_key_1' : 'some_val_1_1',
        'inner_dictionary_key_2' : 'some_val_1_2',
    },
    'outer_dictionary_key_2' : {
        'inner_dictionary_key_1' : {
            'level_3_key' : 'level_3_value',
        },
        'inner_dictionary_key_2' : 'some_val_2_2',
    }
}

def PrintInnerValues(data):

    # check if given element is a dictionary:
    if type(data) is dict:

        # iterate over every key value pair in dictionary:
        for key, value in data.items():

            # recursively call function:
            PrintInnerValues(data[key])

    # otherwise print the value:
    else:
        print(data)

PrintInnerValues(data)

This will result in:

some_val_1_1
some_val_1_2
level_3_value
some_val_2_2


问:
UIWebView webViewDidFinishLoad not getting called iOS
I am loading some file from document directory using UIWebView. I have set the delegate of UIWebView and I am responding to 2 methods of delegate that is
webViewDidStartLoad and webViewDidFinishLoad I am receiving the webViewDidStartLoad But I am not receiving webViewDidFinishLoad method.

Below is the code:

```<code>@interface MyView: UIViewController <UIWebViewDelegate> {
           UIWebView *webView;
}

@property (nonatomic, retain) UIWebView *webView;

========================= Class ===========================

-(void)viewDidLoad {
    CGRect webFrame = [[UIScreen mainScreen] applicationFrame];
    mWebView = [[UIWebView alloc] initWithFrame:webFrame];
    mWebView.delegate = self;
    mWebView.scalesPageToFit = YES;
    [self.view addSubview:mWebView];
        NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", pathString]];

    [mWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]] ];
}

// Delegate methods

-(void)webViewDidStartLoad:(UIWebView *)webView {
    NSLog(@"start");
}

-(void)webViewDidFinishLoad:(UIWebView *)webView {
    NSLog(@"finish");
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    NSLog(@"Error for WEBVIEW: %@", [error description]);
}
</code>```

Please let me know what is going wrong. I am not getting any error in didFailLoadWithError delegate method.

Note:- the file that I am loading are huge say 3 MB.

Thanks

=============EDITED==================

As I was loading very huge File the delegate was coming after very long duration that I was not able to notice but for small files everything is working fine

答:
Well, does your webview actually finish loading? You should implement the webView:didFailLoadWithError:, too to catch failures.

Since you're not getting either the failure or success message. There might be something wrong with the data that you're trying to load.

Try telling the webView to load an HTML string ("Hello World!"), and see if that succeeds. If it does, then the problem is with your data resource or the path to it.

Body:
I am loading some file from document directory using UIWebView. I have set the delegate of UIWebView and I am responding to 2 methods of delegate that is
webViewDidStartLoad and webViewDidFinishLoad I am receiving the webViewDidStartLoad But I am not receiving webViewDidFinishLoad method.

Below is the code:

@interface MyView: UIViewController <UIWebViewDelegate> {
           UIWebView *webView;
}

@property (nonatomic, retain) UIWebView *webView;

========================= Class ===========================

-(void)viewDidLoad {
    CGRect webFrame = [[UIScreen mainScreen] applicationFrame];
    mWebView = [[UIWebView alloc] initWithFrame:webFrame];
    mWebView.delegate = self;
    mWebView.scalesPageToFit = YES;
    [self.view addSubview:mWebView];
        NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", pathString]];

    [mWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]] ];
}

// Delegate methods

-(void)webViewDidStartLoad:(UIWebView *)webView {
    NSLog(@"start");
}

-(void)webViewDidFinishLoad:(UIWebView *)webView {
    NSLog(@"finish");
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    NSLog(@"Error for WEBVIEW: %@", [error description]);
}

Please let me know what is going wrong. I am not getting any error in didFailLoadWithError delegate method.

Note:- the file that I am loading are huge say 3 MB.

Thanks

=============EDITED==================

As I was loading very huge File the delegate was coming after very long duration that I was not able to notice but for small files everything is working fine


问:
Nested Array in React Object
How do I structure this to stop getting the cant read property map of undefined? The note Object itself looks like this.  I will need to repeat this for a secondary array tasks as well. The problem I'm running into with a lot of other examples is they are either class-based or mapping an array with an array. This should be easier I feel like, but I've tried 1000 things and none of them work.

const notes = [
  {
    id: noteId,
    note: noteText,
    notePostedBy: ''
  }
];
```

<pre class="lang-js prettyprint-override"><code>import React, { useContext, useEffect  } from 'react';
import NoteItem from './NoteItem';
import LeadContext from '../../context/Lead/leadContext';

const Notes = () => {
  const leadContext = useContext(LeadContext);
  const { lead } = leadContext;

  return (
    <div className='leadul'>
     {lead.notes.map((note => <NoteItem key={note.id} note={note}/>))}
    </div>
  );
}

export default Notes;
</code>```

```<code>{notes: Array(1), tasks: Array(0), createdate: "2020-02-19T23:25:11.033Z", claimedBy: "unclaimed", isClaimed: false, …}
notes: [{…}]
tasks: []
createdate: "2020-02-19T23:25:11.033Z"
claimedBy: "unclaimed"
isClaimed: false
isClosed: false
isPaid: false
isApproved: false
name2: ""
address2: ""
city2: ""
state2: ""
zip2: ""
employerTime: ""
ssn2: ""
lexId2: ""
relation: ""
phone2: ""
phone3: ""
email2: ""
email3: ""
prac: ""
problem1: ""
problem2: ""
problem3: ""
resSold: ""
resSold2: ""
home: ""
homePay: ""
wages: ""
income1Type: ""
income1Value: ""
income2Type: ""
income2Value: ""
income3Type: ""
income3Value: ""
otherIncomeType: ""
otherIncomeValue: ""
availableCredit: ""
totalCredit: ""
employerName: ""
employerPhone: ""
_id: "5e4dc4354b3bcd36ec86fd53"
notePostedBy: "5e3b346d572df30017a39ef7"
name: "xxxxx"
address: "xxxxx"
city: "xxxxxx"
state: "xxxxx"
zip: "xxxxx"
plaintiff: "STATE OF WEST VIRGINIA"
amount: "10144"
lexId: ""
compliant: "filed"
filingStatus: "m"
cpa: "cpa"
ssn: ""
createdBy: "5e3b346d572df30017a39ef7"
__v: 0
__proto__: Object
</code>```

```<code>×
TypeError: Cannot read property 'map' of undefined
Notes
C:/Webdev/ntenet/client/src/components/popkis/Notes.js:13
  10 |
  11 |
  12 | return (
> 13 |   <div className='leadul'>
  14 |    {lead.notes.map((note => <NoteItem key={note.id} note={note}/>))}
  15 |   </div>
  16 |   );
</code>```

答:
when rending your component react has not gotten any data and the view is already rendered yous a conditional statement there eg</p>

```<code> return (
    <div className='leadul'>
      {
        lead && lead.notes ?
         lead.notes.map(note => (
           <NoteItem
            key={note.id}
            note={note}
           />
          )
         ) : <></>
       }
     </div>
 );
</code>```

Title: Nested Array in React Object

Body:
How do I structure this to stop getting the cant read property map of undefined? The note Object itself looks like this.  I will need to repeat this for a secondary array tasks as well. The problem I'm running into with a lot of other examples is they are either class-based or mapping an array with an array. This should be easier I feel like, but I've tried 1000 things and none of them work.

const notes = [
  {
    id: noteId,
    note: noteText,
    notePostedBy: ''
  }
];

import React, { useContext, useEffect  } from 'react';
import NoteItem from './NoteItem';
import LeadContext from '../../context/Lead/leadContext';

const Notes = () => {
  const leadContext = useContext(LeadContext);
  const { lead } = leadContext;

  return (

     {lead.notes.map((note => <NoteItem key={note.id} note={note}/>))}

  );
}

export default Notes;

{notes: Array(1), tasks: Array(0), createdate: "2020-02-19T23:25:11.033Z", claimedBy: "unclaimed", isClaimed: false, …}
notes: [{…}]
tasks: []
createdate: "2020-02-19T23:25:11.033Z"
claimedBy: "unclaimed"
isClaimed: false
isClosed: false
isPaid: false
isApproved: false
name2: ""
address2: ""
city2: ""
state2: ""
zip2: ""
employerTime: ""
ssn2: ""
lexId2: ""
relation: ""
phone2: ""
phone3: ""
email2: ""
email3: ""
prac: ""
problem1: ""
problem2: ""
problem3: ""
resSold: ""
resSold2: ""
home: ""
homePay: ""
wages: ""
income1Type: ""
income1Value: ""
income2Type: ""
income2Value: ""
income3Type: ""
income3Value: ""
otherIncomeType: ""
otherIncomeValue: ""
availableCredit: ""
totalCredit: ""
employerName: ""
employerPhone: ""
_id: "5e4dc4354b3bcd36ec86fd53"
notePostedBy: "5e3b346d572df30017a39ef7"
name: "xxxxx"
address: "xxxxx"
city: "xxxxxx"
state: "xxxxx"
zip: "xxxxx"
plaintiff: "STATE OF WEST VIRGINIA"
amount: "10144"
lexId: ""
compliant: "filed"
filingStatus: "m"
cpa: "cpa"
ssn: ""
createdBy: "5e3b346d572df30017a39ef7"
__v: 0
__proto__: Object

×
TypeError: Cannot read property 'map' of undefined
Notes
C:/Webdev/ntenet/client/src/components/popkis/Notes.js:13
  10 |
  11 |
  12 | return (
> 13 |

  14 |    {lead.notes.map((note => <NoteItem key={note.id} note={note}/>))}
  15 |

  16 |   );

Body:
when rending your component react has not gotten any data and the view is already rendered yous a conditional statement there eg

 return (
    <div className='leadul'>
      {
        lead && lead.notes ?
         lead.notes.map(note => (
           <NoteItem
            key={note.id}
            note={note}
           />
          )
         ) : <></>
       }
     </div>
 );


问:
JavaScript Mini-Max Sum - Challenge from HackerRank website
Here is the Challenge:

https://www.hackerrank.com/challenges/mini-max-sum/problem

Despite my answer is returning the same number that matches the expected result, I have done something wrong because my answer has been rejected.
How can I solve it?

Here is the solution I had tried:

```<code>function miniMaxSum(arr) {

  var arrClone1 = arr.slice()
  var arrClone2 = arr.slice()

  var arrMinor = arrClone1.sort(function(a, b){return a - b;})
  arrMinor.pop()

  var arrMajor = arrClone2.sort(function(a, b){return b - a;})
  arrMajor.pop()

  function getSum(a, b) {
    return a + b;
  }

  var result1 = arrMinor.reduce(getSum)
  var result2 = arrMajor.reduce(getSum)

  console.log(`${result1} ${result2}`) // it is returning: 10 14
</code>```

答:
I think the solution should be easier:</p>

```<code>function miniMaxSum(arr) {
    let sum = arr.reduce((a, b) => a + b);
    let maxVal = Math.max(...arr);
    let minVal = Math.min(...arr);
    console.log((sum - maxVal) + ' ' + (sum - minVal));
}
</code>```

Body:
Here is the Challenge:

https://www.hackerrank.com/challenges/mini-max-sum/problem

Despite my answer is returning the same number that matches the expected result, I have done something wrong because my answer has been rejected.
How can I solve it?

Here is the solution I had tried:

function miniMaxSum(arr) {

  var arrClone1 = arr.slice()
  var arrClone2 = arr.slice()

  var arrMinor = arrClone1.sort(function(a, b){return a - b;})
  arrMinor.pop()

  var arrMajor = arrClone2.sort(function(a, b){return b - a;})
  arrMajor.pop()

  function getSum(a, b) {
    return a + b;
  }

  var result1 = arrMinor.reduce(getSum)
  var result2 = arrMajor.reduce(getSum)

  console.log(`${result1} ${result2}`) // it is returning: 10 14

Body:
I think the solution should be easier:

function miniMaxSum(arr) {
    let sum = arr.reduce((a, b) => a + b);
    let maxVal = Math.max(...arr);
    let minVal = Math.min(...arr);
    console.log((sum - maxVal) + ' ' + (sum - minVal));
}


问:
Efficiently removing shared elements from grouped data
I have the following data.table:

```<code>dt
#    unique_id group_id primary_id  ph1  ph2  ph3
# 1:         1        1       TRUE   07   03 <NA>
# 2:         2        1      FALSE   07   03   84
# 3:         3        2      FALSE   10 <NA> <NA>
# 4:         4        2       TRUE <NA>   10 <NA>
# 5:         5        2      FALSE <NA> <NA>   10
# 6:         6        3      FALSE   22   03 <NA>
# 7:         7        3       TRUE <NA>   13   03
</code>```

unique_ids are grouped by common phone numbers (ph1, ph2, ph3) which are common across rows (e.g. in the first group "07", "03" are common across the group and in the third group, "03" is shared, but not in the same column, as per group 2).

Each group has 1 primary_id.

Within each group I want to remove the common phone number element(s) in the non primary_id's and retain it for the primary id, so they are no longer linked.

I can achieve this easily in a for loop, however, it's across millions of groups and it's extremely slow.

Looking for a quicker method.

Data:

```<code>library(data.table)

dt <- data.table(structure(list(unique_id = c(1, 2, 3, 4, 5, 6, 7), group_id = c(1,
    1, 2, 2, 2, 3, 3), primary_id = c(TRUE, FALSE, FALSE, TRUE, FALSE,
    FALSE, TRUE), ph1 = c("07", "07", "10", NA, NA, "22", NA), ph2 = c("03",
    "03", NA, "10", NA, "03", "13"), ph3 = c(NA, "84", NA, NA, "10",
    NA, "03")), class = "data.frame", row.names = c(NA, -7L))
)
</code>```

Desired output is:

```<code>output <- data.table(structure(list(unique_id = c(1, 2, 3, 4, 5, 6, 7), group_id = c(1,
1, 2, 2, 2, 3, 3), primary_id = c(TRUE, FALSE, FALSE, TRUE, FALSE,
FALSE, TRUE), ph1 = c("07", NA, NA, NA, NA, "22", NA), ph2 = c("03",
NA, NA, "10", NA, NA, "13"), ph3 = c(NA, "84", NA, NA, NA, NA,
"03")), class = "data.frame", row.names = c(NA, -7L)))

output
#    unique_id group_id primary_id  ph1  ph2  ph3
# 1:         1        1       TRUE   07   03 <NA>
# 2:         2        1      FALSE <NA> <NA>   84
# 3:         3        2      FALSE <NA> <NA> <NA>
# 4:         4        2       TRUE <NA>   10 <NA>
# 5:         5        2      FALSE <NA> <NA> <NA>
# 6:         6        3      FALSE   22 <NA> <NA>
# 7:         7        3       TRUE <NA>   13   03
</code>```

If still unclear, it may be easier to visualize it like this:

答:
Since you have millions of small groups, this might be faster

```<code>cols <- paste0("ph", 1:3)
dt[order(-primary_id), (cols) := {
        m <- t(as.matrix(.SD))
        ri <- rowid(rep(group_id, each=ncol(.SD)), as.vector(m))
        m[ri > 1L] <- NA_character_
        as.data.table(t(m))
    }, .SDcols=cols]
</code>```

output:

```<code>   unique_id group_id primary_id  ph1  ph2  ph3
1:         1        1       TRUE   07   03 <NA>
2:         2        1      FALSE <NA> <NA>   84
3:         3        2      FALSE <NA> <NA> <NA>
4:         4        2       TRUE <NA>   10 <NA>
5:         5        2      FALSE <NA> <NA> <NA>
6:         6        3      FALSE   22 <NA> <NA>
7:         7        3       TRUE <NA>   13   03
</code>```

Will be interested in the timing on your actual dataset

Body:
I have the following data.table:

dt
#    unique_id group_id primary_id  ph1  ph2  ph3
# 1:         1        1       TRUE   07   03 <NA>
# 2:         2        1      FALSE   07   03   84
# 3:         3        2      FALSE   10 <NA> <NA>
# 4:         4        2       TRUE <NA>   10 <NA>
# 5:         5        2      FALSE <NA> <NA>   10
# 6:         6        3      FALSE   22   03 <NA>
# 7:         7        3       TRUE <NA>   13   03

unique_ids are grouped by common phone numbers (ph1, ph2, ph3) which are common across rows (e.g. in the first group "07", "03" are common across the group and in the third group, "03" is shared, but not in the same column, as per group 2).

Each group has 1 primary_id.

Within each group I want to remove the common phone number element(s) in the non primary_id's and retain it for the primary id, so they are no longer linked.

I can achieve this easily in a for loop, however, it's across millions of groups and it's extremely slow.

Looking for a quicker method.

Data:

library(data.table)

dt <- data.table(structure(list(unique_id = c(1, 2, 3, 4, 5, 6, 7), group_id = c(1,
    1, 2, 2, 2, 3, 3), primary_id = c(TRUE, FALSE, FALSE, TRUE, FALSE,
    FALSE, TRUE), ph1 = c("07", "07", "10", NA, NA, "22", NA), ph2 = c("03",
    "03", NA, "10", NA, "03", "13"), ph3 = c(NA, "84", NA, NA, "10",
    NA, "03")), class = "data.frame", row.names = c(NA, -7L))
)

Desired output is:

output <- data.table(structure(list(unique_id = c(1, 2, 3, 4, 5, 6, 7), group_id = c(1,
1, 2, 2, 2, 3, 3), primary_id = c(TRUE, FALSE, FALSE, TRUE, FALSE,
FALSE, TRUE), ph1 = c("07", NA, NA, NA, NA, "22", NA), ph2 = c("03",
NA, NA, "10", NA, NA, "13"), ph3 = c(NA, "84", NA, NA, NA, NA,
"03")), class = "data.frame", row.names = c(NA, -7L)))

output
#    unique_id group_id primary_id  ph1  ph2  ph3
# 1:         1        1       TRUE   07   03 <NA>
# 2:         2        1      FALSE <NA> <NA>   84
# 3:         3        2      FALSE <NA> <NA> <NA>
# 4:         4        2       TRUE <NA>   10 <NA>
# 5:         5        2      FALSE <NA> <NA> <NA>
# 6:         6        3      FALSE   22 <NA> <NA>
# 7:         7        3       TRUE <NA>   13   03

If still unclear, it may be easier to visualize it like this:

Body:
Since you have millions of small groups, this might be faster

cols <- paste0("ph", 1:3)
dt[order(-primary_id), (cols) := {
        m <- t(as.matrix(.SD))
        ri <- rowid(rep(group_id, each=ncol(.SD)), as.vector(m))
        m[ri > 1L] <- NA_character_
        as.data.table(t(m))
    }, .SDcols=cols]

output:

   unique_id group_id primary_id  ph1  ph2  ph3
1:         1        1       TRUE   07   03 <NA>
2:         2        1      FALSE <NA> <NA>   84
3:         3        2      FALSE <NA> <NA> <NA>
4:         4        2       TRUE <NA>   10 <NA>
5:         5        2      FALSE <NA> <NA> <NA>
6:         6        3      FALSE   22 <NA> <NA>
7:         7        3       TRUE <NA>   13   03

Will be interested in the timing on your actual dataset


问:
Using ++ operator leads to unexpected results
I do not understand why the two codes below lead to the same result. Shouldn't the latter print from 6 to 10 since n is incremented first?

Edit: I used both Visual Studio 2019 and repl.it.

```<code>#include <iostream>
using namespace std;

int main() {
    int n=5;
    for (n; n<10; n++)
        cout << n << endl;
    return 0;
}

>>> 5
6
7
8
9

#include <iostream>
using namespace std;

int main() {
    int n=5;
    for (n; n<10; ++n)
        cout << n << endl;
    return 0;
}

>>> 5
6
7
8
9
</code>```

答:
From https://en.cppreference.com/w/cpp/language/for

attr(optional) for ( init-statement condition(optional) ; iteration_expression(optional) ) statement

The above syntax produces code equivalent to:

```<code>{
    init_statement
    while ( condition ) {
        statement
        iteration_expression ;
    }
}
</code>```

Your two for loops are therefore equivalent to

```<code>{
    n;
    while (n < 10) {
        cout << n << endl;
        n++;
    }
}
</code>```

and

```<code>{
    n;
    while (n < 10) {
        cout << n << endl;
        ++n;
    }
}
</code>```

In a for loop:

The first statement is executed exactly once

The conditional is checked, and if true

The body is executed

Then the iteration expression is executed

Goto (2.)

If you want your loop to start at 6, you need to explicitly tell it to start at 6.

Body:
I do not understand why the two codes below lead to the same result. Shouldn't the latter print from 6 to 10 since n is incremented first?

Edit: I used both Visual Studio 2019 and repl.it.

#include <iostream>
using namespace std;

int main() {
    int n=5;
    for (n; n<10; n++)
        cout << n << endl;
    return 0;
}

>>> 5
6
7
8
9

#include <iostream>
using namespace std;

int main() {
    int n=5;
    for (n; n<10; ++n)
        cout << n << endl;
    return 0;
}

>>> 5
6
7
8
9

Body:
From https://en.cppreference.com/w/cpp/language/for

attr(optional) for ( init-statement condition(optional) ; iteration_expression(optional) ) statement

The above syntax produces code equivalent to:

{
    init_statement
    while ( condition ) {
        statement
        iteration_expression ;
    }
}

Your two for loops are therefore equivalent to

{
    n;
    while (n < 10) {
        cout << n << endl;
        n++;
    }
}

and

{
    n;
    while (n < 10) {
        cout << n << endl;
        ++n;
    }
}

In a for loop:

The first statement is executed exactly once

The conditional is checked, and if true

The body is executed

Then the iteration expression is executed

Goto (2.)

If you want your loop to start at 6, you need to explicitly tell it to start at 6.


问:
VirtualBox: VBoxManage modifyhd hosting on mac os x resize not supported
I'm hosting a VM on OS X using VirtualBox.  I'm trying to resize the virtual hard drive by using the following command:

```<code>VBoxManage modifyhd [file path]/ubuntu_vm-disk1.vmdk --resize 16000
</code>```

And I get the following error:

```<code>0%...
Progress state: VBOX_E_NOT_SUPPORTED
VBoxManage: error: Resize hard disk operation for this format is not implemented yet!
</code>```

here is my showhdinfo:

```<code>Accessible:           yes
Logical size:         15719 MBytes
Current size on disk: 6066 MBytes
Type:                 normal (base)
Storage format:       VMDK
Format variant:       dynamic default
</code>```

what am I doing wrong?

UPDATED
I removed all snapshots and retried the command with "" around the path and now getting following error:

```<code>VBoxManage: error: Failed to lock media when compacting '/Users/dwstein_old/VirtualBox VMs/Ubuntu_120723/ubuntu_vm-disk1.vmdk'
VBoxManage: error: Details: code VBOX_E_INVALID_OBJECT_STATE (0x80bb0007), component Medium, interface IMedium, callee nsISupports
Context: "Resize(cbResize, progress.asOutParam())" at line 522 of file VBoxManageDisk.cpp
VBoxManage: error: Code VBOX_E_INVALID_OBJECT_STATE (0x80BB0007) - Current object state prohibits operation (extended info not available)
</code>```

答:
My situation - Virtual box 6.0 with snapshots and dynamically allocated memory.

Backup your virtual machine and shut it down.

Step 1. - Delete the snapshots.

Step 2. - Using the command given below increase the virtual size.

```<code>VBoxManage modifymedium disk "\Path\To\Vdi\xyz.vdi" --resize XXXXX
</code>```

(new size in MB)

Step 3. - Startup the virtual machine and open terminal.

Step 4. - This step will provide you with the list of all the drive partitions. in my case it was /dev/disk1's disk1s2 which was supposed to increase in size.

```<code>diskutil list
</code>```

Step 5. -

```<code>diskutil repairdisk disk1
</code>```

Step 6. -

```<code>diskutil apfs resizeContainer disk1s2 124g
</code>```

(here 124g is the size that i actually wanted it to be.)

Body:
I'm hosting a VM on OS X using VirtualBox.  I'm trying to resize the virtual hard drive by using the following command:

VBoxManage modifyhd [file path]/ubuntu_vm-disk1.vmdk --resize 16000

And I get the following error:

0%...
Progress state: VBOX_E_NOT_SUPPORTED
VBoxManage: error: Resize hard disk operation for this format is not implemented yet!

here is my showhdinfo:

Accessible:           yes
Logical size:         15719 MBytes
Current size on disk: 6066 MBytes
Type:                 normal (base)
Storage format:       VMDK
Format variant:       dynamic default

what am I doing wrong?

UPDATED
I removed all snapshots and retried the command with "" around the path and now getting following error:

VBoxManage: error: Failed to lock media when compacting '/Users/dwstein_old/VirtualBox VMs/Ubuntu_120723/ubuntu_vm-disk1.vmdk'
VBoxManage: error: Details: code VBOX_E_INVALID_OBJECT_STATE (0x80bb0007), component Medium, interface IMedium, callee nsISupports
Context: "Resize(cbResize, progress.asOutParam())" at line 522 of file VBoxManageDisk.cpp
VBoxManage: error: Code VBOX_E_INVALID_OBJECT_STATE (0x80BB0007) - Current object state prohibits operation (extended info not available)

Body:
My situation - Virtual box 6.0 with snapshots and dynamically allocated memory.

Backup your virtual machine and shut it down.

Step 1. - Delete the snapshots.

Step 2. - Using the command given below increase the virtual size.

VBoxManage modifymedium disk "\Path\To\Vdi\xyz.vdi" --resize XXXXX

(new size in MB)

Step 3. - Startup the virtual machine and open terminal.

Step 4. - This step will provide you with the list of all the drive partitions. in my case it was /dev/disk1's disk1s2 which was supposed to increase in size.

diskutil list

Step 5. -

diskutil repairdisk disk1

Step 6. -

diskutil apfs resizeContainer disk1s2 124g

(here 124g is the size that i actually wanted it to be.)


问:
Show different files between local and remote
I have a local folder which is linked to a remote git repository.

Sometimes, We have instructions to check the difference between local and remote.

But their difference could be big and long. Sometimes, I just want to see which files are different/added/removed, and don't need to go into details.

Does anyone know how could I quickly get that information?

Edit 1:

Additionally, I just realised that I need to eventually git add new local files, and locally make a new git commit before git fetch and git diff. Am I correct?

答:
You'll definitely need to fetch the remote repository in order to do that.  There's no way to avoid that.  Once you've done that, you can do a comparison.  There are a couple of ways to do that.

One is to do git diff --stat master origin/master and see the stat output:

```<code>$ git diff --stat master origin/master
 Documentation/RelNotes/2.26.0.txt | 44 +++++++++++++++-----------------------------
 1 file changed, 15 insertions(+), 29 deletions(-)
</code>```

You can also view only the names of the files with git diff --name-only.  If you want to see specifically which files have been added or removed, you can use the --diff-filter option to list only the files that have changed in the given way.

Finally, if you want something more like git status -s output, you can use git diff --name-status.

Body:
You'll definitely need to fetch the remote repository in order to do that.  There's no way to avoid that.  Once you've done that, you can do a comparison.  There are a couple of ways to do that.

One is to do git diff --stat master origin/master and see the stat output:

$ git diff --stat master origin/master
 Documentation/RelNotes/2.26.0.txt | 44 +++++++++++++++-----------------------------
 1 file changed, 15 insertions(+), 29 deletions(-)

You can also view only the names of the files with git diff --name-only.  If you want to see specifically which files have been added or removed, you can use the --diff-filter option to list only the files that have changed in the given way.

Finally, if you want something more like git status -s output, you can use git diff --name-status.


问:
Auth0 as SP: React app receives a SAML response instead the redirect with code and state params
We implemented Auth0 as Service Provider, like this url
In React we are using this library.

After login success, in the react app we are receiving a POST with the SAML response, instead of POST redirect with code and state params, that the library uses to authenticate the user.

So my question is, The React app should handle the SAML response? if so, it's needed a node server to do this.

The Auth0 should handle the SAML response and redirect to the application with the above params? what configuration it's left to implement.

答:
SPA uses OpenID Connect and that should return the code etc.

However, the Auth0 example is for SAML.

You should configure an Auth0 OpenID Connect connector instead.


问:
Matching subset of data
I am populating ActiveX control labels with a subset of Excel data in VBA. My code previously worked for the entire Excel workbook, but once I changed my code to only reference a subset of the data, the incorrect data is being entered.

Here is a snapshot of example data. In my code, Column 6= CY and Column 7 = FY. The code is currently populating my labels with the headers of Column 6 and 7 rather than the values of 'active' or 'merged' projects.

As mentioned, I am not receiving any error messages, but the correct data is not being added to my ActiveX labels. FYI... In line 31 Code1 is the name of an ActiveX label.

```<code>Private Sub CommandButton1_Click()

    Dim objExcel As Excel.Application
    Dim exWB As Excel.Workbook
    Dim rng As Excel.Range, m, rw As Excel.Range
    Dim num, TableNo, seq As Integer
    Dim ctl As MSForms.Label
    Dim ils As Word.InlineShape
    Dim rngrow As Excel.Range
    Dim active As Excel.Range

    Set objExcel = New Excel.Application
    TableNo = ActiveDocument.Tables.Count
    num = 3
    seq = 1

Set exWB = objExcel.Workbooks.Open("O:\Documents\"Database.csv")
Set rng = exWB.Sheets("Sheet1").Cells

''''Select active projects as subset
    For Each rngrow In rng.Range("A1:L144")
     If rngrow.Columns(8).value = "Active" Or rngrow.Columns(8).value = "Merged" Then
            If active Is Nothing Then
                Set active = rngrow
            Else
                Set active = Union(active, rngrow)
            End If
        End If
    Next rngrow

    m = objExcel.Match(ActiveDocument.Code1.Caption, active.Columns(3), 0)

'' Now, create all ActiveX FY labels and populate with FY Use
Do
    Set ils = ActiveDocument.Tables(num).cell(6, 2).Range.InlineShapes.AddOLEControl(ClassType:="Forms.Label.1")
    Set ctl = ils.OLEFormat.Object
    ctl.Name = "FY" & seq
    If Not IsError(m) Then
    Set rw = rng.Rows(m)
    ctl.Caption = rw.Cells(7).value
    Else
        MsgBox "No match found"
    End If
    seq = seq + 1
    num = num + 1
Loop Until num = TableNo + 1

'' Now, create all ActiveX CY labels and populate with CY
num = 3
seq = 1
Do
    Set ils = ActiveDocument.Tables(num).cell(7, 2).Range.InlineShapes.AddOLEControl(ClassType:="Forms.Label.1")
    Set ctl = ils.OLEFormat.Object
    ctl.Name = "CY" & seq
    If Not IsError(m) Then
    Set rw = rng.Rows(m)
    ctl.Caption = rw.Cells(6).value
    Else
        MsgBox "No match found"
    End If
    seq = seq + 1
    num = num + 1
Loop Until num = TableNo + 1

Set exWB = Nothing

End Sub
</code>```

Link to my previous question below:
Using Excel data to create Word Doc caption labels in VBA

答:
This:

```<code>For Each rngrow In rng.Range("A1:L144")
</code>```

will be interpreted as

```<code>For Each rngrow In rng.Range("A1:L144").Cells
</code>```

so your loop will be A1, B1, C1, ... L1 then A2, B2 etc.

It seems like you meant it to be:

```<code>For Each rngrow In rng.Range("A1:L144").Rows
</code>```

so rngRow will be A1:L1, then A2:L2, etc.

EDIT - You can't refer to active using something like MsgBox(active.Range ("A2")), since it's a multi-area range.

Try this for example -

```<code>For Each rw in active.Rows
    debug.print "Row:" & rw.Row, rw.cells(8).value
Next rw
</code>```

EDIT2: try this instead.  Untested but I think it should work OK

```<code>Private Sub CommandButton1_Click()

    Dim objExcel As Excel.Application
    Dim exWB As Excel.Workbook
    Dim data, r As Long, resRow As Long, seq As Long, num As Long
    Dim doc As Document

    'get the Excel data as a 2D array
    Set objExcel = New Excel.Application
    Set exWB = objExcel.Workbooks.Open("O:\Documents\Database.csv")
    data = exWB.Sheets("Sheet1").Range("A1:L144").Value '>> 2D array
    exWB.Close False
    objExcel.Quit

    resRow = 0
    'find the first matching row, if any
    For r = 1 To UBound(data, 1)
        If (data(r, 8) = "Active" Or data(r, 8) = "Merged") And _
                              data(r, 3) = doc.Code1.Caption Then
            resRow = r        'this is the row we want
            Exit Sub          'done looking
        End If
    Next r

    Set doc = ActiveDocument
    seq = 1
    For num = 3 To doc.Tables.Count
        With doc.Tables(num)
            AddLabel .Cell(6, 2), "FY" & seq, IIf(resRow > 0, data(resRow, 7), "Not found")
            AddLabel .Cell(7, 2), "CY" & seq, IIf(resRow > 0, data(resRow, 6), "Not found")
        End With
        seq = seq + 1
    Next num

End Sub

'add a label to a cell, set its name and caption
Sub AddLabel(theCell As Cell, theName As String, theCaption As String)
    Dim ils As InlineShape, ctl As MSForms.Label
    Set ils = theCell.Range.InlineShapes.AddOLEControl(ClassType:="Forms.Label.1")
    Set ctl = ils.OLEFormat.Object
    ctl.Name = theName
    ctl.Caption = theCaption
End Sub
</code>```

Title: Matching subset of data

Body:
I am populating ActiveX control labels with a subset of Excel data in VBA. My code previously worked for the entire Excel workbook, but once I changed my code to only reference a subset of the data, the incorrect data is being entered.

Here is a snapshot of example data. In my code, Column 6= CY and Column 7 = FY. The code is currently populating my labels with the headers of Column 6 and 7 rather than the values of 'active' or 'merged' projects.

As mentioned, I am not receiving any error messages, but the correct data is not being added to my ActiveX labels. FYI... In line 31 Code1 is the name of an ActiveX label.

Private Sub CommandButton1_Click()

    Dim objExcel As Excel.Application
    Dim exWB As Excel.Workbook
    Dim rng As Excel.Range, m, rw As Excel.Range
    Dim num, TableNo, seq As Integer
    Dim ctl As MSForms.Label
    Dim ils As Word.InlineShape
    Dim rngrow As Excel.Range
    Dim active As Excel.Range

    Set objExcel = New Excel.Application
    TableNo = ActiveDocument.Tables.Count
    num = 3
    seq = 1

Set exWB = objExcel.Workbooks.Open("O:\Documents\"Database.csv")
Set rng = exWB.Sheets("Sheet1").Cells

''''Select active projects as subset
    For Each rngrow In rng.Range("A1:L144")
     If rngrow.Columns(8).value = "Active" Or rngrow.Columns(8).value = "Merged" Then
            If active Is Nothing Then
                Set active = rngrow
            Else
                Set active = Union(active, rngrow)
            End If
        End If
    Next rngrow

    m = objExcel.Match(ActiveDocument.Code1.Caption, active.Columns(3), 0)

'' Now, create all ActiveX FY labels and populate with FY Use
Do
    Set ils = ActiveDocument.Tables(num).cell(6, 2).Range.InlineShapes.AddOLEControl(ClassType:="Forms.Label.1")
    Set ctl = ils.OLEFormat.Object
    ctl.Name = "FY" & seq
    If Not IsError(m) Then
    Set rw = rng.Rows(m)
    ctl.Caption = rw.Cells(7).value
    Else
        MsgBox "No match found"
    End If
    seq = seq + 1
    num = num + 1
Loop Until num = TableNo + 1

'' Now, create all ActiveX CY labels and populate with CY
num = 3
seq = 1
Do
    Set ils = ActiveDocument.Tables(num).cell(7, 2).Range.InlineShapes.AddOLEControl(ClassType:="Forms.Label.1")
    Set ctl = ils.OLEFormat.Object
    ctl.Name = "CY" & seq
    If Not IsError(m) Then
    Set rw = rng.Rows(m)
    ctl.Caption = rw.Cells(6).value
    Else
        MsgBox "No match found"
    End If
    seq = seq + 1
    num = num + 1
Loop Until num = TableNo + 1

Set exWB = Nothing

End Sub

Link to my previous question below:
Using Excel data to create Word Doc caption labels in VBA

Body:
This:

For Each rngrow In rng.Range("A1:L144")

will be interpreted as

For Each rngrow In rng.Range("A1:L144").Cells

so your loop will be A1, B1, C1, ... L1 then A2, B2 etc.

It seems like you meant it to be:

For Each rngrow In rng.Range("A1:L144").Rows

so rngRow will be A1:L1, then A2:L2, etc.

EDIT - You can't refer to active using something like MsgBox(active.Range ("A2")), since it's a multi-area range.

Try this for example -

For Each rw in active.Rows
    debug.print "Row:" & rw.Row, rw.cells(8).value
Next rw

EDIT2: try this instead.  Untested but I think it should work OK

Private Sub CommandButton1_Click()

    Dim objExcel As Excel.Application
    Dim exWB As Excel.Workbook
    Dim data, r As Long, resRow As Long, seq As Long, num As Long
    Dim doc As Document

    'get the Excel data as a 2D array
    Set objExcel = New Excel.Application
    Set exWB = objExcel.Workbooks.Open("O:\Documents\Database.csv")
    data = exWB.Sheets("Sheet1").Range("A1:L144").Value '>> 2D array
    exWB.Close False
    objExcel.Quit

    resRow = 0
    'find the first matching row, if any
    For r = 1 To UBound(data, 1)
        If (data(r, 8) = "Active" Or data(r, 8) = "Merged") And _
                              data(r, 3) = doc.Code1.Caption Then
            resRow = r        'this is the row we want
            Exit Sub          'done looking
        End If
    Next r

    Set doc = ActiveDocument
    seq = 1
    For num = 3 To doc.Tables.Count
        With doc.Tables(num)
            AddLabel .Cell(6, 2), "FY" & seq, IIf(resRow > 0, data(resRow, 7), "Not found")
            AddLabel .Cell(7, 2), "CY" & seq, IIf(resRow > 0, data(resRow, 6), "Not found")
        End With
        seq = seq + 1
    Next num

End Sub

'add a label to a cell, set its name and caption
Sub AddLabel(theCell As Cell, theName As String, theCaption As String)
    Dim ils As InlineShape, ctl As MSForms.Label
    Set ils = theCell.Range.InlineShapes.AddOLEControl(ClassType:="Forms.Label.1")
    Set ctl = ils.OLEFormat.Object
    ctl.Name = theName
    ctl.Caption = theCaption
End Sub


问:
java web app calling a web service client (in cxf)
I need a very performant and scalable solution to calling web services from java webapp.

Could someone please suggest the best options for calling webservices from java webapp?

Much appreciated

答: If you are using a restful web service, there are a lot of client libraries which you can choose. Eg. RestEasy Client, Jersey Client,....</p>


问:
Ran caret model and it stopped. It mentioned of missing values in resampled performance measure
[Dataset] I tried the titanic question, being a newbie.  Just about to train using a dataset and that is where I got stuck:

[data_prepro_maf_train]

```<code>all_model<-modelLookup()
classification_model<-all_model%>%filter(forClass==TRUE,!duplicated(model))
class_model<-classification_model$model
set.seed(123)
number<-3
repeats<-2
control<-trainControl(method="repeatedcv",number=number,repeats=repeats,classProbs = TRUE,savePredictions = "final",index=createResample(data_prepro_maf_train$Embarked,repeats*number),summaryFunction = multiClassSummary,allowParallel = TRUE)
x<-data_prepro_maf_train[,c(1,3,5,6,7,8)]
y<-data_prepro_maf_train[,12]
levels(y)<-make.names(levels(factor(data_prepro_maf_train[,12])))
y<-make.names(data_prepro_maf_train[,12],unique=TRUE,allow_=TRUE)
#Train the models
model_list1<-caretList(x,y,data=data_prepro_maf_train,trControl = control,metric="Accuracy",methodList = class_model[1])
</code>```

I made sure to pick columns with no missing value like "Cabin" and already removed missing values for required columns.

Packages used:

```<code>library(caret)
library(caretEnsemble)
library(tidyverse)
library(magrittr)
library(doParallel)
</code>```

答:
Tried taking on the problem with research and hence the hiatus.  The possible solution to my problem could be:

1) One hot encoding: basically a reprocessing method of converting training data to simple factors/numerics

2)Argument input method:

```<code>x<-data_prepro_maf_train[,c(1,3,5,6,7,8)]
y<-data_prepro_maf_train[,12]
model_list1<-caretList(x,y,data=data_prepro_maf_train,trControl = control,metric="Accuracy",methodList = class_model[1])
</code>```

I changed it to y~X1+X2+X3 method and at least now CaretList is running some models
[Discussion on formula formula-vs-non-formula-interface-in-train1

Below are the changes made:

```<code>#Let’s one hot encode the data_prepro_maf_train data
dummy_model1<-dummyVars(title~.,data=data_prepro_maf_train[c(1,2,3,5,6,7,8,10)])

data_train_mat1<-predict(dummy_model1,newdata=data_prepro_maf_train)

data_prepro_maf_train2<-data.frame(data_train_mat1)

#Add back columns “title” and “Embarked”, which have vital factors for the model
data_prepro_maf_train2<-cbind(data_prepro_maf_train$Embarked,data_prepro_maf_train$title,data_prepro_maf_train2)

colnames(data_prepro_maf_train2)[1]<-"Embarked"
colnames(data_prepro_maf_train2)[2]<-"title"
#Adjust consistency of levels in the new train data. If the error below shows up, try running this code again before running model_list2 (not sure why it is not saved):
"Error: One or more factor levels in the outcome has no data: 'Q'"

levels(data_prepro_maf_train2$Embarked)<-droplevels(data_prepro_maf_train2$Embarked)

set.seed(123)
number<-3
repeats<-2
control<-trainControl(method="repeatedcv",number=number,repeats=repeats,classProbs = TRUE,savePredictions = "all",index=createResample(data_prepro_maf_train$Embarked,repeats*number),summaryFunction = multiClassSummary,allowParallel = TRUE)
#Since the class_model has over 100 models...let's select a few that we know for testing the previous error (I stumbled upon the “preProcess=c(“center”,”scale”) which said to help in my situation…not sure how it works and would appreciate if someone could explain it??  :
model_list2<-caretList(Embarked~title+Pclass+Age+Sex.male+Sex.female+SibSp+Parch,data=data_prepro_maf_train1,preProcess = c("center", "scale"),trControl = control,metric="Accuracy",methodList = class_model[c(37,52,55,68,102,145,167,189)])
</code>```

Not confident if this is the end of my problem....at least the model is running and not stopping without any findings

Body:
[Dataset] I tried the titanic question, being a newbie.  Just about to train using a dataset and that is where I got stuck:

[data_prepro_maf_train]

all_model<-modelLookup()
classification_model<-all_model%>%filter(forClass==TRUE,!duplicated(model))
class_model<-classification_model$model
set.seed(123)
number<-3
repeats<-2
control<-trainControl(method="repeatedcv",number=number,repeats=repeats,classProbs = TRUE,savePredictions = "final",index=createResample(data_prepro_maf_train$Embarked,repeats*number),summaryFunction = multiClassSummary,allowParallel = TRUE)
x<-data_prepro_maf_train[,c(1,3,5,6,7,8)]
y<-data_prepro_maf_train[,12]
levels(y)<-make.names(levels(factor(data_prepro_maf_train[,12])))
y<-make.names(data_prepro_maf_train[,12],unique=TRUE,allow_=TRUE)
#Train the models
model_list1<-caretList(x,y,data=data_prepro_maf_train,trControl = control,metric="Accuracy",methodList = class_model[1])

I made sure to pick columns with no missing value like "Cabin" and already removed missing values for required columns.

Packages used:

library(caret)
library(caretEnsemble)
library(tidyverse)
library(magrittr)
library(doParallel)

Body:
Tried taking on the problem with research and hence the hiatus.  The possible solution to my problem could be:

1) One hot encoding: basically a reprocessing method of converting training data to simple factors/numerics

2)Argument input method:

x<-data_prepro_maf_train[,c(1,3,5,6,7,8)]
y<-data_prepro_maf_train[,12]
model_list1<-caretList(x,y,data=data_prepro_maf_train,trControl = control,metric="Accuracy",methodList = class_model[1])

I changed it to y~X1+X2+X3 method and at least now CaretList is running some models
[Discussion on formula formula-vs-non-formula-interface-in-train1

Below are the changes made:

#Let’s one hot encode the data_prepro_maf_train data
dummy_model1<-dummyVars(title~.,data=data_prepro_maf_train[c(1,2,3,5,6,7,8,10)])

data_train_mat1<-predict(dummy_model1,newdata=data_prepro_maf_train)

data_prepro_maf_train2<-data.frame(data_train_mat1)

#Add back columns “title” and “Embarked”, which have vital factors for the model
data_prepro_maf_train2<-cbind(data_prepro_maf_train$Embarked,data_prepro_maf_train$title,data_prepro_maf_train2)

colnames(data_prepro_maf_train2)[1]<-"Embarked"
colnames(data_prepro_maf_train2)[2]<-"title"
#Adjust consistency of levels in the new train data. If the error below shows up, try running this code again before running model_list2 (not sure why it is not saved):
"Error: One or more factor levels in the outcome has no data: 'Q'"

levels(data_prepro_maf_train2$Embarked)<-droplevels(data_prepro_maf_train2$Embarked)

set.seed(123)
number<-3
repeats<-2
control<-trainControl(method="repeatedcv",number=number,repeats=repeats,classProbs = TRUE,savePredictions = "all",index=createResample(data_prepro_maf_train$Embarked,repeats*number),summaryFunction = multiClassSummary,allowParallel = TRUE)
#Since the class_model has over 100 models...let's select a few that we know for testing the previous error (I stumbled upon the “preProcess=c(“center”,”scale”) which said to help in my situation…not sure how it works and would appreciate if someone could explain it??  :
model_list2<-caretList(Embarked~title+Pclass+Age+Sex.male+Sex.female+SibSp+Parch,data=data_prepro_maf_train1,preProcess = c("center", "scale"),trControl = control,metric="Accuracy",methodList = class_model[c(37,52,55,68,102,145,167,189)])

Not confident if this is the end of my problem....at least the model is running and not stopping without any findings