问:
Loading a random class using reflection and have it register as a component in springboot
I have a random class in a random package that is loaded through reflection after the app launches, is there a way for it to be registered as a component under springboot and have annotations such as @Autowired and @Value etc work for that class.

It works when it is in the same package at launch time, but if introduce it thorough another jar at runtime (same package or not) it doesn't work.

Below are samples that don't work even if it is in the same jar. I can't change the app's configuration - it would defeat the "random package/random class" objective.

Code in Spring boot application package

```<code>package sample.app
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        // Code that starts app
        //
        //
        try {
            Thread.sleep(7000);
            Class test = Class.forName("test.Test", true, Application.class.getClassLoader());
            System.out.println(test.getMethod("getName").invoke(null));     //NPE
            System.out.println(test.getMethod("getProfiles").invoke(null)); //NPE
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}
</code>```

Test.java

```<code>package test;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.DependsOn;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

@DependsOn("blaaaaaaaah")
@ComponentScan
public class Test {

    @DependsOn("blaaaaaaaah")
    public static String getName() {
        return SpringGetter.instance.getApplicationName();
    }

    @DependsOn("blaaaaaaaah")
    public static String[] getProfiles() {
        String[] profiles = SpringGetter.instance.getEnv().getActiveProfiles();
        if (profiles == null || profiles.length == 0) {
            profiles = SpringGetter.instance.getEnv().getDefaultProfiles();
        }
        return profiles;
    }

}
</code>```

SpringGetter.java

```<code>package test;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component("blaaaaaaaah")
public class SpringGetter implements InitializingBean {
    public static SpringGetter instance;

    @Value("${spring.application.name}")
    private  String applicationName;
    @Autowired
    private Environment env;

    public SpringGetter() {
        System.out.println("consASFJEFWEFJWDNFWJVNJSBVJWNCJWBVJNVJNVJSNJSNCSDJVNSVJtruct");
    }

    public String getApplicationName() {
        return applicationName;
    }

    public void setApplicationName(String applicationName) {
        this.applicationName = applicationName;
    }

    public Environment getEnv() {
        return env;
    }

    public void setEnv(Environment env) {
        this.env = env;
    }

    @PostConstruct
    public void setInstance() {
        instance = this;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        instance = this;
    }
}
</code>```

EDIT:
I managed to dynamically create the SpringGetter class as part of the same package as the Application class(the one with the @SpringBootApplication). I got Test.java to point to that dynamic class and yet no luck.

答:
To simply inject fields into a POJO as if it were a Spring-managed bean, you can use something like the following:

@Component
public class BeanInitializer implements ApplicationContextAware {

  private AutowireCapableBeanFactory beanFactory;

  @Override
  public void setApplicationContext(final ApplicationContext applicationContext) {
      beanFactory = applicationContext.getAutowireCapableBeanFactory();
  }

  public void initializeObject(Object pojo) {
      beanFactory.autowireBean(pojo);
  }
}
```

Note, however, that this only injects fields marked as @Autowired or @Injected. It does not create proxies that honor method interception strategies based on e.g. @Transactional, @Async, etc.

Body:
I have a random class in a random package that is loaded through reflection after the app launches, is there a way for it to be registered as a component under springboot and have annotations such as @Autowired and @Value etc work for that class.

It works when it is in the same package at launch time, but if introduce it thorough another jar at runtime (same package or not) it doesn't work.

Below are samples that don't work even if it is in the same jar. I can't change the app's configuration - it would defeat the "random package/random class" objective.

Code in Spring boot application package

package sample.app
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        // Code that starts app
        //
        //
        try {
            Thread.sleep(7000);
            Class test = Class.forName("test.Test", true, Application.class.getClassLoader());
            System.out.println(test.getMethod("getName").invoke(null));     //NPE
            System.out.println(test.getMethod("getProfiles").invoke(null)); //NPE
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

Test.java

package test;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.DependsOn;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

@DependsOn("blaaaaaaaah")
@ComponentScan
public class Test {

    @DependsOn("blaaaaaaaah")
    public static String getName() {
        return SpringGetter.instance.getApplicationName();
    }

    @DependsOn("blaaaaaaaah")
    public static String[] getProfiles() {
        String[] profiles = SpringGetter.instance.getEnv().getActiveProfiles();
        if (profiles == null || profiles.length == 0) {
            profiles = SpringGetter.instance.getEnv().getDefaultProfiles();
        }
        return profiles;
    }

}

SpringGetter.java

package test;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component("blaaaaaaaah")
public class SpringGetter implements InitializingBean {
    public static SpringGetter instance;

    @Value("${spring.application.name}")
    private  String applicationName;
    @Autowired
    private Environment env;

    public SpringGetter() {
        System.out.println("consASFJEFWEFJWDNFWJVNJSBVJWNCJWBVJNVJNVJSNJSNCSDJVNSVJtruct");
    }

    public String getApplicationName() {
        return applicationName;
    }

    public void setApplicationName(String applicationName) {
        this.applicationName = applicationName;
    }

    public Environment getEnv() {
        return env;
    }

    public void setEnv(Environment env) {
        this.env = env;
    }

    @PostConstruct
    public void setInstance() {
        instance = this;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        instance = this;
    }
}

EDIT:
I managed to dynamically create the SpringGetter class as part of the same package as the Application class(the one with the @SpringBootApplication). I got Test.java to point to that dynamic class and yet no luck.

Body:
To simply inject fields into a POJO as if it were a Spring-managed bean, you can use something like the following:

@Component
public class BeanInitializer implements ApplicationContextAware {

  private AutowireCapableBeanFactory beanFactory;

  @Override
  public void setApplicationContext(final ApplicationContext applicationContext) {
      beanFactory = applicationContext.getAutowireCapableBeanFactory();
  }

  public void initializeObject(Object pojo) {
      beanFactory.autowireBean(pojo);
  }
}

Note, however, that this only injects fields marked as @Autowired or @Injected. It does not create proxies that honor method interception strategies based on e.g. @Transactional, @Async, etc.


来源: stackexchange

问:
Django: make comma separated list based on day name from querySet
How can I make a dictionary efficiently from a queryset.

I have days and each day has times associated with it like

Day1 - Time1

Day1 - Time2

Day1 - Time3

Day2 - Time1

I would like to make a list of dictionary like [{"day":'Day1', "time":'Time1, Time2, Time3'}, ...]

This join

```<code>listof = ",".join(str([ab.day.day, str(ab.time)]) for ab in vqs.clinicDoctor_dayShift.all().order_by('day__id'))
</code>```

gives me string like

```<code>['Sunday', '15:01:00'],['Sunday', '16:02:00'],['Monday', '09:01:00'],['Monday', '15:01:00'],['Monday', '16:02:00'],['Tuesday', '09:01:00'],['Tuesday', '16:02:00']
</code>```

I would like to have a list like this

```<code>[{'day':'Sunday', 'time':'15:01:00, 16:02:00, 09:01:00'},{'day':'Monday', 'time':'15:01:00, 16:02:00'},{'day':'Tuesday', 'time':'09:01:00, 16:02:00'}]
</code>```

Can anyone please help me with this.

Thank you.

答:
I went with a loop in the template

```<code># views.py
ms = M.objects.filter(foo=bar).all()
for m in ms:
    favorited = m.baz.qux_set.filter(foo=request.user.id).first()
    if favorited:
        m.tags = favorited.tags.names()
</code>```

and

```<code># template.html
{% for m in ms %}
  {% for tag in m.tags %}{{ tag }} , {% endfor %}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I make a dictionary efficiently from a queryset.

I have days and each day has times associated with it like

Day1 - Time1

Day1 - Time2

Day1 - Time3

Day2 - Time1

I would like to make a list of dictionary like [{"day":'Day1', "time":'Time1, Time2, Time3'}, ...]

This join

listof = ",".join(str([ab.day.day, str(ab.time)]) for ab in vqs.clinicDoctor_dayShift.all().order_by('day__id'))

gives me string like

['Sunday', '15:01:00'],['Sunday', '16:02:00'],['Monday', '09:01:00'],['Monday', '15:01:00'],['Monday', '16:02:00'],['Tuesday', '09:01:00'],['Tuesday', '16:02:00']

I would like to have a list like this

[{'day':'Sunday', 'time':'15:01:00, 16:02:00, 09:01:00'},{'day':'Monday', 'time':'15:01:00, 16:02:00'},{'day':'Tuesday', 'time':'09:01:00, 16:02:00'}]

Can anyone please help me with this.

Thank you.

Body:
I went with a loop in the template

# views.py
ms = M.objects.filter(foo=bar).all()
for m in ms:
    favorited = m.baz.qux_set.filter(foo=request.user.id).first()
    if favorited:
        m.tags = favorited.tags.names()

and

# template.html
{% for m in ms %}
  {% for tag in m.tags %}{{ tag }} , {% endfor %}

ContentLicense: CC BY-SA 4.0


问:
SwiftUI Position Overlay on Camera Preview
I'm trying to add a target-like overlay to the photo preview in an app that uses
portrait on some devices and landscape on others. I can manually set coordinates but
have not been able to get the correct coordinates of the frame of the camera preview.

This is a SwiftUI application, so I am doing the camera work in a
UIViewControllerRepresentable. Here's what I have and obviously, the target circle is
always wrong when the device and/or orientation change. I don't seem to be able to capture
the frame of the modal view where the camera preview exists. I would settle to be
able to specify the frame and location of the camera preview on the modal view.

```<code>struct CaptureImageView: View {
    @Binding var isShown: Bool
    @Binding var image: Image?
    @Binding var newUIImage: UIImage?
    @Binding var showSaveButton: Bool

    func makeCoordinator() -> Coordinator {
        return Coordinator(isShown: $isShown, image: $newUIImage, showSaveButton: $showSaveButton)
    }
}

extension CaptureImageView: UIViewControllerRepresentable {

    func makeUIViewController(context: UIViewControllerRepresentableContext<CaptureImageView>) -> UIImagePickerController {

        let vc = UIImagePickerController()

        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) {
            vc.sourceType = .camera
            vc.allowsEditing = true
            vc.delegate = context.coordinator

            let screenSize: CGRect = UIScreen.main.bounds
            let screenWidth = screenSize.width
            let screenHeight = screenSize.height

            vc.cameraOverlayView = CircleView(frame: CGRect(x: (screenWidth / 2) - 50, y: (screenWidth / 2) + 25, width: 100, height: 100))

            return vc
        }
        return UIImagePickerController()
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<CaptureImageView>) {
    }
}
</code>```

Here is the idea - but the target always needs to be centered:

And the target file:

```<code>class CircleView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.clear
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func draw(_ rect: CGRect) {
        if let context = UIGraphicsGetCurrentContext() {
            context.setLineWidth(3.0)
            UIColor.red.set()

            let center = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
            let radius = (frame.size.width - 10) / 2

            context.addArc(center: center, radius: radius, startAngle: 0.0, endAngle: .pi * 2.0, clockwise: true)
            context.strokePath()
        }
    }
}
</code>```

Any guidance would be appreciated. Xcode Version 11.3.1 (11C504)

答:
While I would still like to find an answer for the way to get the frame of the camera - my goal could be mostly achieved by creating a circle view in a ZStack placing the camera view behind my circle view in SwiftUI like this:</p>
```<code>if showCaptureImageView {
    ZStack {
        CaptureImageView(isShown: $showCaptureImageView, image: $myImage, newUIImage: $newUIImage, showSaveButton: $showSaveButton)

        Circle()
            .stroke(Color.red, style: StrokeStyle(lineWidth: 10 ))
            .frame(width: 100, height: 100)
            .offset(CGSize(width: 0, height: -50.0))
    }
}//if show
</code>```

Body:
I'm trying to add a target-like overlay to the photo preview in an app that uses
portrait on some devices and landscape on others. I can manually set coordinates but
have not been able to get the correct coordinates of the frame of the camera preview.

This is a SwiftUI application, so I am doing the camera work in a
UIViewControllerRepresentable. Here's what I have and obviously, the target circle is
always wrong when the device and/or orientation change. I don't seem to be able to capture
the frame of the modal view where the camera preview exists. I would settle to be
able to specify the frame and location of the camera preview on the modal view.

struct CaptureImageView: View {
    @Binding var isShown: Bool
    @Binding var image: Image?
    @Binding var newUIImage: UIImage?
    @Binding var showSaveButton: Bool

    func makeCoordinator() -> Coordinator {
        return Coordinator(isShown: $isShown, image: $newUIImage, showSaveButton: $showSaveButton)
    }
}

extension CaptureImageView: UIViewControllerRepresentable {

    func makeUIViewController(context: UIViewControllerRepresentableContext<CaptureImageView>) -> UIImagePickerController {

        let vc = UIImagePickerController()

        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) {
            vc.sourceType = .camera
            vc.allowsEditing = true
            vc.delegate = context.coordinator

            let screenSize: CGRect = UIScreen.main.bounds
            let screenWidth = screenSize.width
            let screenHeight = screenSize.height

            vc.cameraOverlayView = CircleView(frame: CGRect(x: (screenWidth / 2) - 50, y: (screenWidth / 2) + 25, width: 100, height: 100))

            return vc
        }
        return UIImagePickerController()
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<CaptureImageView>) {
    }
}

Here is the idea - but the target always needs to be centered:

And the target file:

class CircleView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.clear
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func draw(_ rect: CGRect) {
        if let context = UIGraphicsGetCurrentContext() {
            context.setLineWidth(3.0)
            UIColor.red.set()

            let center = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
            let radius = (frame.size.width - 10) / 2

            context.addArc(center: center, radius: radius, startAngle: 0.0, endAngle: .pi * 2.0, clockwise: true)
            context.strokePath()
        }
    }
}

Any guidance would be appreciated. Xcode Version 11.3.1 (11C504)

Body:
While I would still like to find an answer for the way to get the frame of the camera - my goal could be mostly achieved by creating a circle view in a ZStack placing the camera view behind my circle view in SwiftUI like this:

if showCaptureImageView {
    ZStack {
        CaptureImageView(isShown: $showCaptureImageView, image: $myImage, newUIImage: $newUIImage, showSaveButton: $showSaveButton)

        Circle()
            .stroke(Color.red, style: StrokeStyle(lineWidth: 10 ))
            .frame(width: 100, height: 100)
            .offset(CGSize(width: 0, height: -50.0))
    }
}//if show


答:
Your example is a bit confusing, but I'll take a stab at helping.

What it sounds like you want to do is dedupe the original array, based on a key in one of the nested objects. Common way to dedupe like this is to use a map object.
and you also want to collect info from that object in a new array. You can actually do both these operations at the same time because of how object references work.

Full disclosuer: This could be written nicer with some newer JS syntax, tried to keep it simple :)

const customerInformation = [
{"id":"12345678","timestamp":"2019-01-21T11:53:29.338Z","userConnection":"1942f0e6","ownerId":"234566654","exec":{"execId":"20326379004","eventTime":"2019-01-21T11:53:29.223Z","communication":[{"name":"John Smith","accountId":"234566654","comid":"cs169612397275616092-1","status":"Active","phoneNumber":"+442222222222","extensionId":"234566654","missedCall":false,"standAlone":false,"muted":false}]}},
{"id":"6374595864","timestamp":"2019-01-21T11:53:29.338Z","userConnection":"1942f0e6","ownerId":"155464348743","exec":{"execId":"1521648743","eventTime":"2019-01-21T11:53:29.223Z","communication":[{"name":"Math Lo","accountId":"26726447342","comid":"cs169612397275616092-1","status":"Active","phoneNumber":"+442222222222","extensionId":"234566654","missedCall":false,"standAlone":false,"muted":false}]}},
{"id":"98736478","timestamp":"2019-01-21T11:53:29.338Z","userConnection":"hblwrv890","ownerId":"98765322","exec":{"execId":"20326379004","eventTime":"2019-01-21T11:53:29.223Z","communication":[{"name":"James Olive","accountId":"234566654","comid":"cs169612397275616092-2","status":"Active","phoneNumber":"+442222222222","extensionId":"2763648749","missedCall":false,"standAlone":false,"muted":false}]}},
{"id":"256644477","timestamp":"2019-01-21T11:53:29.338Z","userConnection":"sbdbbgbg","ownerId":"32545453565","exec":{"execId":"32254655464","eventTime":"2019-01-21T11:53:29.223Z","communication":[{"name":"Ben Right","accountId":"234566654","comid":"cs169612397275616092-2","status":"Active","phoneNumber":"+442222222222","extensionId":"2763648749","missedCall":false,"standAlone":false,"muted":false}]}},
{"id":"99326672378372","timestamp":"2019-01-21T11:53:29.338Z","userConnection":"sjvjvnfrrev","ownerId":"28643872329","exec":{"execId":"268474374938","eventTime":"2019-01-21T11:53:29.223Z","communication":[{"name":"Lowe John","accountId":"2225454354","comid":"cs169612397275616092-2","status":"Active","phoneNumber":"+442222222222","extensionId":"2763648749","missedCall":false,"standAlone":false,"muted":false}]}},
]

const map = {};
const newArr = [];

for (const info of customerInformation) {
    const id = info.exec.communication[0].comid;
    if (!map[id]) {
 map[id] = {};
 newArr.push(map[id]);
    }
    Object.assign(map[id], {
 ownerId: info.ownerId,
 comid: id,
 extensionId: info.id,
 userConnection: info.userConnection
 // add whatever fields and other logic you want here
    });
}

console.log('customerInformation', newArr);```

I didn't understand some of the question so just trying to do my best to lend a hand. Wasn't sure what you meant by Also the second value has to return undefined, as it's the requirement

Title: Manipulating Array of object in Javascript

Body:
Your example is a bit confusing, but I'll take a stab at helping.

What it sounds like you want to do is dedupe the original array, based on a key in one of the nested objects. Common way to dedupe like this is to use a map object.
and you also want to collect info from that object in a new array. You can actually do both these operations at the same time because of how object references work.

Full disclosuer: This could be written nicer with some newer JS syntax, tried to keep it simple :)

const customerInformation = [
{"id":"12345678","timestamp":"2019-01-21T11:53:29.338Z","userConnection":"1942f0e6","ownerId":"234566654","exec":{"execId":"20326379004","eventTime":"2019-01-21T11:53:29.223Z","communication":[{"name":"John Smith","accountId":"234566654","comid":"cs169612397275616092-1","status":"Active","phoneNumber":"+442222222222","extensionId":"234566654","missedCall":false,"standAlone":false,"muted":false}]}},
{"id":"6374595864","timestamp":"2019-01-21T11:53:29.338Z","userConnection":"1942f0e6","ownerId":"155464348743","exec":{"execId":"1521648743","eventTime":"2019-01-21T11:53:29.223Z","communication":[{"name":"Math Lo","accountId":"26726447342","comid":"cs169612397275616092-1","status":"Active","phoneNumber":"+442222222222","extensionId":"234566654","missedCall":false,"standAlone":false,"muted":false}]}},
{"id":"98736478","timestamp":"2019-01-21T11:53:29.338Z","userConnection":"hblwrv890","ownerId":"98765322","exec":{"execId":"20326379004","eventTime":"2019-01-21T11:53:29.223Z","communication":[{"name":"James Olive","accountId":"234566654","comid":"cs169612397275616092-2","status":"Active","phoneNumber":"+442222222222","extensionId":"2763648749","missedCall":false,"standAlone":false,"muted":false}]}},
{"id":"256644477","timestamp":"2019-01-21T11:53:29.338Z","userConnection":"sbdbbgbg","ownerId":"32545453565","exec":{"execId":"32254655464","eventTime":"2019-01-21T11:53:29.223Z","communication":[{"name":"Ben Right","accountId":"234566654","comid":"cs169612397275616092-2","status":"Active","phoneNumber":"+442222222222","extensionId":"2763648749","missedCall":false,"standAlone":false,"muted":false}]}},
{"id":"99326672378372","timestamp":"2019-01-21T11:53:29.338Z","userConnection":"sjvjvnfrrev","ownerId":"28643872329","exec":{"execId":"268474374938","eventTime":"2019-01-21T11:53:29.223Z","communication":[{"name":"Lowe John","accountId":"2225454354","comid":"cs169612397275616092-2","status":"Active","phoneNumber":"+442222222222","extensionId":"2763648749","missedCall":false,"standAlone":false,"muted":false}]}},
]

const map = {};
const newArr = [];

for (const info of customerInformation) {
    const id = info.exec.communication[0].comid;
    if (!map[id]) {
 map[id] = {};
 newArr.push(map[id]);
    }
    Object.assign(map[id], {
 ownerId: info.ownerId,
 comid: id,
 extensionId: info.id,
 userConnection: info.userConnection
 // add whatever fields and other logic you want here
    });
}

console.log('customerInformation', newArr);

I didn't understand some of the question so just trying to do my best to lend a hand. Wasn't sure what you meant by Also the second value has to return undefined, as it's the requirement


问:
Signed upload to cloudinary with node-fetch instead of request
I am capable of uploading to the Cloudinary via the REST API using the Node request module like so:

```<code> request.post({
  url: `https://api.cloudinary.com/v1_1/dennis/image/upload`,
  body: {
   file: `data:image/jpeg;base64,${req.body.toString('base64')}`,
   api_key: key,
   folder: 'dennis',
   timestamp: ts,
   signature: sig
  },
  json: true
 }, async (err, response, body) => {

  if (err) return console.error(err)

  res.send({
   'public_id': body.public_id,
   'secure_url': body.secure_url
  })
 })
</code>```

I am only using the request for the cloudinary upload otherwise I use node-fetch throughout my application. I would like to use node-fetch for the cloudinary upload but applying the same logic as in the working example above results in the cryptic error message: 'Upload preset must be specified when using unsigned...'

My node fetch request looks like this:

```<code> let response = await fetch(
  `https://api.cloudinary.com/v1_1/dennis/image/upload`,
  {
   method: 'post',
   body: {
    file: `data:image/jpeg;base64,${req.body.toString('base64')}`,
    api_key: key,
    folder: 'dennis',
    timestamp: ts,
    signature: sig
  }
 })

 if (response.status === 400) return console.error(response)

 let body = await response.json()

 res.send({
  'public_id': body.public_id,
  'secure_url': body.secure_url
 })

</code>```

答:
Have you consider using our Node SDK to achieve this?
Please check the documentation for more info: https://cloudinary.com/documentation/node_integration</p>

Body:
I am capable of uploading to the Cloudinary via the REST API using the Node request module like so:

 request.post({
  url: `https://api.cloudinary.com/v1_1/dennis/image/upload`,
  body: {
   file: `data:image/jpeg;base64,${req.body.toString('base64')}`,
   api_key: key,
   folder: 'dennis',
   timestamp: ts,
   signature: sig
  },
  json: true
 }, async (err, response, body) => {

  if (err) return console.error(err)

  res.send({
   'public_id': body.public_id,
   'secure_url': body.secure_url
  })
 })

I am only using the request for the cloudinary upload otherwise I use node-fetch throughout my application. I would like to use node-fetch for the cloudinary upload but applying the same logic as in the working example above results in the cryptic error message: 'Upload preset must be specified when using unsigned...'

My node fetch request looks like this:

 let response = await fetch(
  `https://api.cloudinary.com/v1_1/dennis/image/upload`,
  {
   method: 'post',
   body: {
    file: `data:image/jpeg;base64,${req.body.toString('base64')}`,
    api_key: key,
    folder: 'dennis',
    timestamp: ts,
    signature: sig
  }
 })

 if (response.status === 400) return console.error(response)

 let body = await response.json()

 res.send({
  'public_id': body.public_id,
  'secure_url': body.secure_url
 })


问:
Replace span's in PHP but keep content inside
I have the following string:

```<code><span style="font-size: 13px;">
   <span style="">
      <span style="">
         <span style="font-family: Roboto, sans-serif;">
            <span style="">
               Some text content
            </span>
         </span>
      </span>
   </span>
</span>
</code>```

and I want to change this string to the following using PHP:

```<code><span style="font-size: 13px;">
   <span style="font-family: Roboto, sans-serif;">
      Some text content
   </span>
</span>
</code>```

I dont have any idea, how to do that, because when I try to use str_replace to replace the  I dont know, how to replace the  and keep the content inside. My next problem is, that I dont know exactly, how much  I have in my string. I also have not only 1 of this blocks in my string.

Thanks in advance for your help, and maybe sorry for my stupid question - I'm still learning.

答:
This is easily done with a proper HTML parser. PHP has DOMDocument which can parse X/HTML into the Document Object Model which can then be manipulated how you want.

The trick to solving this problem is being able to recursively traverse the DOM tree, seeking out each node, and replacing the ones you don't want. To this I've written a short helper method by extending DOMDocument here...

```<code>$html = <<<'HTML'
<span style="font-size: 13px;">
   <span style="">
      <span style="">
         <span style="font-family: Roboto, sans-serif;">
            <span style="">
               Some text content
            </span>
         </span>
      </span>
   </span>
</span>
HTML;

class MyDOMDocument extends DOMDocument {
    public function walk(DOMNode $node, $skipParent = false) {
        if (!$skipParent) {
            yield $node;
        }
        if ($node->hasChildNodes()) {
            foreach ($node->childNodes as $n) {
                yield from $this->walk($n);
            }
        }
    }
}

libxml_use_internal_errors(true);

$dom = new MyDOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$keep = $remove = [];

foreach ($dom->walk($dom->childNodes->item(0)) as $node) {
    if ($node->nodeName !== "span") { // we only care about span nodes
        continue;
    }
    // we'll get rid of all span nodes that don't have the style attribute
    if (!$node->hasAttribute("style") || !strlen($node->getAttribute("style"))) {
        $remove[] = $node;
        foreach($node->childNodes as $child) {
            $keep[] = [$child, $node];
        }
    }
}

// you have to modify them one by one in reverse order to keep the inner nodes
foreach($keep as [$a, $b]) {
    $b->parentNode->insertBefore($a, $b);
}
foreach($remove as $a) {
    if ($a->parentNode) {
        $a->parentNode->removeChild($a);
    }
}

// Now we should have a rebuilt DOM tree with what we expect:
echo $dom->saveHTML();
</code>```

Output:

```
<span style="font-size: 13px;">

         <span style="font-family: Roboto, sans-serif;">

               Some text content

         </span>

</span>
```

Body:
I have the following string:

               Some text content

and I want to change this string to the following using PHP:

      Some text content

I dont have any idea, how to do that, because when I try to use str_replace to replace the  I dont know, how to replace the  and keep the content inside. My next problem is, that I dont know exactly, how much  I have in my string. I also have not only 1 of this blocks in my string.

Thanks in advance for your help, and maybe sorry for my stupid question - I'm still learning.

Body:
This is easily done with a proper HTML parser. PHP has DOMDocument which can parse X/HTML into the Document Object Model which can then be manipulated how you want.

The trick to solving this problem is being able to recursively traverse the DOM tree, seeking out each node, and replacing the ones you don't want. To this I've written a short helper method by extending DOMDocument here...

$html = <<<'HTML'
<span style="font-size: 13px;">
   <span style="">
      <span style="">
         <span style="font-family: Roboto, sans-serif;">
            <span style="">
               Some text content
            </span>
         </span>
      </span>
   </span>
</span>
HTML;

class MyDOMDocument extends DOMDocument {
    public function walk(DOMNode $node, $skipParent = false) {
        if (!$skipParent) {
            yield $node;
        }
        if ($node->hasChildNodes()) {
            foreach ($node->childNodes as $n) {
                yield from $this->walk($n);
            }
        }
    }
}

libxml_use_internal_errors(true);

$dom = new MyDOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$keep = $remove = [];

foreach ($dom->walk($dom->childNodes->item(0)) as $node) {
    if ($node->nodeName !== "span") { // we only care about span nodes
        continue;
    }
    // we'll get rid of all span nodes that don't have the style attribute
    if (!$node->hasAttribute("style") || !strlen($node->getAttribute("style"))) {
        $remove[] = $node;
        foreach($node->childNodes as $child) {
            $keep[] = [$child, $node];
        }
    }
}

// you have to modify them one by one in reverse order to keep the inner nodes
foreach($keep as [$a, $b]) {
    $b->parentNode->insertBefore($a, $b);
}
foreach($remove as $a) {
    if ($a->parentNode) {
        $a->parentNode->removeChild($a);
    }
}

// Now we should have a rebuilt DOM tree with what we expect:
echo $dom->saveHTML();

Output:

<span style="font-size: 13px;">

         <span style="font-family: Roboto, sans-serif;">

               Some text content

         </span>

</span>


问:
How to limit my String to be between 001 and the max string to 999 implementing conditions once it is read by by user

//need to set a condition for a read String by user to be between
  001 and 999
      String str="000";
      int i=Integer.parseInt(str);
      if(i<1||i>999)
        System.out.print("error");

答:
```<code>private boolean isStrInRange(String str){
    return IntStream.range(1, 999)
            .boxed()
            .collect(Collectors.toList())
            .contains(Integer.parseInt(str));
}
</code>```

I think this is the best way, using Stream API

Body:
private boolean isStrInRange(String str){
    return IntStream.range(1, 999)
            .boxed()
            .collect(Collectors.toList())
            .contains(Integer.parseInt(str));
}

I think this is the best way, using Stream API


问:
How to display multiple PathLayer with Deck.gl
I'm not too familiar with React Js and DeckGL. I am trying to display several objects of the PathLayer class on an interactive map. A single object is displayed without problems, but when there are several, it does not work:

```<code>    const token = global.REACT_APP_TOKEN;

    const initialViewState = {
        longitude: 37.6205569,
        latitude: 55.746277,
        zoom: 11
    };

    class ParkingOnMap extends Component {
        state = {
            features: []
        };

        async componentDidMount() {
            const body = await (await fetch(global.path + `/featuresOnlyIDAndCoordinates`)).json();
            this.setState({features: body});
        }

        render() {
            const {features} = this.state;
            const data = [{
                name: "random-name",
                color: [245, 49, 49],//[101, 147, 245],

                path: [[37.639533, 55.7841708], [37.639533, 55.7842522], [37.6398898, 55.7843533], [37.6399059, 55.7846172]],
              //path: features.map(c => {return (c.coordinates)})

        }];

        console.log(data.map(c => {return c.path}));
        console.log(features);

        // below, add whatever layers you need to overlay on your map
        const layer = [
            new PathLayer({
                id: 'path-layer',
                data,
                //data: coordinates,
                getPath: data => data.path,
                getWidth: data => 4,
                getColor: data => data.color,
                widthMinPixels: 4
            })
        ];

        return (
            <div className="App">
                <AppNavbar/>
                <Button onClick={this.setUserLocation}>My Location</Button>
                <div className="map">
                    {<React.Fragment>
                        <DeckGL
                            initialViewState={initialViewState}
                            controller={true}
                            layers={layer}
                        >
                            <StaticMap
                                mapStyle="mapbox://styles/mapbox/streets-v11"
                                mapboxApiAccessToken={token}
                            />
                        </DeckGL>
                    </React.Fragment>}
                </div>
            </div>
        )
    }
}

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

This is a working example with one array of coordinates:

```<code>path: [[37.639533, 55.7841708], [37.639533, 55.7842522], [37.6398898, 55.7843533], [37.6399059, 55.7846172]]
</code>```

This part that doesn't work:

```<code>path: features.map(c => {return (c.coordinates)})
</code>```

In the second case, the data represents an array of json objects like:

```<code>[{"id":"3020148","coordinates":[[37.5948822,55.7154477],[37.595188,55.7157046]]},{"id":"3020149","coordinates":[[37.5954187,55.7158979],[37.5963521,55.7166594]]}, ....etc.
</code>```

I can’t figure out how to make iterate through all the objects in the DeckGL render. The documentation says it's pretty easy.

答: I considered the simplest and most native solution like Leaflet.</p>

Body:
I'm not too familiar with React Js and DeckGL. I am trying to display several objects of the PathLayer class on an interactive map. A single object is displayed without problems, but when there are several, it does not work:

    const token = global.REACT_APP_TOKEN;

    const initialViewState = {
        longitude: 37.6205569,
        latitude: 55.746277,
        zoom: 11
    };

    class ParkingOnMap extends Component {
        state = {
            features: []
        };

        async componentDidMount() {
            const body = await (await fetch(global.path + `/featuresOnlyIDAndCoordinates`)).json();
            this.setState({features: body});
        }

        render() {
            const {features} = this.state;
            const data = [{
                name: "random-name",
                color: [245, 49, 49],//[101, 147, 245],

                path: [[37.639533, 55.7841708], [37.639533, 55.7842522], [37.6398898, 55.7843533], [37.6399059, 55.7846172]],
              //path: features.map(c => {return (c.coordinates)})

        }];

        console.log(data.map(c => {return c.path}));
        console.log(features);

        // below, add whatever layers you need to overlay on your map
        const layer = [
            new PathLayer({
                id: 'path-layer',
                data,
                //data: coordinates,
                getPath: data => data.path,
                getWidth: data => 4,
                getColor: data => data.color,
                widthMinPixels: 4
            })
        ];

        return (

                <AppNavbar/>
                <Button onClick={this.setUserLocation}>My Location</Button>

                    {<React.Fragment>
                        <DeckGL
                            initialViewState={initialViewState}
                            controller={true}
                            layers={layer}
                        >
                            <StaticMap
                                mapStyle="mapbox://styles/mapbox/streets-v11"
                                mapboxApiAccessToken={token}
                            />
                        </DeckGL>
                    </React.Fragment>}

        )
    }
}

export default withRouter (ParkingOnMap);

This is a working example with one array of coordinates:

path: [[37.639533, 55.7841708], [37.639533, 55.7842522], [37.6398898, 55.7843533], [37.6399059, 55.7846172]]

This part that doesn't work:

path: features.map(c => {return (c.coordinates)})

In the second case, the data represents an array of json objects like:

[{"id":"3020148","coordinates":[[37.5948822,55.7154477],[37.595188,55.7157046]]},{"id":"3020149","coordinates":[[37.5954187,55.7158979],[37.5963521,55.7166594]]}, ....etc.

I can’t figure out how to make iterate through all the objects in the DeckGL render. The documentation says it's pretty easy.


问:
Pull a specific commit using libgit2sharp
hopefully someone call help. First off, I am pretty new to git, so forgive me if I make some mistakes in explaining my question.

I would like to pull the source code as it exists up to a specific commit using the library using libgit2sharp. So if there is a history of

Commit

Commit

Commit

Commit

Commit

Commit

Commit

Commit

Commit

Commit

I would like to be able to pull the source code for 5, or any other number in that list. None of the source will be tagged so I have to use the commits for the pull. Hopefully someone can help.

I have looked at https://github.com/libgit2/libgit2sharp/wiki/git-pull but it does not appear to let me pass in a sha or commit id.

Edited my question to be clear I am using the library.

答:
So another dev answered the question. All I needed to do was a clone, then a checkout against the commit I wanted to reset to. This seems to work the way I wanted.

```<code>//clone the master
dir = Path.Combine(localPath, "Target");
Directory.CreateDirectory(dir);
Repository.Clone(tfsUri, dir);

//reset master to the base of the branch
using (var localRepo = new Repository(dir))
{
    var localCommit = localRepo.Lookup<Commit>(priorCommitId);
    Commands.Checkout(localRepo, localCommit);
}
</code>```

Not sure if this is what you meant @0andriy, but your comment was a bit confusing.

Body:
So another dev answered the question. All I needed to do was a clone, then a checkout against the commit I wanted to reset to. This seems to work the way I wanted.

//clone the master
dir = Path.Combine(localPath, "Target");
Directory.CreateDirectory(dir);
Repository.Clone(tfsUri, dir);

//reset master to the base of the branch
using (var localRepo = new Repository(dir))
{
    var localCommit = localRepo.Lookup<Commit>(priorCommitId);
    Commands.Checkout(localRepo, localCommit);
}

Not sure if this is what you meant @0andriy, but your comment was a bit confusing.


问:
Return rows in pandas based on values in multiple columns
Needed some help with pandas...I'm working on this data and I'm trying to calculate some changes over time per region.
Basically, I'm trying to find the oldest quantity and the newest quantity for each area in question. I have code that can give me the year of the most recent and oldest data recordes, however I need to gather the whole row so I can work on the 'quantity' column. Any inputs? here is what i have :

df.groupby(['Country or Area'])['Year'].max()

Thanks in advance!

答:
You need to use
agg functions of groupby()

You can pass the functions or a dict of functions to the columns you need to aggregate

In your case the code should be like Crish solution is the better way to do it.

Sort the dataframe by the value to check and then group and get by .agg() the result that you need

The stack()  method works to deflate the df level


问:
How to identify host machine Mac address from vm machine Mac adrress
How to identify host machine Mac address from vm machine Mac adrress

Example: in our Network we scan and found  one of the  vm machine  Kali Linux is install. And also get Mac address and ip address of that machine. Mac adrress belong to vmware inc. we want to identify physical machine where this vm machine was installed

Thanks for reply Clifford,

but i am asking about Vm workstation (not Esxi and Vcenter). some one installed Kali linux on Vm worksation.

答:
You left out some key information, like if you are using vCenter or just ESXi? Do you have access to vCenter.

The easiest way is to just login to your ESXi host or vCenter and right click the VM and edit and check the each nic properties until you find the MAC.

If you environment is large and you have vCenter, you can use PowerCli. You will need access to vCenter.

Download PowerCli here: https://www.powershellgallery.com/packages/VMware.PowerCLI/11.5.0.14912921

```<code>Install-Module -Name VMware.PowerCLI

Import-Module VMware.VimAutomation.Core

Connect-VIServer -Server <IP/FQDN> -Protocol https -User <username> -Password <password>

Get-VM | Get-NetworkAdapter | Where {$_.MacAddress -eq “XX:XX:XX:XX:XX:XX”} | Select-Object Parent,Name,MacAddress

Get-VMHost -VM <name of VM you got from Get-VM>
</code>```

Body:
You left out some key information, like if you are using vCenter or just ESXi? Do you have access to vCenter.

The easiest way is to just login to your ESXi host or vCenter and right click the VM and edit and check the each nic properties until you find the MAC.

If you environment is large and you have vCenter, you can use PowerCli. You will need access to vCenter.

Download PowerCli here: https://www.powershellgallery.com/packages/VMware.PowerCLI/11.5.0.14912921

Install-Module -Name VMware.PowerCLI

Import-Module VMware.VimAutomation.Core

Connect-VIServer -Server <IP/FQDN> -Protocol https -User <username> -Password <password>

Get-VM | Get-NetworkAdapter | Where {$_.MacAddress -eq “XX:XX:XX:XX:XX:XX”} | Select-Object Parent,Name,MacAddress

Get-VMHost -VM <name of VM you got from Get-VM>


问:
How do I make images the same height in a flexbox side-by-side, without knowing their dimensions
I would want to make 2 images with different widths, displayed the same height side-by-side, ideally in a flex box.

The following works if I know the image dimensions (962x706 and 962x1275).

Is there a way to do this without knowing their dimensions?

```<code><div style="display: flex; margin: 0 -5px">
    <div style="flex: calc(962/706); margin: 0 5px">
        <img src="https://i.stack.imgur.com/H7QKE.jpg"/>
    </div>
    <div style="flex: calc(962/1275); margin: 0 5px">
        <img src="https://i.stack.imgur.com/nsyuX.jpg"/>
    </div>
</div>
</code>```

```<code>img {
  width: 100%;
}
</code>```

A fiddle for convenience https://jsfiddle.net/b1f6v3kc/

答:
You could set a fixed height for the all the images or use javascript to know the dimensions.
You must take in count that if you modify the height only the aspect ratio change and the image could look bad

```<code><div style="display: flex; margin: 0 -5px">
    <div style="margin: 0 5px">
        <img src="https://i.stack.imgur.com/nsyuX.jpg"/>
    </div>
    <div style="margin: 0 5px">
        <img src="https://i.stack.imgur.com/H7QKE.jpg"/>
    </div>
</div>

img {
  width: 100%;
  height: 300px;
}
</code>```

https://jsfiddle.net/xsn07yaw/

Body:
I would want to make 2 images with different widths, displayed the same height side-by-side, ideally in a flex box.

The following works if I know the image dimensions (962x706 and 962x1275).

Is there a way to do this without knowing their dimensions?

img {
  width: 100%;
}

A fiddle for convenience https://jsfiddle.net/b1f6v3kc/

Body:
You could set a fixed height for the all the images or use javascript to know the dimensions.
You must take in count that if you modify the height only the aspect ratio change and the image could look bad

<div style="display: flex; margin: 0 -5px">
    <div style="margin: 0 5px">
        <img src="https://i.stack.imgur.com/nsyuX.jpg"/>
    </div>
    <div style="margin: 0 5px">
        <img src="https://i.stack.imgur.com/H7QKE.jpg"/>
    </div>
</div>

img {
  width: 100%;
  height: 300px;
}

https://jsfiddle.net/xsn07yaw/


问:
Dynamics CRM Email correlation issue
When a user creates a case, an email is shot. If this email is answered, it can be tracked. Issue is that sometimes, the person who replies to the email clears the subject text field. Instead of getting RE: or RV:, once this subject is cleared the email is "lost" and cannot be tracked.

Does anyone know a solution? Some kind of "hidden code" inside the email that let us still track the email even the user changes the subject?

答:
CRM emails & replies are tracked as conversations, regarded to existing records using these correlation techniques, but somewhat they are tightly coupled with Email subject. So advise the users not to edit the subject line when they reply, maybe some info text in Email signature or something.

Correlation is used to link an email to records in CRM, three methods of automatic correlation exist;

•   Email headers

•   Smart Matching

•   Tracking token

Learn more

Each of this has its own limitations and one will overcome the limits & solve the problem of others, but still Subject plays a crucial role - like tracking token per activity and regular expression based Smart matching.

Otherwise you have to write a plugin on Email pre-create, to manually correlate which is unnecessary overkill.

Title: Dynamics CRM Email correlation issue


问:
How to Implement Integrated Random Walk Trend Component in Tensorflow Probability
I'm running tensorflow 2.1 and tensorflow_probability 0.9. I have fit a Structural Time Series Model with a seasonal component.

I wish to implement an Integrated Random walk in order to smooth the trend component, as per Time Series Analysis by State Space Methods: Second Edition, Durbin & Koopman.  The integrated random walk is achieved by setting the level component variance to equal 0.

Is implementing this constraint possible in Tensorflow Probability?

Further to this in Durbin & Koopman, higher order random walks are discussed.  Could this be implemented?

Thanks in advance for your time.

答:
If I understand correctly, an integrated random walk is just the special case of LocalLinearTrend in which the level simply integrates the randomly-evolving slope component (ie it has no independent source of variation). You could patch this in by subclassing LocalLinearTrend and fixing level_scale = 0. in the models it builds:

class IntegratedRandomWalk(sts.LocalLinearTrend):

  def __init__(self,
               slope_scale_prior=None,
               initial_slope_prior=None,
               observed_time_series=None,
               name=None):
    super(IntegratedRandomWalk, self).__init__(
      slope_scale_prior=slope_scale_prior,
      initial_slope_prior=initial_slope_prior,
      observed_time_series=observed_time_series,
      name=None)
    # Remove 'level_scale' parameter from the model.
    del self._parameters[0]

  def _make_state_space_model(self,
                              num_timesteps,
                              param_map,
                              initial_state_prior=None,
                              initial_step=0):

    # Fix `level_scale` to zero, so that the level
    # cannot change except by integrating the
    # slope.
    param_map['level_scale'] = 0.

    return super(IntegratedRandomWalk, self)._make_state_space_model(
      num_timesteps=num_timesteps,
      param_map=param_map,
      initial_state_prior=initial_state_prior,
      initial_step=initial_step)
```

(it would be mathematically equivalent to build a LocalLinearTrend with level_scale_prior concentrated at zero, but that constraint makes inference difficult, so it's generally better to just ignore or remove the parameter entirely, as I did here).

By higher-order random walks, do you mean autoregressive models? If so, sts.Autoregressive might be relevant.

Body:
If I understand correctly, an integrated random walk is just the special case of LocalLinearTrend in which the level simply integrates the randomly-evolving slope component (ie it has no independent source of variation). You could patch this in by subclassing LocalLinearTrend and fixing level_scale = 0. in the models it builds:

class IntegratedRandomWalk(sts.LocalLinearTrend):

  def __init__(self,
               slope_scale_prior=None,
               initial_slope_prior=None,
               observed_time_series=None,
               name=None):
    super(IntegratedRandomWalk, self).__init__(
      slope_scale_prior=slope_scale_prior,
      initial_slope_prior=initial_slope_prior,
      observed_time_series=observed_time_series,
      name=None)
    # Remove 'level_scale' parameter from the model.
    del self._parameters[0]

  def _make_state_space_model(self,
                              num_timesteps,
                              param_map,
                              initial_state_prior=None,
                              initial_step=0):

    # Fix `level_scale` to zero, so that the level
    # cannot change except by integrating the
    # slope.
    param_map['level_scale'] = 0.

    return super(IntegratedRandomWalk, self)._make_state_space_model(
      num_timesteps=num_timesteps,
      param_map=param_map,
      initial_state_prior=initial_state_prior,
      initial_step=initial_step)

(it would be mathematically equivalent to build a LocalLinearTrend with level_scale_prior concentrated at zero, but that constraint makes inference difficult, so it's generally better to just ignore or remove the parameter entirely, as I did here).

By higher-order random walks, do you mean autoregressive models? If so, sts.Autoregressive might be relevant.


问:
Mod rewrite issue
As many others I am having issues with doing some very simple mod_rewriting in apache.

I have the following in my .htaccess:

```<code>Options +FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteRule ^view/([0-9]+)/([0-9]+)$ view.php?advertId=$1&publisherId=$2 [NC,QSA,L]
</code>```

Which is supposed to translate /view/4093/203?qs=val -> /view.php?advertId=4093&publisherId=203?qs=val

Now, it works when calling it with /View..., but when doing lowercase /view, it redirects to the right file, but advertId and publisherId is not set within my PHP script as it is with the first-letter-uppercase View and I simply put have no clue whatsoever with what is going on on that front (I have been testing and watching that behavior simply by doing a  on my view.php).

Anyone know why this is happening?

I may want to add, my server info is as follows:

```<code>Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny2 with Suhosin-Patch mod_python/3.3.1 Python/2.5.2 mod_perl/2.0.4 Perl/v5.10.0
</code>```

IE. a stock brand new debian install with default debian packages + php-mssql.

答:
MultiViews might cause this behavior, that is trying to map the request to a siminar existing file before passing the request to mod_rewrite. Try to disable it:

```<code>Options -MultiViews
</code>```

ContentLicense: CC BY-SA 2.5

Title: Mod rewrite issue

Body:
As many others I am having issues with doing some very simple mod_rewriting in apache.

I have the following in my .htaccess:

Options +FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteRule ^view/([0-9]+)/([0-9]+)$ view.php?advertId=$1&publisherId=$2 [NC,QSA,L]

Which is supposed to translate /view/4093/203?qs=val -> /view.php?advertId=4093&publisherId=203?qs=val

Now, it works when calling it with /View..., but when doing lowercase /view, it redirects to the right file, but advertId and publisherId is not set within my PHP script as it is with the first-letter-uppercase View and I simply put have no clue whatsoever with what is going on on that front (I have been testing and watching that behavior simply by doing a  on my view.php).

Anyone know why this is happening?

I may want to add, my server info is as follows:

Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny2 with Suhosin-Patch mod_python/3.3.1 Python/2.5.2 mod_perl/2.0.4 Perl/v5.10.0

IE. a stock brand new debian install with default debian packages + php-mssql.

Body:
MultiViews might cause this behavior, that is trying to map the request to a siminar existing file before passing the request to mod_rewrite. Try to disable it:

Options -MultiViews

OwnerDisplayName: Gumbo


问:
How to proportionally (respecting aspect ratio) scale a rectangle?
I'm trying to simply take a given box of x by y and scale it up, either by setting x and finding y, or vice versa. How would this formula be expressed in Python (for readability's sake). I'm trying to fit this box inside of a larger box so that the inner box always fits within the larger box.

答:
NB: I don't really do Python, so this is pseudocode.

What you need is the relative aspect ratios of the two boxes, since that determines which of the new axes must be the same size as the new box:

```<code>r_old = old_w / old_h
r_new = new_w / new_h

if (r_old > r_new) then
   w = new_w              // width of mapped rect
   h = w / r_old          // height of mapped rect
   x = 0                  // x-coord of mapped rect
   y = (new_h - h) / 2    // y-coord of centered mapped rect
else
   h = new_h
   w = h * r_old
   y = 0
   x = (new_w - w) / 2
endif
</code>```

Body:
NB: I don't really do Python, so this is pseudocode.

What you need is the relative aspect ratios of the two boxes, since that determines which of the new axes must be the same size as the new box:

r_old = old_w / old_h
r_new = new_w / new_h

if (r_old > r_new) then
   w = new_w              // width of mapped rect
   h = w / r_old          // height of mapped rect
   x = 0                  // x-coord of mapped rect
   y = (new_h - h) / 2    // y-coord of centered mapped rect
else
   h = new_h
   w = h * r_old
   y = 0
   x = (new_w - w) / 2
endif


问:
Is the t2.micro instance enough to fetch hundreds of thousands of rows?
I recently hosted an API on AWS Elastic Beanstalk with the free tier, I inserted 6 million rows. But I can't seem to consistently fetch data (usually around 200k at a time). Sometimes I can fetch around 100k, usually I get the error:

SyntaxError: Unexpected end of JSON input at http://***********.us-east-2.elasticbeanstalk.com/

or:

SyntaxError: Unexpected token < in JSON at position 0

which means it's fetching an HTML string.  I inserted one fake row and tried to fetch that and I'm able to consistently fetch it.

Am I right in assuming the free tier just isn't enough?

答:
You can check if the instance is hitting the the limit and facing any resource crunch using some basic Monitoring tool. One thing to note here is also your Instance can hit the bandwidth and be throttled by your EBS volume capabilities.

Check the performance metrics of the EBS volume as well.

After monitoring you can try and modify the size of the instance as AWS gives flexibility to modify the instance size and family.


问:
Webcrawling webpages using python charm
[enter image description here][1]Id like to scrape a web page for the name of subject and words find all words for a word i decide to search within the web page. My code so far not working

```<code>import requests
import csv
from bs4 import BeautifulSoup
start_urls = 'https://en.wikipedia.org/wiki/Data_science'
r = requests.get(start_urls)
soup = BeautifulSoup(r.content, 'html.parser')
crawled_page =[]
for page in soup.findAll('data'):
  crawled_page.append(page.get('href'))
print(crawled_page

Errormessage:
C:\Users\tette\PycharmProjects\WebcrawlerProject\venv\Scripts\python.exe
C:/Users/tette/PycharmProjects/WebcrawlerProject/webScrapy/webScrapy/spiders
</code>```

/webcrawler.py
    []

```<code>Process finished with exit code 0
</code>```

答:
if you want to search word in text then you should use

```<code>import re

soup.findAll(string=re.compile('data'))
</code>```

but it finds strings (NavigableString), not tags, so you may have to get they parent to search attributes like href

```<code>import requests
from bs4 import BeautifulSoup, NavigableString
import re

start_urls = 'https://en.wikipedia.org/wiki/Data_science'

r = requests.get(start_urls)

soup = BeautifulSoup(r.content, 'html.parser')
crawled_page =[]
for page in soup.findAll(string=re.compile('data')):
    #print(isinstance(page, NavigableString))
    #print(page.parent)
    href = page.parent.get('href')
    if href: # skip None
        crawled_page.append(href)
print(crawled_page)
</code>```

EDIT: similar with lxml using xpath

```<code>import requests
import lxml.html
import re

start_urls = 'https://en.wikipedia.org/wiki/Data_science'

r = requests.get(start_urls)

soup = lxml.html.fromstring(r.content)

crawled_page =[]

for page in soup.xpath('//*[contains(text(), "data")]'):
    href = page.attrib.get('href')
    if href: # skip None
        crawled_page.append(href)

print(crawled_page)
</code>```

Title: Webcrawling webpages using python charm

Body:
[enter image description here][1]Id like to scrape a web page for the name of subject and words find all words for a word i decide to search within the web page. My code so far not working

import requests
import csv
from bs4 import BeautifulSoup
start_urls = 'https://en.wikipedia.org/wiki/Data_science'
r = requests.get(start_urls)
soup = BeautifulSoup(r.content, 'html.parser')
crawled_page =[]
for page in soup.findAll('data'):
  crawled_page.append(page.get('href'))
print(crawled_page

Errormessage:
C:\Users\tette\PycharmProjects\WebcrawlerProject\venv\Scripts\python.exe
C:/Users/tette/PycharmProjects/WebcrawlerProject/webScrapy/webScrapy/spiders

/webcrawler.py
    []

Process finished with exit code 0

Body:
if you want to search word in text then you should use

import re

soup.findAll(string=re.compile('data'))

but it finds strings (NavigableString), not tags, so you may have to get they parent to search attributes like href

import requests
from bs4 import BeautifulSoup, NavigableString
import re

start_urls = 'https://en.wikipedia.org/wiki/Data_science'

r = requests.get(start_urls)

soup = BeautifulSoup(r.content, 'html.parser')
crawled_page =[]
for page in soup.findAll(string=re.compile('data')):
    #print(isinstance(page, NavigableString))
    #print(page.parent)
    href = page.parent.get('href')
    if href: # skip None
        crawled_page.append(href)
print(crawled_page)

EDIT: similar with lxml using xpath

import requests
import lxml.html
import re

start_urls = 'https://en.wikipedia.org/wiki/Data_science'

r = requests.get(start_urls)

soup = lxml.html.fromstring(r.content)

crawled_page =[]

for page in soup.xpath('//*[contains(text(), "data")]'):
    href = page.attrib.get('href')
    if href: # skip None
        crawled_page.append(href)

print(crawled_page)


问:
ASP.NET :- Deleting records from two tables using single view
I want to delete data from 2 tables. I am using entity framework.

Here is the class .

```<code>[HttpPost]
        public ActionResult Delete(int employeeId)
        {
            int id = employeeId;
            MvcWebApp.DbModel.profile profile = dbContext.profiles.Find(employeeId);
            dbContext.profiles.Remove(profile);
            dbContext.SaveChanges();
            regi regi = dbContext.regis.Find(id);
            dbContext.regis.Remove(regi);
            dbContext.SaveChanges();
            return RedirectToAction("Index");
        }
</code>```

Where employeeId is the Column name of child table and Id is column name of parent table .

MvcWebApp.DbModel.profile This is fully qualified name of class.

I am getting profile object null.

答:
my suggestion would be first, check to see you have that employee with Id you provided or not this is the easiest, i guess there MUST not be any! as you say it returns null.
are you getting this NULL for ALL inputs?

Second, try to run your code in debugger mode, put a break point at first line to see what EmployeeId is being sent to the Method. check it might be zero, so there is a problem in your POST method

Body:
I want to delete data from 2 tables. I am using entity framework.

Here is the class .

[HttpPost]
        public ActionResult Delete(int employeeId)
        {
            int id = employeeId;
            MvcWebApp.DbModel.profile profile = dbContext.profiles.Find(employeeId);
            dbContext.profiles.Remove(profile);
            dbContext.SaveChanges();
            regi regi = dbContext.regis.Find(id);
            dbContext.regis.Remove(regi);
            dbContext.SaveChanges();
            return RedirectToAction("Index");
        }

Where employeeId is the Column name of child table and Id is column name of parent table .

MvcWebApp.DbModel.profile This is fully qualified name of class.

I am getting profile object null.


问:
NLog EventProperties in .NET Core
I'm using ILogger<MyController> to write logs using DI (see step 6)

I'm also using NLog EventProperties

I want to add traceId to all my logs in my controller automatically.

This is working:

```<code>logger.Info("Some log. TraceId:{traceId}", 123);
</code>```

However, then I need to change all my log commands (a lot of them!), which is a pain.

If I do the following, it's not tread safe:

```<code>using NLog;
public class MyController : Controller
{
    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
    public MyConstructor(Apilog apilog)
    {
        Logger.SetProperty("traceid", apilog.TraceId);
    }
}
</code>```

Is there some way to use SetProperty with ILogger<MyController>?

Or some way of using NLog with SetProperty in a fast and thread safe way?

Many thanks in advance!

答:
When you share loggers between threads, then you could use WithProperty to ensure thread safeness.

Please note that WithProperty/SetProperty is only available on the Logger of NLog. (so not ILogger of Microsoft.Extensions.Logging`). See below.

Example:

```<code>using NLog;
public class MyController : Controller
{
    private static readonly Logger BaseLogger = LogManager.GetCurrentClassLogger();

    private readonly Logger Logger; // non static because of traceid.
    public MyConstructor(Apilog apilog)
    {
        Logger = BaseLogger.WithProperty("traceid", apilog.TraceId);
    }
}
</code>```

Is there some way to use SetProperty with ILogger<MyController>?

There is no SetProperty on the ILogger interface of Microsoft.Extensions.Logging, but you could do this:

using (_logger.BeginScope(new[] { new KeyValuePair<string, object>("traceid", apilog.TraceId) }))
{
   _logger.LogDebug("Log message");
}
```

And use in your config: ${mdlc:traceid}. See more details and options here

Title: NLog EventProperties in .NET Core

Body:
I'm using ILogger<MyController> to write logs using DI (see step 6)

I'm also using NLog EventProperties

I want to add traceId to all my logs in my controller automatically.

This is working:

logger.Info("Some log. TraceId:{traceId}", 123);

However, then I need to change all my log commands (a lot of them!), which is a pain.

If I do the following, it's not tread safe:

using NLog;
public class MyController : Controller
{
    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
    public MyConstructor(Apilog apilog)
    {
        Logger.SetProperty("traceid", apilog.TraceId);
    }
}

Is there some way to use SetProperty with ILogger<MyController>?

Or some way of using NLog with SetProperty in a fast and thread safe way?

Many thanks in advance!

Body:
When you share loggers between threads, then you could use WithProperty to ensure thread safeness.

Please note that WithProperty/SetProperty is only available on the Logger of NLog. (so not ILogger of Microsoft.Extensions.Logging`). See below.

Example:

using NLog;
public class MyController : Controller
{
    private static readonly Logger BaseLogger = LogManager.GetCurrentClassLogger();

    private readonly Logger Logger; // non static because of traceid.
    public MyConstructor(Apilog apilog)
    {
        Logger = BaseLogger.WithProperty("traceid", apilog.TraceId);
    }
}

Is there some way to use SetProperty with ILogger<MyController>?

There is no SetProperty on the ILogger interface of Microsoft.Extensions.Logging, but you could do this:

using (_logger.BeginScope(new[] { new KeyValuePair<string, object>("traceid", apilog.TraceId) }))
{
   _logger.LogDebug("Log message");
}

And use in your config: ${mdlc:traceid}. See more details and options here


问:
Find the minimum values for each subarray and return the maximum of these minima
I am trying to find the minimum values for each subarray of size x in array arr, return an integer denoting the maximum of these minima.

Here is what I have so far:

```<code>def segment(x, arr):
    n = len(arr)
    if (n < x):
        return -1
    res = 0
    for i in range(x):
        res += arr[i]
    curr_sum = res
    for i in range(x, n):
        curr_sum += arr[i] - arr[i-x]
        res = max(res, curr_sum)
    return res
</code>```

```<code>segment(2,[8,2,4])
</code>```

```<code>Output = 10
</code>```

```<code>Expected output = 2
</code>```

Can someone help me with what I'm missing? I guess my code is finding the maximum sum instead of maximum value of the minimum subarrays.

It works perfectly when size x = 1.

Thanks.

答:
I'm not exactly sure about the wording of your question. I'm assuming you mean each continuous subarray of length x in arr.

So in the example, arr = [8,2,4] so you have subarrays [8,2] and [2,4]. The min of each subarray is 2, and the max is therefore 2.

def segment(x, arr):
    n = len(arr)
    if (n < x):
        return -1
    segment_mins = []
    for i in range(n-x+1):
        segment_mins.append(min(arr[i:i+x]))
    return max(segment_mins)
```

<p>Edit: You might achieve a speedup by doing it in one line</p>

<pre class="lang-py prettyprint-override"><code>def segment(x, arr):
    n = len(arr)
    if (n < x):
        return -1
    return max(min(arr[i:i+x]) for i in range(n-x+1))
</code>```

Body:
I am trying to find the minimum values for each subarray of size x in array arr, return an integer denoting the maximum of these minima.

Here is what I have so far:

def segment(x, arr):
    n = len(arr)
    if (n < x):
        return -1
    res = 0
    for i in range(x):
        res += arr[i]
    curr_sum = res
    for i in range(x, n):
        curr_sum += arr[i] - arr[i-x]
        res = max(res, curr_sum)
    return res

segment(2,[8,2,4])

Output = 10

Expected output = 2

Can someone help me with what I'm missing? I guess my code is finding the maximum sum instead of maximum value of the minimum subarrays.

It works perfectly when size x = 1.

Thanks.

Body:
I'm not exactly sure about the wording of your question. I'm assuming you mean each continuous subarray of length x in arr.

So in the example, arr = [8,2,4] so you have subarrays [8,2] and [2,4]. The min of each subarray is 2, and the max is therefore 2.

def segment(x, arr):
    n = len(arr)
    if (n < x):
        return -1
    segment_mins = []
    for i in range(n-x+1):
        segment_mins.append(min(arr[i:i+x]))
    return max(segment_mins)

Edit: You might achieve a speedup by doing it in one line

def segment(x, arr):
    n = len(arr)
    if (n < x):
        return -1
    return max(min(arr[i:i+x]) for i in range(n-x+1))


问:
the html crawled is different from the one in browser
I use web harvest to get HTMLs, but I find that the one I've got is slightly different from the one in my browser. A couple of numbers in the html are replaced with a dash (-) in the HTML crawled with web harvest.

All other content of the HTMLs are the same. Even if I replaced the http statement of web harvest with Java code to request the HTML, that still didn't work.

I guarantee the URLs in my browser and in http request in web harvest are identical. How can I make this work?

答:
This problem is very common, often there is a problem with CSS related content. The main reasons are
1. The elements is different from the web source code, which is the most common phenomenon. The code of the elements has been rendered by JS. It's normal that it's different. You can check the elements and source code of Google's homepage, which is obviously different as shown below.ElementsView-Source This should take the web page source code as the standard.
2. Asynchronous problem.
3. If the source code of the web page is different from that of the crawler, it may be due to anti crawling</p>


问:
Entrybox input copied into another entrybox and still be able to edit input independently
Im trying to gather the input from one entrybox and then putting it into another entrybox. I can do this using a Stringvar but i want to
be able to edit the second entry without changing the other.</p>

```<code>from tkinter import *

my_window = Tk()

var_ip = StringVar()
var_mask = StringVar()
var_gateway = StringVar()

def user_input_ip():
    input_ip = entry_ip.get()
    display_ip = input_ip
    var_ip.set(display_ip)

entry_ip = Entry(my_window, font="Helvetica 15", textvariable=var_ip)
entry_ip.place(x=35, y=100, width=158, height=30)
entry_ip.bind("<Tab>", focus_next_widget)
entry_ip.bind("<Return>", enter_key)

def user_input_mask():
    input_mask = entry_mask.get()
    display_mask = input_mask
    var_mask.set(display_mask)

entry_mask = Entry(my_window, font="Helvetica 15", textvariable=var_mask)
entry_mask.place(x=35, y=165, width=158, height=30)
entry_mask.bind("<Tab>", focus_next_widget)
entry_mask.insert(END, "255.255.255.255")

def user_input_gateway():
    input_gateway = entry_gateway.get()
    display_gateway = input_gateway
    var_gateway.set(display_gateway)

entry_gateway = Entry(my_window, font="Helvetica 15", textvariable=var_gateway)
entry_gateway.place(x=35, y=230, width=158, height=30)
entry_gateway.bind("<Tab>", focus_next_widget)

my_window.mainloop()
</code>```

答:
You can bind <KeyRelease> event on the first entry and update second entry in the callback:

```<code>def on_entry_input(event):
    text = event.widget.get()
    # direct update second_entry
    second_entry.delete(0, 'end')
    second_entry.insert('end', text)
    # or via separate variable associated to second entry
    # second_entry_var.set(text)

first_entry = Entry(...)
first_entry.bind('<KeyRelease>', on_entry_input)

second_entry = Entry(...)
</code>```

Body:
Im trying to gather the input from one entrybox and then putting it into another entrybox. I can do this using a Stringvar but i want to
be able to edit the second entry without changing the other.

from tkinter import *

my_window = Tk()

var_ip = StringVar()
var_mask = StringVar()
var_gateway = StringVar()

def user_input_ip():
    input_ip = entry_ip.get()
    display_ip = input_ip
    var_ip.set(display_ip)

entry_ip = Entry(my_window, font="Helvetica 15", textvariable=var_ip)
entry_ip.place(x=35, y=100, width=158, height=30)
entry_ip.bind("<Tab>", focus_next_widget)
entry_ip.bind("<Return>", enter_key)

def user_input_mask():
    input_mask = entry_mask.get()
    display_mask = input_mask
    var_mask.set(display_mask)

entry_mask = Entry(my_window, font="Helvetica 15", textvariable=var_mask)
entry_mask.place(x=35, y=165, width=158, height=30)
entry_mask.bind("<Tab>", focus_next_widget)
entry_mask.insert(END, "255.255.255.255")

def user_input_gateway():
    input_gateway = entry_gateway.get()
    display_gateway = input_gateway
    var_gateway.set(display_gateway)

entry_gateway = Entry(my_window, font="Helvetica 15", textvariable=var_gateway)
entry_gateway.place(x=35, y=230, width=158, height=30)
entry_gateway.bind("<Tab>", focus_next_widget)

my_window.mainloop()

Body:
You can bind <KeyRelease> event on the first entry and update second entry in the callback:

def on_entry_input(event):
    text = event.widget.get()
    # direct update second_entry
    second_entry.delete(0, 'end')
    second_entry.insert('end', text)
    # or via separate variable associated to second entry
    # second_entry_var.set(text)

first_entry = Entry(...)
first_entry.bind('<KeyRelease>', on_entry_input)

second_entry = Entry(...)


问:
Type hints for a function that accepts a (homogeneous) sequence of one of several types
I'm trying to provide type hints for a function that accepts a sequence
with one of two types of elements, and I'm at a loss how to make mypy happy.  Please note, the sequence is homogeneous, meaning the types can't be mixed, either-or.  Usually I do this when they are "compatible" types, e.g. a path str or a pathlib.Path object, and annotating that with Union works just fine.  But in the case of a sequence, Sequence[Union[..]] (or Union[Sequence[..]]) doesn't seem to work.  Here's a minimal working example:

```<code>from pathlib import Path
from typing import Sequence, Dict, Union

def fn_accepts_dict(adict):
    """Function from an external module that accepts `dict`s."""
    for key, val in adict.items():
        print(f"{key}, {val}")

def vararg_test(resources: Sequence[Union[str, Dict]]):
    """My function where I want to provide type hints"""
    if isinstance(resources[0], str):
        resources2 = [{"path": Path(f)} for f in resources]
    else:
        resources2 = resources
    for d in resources2:
        fn_accepts_dict(d)
</code>```

Now, with the above definitions, calling vararg_test with either of
these two work as expected:

```<code>l1 = ["foo/bar", "bar/baz"]
l2 = [{"path": Path("foo/bar")}, {"path": Path("bar/baz")}]
</code>```

But running mypy gives me the following errors:

```<code>type_hints.py:14: error: Argument 1 to "Path" has incompatible type "Union[str, Dict[Any, Any]]"; expected "Union[str, _PathLike[str]]"
type_hints.py:16: error: Incompatible types in assignment (expression has type "Sequence[Union[str, Dict[Any, Any]]]", variable has type "List[Dict[str, Path]]")
Found 2 errors in 1 file (checked 1 source file)
</code>```

How can I resolve this?

Edit:
To give some background, the str is a path, and the dict has metadata corresponding to that path, and the function fn_accepts_dict collates metadata into one metadata object.  So they logical flow is either: str -> dict -> fn_accepts_dict or, dict -> fn_accepts_dict.

While @ShadowRanger's suggestion looked promising, no luck.  I get the same error with the following hints:

```<code>def vararg_test2(resources: Union[Sequence[str], Sequence[Dict]]):
    ... # same implementation as above
</code>```

mypy error:

```<code>type_hints.py:24: error: Argument 1 to "Path" has incompatible type "Union[str, Dict[Any, Any]]"; expected "Union[str, _PathLike[str]]"
type_hints.py:26: error: Incompatible types in assignment (expression has type "Union[Sequence[str], Sequence[Dict[Any, Any]]]", variable has type "List[Dict[str, Path]]")
</code>```

Edit 2:  unfortunately, with all the annotations, it looks more like C/C++ than Python; see my own answer below for a much more Pythonic solution.

答:
I would recommend not trying to do two different things in one function, based on the type of the argument. Define two different functions instead, each taking a specific type of sequence.

```<code>def do_with_strings(resources: Sequence[str]):
    do_with_dicts([{"path": Path(f)} for f in resources])

def do_with_dicts(resources: Sequence[dict]):
    for d in resources:
        fn_accepts_dict(d)
</code>```

For your code as written, the type of resources has to be, as ShadowRanger suggested in the comments, Union[Sequence[str],Sequence[dict]], since you assume that the entire list has the same type as the first element.

If you want to keep the heterogenous type, you need to check each and every element to determine it needs to be turned into a dict:

```<code>def vararg_test(resources: Sequence[Union[str, Dict]]):
    for f in resources:
        if isinstance(f, str):
            f = {"path": Path(f)}
        fn_accepts_dict(f)
</code>```

Body:
I'm trying to provide type hints for a function that accepts a sequence
with one of two types of elements, and I'm at a loss how to make mypy happy.  Please note, the sequence is homogeneous, meaning the types can't be mixed, either-or.  Usually I do this when they are "compatible" types, e.g. a path str or a pathlib.Path object, and annotating that with Union works just fine.  But in the case of a sequence, Sequence[Union[..]] (or Union[Sequence[..]]) doesn't seem to work.  Here's a minimal working example:

from pathlib import Path
from typing import Sequence, Dict, Union

def fn_accepts_dict(adict):
    """Function from an external module that accepts `dict`s."""
    for key, val in adict.items():
        print(f"{key}, {val}")

def vararg_test(resources: Sequence[Union[str, Dict]]):
    """My function where I want to provide type hints"""
    if isinstance(resources[0], str):
        resources2 = [{"path": Path(f)} for f in resources]
    else:
        resources2 = resources
    for d in resources2:
        fn_accepts_dict(d)

Now, with the above definitions, calling vararg_test with either of
these two work as expected:

l1 = ["foo/bar", "bar/baz"]
l2 = [{"path": Path("foo/bar")}, {"path": Path("bar/baz")}]

But running mypy gives me the following errors:

type_hints.py:14: error: Argument 1 to "Path" has incompatible type "Union[str, Dict[Any, Any]]"; expected "Union[str, _PathLike[str]]"
type_hints.py:16: error: Incompatible types in assignment (expression has type "Sequence[Union[str, Dict[Any, Any]]]", variable has type "List[Dict[str, Path]]")
Found 2 errors in 1 file (checked 1 source file)

How can I resolve this?

Edit:
To give some background, the str is a path, and the dict has metadata corresponding to that path, and the function fn_accepts_dict collates metadata into one metadata object.  So they logical flow is either: str -> dict -> fn_accepts_dict or, dict -> fn_accepts_dict.

While @ShadowRanger's suggestion looked promising, no luck.  I get the same error with the following hints:

def vararg_test2(resources: Union[Sequence[str], Sequence[Dict]]):
    ... # same implementation as above

mypy error:

type_hints.py:24: error: Argument 1 to "Path" has incompatible type "Union[str, Dict[Any, Any]]"; expected "Union[str, _PathLike[str]]"
type_hints.py:26: error: Incompatible types in assignment (expression has type "Union[Sequence[str], Sequence[Dict[Any, Any]]]", variable has type "List[Dict[str, Path]]")

Edit 2:  unfortunately, with all the annotations, it looks more like C/C++ than Python; see my own answer below for a much more Pythonic solution.

Body:
I would recommend not trying to do two different things in one function, based on the type of the argument. Define two different functions instead, each taking a specific type of sequence.

def do_with_strings(resources: Sequence[str]):
    do_with_dicts([{"path": Path(f)} for f in resources])

def do_with_dicts(resources: Sequence[dict]):
    for d in resources:
        fn_accepts_dict(d)

For your code as written, the type of resources has to be, as ShadowRanger suggested in the comments, Union[Sequence[str],Sequence[dict]], since you assume that the entire list has the same type as the first element.

If you want to keep the heterogenous type, you need to check each and every element to determine it needs to be turned into a dict:

def vararg_test(resources: Sequence[Union[str, Dict]]):
    for f in resources:
        if isinstance(f, str):
            f = {"path": Path(f)}
        fn_accepts_dict(f)


问:
Route.get() requires callback functions but got a "object Undefined"
I am learning making Todo app.
On the website, I am studying is https://coderwall.com/p/4gzjqw/build-a-javascript-todo-app-with-express-jade-and-mongodb

I typed as instruction describes,

app.js

var main = require('./routes/main');
var todo = require('./routes/todo');
var todoRouter = express.Router();
app.use('/todos', todoRouter);
app.get('/', main.index);
todoRouter.get('/',todo.all);
todoRouter.post('/create', todo.create);
todoRouter.post('/destroy/:id', todo.destroy);
todoRouter.post('/edit/:id', todo.edit);
```
<p><strong>/routes/todo.js</strong></p>
<pre class="lang-js prettyprint-override"><code>module.exports ={
  all: function(req, res){
    res.send('All todos');
  },
  viewOne: function(req, res){
    console.log('Viewing '+req.params.id);
  },
  create: function(req, res){
    console.log('Todo created');
  },
  destroy: function(req, res){
    console.log('Todo deleted');
  },
  edit: function(req, res){
    console.log('Todo '+req.params.id+' updated');
  }
};
</code>```

and I got this error message

Error: Route.get() requires callback functions but got a [object
Undefined]

Did I miss something here?

答:
I got the same error.
After debugging, I found that I misspelled the method name that I imported from the controller into the route file.
Please check the method name.</p>

Body:
I am learning making Todo app.
On the website, I am studying is https://coderwall.com/p/4gzjqw/build-a-javascript-todo-app-with-express-jade-and-mongodb

I typed as instruction describes,

app.js

var main = require('./routes/main');
var todo = require('./routes/todo');
var todoRouter = express.Router();
app.use('/todos', todoRouter);
app.get('/', main.index);
todoRouter.get('/',todo.all);
todoRouter.post('/create', todo.create);
todoRouter.post('/destroy/:id', todo.destroy);
todoRouter.post('/edit/:id', todo.edit);

/routes/todo.js

module.exports ={
  all: function(req, res){
    res.send('All todos');
  },
  viewOne: function(req, res){
    console.log('Viewing '+req.params.id);
  },
  create: function(req, res){
    console.log('Todo created');
  },
  destroy: function(req, res){
    console.log('Todo deleted');
  },
  edit: function(req, res){
    console.log('Todo '+req.params.id+' updated');
  }
};

and I got this error message

Error: Route.get() requires callback functions but got a [object
Undefined]

Did I miss something here?


问:
MongoDB: update dictionary in document
I have a MongoDB document that saves occurrences of some things in a dictionary:

```<code>{
  "id" : 1,
  "occurrences" : {
    "1" : 1,
    "2" : 5,
    "17" : 1,
    "35" : 4
  }
}
</code>```

I now want to add or update some entries, for example add a "12:3" to the occurrences, or update the number of occurrences of "17" to 2, so let's say as an example I want to add {"12":3} and {"17":2} to this dictionary.
It is driving me crazy because I simply can not get it to work. I could use arrays and all that, but I would really like to have it in this particular design. Any ideas on how to solve this? I tried so many different things with $set and $each and so on.

答:
I wrote a function to convert a dictionary to a new dictionary which only updates fields in that dictionary:

```<code>def convert_2_dict_mongodb(obj):
    result = {}
    for key, val in obj.items():
        if not isinstance(val, dict):
            result[key] = val
            continue

        for sub_key, sub_val in val.items():
            new_key = '{}.{}'.format(key, sub_key)
            result[new_key] = sub_val
            if not isinstance(sub_val, dict):
                continue

            result.update(convert_2_dict_mongodb(result))
            if new_key in result:
                del result[new_key]

    return result
</code>```

Example:

```<code>abc = {
    'a': 1,
    'b': {
        'x': 1,
        'y': 2,
        'z': {
            'g': 1,
            'h': {
                'e': [1, 2, 3]
            }
        }
    },
    'h': {
        'a': [1, 2, 3]
    }
}
</code>```

To:

```<code>{'h.a': [1, 2, 3], 'b.x': 1, 'b.z.h.e': [1, 2, 3], 'b.z.g': 1, 'a': 1, 'b.y': 2}
</code>```

Title: MongoDB: update dictionary in document

Body:
I have a MongoDB document that saves occurrences of some things in a dictionary:

{
  "id" : 1,
  "occurrences" : {
    "1" : 1,
    "2" : 5,
    "17" : 1,
    "35" : 4
  }
}

I now want to add or update some entries, for example add a "12:3" to the occurrences, or update the number of occurrences of "17" to 2, so let's say as an example I want to add {"12":3} and {"17":2} to this dictionary.
It is driving me crazy because I simply can not get it to work. I could use arrays and all that, but I would really like to have it in this particular design. Any ideas on how to solve this? I tried so many different things with $set and $each and so on.

Body:
I wrote a function to convert a dictionary to a new dictionary which only updates fields in that dictionary:

def convert_2_dict_mongodb(obj):
    result = {}
    for key, val in obj.items():
        if not isinstance(val, dict):
            result[key] = val
            continue

        for sub_key, sub_val in val.items():
            new_key = '{}.{}'.format(key, sub_key)
            result[new_key] = sub_val
            if not isinstance(sub_val, dict):
                continue

            result.update(convert_2_dict_mongodb(result))
            if new_key in result:
                del result[new_key]

    return result

Example:

abc = {
    'a': 1,
    'b': {
        'x': 1,
        'y': 2,
        'z': {
            'g': 1,
            'h': {
                'e': [1, 2, 3]
            }
        }
    },
    'h': {
        'a': [1, 2, 3]
    }
}

To:

{'h.a': [1, 2, 3], 'b.x': 1, 'b.z.h.e': [1, 2, 3], 'b.z.g': 1, 'a': 1, 'b.y': 2}


问:
Does Rails has a way to validate if the foreign key value exists in an optional relationship?
I am using Rails version 5.1.3.

Does Rails have a way to validate if the foreign key value exists in an optional relationship?

I have the next model:

class Post < ApplicationRecord

  belongs_to :category, optional: true
  validates :category, presence: true, allow_nil: true

end
```

<p>This is the migration:</p>

<pre class="lang-ruby prettyprint-override"><code>class CreatePosts < ActiveRecord::Migration[5.1]
  def change
    create_table :posts do |t|
      t.string :name, limit: 100
      t.references :category, foreign_key: true, null: true

      t.timestamps
    end
  end
end
</code>```

These are the cases:

# Case 1
p1 = Post.new({})
p1.save #Working as I expected ... record Inserted

# Case 2
p2 = Post.new({category_id: 3})  # A category with id 3 exists
p2.save #Working as I expected ... record Inserted

# Case 3
p3 = Post.new({category_id: 30})  # A category with id 30 does not exists.
p3.save # Not working as I expected
```

<p>In the case 3 I was expecting an Active Record validation error something like This Category does not exists but instead of I get
  an SQL message: </p>

<pre class="lang-ruby prettyprint-override"><code>INSERT INTO "posts" ("category_id", "created_at", "updated_at") VALUES (?, ?, ?)  [["category_id", 10], ["created_at", "2017-09-26 00:59:47.645185"], ["updated_at", "2017-09-26 00:59:47.645185"]]

ActiveRecord::InvalidForeignKey: SQLite3::ConstraintException: FOREIGN KEY constraint failed: INSERT INTO "posts" ("category_id", "created_at", "updated_at") VALUES (?, ?, ?)
</code>```

答:
This could help:

validates :category,
  presence: true,
  if: -> { category_id.present? }
```

Body:
I am using Rails version 5.1.3.

Does Rails have a way to validate if the foreign key value exists in an optional relationship?

I have the next model:

class Post < ApplicationRecord

  belongs_to :category, optional: true
  validates :category, presence: true, allow_nil: true

end

This is the migration:

class CreatePosts < ActiveRecord::Migration[5.1]
  def change
    create_table :posts do |t|
      t.string :name, limit: 100
      t.references :category, foreign_key: true, null: true

      t.timestamps
    end
  end
end

These are the cases:

# Case 1
p1 = Post.new({})
p1.save #Working as I expected ... record Inserted

# Case 2
p2 = Post.new({category_id: 3})  # A category with id 3 exists
p2.save #Working as I expected ... record Inserted

# Case 3
p3 = Post.new({category_id: 30})  # A category with id 30 does not exists.
p3.save # Not working as I expected

In the case 3 I was expecting an Active Record validation error something like This Category does not exists but instead of I get
  an SQL message:

INSERT INTO "posts" ("category_id", "created_at", "updated_at") VALUES (?, ?, ?)  [["category_id", 10], ["created_at", "2017-09-26 00:59:47.645185"], ["updated_at", "2017-09-26 00:59:47.645185"]]

ActiveRecord::InvalidForeignKey: SQLite3::ConstraintException: FOREIGN KEY constraint failed: INSERT INTO "posts" ("category_id", "created_at", "updated_at") VALUES (?, ?, ?)


问:
PHP uploader and htaccess password problems
I've got a rather baffling question/problem, let me lay it out for you.

I have two directories -- gallery and uploader

The uploader directory is htaccess password protected. This is where several PHP pages and the PHP file uploader reside. I enter my credentials when I access the index PHP file when I load a the index within the directory.

The problem is that the uploader is uploading the files and then moving it to the gallery directory (not password protected). It then runs other scripts to copy that image, resize it, then delete the original. This process works beautifully until I put the htaccess password on the uploader directory.  So for some reason the PHP uploader in a protected directory can't move/work on the uploaded image and then copy it to the un-protected directory.

Any ideas of what I need to do? I'm not sure if the issue is the PHP uploader calling other scripts in the protected directory or if it's having troubles when moving it to the un-protected directory.

EDIT:
Here is some sample code and as you can see URLs aren't being used (nor are they in the resizeMyImageTN method).

```<code>//WHERE THE SAVE HAPPENS!

move_uploaded_file($_FILES['Filedata']['tmp_name'], '../../uploads/'.$folder.'/'.$new_index.'-' . $_FILES['Filedata']['name']);

//Call function to resize images pass in path

resizeMyImageTN($_FILES['Filedata']['name'],$folder, $new_index);

unlink('../../uploads/'.$folder.'/'.$new_index.'-' . $_FILES['Filedata']['name']);
</code>```

答:
.htaccess protection works at the webserver level. But, UNLESS you're using URLs in your various file-manipulation calls, the PHP script works at the filesystem level and would never see the .htaccess protection.

```<code>move_uploaded_file($_FILES['uploaded']['tmp_name'], '/some/dir/that/is/protected/newname.txt');
</code>```

would not involve the HTTP layer, which means no protection. But if you were try

```<code>move_uploaded_file($_FILES['uploaded']['tmp_name'], 'http://myserver.com/newname.txt');
</code>```

that would involve a new HTTP request, re-upload the file, and be subject to any URl restrictions in place on the server.

Without seeing some code, we most likely can't answer your question.

Body:
I've got a rather baffling question/problem, let me lay it out for you.

I have two directories -- gallery and uploader

The uploader directory is htaccess password protected. This is where several PHP pages and the PHP file uploader reside. I enter my credentials when I access the index PHP file when I load a the index within the directory.

The problem is that the uploader is uploading the files and then moving it to the gallery directory (not password protected). It then runs other scripts to copy that image, resize it, then delete the original. This process works beautifully until I put the htaccess password on the uploader directory.  So for some reason the PHP uploader in a protected directory can't move/work on the uploaded image and then copy it to the un-protected directory.

Any ideas of what I need to do? I'm not sure if the issue is the PHP uploader calling other scripts in the protected directory or if it's having troubles when moving it to the un-protected directory.

EDIT:
Here is some sample code and as you can see URLs aren't being used (nor are they in the resizeMyImageTN method).

//WHERE THE SAVE HAPPENS!

move_uploaded_file($_FILES['Filedata']['tmp_name'], '../../uploads/'.$folder.'/'.$new_index.'-' . $_FILES['Filedata']['name']);

//Call function to resize images pass in path

resizeMyImageTN($_FILES['Filedata']['name'],$folder, $new_index);

unlink('../../uploads/'.$folder.'/'.$new_index.'-' . $_FILES['Filedata']['name']);

Body:
.htaccess protection works at the webserver level. But, UNLESS you're using URLs in your various file-manipulation calls, the PHP script works at the filesystem level and would never see the .htaccess protection.

move_uploaded_file($_FILES['uploaded']['tmp_name'], '/some/dir/that/is/protected/newname.txt');

would not involve the HTTP layer, which means no protection. But if you were try

move_uploaded_file($_FILES['uploaded']['tmp_name'], 'http://myserver.com/newname.txt');

that would involve a new HTTP request, re-upload the file, and be subject to any URl restrictions in place on the server.

Without seeing some code, we most likely can't answer your question.


问:
relationship semaphores, mutexes, monitors, test-and-set and message passing
I'm learning for an exam but the slides given by the professor aren't very helpful, and any searches I do give only muddy results. From what I could gather:

Semaphore: counter with down() and up() operations that busy waits when calling down(counter) when counter = 0 until counter > 0 again

Mutex: binary semaphore that can only be released by its owning process/thread

Test-and-set: CPU instruction for retrieving a binary value and setting it to 1 atomically; used to implement mutexes

Monitor: object that forces synchronized access, i.e. only one process/thread can access it at a time; can be implemented using
  mutexes

Message passing: processes send messages over some shared memory location to tell each other when the other can continue their work; this is effectively a semaphore that acts not only as a counter, but can also be used to exchange other data, i.e. some produce in the producer-consumer problem

I have the following questions:

Are these definitions correct?

Is there a way to implement monitors without mutexes?

Is there a way to implement mutexes without test-and-set, specifically without busy-waiting?

Are there uses for test-and-set other than to implement mutexes?

答:
No.   You may or may not be able to implement them with busy waits, but that is by no means part of the definition.  The definition is Procure will return when the semaphore is available; Liberate will make the semaphore available. How they do that is up to them.  There is no other definition.

Yes.  Roughly speaking you can use any of { message passing, mutexes, semaphores } to implement { message passing, mutees, semaphores }.  By transitivity, anything you can implement with any of these, you can implement with any other of these.  But remember, you can kick a ball down a beach.   A ball is an object like a whale; thus you can kick a whale down a beach.  It might be a bit harder.

Yes.  Ask your favourite search-and-creep service about dekker and his fabulous algorithm.

Yes.  You might implement a multi-cpu state machine using test+set and test+clr, for example. Turing machines are fantastically flexible; simple abstractions like mutexes are meant to constrain that flexibility into something comprehensible.