问:
How to add an observable property when other properties change
I have the following model object that I use to populate a List with a Toggle for each row, which is bound to measurement.isSelected

```<code>final class Model: ObservableObject {

    struct Measurement: Identifiable {
        var id = UUID()
        let name: String
        var isSelected: Binding<Bool>

        var selected: Bool = false

        init(name: String) {
            self.name = name

            let selected = CurrentValueSubject<Bool, Never>(false)
            self.isSelected = Binding<Bool>(get: { selected.value }, set: { selected.value = $0 })
        }
    }

    @Published var measurements: [Measurement]
    @Published var hasSelection: Bool = false  // How to set this?

    init(measurements: [Measurement]) {
        self.measurements = measurements
    }
}
</code>```

I'd like the hasSelection property to be true whenever any measurement.isSelected is true. I'm guessing somehow Model needs to observe changes in measurements and then update its hasSelection property… but I've no idea where to start!

The idea is that hasSelection will be bound to a Button to enable or disable it.

Model is used as follows…

```<code>struct MeasurementsView: View {

    @ObservedObject var model: Model

    var body: some View {
        NavigationView {
            List(model.measurements) { measurement in
                MeasurementView(measurement: measurement)
            }
            .navigationBarTitle("Select Measurements")
            .navigationBarItems(trailing: NavigationLink(destination: NextView(), isActive: $model.hasSelection, label: {
                Text("Next")
            }))
        }
    }
}

struct MeasurementView: View {
    let measurement: Model.Measurement
    var body: some View {
        HStack {
            Text(measurement.name)
                .font(.subheadline)
            Spacer()
            Toggle(measurement.name, isOn: measurement.isSelected)
                .labelsHidden()
        }
    }
}
</code>```

For info, here's a screenshot of what I'm trying to achieve. A list of selectable items, with a navigation link that is enabled when one or more is selected, and disabled when no items are selected.

答:
@user3441734 hasSelection should ideally be a get only property, that
  is true if any of measurement.isSelected is true

```<code>struct Data {
    var bool: Bool
}
class Model: ObservableObject {
    @Published var arr: [Data] = []
    var anyTrue: Bool {
        arr.map{$0.bool}.contains(true)
    }
}
</code>```

example (as before) copy - paste - run

```<code>import SwiftUI

struct Data: Identifiable {
    let id = UUID()
    var name: String
    var on_off: Bool
}

class Model: ObservableObject {
    @Published var data = [Data(name: "alfa", on_off: false), Data(name: "beta", on_off: false), Data(name: "gama", on_off: false)]
    var bool: Bool {
        data.map {$0.on_off} .contains(true)
    }
}

struct ContentView: View {
    @ObservedObject var model = Model()
    var body: some View {
        VStack {
        List(0 ..< model.data.count) { idx in
            HStack {
                Text(verbatim: self.model.data[idx].name)
                Toggle(isOn: self.$model.data[idx].on_off) {
                    EmptyView()
                }
            }
        }
            Text("\(model.bool.description)").font(.largeTitle).padding()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

When the model.data is updated

```<code>@Published var data ....
</code>```

its publisher calls objectWillChange on ObservableObject.

Next SwiftUI recognize that ObservedObject needs the View to be "updated". The View is recreated, and that will force the model.bool.description will have fresh value.

LAST UPDATE

change this part of code

```<code>struct ContentView: View {
    @ObservedObject var model = Model()
    var body: some View {
        NavigationView {
        List(0 ..< model.data.count) { idx in
            HStack {
                Text(verbatim: self.model.data[idx].name)
                Toggle(isOn: self.$model.data[idx].on_off) {
                    EmptyView()
                }
            }
            }.navigationBarTitle("List")
            .navigationBarItems(trailing:

                NavigationLink(destination: Text("next"), label: {
                    Text("Next")
                }).disabled(!model.bool)

            )
        }
    }
}
</code>```

and it is EXACTLY, WHAT YOU HAVE in your updated question

Try it on real device, otherwise the NavigationLink is usable only once (this is well known simulator bug in current Xcode 11.3.1 (11C504)).

Body:
I have the following model object that I use to populate a List with a Toggle for each row, which is bound to measurement.isSelected

final class Model: ObservableObject {

    struct Measurement: Identifiable {
        var id = UUID()
        let name: String
        var isSelected: Binding<Bool>

        var selected: Bool = false

        init(name: String) {
            self.name = name

            let selected = CurrentValueSubject<Bool, Never>(false)
            self.isSelected = Binding<Bool>(get: { selected.value }, set: { selected.value = $0 })
        }
    }

    @Published var measurements: [Measurement]
    @Published var hasSelection: Bool = false  // How to set this?

    init(measurements: [Measurement]) {
        self.measurements = measurements
    }
}

I'd like the hasSelection property to be true whenever any measurement.isSelected is true. I'm guessing somehow Model needs to observe changes in measurements and then update its hasSelection property… but I've no idea where to start!

The idea is that hasSelection will be bound to a Button to enable or disable it.

Model is used as follows…

struct MeasurementsView: View {

    @ObservedObject var model: Model

    var body: some View {
        NavigationView {
            List(model.measurements) { measurement in
                MeasurementView(measurement: measurement)
            }
            .navigationBarTitle("Select Measurements")
            .navigationBarItems(trailing: NavigationLink(destination: NextView(), isActive: $model.hasSelection, label: {
                Text("Next")
            }))
        }
    }
}

struct MeasurementView: View {
    let measurement: Model.Measurement
    var body: some View {
        HStack {
            Text(measurement.name)
                .font(.subheadline)
            Spacer()
            Toggle(measurement.name, isOn: measurement.isSelected)
                .labelsHidden()
        }
    }
}

For info, here's a screenshot of what I'm trying to achieve. A list of selectable items, with a navigation link that is enabled when one or more is selected, and disabled when no items are selected.

Body:
@user3441734 hasSelection should ideally be a get only property, that
  is true if any of measurement.isSelected is true

struct Data {
    var bool: Bool
}
class Model: ObservableObject {
    @Published var arr: [Data] = []
    var anyTrue: Bool {
        arr.map{$0.bool}.contains(true)
    }
}

example (as before) copy - paste - run

import SwiftUI

struct Data: Identifiable {
    let id = UUID()
    var name: String
    var on_off: Bool
}

class Model: ObservableObject {
    @Published var data = [Data(name: "alfa", on_off: false), Data(name: "beta", on_off: false), Data(name: "gama", on_off: false)]
    var bool: Bool {
        data.map {$0.on_off} .contains(true)
    }
}

struct ContentView: View {
    @ObservedObject var model = Model()
    var body: some View {
        VStack {
        List(0 ..< model.data.count) { idx in
            HStack {
                Text(verbatim: self.model.data[idx].name)
                Toggle(isOn: self.$model.data[idx].on_off) {
                    EmptyView()
                }
            }
        }
            Text("\(model.bool.description)").font(.largeTitle).padding()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

When the model.data is updated

@Published var data ....

its publisher calls objectWillChange on ObservableObject.

Next SwiftUI recognize that ObservedObject needs the View to be "updated". The View is recreated, and that will force the model.bool.description will have fresh value.

LAST UPDATE

change this part of code

struct ContentView: View {
    @ObservedObject var model = Model()
    var body: some View {
        NavigationView {
        List(0 ..< model.data.count) { idx in
            HStack {
                Text(verbatim: self.model.data[idx].name)
                Toggle(isOn: self.$model.data[idx].on_off) {
                    EmptyView()
                }
            }
            }.navigationBarTitle("List")
            .navigationBarItems(trailing:

                NavigationLink(destination: Text("next"), label: {
                    Text("Next")
                }).disabled(!model.bool)

            )
        }
    }
}

and it is EXACTLY, WHAT YOU HAVE in your updated question

Try it on real device, otherwise the NavigationLink is usable only once (this is well known simulator bug in current Xcode 11.3.1 (11C504)).


来源: stackexchange

问:
Why I'm getting empty string when trying to get a prefab asset path?
```<code> private void ModifyPrefab(GameObject child)
    {
        var mostPrefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(child);

        // Get the Prefab Asset root GameObject and its asset path.
        string assetPath = AssetDatabase.GetAssetPath(mostPrefabInstanceRoot);

        // Load the contents of the Prefab Asset.
        GameObject contentsRoot = PrefabUtility.LoadPrefabContents(assetPath);

        // Modify Prefab contents.
        DestroyImmediate(child);

        // Save contents back to Prefab Asset and unload contents.
        PrefabUtility.SaveAsPrefabAsset(contentsRoot, assetPath);
        PrefabUtility.UnloadPrefabContents(contentsRoot);
    }
</code>```

assetPath is empty ""

When running the first mostPrefabInstanceRoot is : "Room_Large_Windows_Part_03 (UnityEngine.GameObject)"

And in the editor this object is a prefab :

Then when doing on the prefab right click and Select Prefab Asset it's getting to this :

But in the script the string return ""

I can't figure out why it returns empty string ?

Edit this is my completed script now :

```<code>using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

public class ObjectsReplace : MonoBehaviour
{
    public GameObject prefabToInit;

    // Note your method should probably return something
    public void UpdateOrAddShaderPrefabToDoors()
    {
        GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag("Door_Left");
        GameObject[] doorsRight = GameObject.FindGameObjectsWithTag("Door_Right");

        List<GameObject> allDoors = doorsLeft.Union(doorsRight).ToList();

        allDoors.ForEach(gameObject =>
        {
            Transform childTransform = gameObject.transform.Find("DoorShieldFXLocked Variant");
            GameObject child = childTransform?.gameObject;
            Debug.Log($"Child exist: {child != null}, Name of child: {child?.name}");
            if (child != null)
            {
                ModifyPrefab(child);
            }
        });
    }

    private void ModifyPrefab(GameObject child)
    {
        var mostPrefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(child);

        // Get the Prefab Asset root GameObject and its asset path.
        string assetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(mostPrefabInstanceRoot);

        // Load the contents of the Prefab Asset.
        GameObject contentsRoot = PrefabUtility.LoadPrefabContents(assetPath);

        // Modify Prefab contents.
        DestroyImmediate(child);

        // Save contents back to Prefab Asset and unload contents.
        PrefabUtility.SaveAsPrefabAsset(contentsRoot, assetPath);
        PrefabUtility.UnloadPrefabContents(mostPrefabInstanceRoot);
    }
}
</code>```

But still getting exception in editor when trying to destroy the child :

InvalidOperationException: Destroying a GameObject inside a Prefab instance is not allowed.

The idea is to open the child prefab it's belong to destroy the child and then save and close the prefab like doing Overrides > Apply Changes in the editor but from the script.

答:
It looks like mostPrefabInstanceRoot is not an asset, and that makes sense since it's an instance of the prefab. Use PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot instead of AssetDatabase.GetAssetPath.

string assetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(mostPrefabInstanceRoot);
```

Also, in order for your edit to work, you probably want to save mostPrefabInstanceRoot instead of contentRoot, since contentRoot will be unchanged by deleting the child.

ContentLicense: CC BY-SA 4.0

Body:
 private void ModifyPrefab(GameObject child)
    {
        var mostPrefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(child);

        // Get the Prefab Asset root GameObject and its asset path.
        string assetPath = AssetDatabase.GetAssetPath(mostPrefabInstanceRoot);

        // Load the contents of the Prefab Asset.
        GameObject contentsRoot = PrefabUtility.LoadPrefabContents(assetPath);

        // Modify Prefab contents.
        DestroyImmediate(child);

        // Save contents back to Prefab Asset and unload contents.
        PrefabUtility.SaveAsPrefabAsset(contentsRoot, assetPath);
        PrefabUtility.UnloadPrefabContents(contentsRoot);
    }

assetPath is empty ""

When running the first mostPrefabInstanceRoot is : "Room_Large_Windows_Part_03 (UnityEngine.GameObject)"

And in the editor this object is a prefab :

Then when doing on the prefab right click and Select Prefab Asset it's getting to this :

But in the script the string return ""

I can't figure out why it returns empty string ?

Edit this is my completed script now :

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

public class ObjectsReplace : MonoBehaviour
{
    public GameObject prefabToInit;

    // Note your method should probably return something
    public void UpdateOrAddShaderPrefabToDoors()
    {
        GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag("Door_Left");
        GameObject[] doorsRight = GameObject.FindGameObjectsWithTag("Door_Right");

        List<GameObject> allDoors = doorsLeft.Union(doorsRight).ToList();

        allDoors.ForEach(gameObject =>
        {
            Transform childTransform = gameObject.transform.Find("DoorShieldFXLocked Variant");
            GameObject child = childTransform?.gameObject;
            Debug.Log($"Child exist: {child != null}, Name of child: {child?.name}");
            if (child != null)
            {
                ModifyPrefab(child);
            }
        });
    }

    private void ModifyPrefab(GameObject child)
    {
        var mostPrefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(child);

        // Get the Prefab Asset root GameObject and its asset path.
        string assetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(mostPrefabInstanceRoot);

        // Load the contents of the Prefab Asset.
        GameObject contentsRoot = PrefabUtility.LoadPrefabContents(assetPath);

        // Modify Prefab contents.
        DestroyImmediate(child);

        // Save contents back to Prefab Asset and unload contents.
        PrefabUtility.SaveAsPrefabAsset(contentsRoot, assetPath);
        PrefabUtility.UnloadPrefabContents(mostPrefabInstanceRoot);
    }
}

But still getting exception in editor when trying to destroy the child :

InvalidOperationException: Destroying a GameObject inside a Prefab instance is not allowed.

The idea is to open the child prefab it's belong to destroy the child and then save and close the prefab like doing Overrides > Apply Changes in the editor but from the script.

Body:
It looks like mostPrefabInstanceRoot is not an asset, and that makes sense since it's an instance of the prefab. Use PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot instead of AssetDatabase.GetAssetPath.

string assetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(mostPrefabInstanceRoot);

Also, in order for your edit to work, you probably want to save mostPrefabInstanceRoot instead of contentRoot, since contentRoot will be unchanged by deleting the child.


问:
Can I rely on an unescaped ampersand displaying correctly in a textarea?
I've just notice a routine in our code that doesn't properly escape an ampersand in a textarea:

```<code><textarea>Arts & Crafts</textarea>
</code>```

What surprises me is that this works in every browser I check. Is there an unwritten rule about ampersands inside textareas? If so, is it a rule I can depend on? Or is this just a convenience that browsers provide to make sure your faulty page renders and there are no guarantees whatsoever?

答: It's just a convenience; a standalone & is invalid HTML and XHTML.

ContentLicense: CC BY-SA 3.0

Body:
I've just notice a routine in our code that doesn't properly escape an ampersand in a textarea:

<textarea>Arts & Crafts</textarea>

What surprises me is that this works in every browser I check. Is there an unwritten rule about ampersands inside textareas? If so, is it a rule I can depend on? Or is this just a convenience that browsers provide to make sure your faulty page renders and there are no guarantees whatsoever?


问:
Combine two service calls and return the values
hello I want to combine 2 calls. and return it. but if both fail I should catch it and if any of the 2 calls fail then that´s ok i can just return the one that worked.

this is what I tried.

I have the catch in both calls. how to move it to the promise.all?

```<code>router.get('/services', (req, res) => {

    let arr = [];

    const call1 = service1()
        .then(res => arr.push({ res, type: 'service1'} ))
        .catch(error => res.status(error.status).json(error));

    const call2 = service2()
        .then(res => arr.push({ res, type: 'service2'} ))
        .catch(error => res.status(error.status).json(error));
})

Promise.all([service1, service2]).then(values => {
  // not sure what to do here
});
</code>```

node version: v8.11.1

答:
Calling .catch on the service call will ensure that the callback passed to .then in Promise.all() will always be called, so you need to handle the errors yourself:

```<code>async function callService(fn, type) {
  return service1().then(res => ({ res, type })).catch(err => ({ err }));
}

router.get('/services', (req, res) => {
  const calls = [callService(service1, 'service1'), callService(service2, 'service2')];
  return Promise.all(calls).then(arr => {
    if (arr.every(call => call.err)) {
      // Both elements in arr are errors, handle here
      return;
    }

    // At least 1 was not an error, handle here
  });
</code>```

Body:
hello I want to combine 2 calls. and return it. but if both fail I should catch it and if any of the 2 calls fail then that´s ok i can just return the one that worked.

this is what I tried.

I have the catch in both calls. how to move it to the promise.all?

router.get('/services', (req, res) => {

    let arr = [];

    const call1 = service1()
        .then(res => arr.push({ res, type: 'service1'} ))
        .catch(error => res.status(error.status).json(error));

    const call2 = service2()
        .then(res => arr.push({ res, type: 'service2'} ))
        .catch(error => res.status(error.status).json(error));
})

Promise.all([service1, service2]).then(values => {
  // not sure what to do here
});

node version: v8.11.1

Body:
Calling .catch on the service call will ensure that the callback passed to .then in Promise.all() will always be called, so you need to handle the errors yourself:

async function callService(fn, type) {
  return service1().then(res => ({ res, type })).catch(err => ({ err }));
}

router.get('/services', (req, res) => {
  const calls = [callService(service1, 'service1'), callService(service2, 'service2')];
  return Promise.all(calls).then(arr => {
    if (arr.every(call => call.err)) {
      // Both elements in arr are errors, handle here
      return;
    }

    // At least 1 was not an error, handle here
  });


问:
Find and Replace in entire project in Android Studio
I'm sure this is not a difficult question to answer.
I'm able to replace a specific word or regex expression within a file in Android Studio.

But, I can't seem to know how to do it project wide.

I'm clicking ctrl-R and click on replaceAll button, but it only changes within the current file.

Any idea how to do the same but in the entire project.

答:
Click CTRL+SHIFT+R

This will do a whole project, or folder, or scope replacement.

You can click on any folder on the left window, and do CTRL+SHIFT+R this will confine the replacement to that folder.

You can also do CTRL+SHIFT+F to do a global search without the replacement.

Android Studio is based on IntelliJ and shares all default shortcuts, if you can't find an AndroidStudio answer, its ok to search for Intellij also:

Find and Replace symbol for whole project intellij? https://stackoverflow.com/a/38444457/413127


答:
Promise.all will unfortunately return an error if a Promise fails, so it won't work the way you want it.

Assuming you're using Node.js 8 or above, you can use async/await to make two asynchronous calls and check if one of them returns an error:

router.get(`/services`, (req, res) => {
  // this is just a simple check, but gives you an idea
  const isError = (arg) => {
    return arg instanceof Error
  }

  async function processRequest() {
    const arr = []

    const call1 = await service1().catch(error => error)
    const call2 = await service2().catch(error => error)

    if (!isError(call1)) {
      arr.push({ res: call1, type: `service1` })
    }
    if (!isError(call2)) {
      arr.push({ res: call2, type: `service2` })
    }
    if (isError(cal1) && isError(cal2)) {
      res.status(call1.status).json(call1)
      return
    }
    res.status(200).json(arr)
  }
  processRequest()
})
```

<hr>

<p>Alternatively, if you're using <code>Node</code> <strong>12.10 or above</strong>, you could use <code>Promise.allSettled</code>, which will give you exactly what you need.</p>

<blockquote>
  <p>Promise.allSettled() method returns a promise that resolves after all of the given promises have either resolved or rejected, with an array of objects that each describes the outcome of each promise.</p>
</blockquote>

<p>Applying it in your case, it would look like the following:</p>

<pre class="lang-js prettyprint-override"><code>router.get(`/services`, (req, res) => {
  Promise.allSettled([
    service1(),
    service2()
  ])
  .then(results => {
    const arr = results
      .filter(result => result.status === `fulfilled`)
      .map(result => result.value)

    if (arr.length === 0) {
      const { reason } = results.find(result => result.status === `rejected`)
      res.status(reason.status).json(reason)
      return
    }
    res.status(200).json(arr)
  })
  .catch(error => {
    // handle other errors appropriately
    res.status(500).json(...)
  })
})
</code>```

Title: Combine two service calls and return the values

Body:
Promise.all will unfortunately return an error if a Promise fails, so it won't work the way you want it.

Assuming you're using Node.js 8 or above, you can use async/await to make two asynchronous calls and check if one of them returns an error:

router.get(`/services`, (req, res) => {
  // this is just a simple check, but gives you an idea
  const isError = (arg) => {
    return arg instanceof Error
  }

  async function processRequest() {
    const arr = []

    const call1 = await service1().catch(error => error)
    const call2 = await service2().catch(error => error)

    if (!isError(call1)) {
      arr.push({ res: call1, type: `service1` })
    }
    if (!isError(call2)) {
      arr.push({ res: call2, type: `service2` })
    }
    if (isError(cal1) && isError(cal2)) {
      res.status(call1.status).json(call1)
      return
    }
    res.status(200).json(arr)
  }
  processRequest()
})

Alternatively, if you're using Node 12.10 or above, you could use Promise.allSettled, which will give you exactly what you need.

Promise.allSettled() method returns a promise that resolves after all of the given promises have either resolved or rejected, with an array of objects that each describes the outcome of each promise.

Applying it in your case, it would look like the following:

router.get(`/services`, (req, res) => {
  Promise.allSettled([
    service1(),
    service2()
  ])
  .then(results => {
    const arr = results
      .filter(result => result.status === `fulfilled`)
      .map(result => result.value)

    if (arr.length === 0) {
      const { reason } = results.find(result => result.status === `rejected`)
      res.status(reason.status).json(reason)
      return
    }
    res.status(200).json(arr)
  })
  .catch(error => {
    // handle other errors appropriately
    res.status(500).json(...)
  })
})


问:
Spring TransactionalTemplate does not roll back on exception

Problem Statement

My goal is to:

Read CSV file row --> Convert to DTO object (This step is not related to my question, included for the sake of completeness)

Collect 'n' DTO objects --> Call save()/update() service methods. (Under the same transactional context)

Expected: When one save()/update() call fails --> Rollback the whole batch.

Actual: When one save()/update() call fails --> Spring commits the record for previous call(s).

Implementation

Below is my code implementation. (Omitted helper methods and non-relevant attributes for brevity)

Importer Class:

Groups List(Patient) and calls save()/update() depending upon the operation type.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.github.swapnil.hims.bo.importer.BulkImporter;
import com.github.swapnil.hims.bo.importer.Importer;
import com.github.swapnil.hims.dto.PatientDetail;
import com.github.swapnil.hims.service.PatientService;

@Component
public class PatientImporter extends Importer implements BulkImporter {
    @Autowired
    private PatientService patientSvc;

    private final TransactionTemplate txTmpl;

    public PatientImporter(PlatformTransactionManager transactionManager) {
        this.txTmpl = new TransactionTemplate(transactionManager);
    }

    @Override
    public PatientDetail rowToObject(CSVRecord record) {
        // Convert row to DTO object.
        return patientDetail;
    }

    @Override
    public void saveToDb(List<Object> patients) {
        List<PatientDetail> patientList = patients.stream().map(patient -> (PatientDetail) patient)
                .collect(Collectors.toList());
        saveAll(patientList, this.importType, BATCH_SIZE);
    }

    private void saveAll(List<PatientDetail> patients, Importer.Type action, Integer batchSize) {
        txTmpl.execute(new TransactionCallbackWithoutResult() {
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                createPatients(patients, action, batchSize);
            }
        });
    }

    private void createPatients(List<PatientDetail> patients, Importer.Type action, Integer batchSize) {
        int startAt = 0;
        while (true) {
            List<PatientDetail> patientBatch = patients.stream().skip(startAt).limit(batchSize)
                    .collect(Collectors.toList());

            for (PatientDetail patient : patientBatch) {
                if (action == Importer.Type.CREATE) {
                    patientSvc.save(patient);
                } else {
                    patientSvc.update(patient);
                }
            }

            if (patientBatch.size() != batchSize) {
                break;
            }

            startAt += batchSize;
        }
    }
}
```

<p><strong>PatientService Class:</strong></p>

<blockquote>
  <p>Repository/Service class for Patient.</p>
</blockquote>

<pre class="lang-java prettyprint-override"><code>import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.swapnil.hims.dao.PatientDao;
import com.github.swapnil.hims.dto.PatientDetail;
import com.github.swapnil.hims.entities.Patient;
import com.github.swapnil.hims.exception.PatientException;
import com.github.swapnil.hims.service.PatientService;

@Service
public class PatientServiceImpl implements PatientService {
    private final static Log logger = LogFactory.getLog(PatientServiceImpl.class);

    @Autowired
    private PatientDao patientDao;

    @Override
    @Transactional
    public void save(PatientDetail patientDetail) {
        patientDao.save(getPatient(patientDetail));
    }

    @Override
    @Transactional
    public void update(Long id, PatientDetail patientDetail) {
        patientDao.save(getPatient(id, patientDetail));
    }

    @Override
    public void update(PatientDetail patientDetail) {
        update(patientDetail.getIdentifier(), patientDetail);
    }

    private Patient getPatient(PatientDetail patientDetail) {
        if (StringUtils.isEmpty(patientDetail.getPatientId())) {
            throw new PatientException("Patient ID is required!");
        }

        if (StringUtils.isEmpty(patientDetail.getName())) {
            throw new PatientException("Patient name is required!");
        }

        if (StringUtils.isEmpty(patientDetail.getEmail())) {
            throw new PatientException("Patient e-mail is required!");
        }

        Patient dbPatient = patientDao.findByPatientId(patientDetail.getPatientId());
        if (dbPatient != null) {
            throw new PatientException(String.format("Patient with the same pid '%s' already exists!", dbPatient.getPatientId()));
        }

        return patientDetail.toPatient();
    }

    private Patient getPatient(Long id, PatientDetail patientDetail) {
        Patient patient = patientDao.findById(id);

        if (patient == null) {
            throw new PatientException("Patient with id " + id + " does not exists.");
        }

        patient.setName(StringUtils.isEmpty(patientDetail.getName()) ? patient.getName() : patientDetail.getName());
        patient.setCity(StringUtils.isEmpty(patientDetail.getCity()) ? patient.getCity() : patientDetail.getCity());
        patient.setAddress(StringUtils.isEmpty(patientDetail.getAddress()) ? patient.getAddress() : patientDetail.getAddress());
        patient.setEmail(StringUtils.isEmpty(patientDetail.getEmail()) ? patient.getEmail() : patientDetail.getEmail());
        patient.setContactNumber(patientDetail.getContactNumber() != null ? patient.getContactNumber() : patientDetail.getContactNumber());
        patient.setPatientId(StringUtils.isEmpty(patientDetail.getPatientId()) ? patient.getPatientId() : patientDetail.getPatientId());

        return patient;
    }
}
</code>```

PatientDao.java

import org.springframework.data.jpa.repository.JpaRepository;

import com.github.swapnil.hims.entities.Patient;

public interface PatientDao extends JpaRepository<Patient, String> {
    public Patient findById(Long id);

    public void deleteById(Long id);

    public Patient findByPatientId(String patientId);
}
```

I tried:

try {createPatients(patients, action, batchSize);} catch() {status.setRollbackOnly()}

Setting PropagationBehaviour to PROPAGATION_REQUIRED.

I cannot understand what I'm missing here, I've invested loads of time in solving this and would really, really appreciate any help. I'm using MySQL v8.0.16.

(GitHub repo URL)

EDIT

While debugging, I found that Patient dbPatient = patientDao.findByPatientId(patientDetail.getPatientId()); call causes the hibernate to flush the session and commit the previous object to DB. I'm not sure how to prevent this though. I tried some things but didn't work, I'll keep looking and update this.

答:
Why you didn't use @Transactional like this :</p>

```<code>@Transactional(rollbackFor = Exception.class)
public yourFunctionThatHasAllOperations() {
    // do your logic here
}
</code>```

Body:
Problem Statement

My goal is to:

Read CSV file row --> Convert to DTO object (This step is not related to my question, included for the sake of completeness)

Collect 'n' DTO objects --> Call save()/update() service methods. (Under the same transactional context)

Expected: When one save()/update() call fails --> Rollback the whole batch.

Actual: When one save()/update() call fails --> Spring commits the record for previous call(s).

Implementation

Below is my code implementation. (Omitted helper methods and non-relevant attributes for brevity)

Importer Class:

Groups List(Patient) and calls save()/update() depending upon the operation type.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.github.swapnil.hims.bo.importer.BulkImporter;
import com.github.swapnil.hims.bo.importer.Importer;
import com.github.swapnil.hims.dto.PatientDetail;
import com.github.swapnil.hims.service.PatientService;

@Component
public class PatientImporter extends Importer implements BulkImporter {
    @Autowired
    private PatientService patientSvc;

    private final TransactionTemplate txTmpl;

    public PatientImporter(PlatformTransactionManager transactionManager) {
        this.txTmpl = new TransactionTemplate(transactionManager);
    }

    @Override
    public PatientDetail rowToObject(CSVRecord record) {
        // Convert row to DTO object.
        return patientDetail;
    }

    @Override
    public void saveToDb(List<Object> patients) {
        List<PatientDetail> patientList = patients.stream().map(patient -> (PatientDetail) patient)
                .collect(Collectors.toList());
        saveAll(patientList, this.importType, BATCH_SIZE);
    }

    private void saveAll(List<PatientDetail> patients, Importer.Type action, Integer batchSize) {
        txTmpl.execute(new TransactionCallbackWithoutResult() {
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                createPatients(patients, action, batchSize);
            }
        });
    }

    private void createPatients(List<PatientDetail> patients, Importer.Type action, Integer batchSize) {
        int startAt = 0;
        while (true) {
            List<PatientDetail> patientBatch = patients.stream().skip(startAt).limit(batchSize)
                    .collect(Collectors.toList());

            for (PatientDetail patient : patientBatch) {
                if (action == Importer.Type.CREATE) {
                    patientSvc.save(patient);
                } else {
                    patientSvc.update(patient);
                }
            }

            if (patientBatch.size() != batchSize) {
                break;
            }

            startAt += batchSize;
        }
    }
}

PatientService Class:

Repository/Service class for Patient.

import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.swapnil.hims.dao.PatientDao;
import com.github.swapnil.hims.dto.PatientDetail;
import com.github.swapnil.hims.entities.Patient;
import com.github.swapnil.hims.exception.PatientException;
import com.github.swapnil.hims.service.PatientService;

@Service
public class PatientServiceImpl implements PatientService {
    private final static Log logger = LogFactory.getLog(PatientServiceImpl.class);

    @Autowired
    private PatientDao patientDao;

    @Override
    @Transactional
    public void save(PatientDetail patientDetail) {
        patientDao.save(getPatient(patientDetail));
    }

    @Override
    @Transactional
    public void update(Long id, PatientDetail patientDetail) {
        patientDao.save(getPatient(id, patientDetail));
    }

    @Override
    public void update(PatientDetail patientDetail) {
        update(patientDetail.getIdentifier(), patientDetail);
    }

    private Patient getPatient(PatientDetail patientDetail) {
        if (StringUtils.isEmpty(patientDetail.getPatientId())) {
            throw new PatientException("Patient ID is required!");
        }

        if (StringUtils.isEmpty(patientDetail.getName())) {
            throw new PatientException("Patient name is required!");
        }

        if (StringUtils.isEmpty(patientDetail.getEmail())) {
            throw new PatientException("Patient e-mail is required!");
        }

        Patient dbPatient = patientDao.findByPatientId(patientDetail.getPatientId());
        if (dbPatient != null) {
            throw new PatientException(String.format("Patient with the same pid '%s' already exists!", dbPatient.getPatientId()));
        }

        return patientDetail.toPatient();
    }

    private Patient getPatient(Long id, PatientDetail patientDetail) {
        Patient patient = patientDao.findById(id);

        if (patient == null) {
            throw new PatientException("Patient with id " + id + " does not exists.");
        }

        patient.setName(StringUtils.isEmpty(patientDetail.getName()) ? patient.getName() : patientDetail.getName());
        patient.setCity(StringUtils.isEmpty(patientDetail.getCity()) ? patient.getCity() : patientDetail.getCity());
        patient.setAddress(StringUtils.isEmpty(patientDetail.getAddress()) ? patient.getAddress() : patientDetail.getAddress());
        patient.setEmail(StringUtils.isEmpty(patientDetail.getEmail()) ? patient.getEmail() : patientDetail.getEmail());
        patient.setContactNumber(patientDetail.getContactNumber() != null ? patient.getContactNumber() : patientDetail.getContactNumber());
        patient.setPatientId(StringUtils.isEmpty(patientDetail.getPatientId()) ? patient.getPatientId() : patientDetail.getPatientId());

        return patient;
    }
}

PatientDao.java

import org.springframework.data.jpa.repository.JpaRepository;

import com.github.swapnil.hims.entities.Patient;

public interface PatientDao extends JpaRepository<Patient, String> {
    public Patient findById(Long id);

    public void deleteById(Long id);

    public Patient findByPatientId(String patientId);
}

I tried:

try {createPatients(patients, action, batchSize);} catch() {status.setRollbackOnly()}

Setting PropagationBehaviour to PROPAGATION_REQUIRED.

I cannot understand what I'm missing here, I've invested loads of time in solving this and would really, really appreciate any help. I'm using MySQL v8.0.16.

(GitHub repo URL)

EDIT

While debugging, I found that Patient dbPatient = patientDao.findByPatientId(patientDetail.getPatientId()); call causes the hibernate to flush the session and commit the previous object to DB. I'm not sure how to prevent this though. I tried some things but didn't work, I'll keep looking and update this.

Body:
Why you didn't use @Transactional like this :

@Transactional(rollbackFor = Exception.class)
public yourFunctionThatHasAllOperations() {
    // do your logic here
}


问:
Is this a safe way to start and stop a thread?
Say I have a class called foo which executes some task in a thread. I want to start and stop this task as I see fit. My code is the following:

```<code>class foo
{

public:
    foo() {};
    ~foo() {};

    void start_thread() {
        thread_active = true;
        the_thread = std::thread(&foo::execute, this);
    }
    void stop_thread() {
        thread_active = false;
        the_thread.join();
    }

private:
    void execute() {
        while (thread_active)
            std::cout << "executing...\n";
    }

    std::thread the_thread;
    bool thread_active;
};
</code>```

where I call it like so:

```<code>int main()
{
    foo bar;
    bar.start_thread();
    Sleep(1000);
    bar.stop_thread();
}
</code>```

Is this a safe way to do so?

答:
No, this is not a safe way.

The reason is that the thread_active member is accessed without synchronization from multiple threads in read and write, you should declare it std::atomic_bool or use some other form of synchronization.

Body:
Say I have a class called foo which executes some task in a thread. I want to start and stop this task as I see fit. My code is the following:

class foo
{

public:
    foo() {};
    ~foo() {};

    void start_thread() {
        thread_active = true;
        the_thread = std::thread(&foo::execute, this);
    }
    void stop_thread() {
        thread_active = false;
        the_thread.join();
    }

private:
    void execute() {
        while (thread_active)
            std::cout << "executing...\n";
    }

    std::thread the_thread;
    bool thread_active;
};

where I call it like so:

int main()
{
    foo bar;
    bar.start_thread();
    Sleep(1000);
    bar.stop_thread();
}

Is this a safe way to do so?


问:
How to get value of column by row filtering?
I have the following data table in R:

```<code>threshold   ranking    size
0.70        11         100
0.65        9          102
0.60        12         150
0.55        10         110
</code>```

I need to get the value of ranking for the row when threshold is equal to 0.60.

```<code>threshold_val <- 0.60
out <- as.numeric(filter(df, round(df["threshold"],2) == round(threshold_val,2))["ranking"])
</code>```

But out is equal to NA instead of 12.

What is wrong in my code?

Thanks.

答:
There are functions that have the same name in different packages.  If those packages are loaded, one of them would mask the other function and the behavior can be totally different.  One option is to specify the packageName:: before the function

```<code>dplyr::filter(df, round(df[["threshold"]],2) ==
       round(threshold_val,2))[["ranking"]]
</code>```

Also, when we subset a column, better to use [[ instead of [ as it can lead to some bugs

Body:
I have the following data table in R:

threshold   ranking    size
0.70        11         100
0.65        9          102
0.60        12         150
0.55        10         110

I need to get the value of ranking for the row when threshold is equal to 0.60.

threshold_val <- 0.60
out <- as.numeric(filter(df, round(df["threshold"],2) == round(threshold_val,2))["ranking"])

But out is equal to NA instead of 12.

What is wrong in my code?

Thanks.

Body:
There are functions that have the same name in different packages.  If those packages are loaded, one of them would mask the other function and the behavior can be totally different.  One option is to specify the packageName:: before the function

dplyr::filter(df, round(df[["threshold"]],2) ==
       round(threshold_val,2))[["ranking"]]

Also, when we subset a column, better to use [[ instead of [ as it can lead to some bugs


问:
Re-run the current function when the function is a variable
I have a function named test which is inside the main func.

```<code>//stuff

func main() {
  var test = func() {
    if (/*some condition from main*/) {
      return test()
    }
  }

  val := test()
}
</code>```

When i run this it says:

undefined: test

and it is referencing the return test() inside the test func.
How can i fix this?

答:
You have to declare the variable before you use it:</p>

```<code>var test func()
test=func() {
   if ... {
     test()
   }
}
</code>```

Body:
I have a function named test which is inside the main func.

//stuff

func main() {
  var test = func() {
    if (/*some condition from main*/) {
      return test()
    }
  }

  val := test()
}

When i run this it says:

undefined: test

and it is referencing the return test() inside the test func.
How can i fix this?

Body:
You have to declare the variable before you use it:

var test func()
test=func() {
   if ... {
     test()
   }
}


问:
VBO won't display (sdl with glew)
I'm just starting out using VBOs (using SDL/glew). I'm trying to start out using the simple example of a cube - actually at the moment just the one face of a cube - but I can't get anything to display

my vertex structure is defined as follows:

```<code>struct Vertex
{
float x, y, z;          //Vertex coords
float tx, ty;           //Texture coords
float nx, ny, nz;       //Normal coords
};
</code>```

The cube is then generated like so:

```<code>        Vertex temp;

        //NOTE: Perspective is from looking at the cube from the outside
   //Just trying to display one face for the moment to simplify
        //Back face ------------------------------------------------------------------------------------------
        temp.x = 0.f; temp.y = 0.f; temp.z = 0.f;       //Bottom Right  - 0
        temp.nx = 0.f; temp.ny = 0.f; temp.nz = 1.f; // This stays the same for the rest of the face
        temp.tx = 1.f; temp.ty = 0.f;
        m_vertices.push_back(temp);

        temp.x = 0.f; temp.y = m_fHeight; temp.z = 0.f;         //Top Right - 1
        temp.tx = 1.f; temp.ty = 1.f;
        m_vertices.push_back(temp);

        temp.x = m_fWidth; temp.y = m_fHeight; temp.z = 0.f;    //Top Left      - 2
        temp.tx = 0.f; temp.ty = 1.f;
        m_vertices.push_back(temp);

        temp.x = m_fWidth; temp.y = 0.f; temp.z = 0.f;  //Bottom Left - 3
        temp.tx = 0.f; temp.ty = 0.f;
        m_vertices.push_back(temp);

        m_indeces.push_back(0); m_indeces.push_back(1); m_indeces.push_back(2);
        m_indeces.push_back(2); m_indeces.push_back(3); m_indeces.push_back(0);

        //Generate the vertex buffer
        glGenBuffers(1, &m_vertexBufferID);
        //Bind the vertex buffer
        glBindBuffer(GL_ARRAY_BUFFER, m_vertexBufferID);
        //Fill the vertex buffer - size is 24*sizeof(Vertex) bcs 6 faces with 4 corners
        glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * 4, NULL, GL_STATIC_DRAW);
        glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(Vertex) * 4, &m_vertices); // Actually upload the data

        //Set up the pointers
        glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), BUFFER_OFFSET(12));
        glNormalPointer(GL_FLOAT, sizeof(Vertex), BUFFER_OFFSET(20));
        glVertexPointer(3, GL_FLOAT, sizeof(Vertex), BUFFER_OFFSET(0));

        //Generate the index buffer
        glGenBuffers(1, &m_indexBufferID);
        //Bind the index buffer
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBufferID);
        //Fill the index buffer- size is 36*sizeof(uint) bcs 6 traingle coords in 1 face * 6 faces
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLubyte) * 6, NULL, GL_STATIC_DRAW);
        glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, sizeof(GLubyte) * 6, &m_indeces); // Actually upload the data
</code>```

which is then sent to render in a seperate function:

```<code>glBindBuffer(GL_ARRAY_BUFFER, vertexID);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexID);

glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);

// Resetup the pointers.
glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), BUFFER_OFFSET(12));
glNormalPointer(GL_FLOAT, sizeof(Vertex), BUFFER_OFFSET(20));
glVertexPointer(3, GL_FLOAT, sizeof(Vertex), BUFFER_OFFSET(0));

//Draw the indexed elements
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));

glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
</code>```

and BUFFER_OFFSET() is a simaple macro defined as:

```<code>// A helper macro to get a position
#define BUFFER_OFFSET(i) ((char *)NULL + (i))
</code>```

But I just can't get anything to display - applying the same texture etc. to a cube in immediate mode shows up fine.

The weird thing is that occasionaly something very strange will get displayed, which is different every time - so maybe it's some sort of initialization error?

答: None of your sizes match the comments, I suspect you're reading off the end of the VBO.</p>

Title: VBO won't display (sdl with glew)

Body:
I'm just starting out using VBOs (using SDL/glew). I'm trying to start out using the simple example of a cube - actually at the moment just the one face of a cube - but I can't get anything to display

my vertex structure is defined as follows:

struct Vertex
{
float x, y, z;          //Vertex coords
float tx, ty;           //Texture coords
float nx, ny, nz;       //Normal coords
};

The cube is then generated like so:

        Vertex temp;

        //NOTE: Perspective is from looking at the cube from the outside
   //Just trying to display one face for the moment to simplify
        //Back face ------------------------------------------------------------------------------------------
        temp.x = 0.f; temp.y = 0.f; temp.z = 0.f;       //Bottom Right  - 0
        temp.nx = 0.f; temp.ny = 0.f; temp.nz = 1.f; // This stays the same for the rest of the face
        temp.tx = 1.f; temp.ty = 0.f;
        m_vertices.push_back(temp);

        temp.x = 0.f; temp.y = m_fHeight; temp.z = 0.f;         //Top Right - 1
        temp.tx = 1.f; temp.ty = 1.f;
        m_vertices.push_back(temp);

        temp.x = m_fWidth; temp.y = m_fHeight; temp.z = 0.f;    //Top Left      - 2
        temp.tx = 0.f; temp.ty = 1.f;
        m_vertices.push_back(temp);

        temp.x = m_fWidth; temp.y = 0.f; temp.z = 0.f;  //Bottom Left - 3
        temp.tx = 0.f; temp.ty = 0.f;
        m_vertices.push_back(temp);

        m_indeces.push_back(0); m_indeces.push_back(1); m_indeces.push_back(2);
        m_indeces.push_back(2); m_indeces.push_back(3); m_indeces.push_back(0);

        //Generate the vertex buffer
        glGenBuffers(1, &m_vertexBufferID);
        //Bind the vertex buffer
        glBindBuffer(GL_ARRAY_BUFFER, m_vertexBufferID);
        //Fill the vertex buffer - size is 24*sizeof(Vertex) bcs 6 faces with 4 corners
        glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * 4, NULL, GL_STATIC_DRAW);
        glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(Vertex) * 4, &m_vertices); // Actually upload the data

        //Set up the pointers
        glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), BUFFER_OFFSET(12));
        glNormalPointer(GL_FLOAT, sizeof(Vertex), BUFFER_OFFSET(20));
        glVertexPointer(3, GL_FLOAT, sizeof(Vertex), BUFFER_OFFSET(0));

        //Generate the index buffer
        glGenBuffers(1, &m_indexBufferID);
        //Bind the index buffer
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBufferID);
        //Fill the index buffer- size is 36*sizeof(uint) bcs 6 traingle coords in 1 face * 6 faces
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLubyte) * 6, NULL, GL_STATIC_DRAW);
        glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, sizeof(GLubyte) * 6, &m_indeces); // Actually upload the data

which is then sent to render in a seperate function:

glBindBuffer(GL_ARRAY_BUFFER, vertexID);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexID);

glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);

// Resetup the pointers.
glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), BUFFER_OFFSET(12));
glNormalPointer(GL_FLOAT, sizeof(Vertex), BUFFER_OFFSET(20));
glVertexPointer(3, GL_FLOAT, sizeof(Vertex), BUFFER_OFFSET(0));

//Draw the indexed elements
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));

glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);

and BUFFER_OFFSET() is a simaple macro defined as:

// A helper macro to get a position
#define BUFFER_OFFSET(i) ((char *)NULL + (i))

But I just can't get anything to display - applying the same texture etc. to a cube in immediate mode shows up fine.

The weird thing is that occasionaly something very strange will get displayed, which is different every time - so maybe it's some sort of initialization error?


问:
Why does fstream causes segmentation fault when opening file with format?
I have the following code

```<code>#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <unistd.h>
using namespace std;

int main()
{
  ifstream asmfile("asmcode",ifstream::in);

  if(!asmfile)
  {
     cout << "error" << endl;
  }

  return 0;
}
</code>```

where "asmcode" is just a text file that exists in the same directory as the main file. It's literally an empty file that's created via bash ">dummy.txt".

I'm running this on Ubuntu Linux 18.04, using g++ 9.2.1 as a compiler.

This prints "error" in my machine. I have no clue why the file is not getting opened. I also noticed if I append the file format after the file name, I get a segmentation fault which is even more weird.

What is wrong here?

答:
You should add the file extension, otherwise the program can not make a difference between 2 files with the same name.

ifstream asmfile("asmcode.txt", ifstream::in);

Body:
I have the following code

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <unistd.h>
using namespace std;

int main()
{
  ifstream asmfile("asmcode",ifstream::in);

  if(!asmfile)
  {
     cout << "error" << endl;
  }

  return 0;
}

where "asmcode" is just a text file that exists in the same directory as the main file. It's literally an empty file that's created via bash ">dummy.txt".

I'm running this on Ubuntu Linux 18.04, using g++ 9.2.1 as a compiler.

This prints "error" in my machine. I have no clue why the file is not getting opened. I also noticed if I append the file format after the file name, I get a segmentation fault which is even more weird.

What is wrong here?


问:
Python equivalent of "library(help = PackageName)" and "?FunctionName" (i.e. help() function) from R
There are many handy functions in R, but the two most handy functions I found were

```<code>library(help = dplyr)
?data.frame
# So the library(help = PackageName) & ?FunctionName
</code>```

Are there similar tools in Python I can make use of?

答:
You may use help().

>>> import pandas
>>> help(pandas)
```

```Help on package pandas:

NAME
    pandas

DESCRIPTION
    pandas - a powerful data analysis and manipulation library for Python
    =====================================================================

    **pandas** is a Python package providing fast, flexible, and expressive data
    structures designed to make working with "relational" or "labeled" data both...
```

<p>Or, if you want to know for a specific function/class as oppose to a module:</p>

<pre class="lang-py prettyprint-override"><code>>>> import pandas
>>> help(pandas.DataFrame)
</code>```

```<code>class DataFrame(pandas.core.generic.NDFrame)
 |  DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
 |
 |  Two-dimensional size-mutable, potentially heterogeneous tabular data
 |  structure with labeled axes (rows and columns). Arithmetic operations
 |  align on both row and column labels. Can be thought of as a dict-like
 |  container for Series objects. The primary pandas data structure.
 |
 |  Parameters
 |  ----------
 |  data : ndarray (structured or homogeneous), Iterable, dict, or DataFrame
 |      Dict can contain Series, arrays, constants, or list-like objects
...
</code>```

>>> import pandas
>>> help(pandas.DataFrame.to_csv)
```

```Help on function to_csv in module pandas.core.generic:

to_csv(self, path_or_buf=None, sep=',', na_rep='', float_format=None, columns=None, header=True, index=True, index_label=None, mode='w', encoding=None, compression='infer', quoting=None, quotechar='"', line_terminator=None, chunksize=None, date_format=None, doublequote=True, escapechar=None, decimal='.')
    Write object to a comma-separated values (csv) file.

    .. versionchanged:: 0.24.0
        The order of arguments for Series was changed.

    Parameters
    ----------
    path_or_buf : str or file handle, default None
        File path or object, if None is provided the result is returned as
        a string.  If a file object is passed it should be opened with
        `newline=''`, disabling universal newlines.
....
```

Body:
There are many handy functions in R, but the two most handy functions I found were

library(help = dplyr)
?data.frame
# So the library(help = PackageName) & ?FunctionName

Are there similar tools in Python I can make use of?

Body:
You may use help().

>>> import pandas
>>> help(pandas)

Help on package pandas:

NAME
    pandas

DESCRIPTION
    pandas - a powerful data analysis and manipulation library for Python
    =====================================================================

    **pandas** is a Python package providing fast, flexible, and expressive data
    structures designed to make working with "relational" or "labeled" data both...

Or, if you want to know for a specific function/class as oppose to a module:

>>> import pandas
>>> help(pandas.DataFrame)

class DataFrame(pandas.core.generic.NDFrame)
 |  DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
 |
 |  Two-dimensional size-mutable, potentially heterogeneous tabular data
 |  structure with labeled axes (rows and columns). Arithmetic operations
 |  align on both row and column labels. Can be thought of as a dict-like
 |  container for Series objects. The primary pandas data structure.
 |
 |  Parameters
 |  ----------
 |  data : ndarray (structured or homogeneous), Iterable, dict, or DataFrame
 |      Dict can contain Series, arrays, constants, or list-like objects
...

>>> import pandas
>>> help(pandas.DataFrame.to_csv)

Help on function to_csv in module pandas.core.generic:

to_csv(self, path_or_buf=None, sep=',', na_rep='', float_format=None, columns=None, header=True, index=True, index_label=None, mode='w', encoding=None, compression='infer', quoting=None, quotechar='"', line_terminator=None, chunksize=None, date_format=None, doublequote=True, escapechar=None, decimal='.')
    Write object to a comma-separated values (csv) file.

    .. versionchanged:: 0.24.0
        The order of arguments for Series was changed.

    Parameters
    ----------
    path_or_buf : str or file handle, default None
        File path or object, if None is provided the result is returned as
        a string.  If a file object is passed it should be opened with
        `newline=''`, disabling universal newlines.
....


问:
My ajax request fails, but did upload my post
Why is my ajax request failing, and yet uploading my post.
how can i prevent the failure.

my ajax request code in:

```<code>createRate(){
    var ourNewPost = {
        'title': $(".new-rate-title").val(),
        'content': $('.new-rate-body').val(),
        'rate': $('.custom-star:checked').val(),
        'productId': $('.submit-rate').data('id')
    }

    $.ajax({
        // adding nonce key to make wordpress know we are looged in and has the permision to do that method.
        beforeSend: (xhr) => {
            xhr.setRequestHeader('X-WP-Nonce', ylsData.nonce);
        },
        url: ylsData.root_url + '/wp-json/yls/v1/rating/',
        type: 'POST',
        data: ourNewPost,
        success: (response) => {

            console.log('congrats');
            console.log(response);
        },
        error: (response) => {
            console.log('failed');
            console.log(response);

        }
    });
}
</code>```

my php custom rest api code:

```<code>add_action('rest_api_init','ylsRateRoute');

function ylsRateRoute(){
    register_rest_route('yls/v1','rating',array(
        'methods' => 'POST',
        'callback'=> 'createLike'
    ));
}
function createLike($data){
    if(is_user_logged_in()){
        $title = sanitize_text_field($data['title']);
        $content = sanitize_text_field($data['content']);
        $rateNum = sanitize_text_field($data['rate']);
        $productId = sanitize_text_field($data['productId']);
        if(get_post_type($productId) == 'product'){
            return wp_insert_post(array(
                'post_type' => 'rate',
                'post_status' => 'publish',
                'post_title' => $title,
                'post_content' => $content,
                'meta_input' => array(
                    'rate_related_product' => $productId,
                    'rating_rate' => $rateNum
                )
              ));
        }else{
            die("Invalid product id");
        }
      }else{
        die("you must be logged in first");
      }
}
</code>```

uploaded image of the failure:

the fail message in the console

If i add dataType:'text', it does success but yet the endpoint returns all this details about the post i want to prevent. i want to remain just with the id that the method wp_insert_post() returns. and it comes in the end of the responseText in the ajax response.

appriciate all help.

答: well after many hours trying to fix this question i figured out the problem was in the post type name which was 'rate' probably its some saved post type from woocommerce or some other thing I use on my wordpress site. yet i changed it from 'rate' to anything else it worked completely fine.</p>

Body:
Why is my ajax request failing, and yet uploading my post.
how can i prevent the failure.

my ajax request code in:

createRate(){
    var ourNewPost = {
        'title': $(".new-rate-title").val(),
        'content': $('.new-rate-body').val(),
        'rate': $('.custom-star:checked').val(),
        'productId': $('.submit-rate').data('id')
    }

    $.ajax({
        // adding nonce key to make wordpress know we are looged in and has the permision to do that method.
        beforeSend: (xhr) => {
            xhr.setRequestHeader('X-WP-Nonce', ylsData.nonce);
        },
        url: ylsData.root_url + '/wp-json/yls/v1/rating/',
        type: 'POST',
        data: ourNewPost,
        success: (response) => {

            console.log('congrats');
            console.log(response);
        },
        error: (response) => {
            console.log('failed');
            console.log(response);

        }
    });
}

my php custom rest api code:

add_action('rest_api_init','ylsRateRoute');

function ylsRateRoute(){
    register_rest_route('yls/v1','rating',array(
        'methods' => 'POST',
        'callback'=> 'createLike'
    ));
}
function createLike($data){
    if(is_user_logged_in()){
        $title = sanitize_text_field($data['title']);
        $content = sanitize_text_field($data['content']);
        $rateNum = sanitize_text_field($data['rate']);
        $productId = sanitize_text_field($data['productId']);
        if(get_post_type($productId) == 'product'){
            return wp_insert_post(array(
                'post_type' => 'rate',
                'post_status' => 'publish',
                'post_title' => $title,
                'post_content' => $content,
                'meta_input' => array(
                    'rate_related_product' => $productId,
                    'rating_rate' => $rateNum
                )
              ));
        }else{
            die("Invalid product id");
        }
      }else{
        die("you must be logged in first");
      }
}

uploaded image of the failure:

the fail message in the console

If i add dataType:'text', it does success but yet the endpoint returns all this details about the post i want to prevent. i want to remain just with the id that the method wp_insert_post() returns. and it comes in the end of the responseText in the ajax response.

appriciate all help.


问:
How to remove empty cells and rows from file using ExcelDataReader?
I'm using ExcelDataReader to read excel file but the file which being processed has 16k columns and 1200 records each. In between only 52 columns are filled other are empty so I want to remove empty columns with rows.

tried with :

```<code>var dataset = reader.AsDataSet(new ExcelDataSetConfiguration() {
    ConfigureDataTable = _ => new ExcelDataTableConfiguration() {
        FilterRow = rowReader => rowReader.Depth != 0
    }
});
</code>```

help will be appreciated thank you

答:
With a little inspiration from ShA.t's answer, I was able to make header rows and columns read exactly where they start in the excel document. You only need to filter the empty columns, as long as you know where the rows start. Here's a sample code:

```<code>public class TrimmedTableSample
{
    #region Properties
    int HeaderRowIndex { get; set; }
    #endregion

    #region Methods
    public void Read(string documentPath)
    {
        using (var stream = File.Open(documentPath, FileMode.Open, FileAccess.Read))
        using (var reader = ExcelReaderFactory.CreateReader(stream))
        {
            var dataSet = reader.AsDataSet(new ExcelDataSetConfiguration()
            {
                UseColumnDataType = true,
                ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                {
                    EmptyColumnNamePrefix = "Column ",
                    UseHeaderRow = true,
                    ReadHeaderRow = (reader) =>
                    {
                        bool empty = true;
                        HeaderRowIndex = 0;

                        while (empty)
                        {
                            for (var i = 0; i < reader.FieldCount && empty; i++)
                                empty = string.IsNullOrWhiteSpace(reader.GetString(i));

                            if (empty)
                            {
                                empty = reader.Read(); // Only continue if more content is available
                                HeaderRowIndex++; // Keep track of the first row position.
                            }
                        }
                    },
                    FilterColumn = (reader, index) =>
                    {
                        bool empty = false;
                        string sheet = reader.Name;

                        // Start reading the table from the beginning
                        reader.Reset();

                        // EDIT: Head over the our current excel sheet
                        while (reader.Name != sheet)
                        if (!reader.NextResult())
                            break;

                        // Head to the first row with content
                        int rowIndex = 0;
                        while (rowIndex < HeaderRowIndex)
                        {
                            reader.Read();
                            rowIndex++;
                        }

                        while (reader.Read())
                        {
                            // Decide if the current column is empty
                            if (reader[index] == null || string.IsNullOrEmpty(reader[index].ToString()))
                                continue;

                            empty = true;
                            break;
                        }

                        // Start over again (This allows the reader to automatically read the rest of the content itself)
                        reader.Reset();

                        // EDIT: Head over the our current excel sheet
                        while (reader.Name != sheet)
                        if (!reader.NextResult())
                            break;

                        reader.Read();

                        // Head over to the first row with content
                        rowIndex = 0;
                        while (rowIndex < HeaderRowIndex)
                        {
                            reader.Read();
                            rowIndex++;
                        }

                        // Return info on whether this column should be ignored or not.
                        return empty;
                    }
                }
            });
        }
    }
    #endregion
}
</code>```

Good Luck!

Body:
I'm using ExcelDataReader to read excel file but the file which being processed has 16k columns and 1200 records each. In between only 52 columns are filled other are empty so I want to remove empty columns with rows.

tried with :

var dataset = reader.AsDataSet(new ExcelDataSetConfiguration() {
    ConfigureDataTable = _ => new ExcelDataTableConfiguration() {
        FilterRow = rowReader => rowReader.Depth != 0
    }
});

help will be appreciated thank you

Body:
With a little inspiration from ShA.t's answer, I was able to make header rows and columns read exactly where they start in the excel document. You only need to filter the empty columns, as long as you know where the rows start. Here's a sample code:

public class TrimmedTableSample
{
    #region Properties
    int HeaderRowIndex { get; set; }
    #endregion

    #region Methods
    public void Read(string documentPath)
    {
        using (var stream = File.Open(documentPath, FileMode.Open, FileAccess.Read))
        using (var reader = ExcelReaderFactory.CreateReader(stream))
        {
            var dataSet = reader.AsDataSet(new ExcelDataSetConfiguration()
            {
                UseColumnDataType = true,
                ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                {
                    EmptyColumnNamePrefix = "Column ",
                    UseHeaderRow = true,
                    ReadHeaderRow = (reader) =>
                    {
                        bool empty = true;
                        HeaderRowIndex = 0;

                        while (empty)
                        {
                            for (var i = 0; i < reader.FieldCount && empty; i++)
                                empty = string.IsNullOrWhiteSpace(reader.GetString(i));

                            if (empty)
                            {
                                empty = reader.Read(); // Only continue if more content is available
                                HeaderRowIndex++; // Keep track of the first row position.
                            }
                        }
                    },
                    FilterColumn = (reader, index) =>
                    {
                        bool empty = false;
                        string sheet = reader.Name;

                        // Start reading the table from the beginning
                        reader.Reset();

                        // EDIT: Head over the our current excel sheet
                        while (reader.Name != sheet)
                        if (!reader.NextResult())
                            break;

                        // Head to the first row with content
                        int rowIndex = 0;
                        while (rowIndex < HeaderRowIndex)
                        {
                            reader.Read();
                            rowIndex++;
                        }

                        while (reader.Read())
                        {
                            // Decide if the current column is empty
                            if (reader[index] == null || string.IsNullOrEmpty(reader[index].ToString()))
                                continue;

                            empty = true;
                            break;
                        }

                        // Start over again (This allows the reader to automatically read the rest of the content itself)
                        reader.Reset();

                        // EDIT: Head over the our current excel sheet
                        while (reader.Name != sheet)
                        if (!reader.NextResult())
                            break;

                        reader.Read();

                        // Head over to the first row with content
                        rowIndex = 0;
                        while (rowIndex < HeaderRowIndex)
                        {
                            reader.Read();
                            rowIndex++;
                        }

                        // Return info on whether this column should be ignored or not.
                        return empty;
                    }
                }
            });
        }
    }
    #endregion
}

Good Luck!


问:
Java: runtime method resolution
I'm working on some dynamic invocation of code via an interpreter, and I'm getting into the sticky ugly areas of method resolution as discussed in JLS section 15.12.

The "easy" way to choose a method is when you know the exact types of all the arguments, at which point you can use Class.getDeclaredMethod(String name, Class[] parameterTypes). Maybe you have to check method accessibility and the class's superclasses/superinterfaces.

But this doesn't cover any of the following cases, so it's kind of useless:

boxing/unboxing primitives

subtypes

varargs

a null argument (which can be any type, unless the interpreter knows otherwise; at compile-time any ambiguity would be eliminating by casting null to a class/interface)

primitive type conversion (not part of Java, but allowable in the context of languages -- e.g. Rhino Javascript where all numbers are floating-point, so the Java code might take an int but the caller passes in a number which is either an int or a double)

(see below for a quick example of the first three)

So now I have to write my own method resolution library...

Is there any well-known framework library to assist in this?

```<code>package com.example.test.reflect;

import java.lang.reflect.Method;

public class MethodResolutionTest {
    public void compute(int i)              { /* implementation... */ }
    public void compute(Long l)             { /* implementation... */ }
    public void compute(Object obj)         { /* implementation... */ }
    public void compute(String... strings)  { /* implementation... */ }

    public static void main(String[] args) {
        Class<?> cl = MethodResolutionTest.class;

        /* these succeed */
        findAndPrintMethod(cl, "compute", int.class);
        findAndPrintMethod(cl, "compute", Long.class);
        findAndPrintMethod(cl, "compute", Object.class);
        findAndPrintMethod(cl, "compute", String[].class);

        /* these fail */
        findAndPrintMethod(cl, "compute", Integer.class);
        findAndPrintMethod(cl, "compute", long.class);
        findAndPrintMethod(cl, "compute", MethodResolutionTest.class);
        findAndPrintMethod(cl, "compute", String.class, String.class);
    }
    private static void findAndPrintMethod(Class<?> objectClass,
            String methodName, Class<?>... parameterTypes)
    {
        try {
            Method method = findMethod(objectClass, methodName,
                   parameterTypes);
            System.out.println(method.toString());
        }
        catch (SecurityException e) {
            e.printStackTrace();
        }
        catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
    private static Method findMethod(Class<?> objectClass,
            String methodName, Class<?>[] parameterTypes)
        throws SecurityException, NoSuchMethodException
    {
        return objectClass.getDeclaredMethod(methodName, parameterTypes);
    }
}
</code>```

答:
Commons beanutils have this function for finding matching methods:
getMatchingAccessibleMethod

It works with primitive types but it is somewhat indeterministic as the docs says.

Title: Java: runtime method resolution

Body:
I'm working on some dynamic invocation of code via an interpreter, and I'm getting into the sticky ugly areas of method resolution as discussed in JLS section 15.12.

The "easy" way to choose a method is when you know the exact types of all the arguments, at which point you can use Class.getDeclaredMethod(String name, Class[] parameterTypes). Maybe you have to check method accessibility and the class's superclasses/superinterfaces.

But this doesn't cover any of the following cases, so it's kind of useless:

boxing/unboxing primitives

subtypes

varargs

a null argument (which can be any type, unless the interpreter knows otherwise; at compile-time any ambiguity would be eliminating by casting null to a class/interface)

primitive type conversion (not part of Java, but allowable in the context of languages -- e.g. Rhino Javascript where all numbers are floating-point, so the Java code might take an int but the caller passes in a number which is either an int or a double)

(see below for a quick example of the first three)

So now I have to write my own method resolution library...

Is there any well-known framework library to assist in this?

package com.example.test.reflect;

import java.lang.reflect.Method;

public class MethodResolutionTest {
    public void compute(int i)              { /* implementation... */ }
    public void compute(Long l)             { /* implementation... */ }
    public void compute(Object obj)         { /* implementation... */ }
    public void compute(String... strings)  { /* implementation... */ }

    public static void main(String[] args) {
        Class<?> cl = MethodResolutionTest.class;

        /* these succeed */
        findAndPrintMethod(cl, "compute", int.class);
        findAndPrintMethod(cl, "compute", Long.class);
        findAndPrintMethod(cl, "compute", Object.class);
        findAndPrintMethod(cl, "compute", String[].class);

        /* these fail */
        findAndPrintMethod(cl, "compute", Integer.class);
        findAndPrintMethod(cl, "compute", long.class);
        findAndPrintMethod(cl, "compute", MethodResolutionTest.class);
        findAndPrintMethod(cl, "compute", String.class, String.class);
    }
    private static void findAndPrintMethod(Class<?> objectClass,
            String methodName, Class<?>... parameterTypes)
    {
        try {
            Method method = findMethod(objectClass, methodName,
                   parameterTypes);
            System.out.println(method.toString());
        }
        catch (SecurityException e) {
            e.printStackTrace();
        }
        catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
    private static Method findMethod(Class<?> objectClass,
            String methodName, Class<?>[] parameterTypes)
        throws SecurityException, NoSuchMethodException
    {
        return objectClass.getDeclaredMethod(methodName, parameterTypes);
    }
}


问:
When and how should I use a ThreadLocal variable?
When should I use a ThreadLocal variable?

How is it used?

答:
Try this small example, to get a feel for ThreadLocal variable:

```<code>public class Book implements Runnable {
    private static final ThreadLocal<List<String>> WORDS = ThreadLocal.withInitial(ArrayList::new);

    private final String bookName; // It is also the thread's name
    private final List<String> words;

    public Book(String bookName, List<String> words) {
        this.bookName = bookName;
        this.words = Collections.unmodifiableList(words);
    }

    public void run() {
        WORDS.get().addAll(words);
        System.out.printf("Result %s: '%s'.%n", bookName, String.join(", ", WORDS.get()));
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new Book("BookA", Arrays.asList("wordA1", "wordA2", "wordA3")));
        Thread t2 = new Thread(new Book("BookB", Arrays.asList("wordB1", "wordB2")));
        t1.start();
        t2.start();
    }
}
</code>```

Console output, if thread BookA is done first:

Result BookA: 'wordA1, wordA2, wordA3'.

Result BookB: 'wordB1, wordB2'.

Console output, if thread BookB is done first:

Result BookB: 'wordB1, wordB2'.

Result BookA: 'wordA1, wordA2, wordA3'.

OwnerDisplayName: Sasha

Body:
Try this small example, to get a feel for ThreadLocal variable:

public class Book implements Runnable {
    private static final ThreadLocal<List<String>> WORDS = ThreadLocal.withInitial(ArrayList::new);

    private final String bookName; // It is also the thread's name
    private final List<String> words;

    public Book(String bookName, List<String> words) {
        this.bookName = bookName;
        this.words = Collections.unmodifiableList(words);
    }

    public void run() {
        WORDS.get().addAll(words);
        System.out.printf("Result %s: '%s'.%n", bookName, String.join(", ", WORDS.get()));
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new Book("BookA", Arrays.asList("wordA1", "wordA2", "wordA3")));
        Thread t2 = new Thread(new Book("BookB", Arrays.asList("wordB1", "wordB2")));
        t1.start();
        t2.start();
    }
}

Console output, if thread BookA is done first:

Result BookA: 'wordA1, wordA2, wordA3'.

Result BookB: 'wordB1, wordB2'.

Console output, if thread BookB is done first:

Result BookB: 'wordB1, wordB2'.

Result BookA: 'wordA1, wordA2, wordA3'.


问:
Is Byte Really The Minimum Addressable Unit?
Section 3.6 of C11 standard defines "byte" as "addressable unit of data storage ... to hold ... character".

Section 1.7 of C++11 standard defines "byte" as "the fundamental storage unit in the C++ memory model ... to contain ... character".

Both definitions does not say that "byte" is the minimum addressable unit. Is this because standards intentionally want to abstract from a specific machine ? Can you provide a real example of machine where C/C++ compiler were decided to have "byte" longer/shorter than the minimum addressable unit ?

答:
Both definitions does not say that "byte" is the minimum addressable unit.

That's because they don't need to. Byte-wise types (char, unsigned char, std::byte, etc) have sufficient restrictions that enforce this requirement.

The size of byte-wise types is explicitly defined to be precisely 1:

sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1.

The alignment of byte-wise types is the smallest alignment possible:

Furthermore, the narrow character types (6.9.1) shall have the weakest alignment requirement

This doesn't have to be an alignment of 1, of course. Except... it does.

See, if the alignment were higher than 1, that would mean that a simple byte array wouldn't work. Array indexing is based on pointer arithmetic, and pointer arithmetic determines the next address based on sizeof(T). But if alignof(T) is greater than sizeof(T), then the second element in any array of T would be misaligned. That's not allowed.

So even though the standard doesn't explicitly say that the alignment of bytewise types is 1, other requirements ensure that it must be.

Overall, this means that every pointer to an object has an alignment at least as restrictive as a byte-wise type. So no object pointer can be misaligned, relative to the alignment of byte-wise types. All valid, non-NULL pointers (pointers to a live object or to a past-the-end pointer) must therefore be at least aligned enough to point to a char.

Similarly, the difference between two pointers is defined in C++ as the difference between the array indices of the elements pointed to by those pointers (pointer arithmetic in C++ requires that the two pointers point into the same array). Additive pointer arithmetic is as previously stated based on the sizeof the type being pointed to.

Given all of these facts, even if an implementation has pointers whose addresses can address values smaller than char, it is functionally impossible for the C++ abstract model to generate a pointer and still have that pointer count as valid (pointing to an object/function, a past-the-end of an array, or be NULL). You could create such a pointer value with a cast from an integer. But you would be creating an invalid pointer value.

So while technically there could be smaller addresses on the machine, you could never actually use them in a valid, well-formed C++ program.

Obviously compiler extensions could do anything. But as far as conforming programs are concerned, it simply isn't possible to generate valid pointers that are misaligned for byte-wise types.


问:
Visual Studio.NET 2008 doesn't give me english exception-messages
In previous versions of VS.NET or the .NET framework, you got english exception messages by default.
If you installed a 'language pack', you received exception messages in the language of that language pack.

Now, I'm working with an English VS.NET 2008 (no language packs have been installed) on a dutch Windows Vista.

When I'm developing, and I write some code that triggers an exception, the exception message that I receive, is in dutch (the language of my OS).
I don't want it to be in dutch; I want it to be in English.  (Reasons are obvious: easier to Google, and those translated error-messages are crap).

In VS.NET, my international settings are set to 'English', in Windows Vista, my regional settings are set to 'Dutch/Belgium'.
How can I get English exception messages, without having to change anything to my regional settings in Windows?

答: It is (most likely) because you have a Dutch NetFX installed.</p>

OwnerDisplayName: Frederik Gheysels

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: moocha

OwnerDisplayName: veggerby


问:
Wrap log4j or create custom logger?
I have an application that needs to log two different types of messages: application log messages and audit messages. Application log messages match the standard lo4j Logger perfectly, but there are several required parameters for the audit log.

I think I need to wrap log4j to add the additional required parameters to the debug(), info(), etc methods, but I hate the idea of wrapping log4j. Should I:

Wrap log4j completely and provide my own Logger class that calls a log4j logger behind the scenese?

Extend the log4j Logger class and add "audit log" methods with my required parameters?

Do something even more elegant so I'm not wrapping a logging library...

答:
I think you can use log4j for your application logs creating logs like:

```<code>private final static Logger log = new Logger(MyClass.class);
</code>```

And for your audit log create a specific category:

```<code>private final static Logger log = new Logger("AuditTrail");
</code>```

Having a different appender you can share accross multiple classes will allow you to configure the output destination and the format as ever you want in the config file.

Hope this helps.

Title: Wrap log4j or create custom logger?

Body:
I think you can use log4j for your application logs creating logs like:

private final static Logger log = new Logger(MyClass.class);

And for your audit log create a specific category:

private final static Logger log = new Logger("AuditTrail");

Having a different appender you can share accross multiple classes will allow you to configure the output destination and the format as ever you want in the config file.

Hope this helps.


问:
In C++ is it possible to return an element of the class from a class member function?
In C++ is it possible to return an element of the class from a class member function?</p>

```<code>namespace translation2d
{
    class translation2d
    {
        public:
           double x;
          double y;

        public:
            translation2d()
            {
                x=0;
                y=0;
            }

        public:
            translation2d translateBy(translation2d other);
            //being interpreted as a constructor?
    }

    translation2d translation2d::translateBy(translation2d other)
    {//I need this member function to return an object of type translation2d
        x+=other.x;
        y+=other.y;
    }
};
</code>```

答:
Sure, with something like</p>

```<code>struct Translation2d {
    double x, y;
    Translation2d(double x, double y) : x(x), y(y) {}
    Translation2d translate_by(const Translation2d& other) {
        return Translation2d(x + other.x, y + other.y);
    }
};
</code>```

Body:
In C++ is it possible to return an element of the class from a class member function?

namespace translation2d
{
    class translation2d
    {
        public:
           double x;
          double y;

        public:
            translation2d()
            {
                x=0;
                y=0;
            }

        public:
            translation2d translateBy(translation2d other);
            //being interpreted as a constructor?
    }

    translation2d translation2d::translateBy(translation2d other)
    {//I need this member function to return an object of type translation2d
        x+=other.x;
        y+=other.y;
    }
};

Body:
Sure, with something like

struct Translation2d {
    double x, y;
    Translation2d(double x, double y) : x(x), y(y) {}
    Translation2d translate_by(const Translation2d& other) {
        return Translation2d(x + other.x, y + other.y);
    }
};


问:
Why do I get ValueError: could not broadcast input array from shape (15163,19) into shape (15163,0)?
This looks like a frequent question here on SO, but nevertheless the answers to other questions did not help me. So I try explain what is happening. I want to regression on the following Pandas dataframe

```<code># Data
y = df[['variation']]
x = df.drop(['variation','value_next','id'], axis=1)
</code>```

Now yis

```<code>Name: variation, dtype: float64
<class 'pandas.core.frame.DataFrame'>
Int64Index: 17690 entries, 0 to 17693
Data columns (total 1 columns):
 #   Column     Non-Null Count  Dtype
---  ------     --------------  -----
 0   variation  17690 non-null  float64
dtypes: float64(1)
memory usage: 276.4 KB
</code>```

and x has 19 columns, each with 17690 entries.

Then I try to do regression:

```<code># Uses pipeline to create a polynomial regression equation
def PolynomialRegression(degree=2, **kwargs):
    return make_pipeline(PolynomialFeatures(degree), LinearRegression(**kwargs))

# Uses grid search to find the best polynomial
param_grid = {'polynomialfeatures__degree': np.arange(21),
              'linearregression__fit_intercept': [True, False],
              'linearregression__normalize': [True, False]}

grid = GridSearchCV(PolynomialRegression(), param_grid, cv=7)
grid.fit(x,y)
</code>```

And on the grid.fit call I get that error.
I have also tried to cast xand yas np data but without luck.

答:
The following code snippet should resolve your error:

```<code>param_grid = {
               'polynomialfeatures__degree': np.arange(1,21)
              ,'linearregression__fit_intercept': [True, False]
              ,'linearregression__normalize': [True, False]
             }
</code>```

though I must admit 21 is a huge overstatement.

Body:
This looks like a frequent question here on SO, but nevertheless the answers to other questions did not help me. So I try explain what is happening. I want to regression on the following Pandas dataframe

# Data
y = df[['variation']]
x = df.drop(['variation','value_next','id'], axis=1)

Now yis

Name: variation, dtype: float64
<class 'pandas.core.frame.DataFrame'>
Int64Index: 17690 entries, 0 to 17693
Data columns (total 1 columns):
 #   Column     Non-Null Count  Dtype
---  ------     --------------  -----
 0   variation  17690 non-null  float64
dtypes: float64(1)
memory usage: 276.4 KB

and x has 19 columns, each with 17690 entries.

Then I try to do regression:

# Uses pipeline to create a polynomial regression equation
def PolynomialRegression(degree=2, **kwargs):
    return make_pipeline(PolynomialFeatures(degree), LinearRegression(**kwargs))

# Uses grid search to find the best polynomial
param_grid = {'polynomialfeatures__degree': np.arange(21),
              'linearregression__fit_intercept': [True, False],
              'linearregression__normalize': [True, False]}

grid = GridSearchCV(PolynomialRegression(), param_grid, cv=7)
grid.fit(x,y)

And on the grid.fit call I get that error.
I have also tried to cast xand yas np data but without luck.

Body:
The following code snippet should resolve your error:

param_grid = {
               'polynomialfeatures__degree': np.arange(1,21)
              ,'linearregression__fit_intercept': [True, False]
              ,'linearregression__normalize': [True, False]
             }

though I must admit 21 is a huge overstatement.


问:
log4j not printing logs in selenium
I try to logging automation log using log4j. logs file created but logs not print in log file

log4j.properties File

```<code>#Root logger option
log4j.rootLogger=debug, file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=/home/rohit/akd_e2e/src/test/resources/Logs/Selenium.log
log4j.appender.file.maxFileSize=5000KB
log4j.appender.file.maxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss} %5p %c{1}:%L - %m%n
#do not append the old file. Create a new log file everytime
log4j.appender.file.Append=false

#Application Logs
log4j.logger.devpinoyLogger=DEBUG, dest1
log4j.appender.dest1=org.apache.log4j.RollingFileAppender
log4j.appender.dest1.maxFileSize=5000KB
log4j.appender.dest1.maxBackupIndex=3
log4j.appender.dest1.layout=org.apache.log4j.PatternLayout
log4j.appender.dest1.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss} %c %m%n
log4j.appender.dest1.File=/home/rohit/akd_e2e/src/test/resources/Logs/Application.log
#do not append the old file. Create a new log file everytime
log4j.appender.dest1.Append=false
</code>```

Set Driver file

```<code>import org.apache.log4j.Logger;

public class Set_Driver {
public static Logger log = Logger.getLogger("devpinoyLogger");
</code>```

pom.xml where I add dependencies of log4j

```<code>    <dependencies>
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

    </dependencies>
</project>
</code>```

答:
So I just faced this Issue. On replacing the selenium dependency from 3.141.59 to 2.53.1 the logs started appearing again.

The selenium version 3 is not compatible with log4j I guess. Still not sure, But It sure did consume a lot of time on figuring this out.

Title: log4j not printing logs in selenium

Body:
I try to logging automation log using log4j. logs file created but logs not print in log file

log4j.properties File

#Root logger option
log4j.rootLogger=debug, file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=/home/rohit/akd_e2e/src/test/resources/Logs/Selenium.log
log4j.appender.file.maxFileSize=5000KB
log4j.appender.file.maxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss} %5p %c{1}:%L - %m%n
#do not append the old file. Create a new log file everytime
log4j.appender.file.Append=false

#Application Logs
log4j.logger.devpinoyLogger=DEBUG, dest1
log4j.appender.dest1=org.apache.log4j.RollingFileAppender
log4j.appender.dest1.maxFileSize=5000KB
log4j.appender.dest1.maxBackupIndex=3
log4j.appender.dest1.layout=org.apache.log4j.PatternLayout
log4j.appender.dest1.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss} %c %m%n
log4j.appender.dest1.File=/home/rohit/akd_e2e/src/test/resources/Logs/Application.log
#do not append the old file. Create a new log file everytime
log4j.appender.dest1.Append=false

Set Driver file

import org.apache.log4j.Logger;

public class Set_Driver {
public static Logger log = Logger.getLogger("devpinoyLogger");

pom.xml where I add dependencies of log4j

    <dependencies>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

    </dependencies>
</project>


问:
Reversing a given array and adding to it to given array using python
Given an array A of N numbers, you have to write a program which prints the sum of the elements of array A with the corresponding elements of the reverse of array A.
If array A has elements [1,2,3], then reverse of the array A will be [3,2,1] and the resultant array should be [4,4,4].

Input Format:

The first line of the input contains a number N representing the number of elements in array A.
The second line of the input contains N numbers separated by a space. (after the last elements, there is no space)

Output Format:

Print the resultant array elements separated by a space. (no space after the last element)

Example:

Input:

```<code>4
2 5 3 1
</code>```

Output:

```<code>3883
</code>```

答:
```<code>N=int(input())
A=list(map(int,input().split()))
s=[]
for i in range(N):
  s.append(A[i]+A[N-i-1])
print (*s,end="")
</code>```

Body:
Given an array A of N numbers, you have to write a program which prints the sum of the elements of array A with the corresponding elements of the reverse of array A.
If array A has elements [1,2,3], then reverse of the array A will be [3,2,1] and the resultant array should be [4,4,4].

Input Format:

The first line of the input contains a number N representing the number of elements in array A.
The second line of the input contains N numbers separated by a space. (after the last elements, there is no space)

Output Format:

Print the resultant array elements separated by a space. (no space after the last element)

Example:

Input:

4
2 5 3 1

Output:

3883