问:
How to fix Sandbox bluesnap unsafe legacy renegotiation disabled error when using node.js 17
Node 17 (all versions) return the following error:

https://sandbox.bluesnap.com/services/2/payment-fields-tokens failed, reason: write EPROTO 00DE371301000000:error:0A000152:SSL routines:final_renegotiate:unsafe legacy renegotiation disabled

I don't have the same issue when using Node 16.

I tried setting

    fetch( // node-fetch
      'https://sandbox.bluesnap.com/services/2/payment-fields-tokens',
      {
        agent: new https.Agent({ // fix attempt
          rejectUnauthorized: false,
        }),
        body, // defined somewhere else
      }
    );
```

I also set NODE_TLS_REJECT_UNAUTHORIZED=0 in my .env file

and NODE_OPTIONS=--openssl-legacy-provider

and the same issue happens

I know this is probably a problem with bluesnap but a workaround would help while they resolve their issues and I can keep using the latest node version

答:
If you're using nvm try running this command from the root directory:</p>
```<code>nvm install --lts
</code>```

Body:
Node 17 (all versions) return the following error:

https://sandbox.bluesnap.com/services/2/payment-fields-tokens failed, reason: write EPROTO 00DE371301000000:error:0A000152:SSL routines:final_renegotiate:unsafe legacy renegotiation disabled

I don't have the same issue when using Node 16.

I tried setting

    fetch( // node-fetch
      'https://sandbox.bluesnap.com/services/2/payment-fields-tokens',
      {
        agent: new https.Agent({ // fix attempt
          rejectUnauthorized: false,
        }),
        body, // defined somewhere else
      }
    );

I also set NODE_TLS_REJECT_UNAUTHORIZED=0 in my .env file

and NODE_OPTIONS=--openssl-legacy-provider

and the same issue happens

I know this is probably a problem with bluesnap but a workaround would help while they resolve their issues and I can keep using the latest node version

Body:
If you're using nvm try running this command from the root directory:

nvm install --lts


来源: stackexchange

问:
How to remove an item from a list of Path?
I have a list of lists, where I do have the path of all my training images, like the below one.

```<code>from pathlib import Path
image_list = [[Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0724_Img_Na__Ma_F_.png'),
  Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_033_S_0724_Img_Na__Ma_F_.png')],

 [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0733_Img_Na__Ma_F_.png'),
  Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_033_S_0733_Img_Na__Ma_F_.png')],

  [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0733_Img_Na__Ma_F_.png'),
  Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_034_S_0733_Img_Na__Ma_F_.png')]
  ]
</code>```

Now, I want to remove one item from the list based on a portion of the path (specifically, based on the last part of the path). Say, I want to remove one element from the list whose name starts with Image_033_S_0733....

I was trying to

```<code>final_list = []
for sub_list in listA:
   for sub_sub_list in sub_list:
       if "Image_033_S_0733" not in sub_sub_list.name:
           final_list.append(sub_sub_list)
</code>```

I am getting a flat list instead of a list of lists. The shape of the image_list is (77, 2). The expected output is (after removing the item from the list of lists) (76, 2) but I am getting (228, ).

Is it possible to remove an item from a list of PosixPath?

答:
Use the .name attribute to get the filename from a Path object.

So replace the condition in your loop or list comprehension with:

```<code>'Image_044_S' not in item.name
</code>```

To get a nested loop over results, use nested list comprehensions.

```<code>final_list = [
    [item for item in sub_list if "Image_033_S_0733" not in item.name]
    for sub_list in image_list]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a list of lists, where I do have the path of all my training images, like the below one.

from pathlib import Path
image_list = [[Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0724_Img_Na__Ma_F_.png'),
  Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_033_S_0724_Img_Na__Ma_F_.png')],

 [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_033_S_0733_Img_Na__Ma_F_.png'),
  Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_033_S_0733_Img_Na__Ma_F_.png')],

  [Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_1/Image_034_S_0733_Img_Na__Ma_F_.png'),
  Path('/home/0_knowle/Desktop/project/data/train/Image/Folder_2/Image_034_S_0733_Img_Na__Ma_F_.png')]
  ]

Now, I want to remove one item from the list based on a portion of the path (specifically, based on the last part of the path). Say, I want to remove one element from the list whose name starts with Image_033_S_0733....

I was trying to

final_list = []
for sub_list in listA:
   for sub_sub_list in sub_list:
       if "Image_033_S_0733" not in sub_sub_list.name:
           final_list.append(sub_sub_list)

I am getting a flat list instead of a list of lists. The shape of the image_list is (77, 2). The expected output is (after removing the item from the list of lists) (76, 2) but I am getting (228, ).

Is it possible to remove an item from a list of PosixPath?

Body:
Use the .name attribute to get the filename from a Path object.

So replace the condition in your loop or list comprehension with:

'Image_044_S' not in item.name

To get a nested loop over results, use nested list comprehensions.

final_list = [
    [item for item in sub_list if "Image_033_S_0733" not in item.name]
    for sub_list in image_list]


问:
Is it possible to check if a function with a string as its name exists?(C++)
I want to be able to do something like this:</p>

```<code>if (Is_Function("helloworld")
    // Run code
</code>```

答:
Not in any normal sense, since C++ doesn't support reflection.  You could compile the program with debug information and have it open itself and read its symbol table like a debugger would, but that's probably more trouble than it's worth.

Anyway, why do you need to detect existence of a function at runtime?  That's known at compile time.

If you can separate out the part that might contain the function into a dynamic library, you could open it at runtime and do a symbol lookup on it.  (On a Linux system you'd use dlopen() and dlsym(); there are equivalents on other platforms but I don't know their names offhand.)  This will tell you whether the name exists as a symbol, though it won't tell you whether it's a function.

ContentLicense: CC BY-SA 3.0

Body:
I want to be able to do something like this:

if (Is_Function("helloworld")
    // Run code


问:
REACT rerender on react-video-thumbnail-image
i i use "react-video-thumbnail-image" the video thumbnail is generated on each render of the component. But it only should render one time and not again.

How can i do that?

答:
You have several options to control re-rendering.

For class components:

shouldComponentUpdate (https://reactjs.org/docs/react-component.html#shouldcomponentupdate)

React.PureComponent (https://reactjs.org/docs/react-api.html#reactpurecomponent)

For functional components:

React.memo() (https://reactjs.org/docs/react-api.html#reactmemo)


问:
Adding newline characters to unix shell variables
I have a variable in a shell script in which I'd like to format the data. The variable stores new data during every iteration of a loop. Each time the new data is stored, I'd like to insert a new line character. Here is how I'm trying to store the data into the variable.

VARIABLE="$VARIABLE '\n' SomeData"

Unfortunately, the output includes the literal '\n' Any help would be appreciative.

答:
Your problem is in the echo command, in ash you have to use the option -e to expand special characters. This should work for you:

```<code>VAR="First line"
VAR="$VAR\nSecond line"
echo -e $VAR
</code>```

This outputs

```<code>First line
Second line
</code>```

Body:
Your problem is in the echo command, in ash you have to use the option -e to expand special characters. This should work for you:

VAR="First line"
VAR="$VAR\nSecond line"
echo -e $VAR

This outputs

First line
Second line


问:
NativeBase showing error while using in Jest testing
I want to test a basic component name TitleHeader which uses HStack and VStack from native base.
The component:-

```<code>import {Center, HStack, VStack} from 'native-base';
import React from 'react';
import {View, Text} from 'react-native';
import appColors from '../../constants/appColors';
//Icon Imports
import Ionicons from 'react-native-vector-icons/Ionicons';

import {TouchableOpacity} from 'react-native-gesture-handler';
import {useNavigation} from '@react-navigation/core';

const TitleHeader = ({
  title = 'Header Title',
  navigationBack = false,
  center = false,
  onBackPress,
  drawer = false,
  style = {},
}) => {
  console.log(title);
  const navigation = useNavigation();

  const handleGoBack = () => {
    if (onBackPress && typeof onBackPress === 'function') {
      onBackPress();
    } else if (drawer) {
      navigation.goBack();
    } else {
      navigation.pop();
    }
  };
  return (
    <HStack
      bg={appColors.primaryBlue}
      style={[
        {
          height: 55,
          position: 'relative',
        },
        style,
      ]}
      alignItems="center"
      px={3}>
      {navigationBack ? (
        <View style={{position: 'absolute', zIndex: 10, left: 10}}>
          <TouchableOpacity
            onPress={handleGoBack}
            style={{
              width: 35,
              height: 35,
              justifyContent: 'center',
              alignItems: 'center',
            }}>
            <Ionicons name="arrow-back" size={26} color="white" />
          </TouchableOpacity>
        </View>
      ) : null}
      <VStack flex={1} alignItems="center" pl={2}>
        <Text
          color="white"
          fontSize="lg"
          numberOfLines={1}
          ellipsizeMode="tail"
          style={
            center
              ? {}
              : {
                  width: '80%',
                }
          }>
          {title}
        </Text>
      </VStack>
    </HStack>
  );
};

export default TitleHeader;

</code>```

Following is my test case which uses jest for testing:-

```<code>import React from 'react';
import {render} from '@testing-library/react-native';
import TitleHeader from '../src/components/AppHeaders/TitleHeader';
import renderer from 'react-test-renderer';
import {NavigationContainer} from '@react-navigation/native';
import {NativeBaseProvider} from 'native-base';

jest.mock('native-base');
const wrapper = ({children}) => (
  <NativeBaseProvider
    initialWindowMetrics={{
      frame: {x: 0, y: 0, width: 0, height: 0},
      insets: {top: 0, left: 0, right: 0, bottom: 0},
    }}>
    {children}
  </NativeBaseProvider>
);
describe('Testing Title Header for screens', () => {
  test('should render title header', () => {
    const tree = renderer
      .create(
        <NavigationContainer>
          <TitleHeader title={'HEADER TEST'} />
        </NavigationContainer>,
        {wrapper},
      )
      .toJSON();
    expect(tree).toMatchSnapshot();
  });
});

</code>```

But I am getting this error inspite of using jest.mock('native-base') in my jest.setup.js.

I am new to testing please help me render this component first and test it using jest. Also, one more thing to add is that if I do not use the wrapper function it throws error telling me that "theme is not defined. Did you forget to wrap your app inside NativeBaseProvider?".

答:
If the component that you trying to test has the theme coming from NativeBase you need to provide the <ThemeProvider/> (Spelling might differ depending on the library, in your case <NativeBaseProvider/>

If you do jest.mock('native-base') and you do not return anything will cause Nothing was returned from render error.

Did you add native-base library to transformIgnorePatterns of jest.config as suggested in this issue?

Body:
I want to test a basic component name TitleHeader which uses HStack and VStack from native base.
The component:-

import {Center, HStack, VStack} from 'native-base';
import React from 'react';
import {View, Text} from 'react-native';
import appColors from '../../constants/appColors';
//Icon Imports
import Ionicons from 'react-native-vector-icons/Ionicons';

import {TouchableOpacity} from 'react-native-gesture-handler';
import {useNavigation} from '@react-navigation/core';

const TitleHeader = ({
  title = 'Header Title',
  navigationBack = false,
  center = false,
  onBackPress,
  drawer = false,
  style = {},
}) => {
  console.log(title);
  const navigation = useNavigation();

  const handleGoBack = () => {
    if (onBackPress && typeof onBackPress === 'function') {
      onBackPress();
    } else if (drawer) {
      navigation.goBack();
    } else {
      navigation.pop();
    }
  };
  return (
    <HStack
      bg={appColors.primaryBlue}
      style={[
        {
          height: 55,
          position: 'relative',
        },
        style,
      ]}
      alignItems="center"
      px={3}>
      {navigationBack ? (
        <View style={{position: 'absolute', zIndex: 10, left: 10}}>
          <TouchableOpacity
            onPress={handleGoBack}
            style={{
              width: 35,
              height: 35,
              justifyContent: 'center',
              alignItems: 'center',
            }}>
            <Ionicons name="arrow-back" size={26} color="white" />
          </TouchableOpacity>
        </View>
      ) : null}
      <VStack flex={1} alignItems="center" pl={2}>
        <Text
          color="white"
          fontSize="lg"
          numberOfLines={1}
          ellipsizeMode="tail"
          style={
            center
              ? {}
              : {
                  width: '80%',
                }
          }>
          {title}
        </Text>
      </VStack>
    </HStack>
  );
};

export default TitleHeader;

Following is my test case which uses jest for testing:-

import React from 'react';
import {render} from '@testing-library/react-native';
import TitleHeader from '../src/components/AppHeaders/TitleHeader';
import renderer from 'react-test-renderer';
import {NavigationContainer} from '@react-navigation/native';
import {NativeBaseProvider} from 'native-base';

jest.mock('native-base');
const wrapper = ({children}) => (
  <NativeBaseProvider
    initialWindowMetrics={{
      frame: {x: 0, y: 0, width: 0, height: 0},
      insets: {top: 0, left: 0, right: 0, bottom: 0},
    }}>
    {children}
  </NativeBaseProvider>
);
describe('Testing Title Header for screens', () => {
  test('should render title header', () => {
    const tree = renderer
      .create(
        <NavigationContainer>
          <TitleHeader title={'HEADER TEST'} />
        </NavigationContainer>,
        {wrapper},
      )
      .toJSON();
    expect(tree).toMatchSnapshot();
  });
});

But I am getting this error inspite of using jest.mock('native-base') in my jest.setup.js.

I am new to testing please help me render this component first and test it using jest. Also, one more thing to add is that if I do not use the wrapper function it throws error telling me that "theme is not defined. Did you forget to wrap your app inside NativeBaseProvider?".


问:
Turtle CLI/Expo iOS build failing: "Please ensure xcode is properly installed"
I am trying to create an iOS build of a React Native app locally using Turtle CLI/Expo. When I run my turtle: build:ios command from my React Native project folder I get the following errors:

turtle[849] ERROR: Please ensure xcode is properly installed
err: Error: xcodebuild exited with non-zero code: 1

turtle[849] ERROR: Failed to build standalone app
err: Error: Tools required to perform standalone app build are missing. Please install them.

Xcode is definitely installed through the App Store, and I also ran xcode-select --install which is telling me it is already installed as well.

Any ideas why Turtle can't seem to detect Xcode?

I am running macOS 12.2 and Xcode 13.2.1.

答:
Well, I figured it out myself:

I think I had somehow switched to using just the command line version of Xcode whereas Turtle was expecting the full version. I ran the following command to specify using the full Xcode.app and the error was resolved:

sudo xcode-select -s /Applications/Xcode.app/Contents/Developer


问:
What is the difference between a Development release and an Application Store release
I'm trying to understand what the differences are between the two release modes.
Obviously the Application Store is for Application Store.
I'm assuming that Development is if you want to publish without using an Application Store.
Does Development mean its still in Debug Mode?

Also is it ok to do a release for Application Store but publish it on a private URL.

Thanks in advance.

答:
As pointed by Brian in his comment your question is mainly about Target Configurations for the Android Target Platform. That being said:

I'm assuming that Development is if you want to publish without using
an Application Store

Your assumption is safe as of Delphi 11 as the Application Store Target Configuration always produces an .aab file specific for Google Play distribution for the Android 64 Target Platform. On older RAD Studio versions (e.g. 10.3.3) a standard .apk file signed with your production Keystore was generated even for Android 64 if you had .aab file generation turned off.

Does Development mean its still in Debug Mode?

No. Debug is a Build Configuration and it is not conditioned by the current Target Configuration, so you could theoretically have an "Application Store Debug" build but it is useless as Google Play rejects those. You can see the differences between Build Configurations here.

is it ok to do a release for Application Store but publish it on a
private URL

Unless your users are technical savvy enough to deal with an .aab file or your Delphi version allows you to turn off .aab file generation I would recommend distributing a Development (.apk) build over your private URL.


问:
MongoDB - Querying inner object that is an array
I am new to MongoDB queries and looking for some guidance on how to retrieve documents that fit the search criteria. In particular, I need to find all the id(s) of the documents where the code is JPID i.e, "code": "JPID". We can assume the name of the collection is systems.

Since this is a nested object I thought of using the $unwid - but I am still stuck on how  to do it. The example is very trivial. Any help and guidance is appreciated.

```<code>{
      "resourceType": "NamingSystem",
      "id": "example-id",
      "name": "Austalian Healthcare Identifier - Individual",
      "status": "active",
      "kind": "identifier",
      "date": "2015-08-31",
      "publisher": "HL7 Australia on behalf of NEHTA",
      "responsible": "HI Service Operator / NEHTA",
      "type": {
        "coding": [
          {
            "system": "http://hl7.org/fhir/v2/0203",
            "code": "JPID";
            "display": "National unique individual identifier"
          }
        ],
        "text": "IHI"
      },
      "description": "Australian HI Identifier as established by relevant regulations etc",
      "uniqueId": [
        {
          "type": "oid",
          "value": "1.2.36.1.2001.1003.0",
          "comment": "This value is used in Australian CDA documents"
        },
        {
          "type": "uri",
          "value": "http://ns.electronichealth.net.au/id/hi/ihi/1.0",
          "preferred": true,
          "period": {
            "start": "2015-08-21"
          }
        }
      ]
    }
</code>```

答:
You can find all documents that contain at least one element in type.coding array by simple match the code element with the value JPID:

```<code>db.system.find({
 "type.coding.code": "JPID"
})
</code>```

It is recommended to create and index on {"type.coding.code":1} so your searches to perform faster on this field.

playground

If you need to find all documents and filter only the array entries having the code:"JPID" you can use $filter as follow:

```<code>db.system.aggregate([
{
 $match: {
   "type.coding.code": "JPID"
 }
},
{
 $addFields: {
   "type.coding": {
     "$filter": {
      "input": "$type.coding",
      "as": "tc",
      "cond": {
        $eq: [
          "$$tc.code",
          "JPID"
          ]
       }
     }
   }
 }
}
])
</code>```

playground(filter)

Body:
I am new to MongoDB queries and looking for some guidance on how to retrieve documents that fit the search criteria. In particular, I need to find all the id(s) of the documents where the code is JPID i.e, "code": "JPID". We can assume the name of the collection is systems.

Since this is a nested object I thought of using the $unwid - but I am still stuck on how  to do it. The example is very trivial. Any help and guidance is appreciated.

{
      "resourceType": "NamingSystem",
      "id": "example-id",
      "name": "Austalian Healthcare Identifier - Individual",
      "status": "active",
      "kind": "identifier",
      "date": "2015-08-31",
      "publisher": "HL7 Australia on behalf of NEHTA",
      "responsible": "HI Service Operator / NEHTA",
      "type": {
        "coding": [
          {
            "system": "http://hl7.org/fhir/v2/0203",
            "code": "JPID";
            "display": "National unique individual identifier"
          }
        ],
        "text": "IHI"
      },
      "description": "Australian HI Identifier as established by relevant regulations etc",
      "uniqueId": [
        {
          "type": "oid",
          "value": "1.2.36.1.2001.1003.0",
          "comment": "This value is used in Australian CDA documents"
        },
        {
          "type": "uri",
          "value": "http://ns.electronichealth.net.au/id/hi/ihi/1.0",
          "preferred": true,
          "period": {
            "start": "2015-08-21"
          }
        }
      ]
    }

Body:
You can find all documents that contain at least one element in type.coding array by simple match the code element with the value JPID:

db.system.find({
 "type.coding.code": "JPID"
})

It is recommended to create and index on {"type.coding.code":1} so your searches to perform faster on this field.

playground

If you need to find all documents and filter only the array entries having the code:"JPID" you can use $filter as follow:

db.system.aggregate([
{
 $match: {
   "type.coding.code": "JPID"
 }
},
{
 $addFields: {
   "type.coding": {
     "$filter": {
      "input": "$type.coding",
      "as": "tc",
      "cond": {
        $eq: [
          "$$tc.code",
          "JPID"
          ]
       }
     }
   }
 }
}
])

playground(filter)


问:
Play random sound on button that is spammable
I have a problem that i want to have a button, that plays random sound after I press it, but the other thing is that i want to spam the button and so does the sound. What I mean is that i dont want to wait for the sound to finish to play it again and like have 5 sounds or more playing depending on your click speed.

for(var i=0;i<1;i++)
{
  document.getElementById("MyAudio.mp3")[i].addEventListener("click",function(){});
}

function playAudio()
{
    var audio = new Audio("MyAudio.mp3");
    audio.play();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onlick="playAudio()"></button></code>```

答:
That sounds fun and there's many ways to do it. I think the easiest way would be to pre-load the songs ahead of time and randomize it.

// Your sounds
let sounds = [new Audio('https://download.samplelib.com/mp3/sample-3s.mp3'), new Audio('https://download.samplelib.com/mp3/sample-6s.mp3'), new Audio('https://www.soundjay.com/human/fart-01.mp3')];
let lastSound = 0; // Not necessary but we don't want overlapping tracks.
// Listen for click on button (ID soundmachine)
// pointerdown is more suitable so adjusted it.
document.querySelector("#soundmachine1").addEventListener("pointerdown", () => {
// This is a small fix to allow the sound to be spammable and clear last track.
  sounds[lastSound].pause();
  sounds[lastSound].currentTime = 0;
  let random = Math.floor(Math.random() * sounds.length);
  sounds[random].play();
  lastSound = random; // For the next click we want to cancel this sound if it's playing.
  console.log(lastSound); // Just so you can see it count/play
});
document.querySelector("#soundmachine2").addEventListener("pointerdown", () => {
  // Play till completed
  let random = Math.floor(Math.random() * sounds.length);
  sounds[random].play();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="soundmachine1">click me ver1</div>
<button id="soundmachine2">click me ver2</div></code>```

Something like this!

Body:
I have a problem that i want to have a button, that plays random sound after I press it, but the other thing is that i want to spam the button and so does the sound. What I mean is that i dont want to wait for the sound to finish to play it again and like have 5 sounds or more playing depending on your click speed.

for(var i=0;i<1;i++)
{
  document.getElementById("MyAudio.mp3")[i].addEventListener("click",function(){});
}

function playAudio()
{
    var audio = new Audio("MyAudio.mp3");
    audio.play();
}

<button onlick="playAudio()"></button>

Body:
That sounds fun and there's many ways to do it. I think the easiest way would be to pre-load the songs ahead of time and randomize it.

// Your sounds
let sounds = [new Audio('https://download.samplelib.com/mp3/sample-3s.mp3'), new Audio('https://download.samplelib.com/mp3/sample-6s.mp3'), new Audio('https://www.soundjay.com/human/fart-01.mp3')];
let lastSound = 0; // Not necessary but we don't want overlapping tracks.
// Listen for click on button (ID soundmachine)
// pointerdown is more suitable so adjusted it.
document.querySelector("#soundmachine1").addEventListener("pointerdown", () => {
// This is a small fix to allow the sound to be spammable and clear last track.
  sounds[lastSound].pause();
  sounds[lastSound].currentTime = 0;
  let random = Math.floor(Math.random() * sounds.length);
  sounds[random].play();
  lastSound = random; // For the next click we want to cancel this sound if it's playing.
  console.log(lastSound); // Just so you can see it count/play
});
document.querySelector("#soundmachine2").addEventListener("pointerdown", () => {
  // Play till completed
  let random = Math.floor(Math.random() * sounds.length);
  sounds[random].play();
});

<button id="soundmachine1">click me ver1</div>
<button id="soundmachine2">click me ver2</div>

Something like this!


问:
Count and Sum functions with help of ViewBag
I have a question how to solve my problem. There is a table with items. Each item has a status "open" or "closed". For instance, 9 items with "closed" status and 14 ones with "open". I need to find the difference between open and closed items (14 - 9 = 5). How can I do it with help of ViewBag? As I understood, it is required to write "count" function in controller and transmit the result to View via ViewBag. But I don't know how to write this code. The result should be shown on the View page.

Request.cs (Model):

```<code>public class Request
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public string Status { get; set; } = "";
}

</code>```

Controller.cs:

```<code>public IActionResult Requests()
{
    var Requests = _repo.GetAllRequests();
    return View(Requests);
}

</code>```

Repository:

```<code>public Request GetRequest(int id)
{
    return _ctx.Requests.FirstOrDefault(c => c.Id == id);
}

public List<Request> GetAllRequests()
{
    return _ctx.Requests.ToList();
}

</code>```

View:

```<code><div>
    <table>
        @foreach (var request in Model)
        {
        <tr>
            <th>@request.Name</th>
            <th>@request.Status</th>
        </tr>
        }
    </table>
</div>
</code>```

答:
```<code>    private StatisticScore()
    {
        var openCount =_ctx.Requests.Where(m=> m.Status == "Open").Count();
       var closedCount = _ctx.Requests.Where(m=> m.Status == "Closed").Count();
        ViewBag.Difference  = openCount  - closedCount
    }
</code>```

```<code>  <label> Difference </label> @ViewBag.Difference
</code>```

Also, I suggest you; Do not use status fields as strings. It will be easier for you if you keep it as an enum.

Body:
I have a question how to solve my problem. There is a table with items. Each item has a status "open" or "closed". For instance, 9 items with "closed" status and 14 ones with "open". I need to find the difference between open and closed items (14 - 9 = 5). How can I do it with help of ViewBag? As I understood, it is required to write "count" function in controller and transmit the result to View via ViewBag. But I don't know how to write this code. The result should be shown on the View page.

Request.cs (Model):

public class Request
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public string Status { get; set; } = "";
}

Controller.cs:

public IActionResult Requests()
{
    var Requests = _repo.GetAllRequests();
    return View(Requests);
}

Repository:

public Request GetRequest(int id)
{
    return _ctx.Requests.FirstOrDefault(c => c.Id == id);
}

public List<Request> GetAllRequests()
{
    return _ctx.Requests.ToList();
}

View:

        @foreach (var request in Model)
        {

            @request.Name
            @request.Status

        }

Body:
    private StatisticScore()
    {
        var openCount =_ctx.Requests.Where(m=> m.Status == "Open").Count();
       var closedCount = _ctx.Requests.Where(m=> m.Status == "Closed").Count();
        ViewBag.Difference  = openCount  - closedCount
    }

  <label> Difference </label> @ViewBag.Difference

Also, I suggest you; Do not use status fields as strings. It will be easier for you if you keep it as an enum.


问:
Auto-populating first column in an HTML table with the first date of actual months
For the code below, $count++ prints out rows of numbers ascending from 1 on up.

How could I replace it with monthly intervals starting with September 1, 2010 6 am eastern?  (I. e. row one has September 1, 2010, row 2 has October 1, 2010, etc.?)

I would like the dates to be in a format that would allow me to compare to timestamps from MySQL

```<code>$result = mysql_query($sqlStr3);
$count = 1;
$arr = array();
echo "<table>";
    while ($row = mysql_fetch_array($result)) {

            echo '<tr >';
            echo '<td >'.$count++.'</td>';
</code>```

答:
I'm a fan of the strtotime() function. It takes a readable string and converts it into a Unix timestamp, and it handles relative time really well as well.

First, create a variable with your initial date:

```<code>$date = strtotime("September 1, 2010");
</code>```

Each month in the loop is created by simply adding one month to the variable:

```<code>$date = strtotime("+1 month", $date);
</code>```

You can use date() to format the timestamp to output it in your list:

```<code>echo date("F j, Y", $date);
</code>```

You can see the full range of formats here.

Alternately, if you're using PHP 5.3, you can take full advantage of the DateTime object (introduced in 5.2, but things like DateTime::add() didn't exist until 5.3).

As far as compatibility with MySQL, you can either use the MySQL function UNIX_TIMESTAMP to return a Unix timestamp from your query, or run the MySQL timestamp through strtotime() as well to convert it to a Unix timestamp.

Body:
For the code below, $count++ prints out rows of numbers ascending from 1 on up.

How could I replace it with monthly intervals starting with September 1, 2010 6 am eastern?  (I. e. row one has September 1, 2010, row 2 has October 1, 2010, etc.?)

I would like the dates to be in a format that would allow me to compare to timestamps from MySQL

$result = mysql_query($sqlStr3);
$count = 1;
$arr = array();
echo "
";
    while ($row = mysql_fetch_array($result)) {

            echo '
';
            echo ''.$count++.'	';

Body:
I'm a fan of the strtotime() function. It takes a readable string and converts it into a Unix timestamp, and it handles relative time really well as well.

First, create a variable with your initial date:

$date = strtotime("September 1, 2010");

Each month in the loop is created by simply adding one month to the variable:

$date = strtotime("+1 month", $date);

You can use date() to format the timestamp to output it in your list:

echo date("F j, Y", $date);

You can see the full range of formats here.

Alternately, if you're using PHP 5.3, you can take full advantage of the DateTime object (introduced in 5.2, but things like DateTime::add() didn't exist until 5.3).

As far as compatibility with MySQL, you can either use the MySQL function UNIX_TIMESTAMP to return a Unix timestamp from your query, or run the MySQL timestamp through strtotime() as well to convert it to a Unix timestamp.


问:
Factory for Generic types
I guess most Python lovers know it but, in order to provide some context, the typing module provides a mechanism for defining type hints as follows:

from typing import List

x = List[int]
```
<p>In the code above, x represents a List whose items are integers.</p>
<p>In the scope of microservices, FastAPI library allows defining the endpoint argument types through the use of Pydantic library.</p>
<pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    friends: List[int] = []
</code>```

I am trying to generate an endpoint for a ML model without knowing its input format. My approach is to extract is metadata and see the input schema, and generate a Pydantic class from it.

My question is...

Is there a way of programmatically obtaining get a type like those referenced by x, so I can implement a factory for generating them based on some input?

答:
You can create your own generic class:</p>
```<code>from pydantic import GenericModel
from typing import Generic, TypeVar

F = TypeVar("F")

class User(GenericModel, Generic[F]):
    id: int
    name: str
    friends: List[F]
</code>```

Title: Factory for Generic types

Body:
I guess most Python lovers know it but, in order to provide some context, the typing module provides a mechanism for defining type hints as follows:

from typing import List

x = List[int]

In the code above, x represents a List whose items are integers.

In the scope of microservices, FastAPI library allows defining the endpoint argument types through the use of Pydantic library.

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    friends: List[int] = []

I am trying to generate an endpoint for a ML model without knowing its input format. My approach is to extract is metadata and see the input schema, and generate a Pydantic class from it.

My question is...

Is there a way of programmatically obtaining get a type like those referenced by x, so I can implement a factory for generating them based on some input?

Body:
You can create your own generic class:

from pydantic import GenericModel
from typing import Generic, TypeVar

F = TypeVar("F")

class User(GenericModel, Generic[F]):
    id: int
    name: str
    friends: List[F]


问:
Can a Azure function write back data to synapse database
I am new to azure stack, so my please bear with my question.

I have a synapse database and I have a powerapp that reads data from synapse database. So, powerapps cannot writeback to synapse database. So I am thinking of developing a azure function with https trigger and integrate with the powerapp button on click functionality. So, my question is CAN AZURE FUNCTION WRITE BACK TO SYNAPSE DATABASE?

PS: I have tried the same with logic apps, with new row in sql trigger, and it didn't work.

Any help would be appreciated?

答: if you have a library for connecting to the synapse database that does not need to be installed but can be loaded in your application then yes Function Apps can write to the synapse DB as long as the connectivity is there</p>


答:
Simple answer: no

Complicated answer: yes if debugging symbols are turned on and you write some helper functions to look through the debug symbols. But this is really horrible, buggy (functions can be automatically inlined and will be magically absent from your symbol table), and most of all stops working as soon as you build the release version of the program.

Final answer: no

Title: Is it possible to check if a function with a string as its name exists?(C++)


问:
How to convert xml to hashmap and ignore empty tags in Kotlin
I want to convert an xml value to a map, but empty tags also come into the map.
I don't want empty tags. maybe a has nested nodes. See below for an example

a = "<rootTag><name>Ali Tan</name><address><tag1>aaa</tag1><tag2></tag2></address></rootTag>"

```<code>  @Test
fun contextLoads() {
    var a = "<rootTag><name>Ali Tan</name><address></address></rootTag>"
    val xmlMapper = XmlMapper()
    val aa = xmlMapper.readValue(a, HashMap::class.java)
    println(aa)

}
</code>```

code result:

{address=, name=Ali Tan}

i want to see

{name=Ali Tan}

答:
Just filter out empty values afterward:

val aa = xmlMapper.readValue(a, HashMap::class.java).filterValues { it.isNotEmpty() })
```

Body:
I want to convert an xml value to a map, but empty tags also come into the map.
I don't want empty tags. maybe a has nested nodes. See below for an example

a = "<rootTag><name>Ali Tan</name><address><tag1>aaa</tag1><tag2></tag2></address></rootTag>"

  @Test
fun contextLoads() {
    var a = "<rootTag><name>Ali Tan</name><address></address></rootTag>"
    val xmlMapper = XmlMapper()
    val aa = xmlMapper.readValue(a, HashMap::class.java)
    println(aa)

}

code result:

{address=, name=Ali Tan}

i want to see

{name=Ali Tan}


问:
How to return start of linked list from function C
I have a function readPatientDataFromFile that reads data from a file and stores it in a struct. The function should return a pointer that points to the start of a linked list but instead the pointer that is returned points to the end of the list.

Here is the complete implementation of the code:

```<code>#include <stdio.h>
#include <stdlib.h>

struct patient
 {
    char firstname[30];
    char lastname[30];
    int age;
    struct appointment *appointment_details;
    struct patient *next;

};

struct patient * readPatientsFromFile(char *filename);
struct patient * appendPatient(struct patient *endPtr, struct patient *newPatient);

int main(){
    struct patient *patientPtr;
    int i = 1;

    char patients_filename[] = "patients.txt";

    patientPtr = readPatientsFromFile(patients_filename);
    printf("---------------------------\n");
    while(patientPtr != NULL){
        printf("Patient ID: %d\n", i);
        printf("Name: %s %s\n", patientPtr->lastname, patientPtr->firstname);
        printf("Age: %d\n", patientPtr->age);
        printf("----------------------------\n");
        patientPtr = patientPtr->next;
        i++;
    }
}

struct patient * appendPatient(struct patient *endPtr, struct patient *newPatient){
    endPtr->next = newPatient;
    return (endPtr->next);
}

struct patient * readPatientsFromFile(char *filename){
    FILE *ifile;
    ifile = fopen(filename, "r");
    struct patient *startPtr = NULL;
    struct patient *endOfPatients = NULL;
    size_t c;
    if (ifile != NULL){
        struct patient *patientPtr = (struct patient *) malloc(sizeof(struct patient));
        do {
            c = fread(patientPtr, sizeof(struct patient), 1, ifile);
            // create linked list
            if (startPtr == NULL){
                startPtr = patientPtr;
                endOfPatients = startPtr;
            }
            else {
                endOfPatients = appendPatient(endOfPatients, patientPtr);
            }
            printf("First Name: %s\n", startPtr->firstname);
        }
        while(c >= 1);
        endOfPatients->next = NULL;
        fclose(ifile);
        printf("Reading data from file successful!!!\n");
    }
    else {
        printf("Error reading from file");
    }
    return startPtr;
}
</code>```

As I understand it, the printf statement in the readPatientsFromFile function should always output the same thing but from the output (attached) below, it seems that the pointer that should point to the start of the list keeps getting updated for each iteration of the loop.
Here's the output of the code:

```<code>First Name: John
First Name: Jane
First Name: Lloyd
First Name: Jane
First Name: Jane
First Name: John
First Name: Jane
First Name: Lloyd
First Name: Paulo
First Name: Paulo
Reading data from file successful!!!
---------------------------
Patient ID: 1
Name: Coelho Paulo
Age: 49
----------------------------
</code>```

I'd like to know why the code is not running as expected. Thanks.

答:
Thanks to @EdmCoff, the problem was that I didn't allocate memory for new nodes in the list with malloc so the data was being assigned to the node each time. The solution was to move the malloc statement into the while loop.
The corrected readPatientsFromFile is given below:

```<code>struct patient * readPatientsFromFile(char *filename){
    FILE *ifile;
    ifile = fopen(filename, "r");
    struct patient *startPtr = NULL;
    struct patient *endOfPatients = NULL;
    size_t c;
    struct patient *patientPtr

    if (ifile != NULL){

        do {
            patientPtr = (struct patient *) malloc(sizeof(struct patient)); // corrected portion
            c = fread(patientPtr, sizeof(struct patient), 1, ifile);
            // create linked list
            if (startPtr == NULL){
                startPtr = patientPtr;
                endOfPatients = startPtr;
            }
            else {
                endOfPatients = appendPatient(endOfPatients, patientPtr);
            }
            printf("First Name: %s\n", startPtr->firstname);
        }
        while(c >= 1);
        endOfPatients->next = NULL;
        fclose(ifile);
        printf("Reading data from file successful!!!\n");
    }
    else {
        printf("Error reading from file");
    }
    return startPtr;
}
</code>```

Body:
I have a function readPatientDataFromFile that reads data from a file and stores it in a struct. The function should return a pointer that points to the start of a linked list but instead the pointer that is returned points to the end of the list.

Here is the complete implementation of the code:

#include <stdio.h>
#include <stdlib.h>

struct patient
 {
    char firstname[30];
    char lastname[30];
    int age;
    struct appointment *appointment_details;
    struct patient *next;

};

struct patient * readPatientsFromFile(char *filename);
struct patient * appendPatient(struct patient *endPtr, struct patient *newPatient);

int main(){
    struct patient *patientPtr;
    int i = 1;

    char patients_filename[] = "patients.txt";

    patientPtr = readPatientsFromFile(patients_filename);
    printf("---------------------------\n");
    while(patientPtr != NULL){
        printf("Patient ID: %d\n", i);
        printf("Name: %s %s\n", patientPtr->lastname, patientPtr->firstname);
        printf("Age: %d\n", patientPtr->age);
        printf("----------------------------\n");
        patientPtr = patientPtr->next;
        i++;
    }
}

struct patient * appendPatient(struct patient *endPtr, struct patient *newPatient){
    endPtr->next = newPatient;
    return (endPtr->next);
}

struct patient * readPatientsFromFile(char *filename){
    FILE *ifile;
    ifile = fopen(filename, "r");
    struct patient *startPtr = NULL;
    struct patient *endOfPatients = NULL;
    size_t c;
    if (ifile != NULL){
        struct patient *patientPtr = (struct patient *) malloc(sizeof(struct patient));
        do {
            c = fread(patientPtr, sizeof(struct patient), 1, ifile);
            // create linked list
            if (startPtr == NULL){
                startPtr = patientPtr;
                endOfPatients = startPtr;
            }
            else {
                endOfPatients = appendPatient(endOfPatients, patientPtr);
            }
            printf("First Name: %s\n", startPtr->firstname);
        }
        while(c >= 1);
        endOfPatients->next = NULL;
        fclose(ifile);
        printf("Reading data from file successful!!!\n");
    }
    else {
        printf("Error reading from file");
    }
    return startPtr;
}

As I understand it, the printf statement in the readPatientsFromFile function should always output the same thing but from the output (attached) below, it seems that the pointer that should point to the start of the list keeps getting updated for each iteration of the loop.
Here's the output of the code:

First Name: John
First Name: Jane
First Name: Lloyd
First Name: Jane
First Name: Jane
First Name: John
First Name: Jane
First Name: Lloyd
First Name: Paulo
First Name: Paulo
Reading data from file successful!!!
---------------------------
Patient ID: 1
Name: Coelho Paulo
Age: 49
----------------------------

I'd like to know why the code is not running as expected. Thanks.

Body:
Thanks to @EdmCoff, the problem was that I didn't allocate memory for new nodes in the list with malloc so the data was being assigned to the node each time. The solution was to move the malloc statement into the while loop.
The corrected readPatientsFromFile is given below:

struct patient * readPatientsFromFile(char *filename){
    FILE *ifile;
    ifile = fopen(filename, "r");
    struct patient *startPtr = NULL;
    struct patient *endOfPatients = NULL;
    size_t c;
    struct patient *patientPtr

    if (ifile != NULL){

        do {
            patientPtr = (struct patient *) malloc(sizeof(struct patient)); // corrected portion
            c = fread(patientPtr, sizeof(struct patient), 1, ifile);
            // create linked list
            if (startPtr == NULL){
                startPtr = patientPtr;
                endOfPatients = startPtr;
            }
            else {
                endOfPatients = appendPatient(endOfPatients, patientPtr);
            }
            printf("First Name: %s\n", startPtr->firstname);
        }
        while(c >= 1);
        endOfPatients->next = NULL;
        fclose(ifile);
        printf("Reading data from file successful!!!\n");
    }
    else {
        printf("Error reading from file");
    }
    return startPtr;
}


答:
There's some odd things going on with this code, so let's rethink it from the beginning. First of all, you want to create an onclick handler on your button that plays your mp3 file. Let's do that first:

```<code>let audio = new Audio("MyAudio.mp3");
document.querySelector("button").addEventListener("click", () => {
  audio.play()
});
</code>```

Now, it sounds like you want it to play from the beginning every time when clicked, and not wait till it completes (which is the default behavior). So we need to reset the playback every time you click.

```<code>let audio = new Audio("MyAudio.mp3");
document.querySelector("button").addEventListener("click", () => {
  audio.currentTime = 0;
  audio.play();
});
</code>```

And your HTML can just look like this:

```<code><button>Play</button>
</code>```

Title: Play random sound on button that is spammable

Body:
There's some odd things going on with this code, so let's rethink it from the beginning. First of all, you want to create an onclick handler on your button that plays your mp3 file. Let's do that first:

let audio = new Audio("MyAudio.mp3");
document.querySelector("button").addEventListener("click", () => {
  audio.play()
});

Now, it sounds like you want it to play from the beginning every time when clicked, and not wait till it completes (which is the default behavior). So we need to reset the playback every time you click.

let audio = new Audio("MyAudio.mp3");
document.querySelector("button").addEventListener("click", () => {
  audio.currentTime = 0;
  audio.play();
});

And your HTML can just look like this:

<button>Play</button>


问:
How to calculate relative frequency of array elements using Ramda.js?
I have an array with repeating values, and I want to get the relative frequency (i.e., proportions) for each repeating value.

It seems natural to me to treat this as a 2-step procedure:

count the occurrences of each value; and

divide that count by the length of the original array.

To accomplish the first step we can use R.countBy() from ramda.js:

const R = require("ramda")

const myLetters = ["a", "a", "a", "a", "b", "b", "c", "c", "c", "c"]
const counted = R.countBy(R.identity)(myLetters)
counted // => gives {"a": 4, "b": 2, "c": 4}
```
<p>Now the second step would be to divide <code>counted</code> by the length of <code>myLetters</code>:</p>
<pre class="lang-js prettyprint-override"><code>counted / R.length(myLetters) // obviously this doesn't work because it's not mapped
</code>```

I'm a bit lost with how to map this correctly. My current clunky solution that I dislike:

// 1. manually calculate the length and store to a variable
const nvals = R.length(myLetters)

// 2. create a custom division function
const divide_by_length = (x) => R.divide(x, nvals)

// 3. map custom function to `counted`
R.map(divide_by_length, counted) // gives {"a": 0.4, "b": 0.2, "c": 0.4}
```

Although this works, there's gotta be a more straightforward way with ramda to get from counted to {"a": 0.4, "b": 0.2, "c": 0.4}.

答:
I very much like the approach from Ori Drori, using the fact that ap (f, g) //~> (x) => f (x) (g (x)).  (chain used for functions is the related chain (f, g) //~> (x) => f (g (x)) (x).)

My initial thought was similar, using instead lift, which lifts a function that operates on values up to become a one that operates on containers of those values.  When the containers are functions, it operates something like lift (f) (g, h) //~> (x) => f (g (x), h (x)), although it's more generic, as lift (f) is variadic, as are the functions supplied to it and therefore also the function it generates, e.g.  lift (f) (g, h, i, j) //~> (a, b, c) => f (g (a, b, c), h (a, b, c), i (a, b, c), j (a, b, c))

So, very similarly, I wrote:

const frequencies = lift (map) (
  pipe (length, flip (divide)),
  countBy (identity)
)

const myLetters = ["a", "a", "a", "a", "b", "b", "c", "c", "c", "c"]

console .log (frequencies (myLetters))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js"></script>
<script> const {lift, map, pipe, length, flip, divide, countBy, identity} = R </script></code>```

Nonetheless, it's not clear to me that a point-free approach offers any benefit here.  I'm not sure which I prefer, but this non-point-free Ramda is about as readable to my mind:

const frequencies = (letters, total = letters.length) =>
  map (n => n / total) (countBy (identity) (letters) )

const myLetters = ["a", "a", "a", "a", "b", "b", "c", "c", "c", "c"]

console .log (frequencies (myLetters))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js"></script>
<script> const {lift, map, pipe, length, flip, divide, countBy, identity} = R </script></code>```

Body:
I have an array with repeating values, and I want to get the relative frequency (i.e., proportions) for each repeating value.

It seems natural to me to treat this as a 2-step procedure:

count the occurrences of each value; and

divide that count by the length of the original array.

To accomplish the first step we can use R.countBy() from ramda.js:

const R = require("ramda")

const myLetters = ["a", "a", "a", "a", "b", "b", "c", "c", "c", "c"]
const counted = R.countBy(R.identity)(myLetters)
counted // => gives {"a": 4, "b": 2, "c": 4}

Now the second step would be to divide counted by the length of myLetters:

counted / R.length(myLetters) // obviously this doesn't work because it's not mapped

I'm a bit lost with how to map this correctly. My current clunky solution that I dislike:

// 1. manually calculate the length and store to a variable
const nvals = R.length(myLetters)

// 2. create a custom division function
const divide_by_length = (x) => R.divide(x, nvals)

// 3. map custom function to `counted`
R.map(divide_by_length, counted) // gives {"a": 0.4, "b": 0.2, "c": 0.4}

Although this works, there's gotta be a more straightforward way with ramda to get from counted to {"a": 0.4, "b": 0.2, "c": 0.4}.

Body:
I very much like the approach from Ori Drori, using the fact that ap (f, g) //~> (x) => f (x) (g (x)).  (chain used for functions is the related chain (f, g) //~> (x) => f (g (x)) (x).)

My initial thought was similar, using instead lift, which lifts a function that operates on values up to become a one that operates on containers of those values.  When the containers are functions, it operates something like lift (f) (g, h) //~> (x) => f (g (x), h (x)), although it's more generic, as lift (f) is variadic, as are the functions supplied to it and therefore also the function it generates, e.g.  lift (f) (g, h, i, j) //~> (a, b, c) => f (g (a, b, c), h (a, b, c), i (a, b, c), j (a, b, c))

So, very similarly, I wrote:

const frequencies = lift (map) (
  pipe (length, flip (divide)),
  countBy (identity)
)

const myLetters = ["a", "a", "a", "a", "b", "b", "c", "c", "c", "c"]

console .log (frequencies (myLetters))

<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js"></script>
<script> const {lift, map, pipe, length, flip, divide, countBy, identity} = R </script>

Nonetheless, it's not clear to me that a point-free approach offers any benefit here.  I'm not sure which I prefer, but this non-point-free Ramda is about as readable to my mind:

const frequencies = (letters, total = letters.length) =>
  map (n => n / total) (countBy (identity) (letters) )

const myLetters = ["a", "a", "a", "a", "b", "b", "c", "c", "c", "c"]

console .log (frequencies (myLetters))

<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js"></script>
<script> const {lift, map, pipe, length, flip, divide, countBy, identity} = R </script>


问:
C comparison between -1 and 65535/4294967295/18446744073709551615
I have a misunderstanding about the following statements:

```<code>printf("%d\n", -1 == 65535);
printf("%d\n", -1 == 4294967295UL);
printf("%d\n", -1 == 18446744073709551615);
printf("%d\n", -1 == 18446744073709551615UL);
</code>```

The output is:

```<code>0
0
0
1
</code>```

If if don't add the UL suffixes the compiler gives the following warning: main.c:36:28: warning: integer constant is so large that it is unsigned

Can someone explain this to me please? Why for 18446744073709551615 the result is 0 but for 18446744073709551615UL the results is 1? It's ok not to add that suffix?

Thanks

答:
Case 3 exhibits a bug in GCC.

In GCC 11.2 for x86_64, the signed and unsigned int types are 32 bits, the signed and unsigned long and long long types are 64 bits, and there are also extended types __int128_t and __uint128_t with width 128.

In -1 == 65535, -1 and 65535 are both int. They are unequal, so the comparison produces 0.

In -1 == 4294967295UL, -1 is an int, and 4294967295UL is an unsigned long. Per the usual arithmetic conversions, −1 is converted to unsigned long, which wraps modulo 264, producing 18,446,744,073,709,551,615. That does not equal 4,294,967,295, so the comparison produces 0.

In -1 == 18446744073709551615, 18446744073709551615 is too large for the normal types. C 2018 6.4.4.1 5 says the type of an unsuffixed decimal integer constant is the first of int, long int, or long long int that can represent it. Since none of those can represent it in this C implementation, paragraph 6 applies:

If an integer constant cannot be represented by any type in its list, it may have an extended integer type, if the extended integer type can represent its value. If all of the types in the list for the constant are signed, the extended integer type shall be signed…

From this, we see the type of 18446744073709551615 should be __int128_t. This is confirmed by using _Generic to reveal the type; the following program prints “__int128_t”:

```<code>#include <stdio.h>

int main(void)
{
    printf("%s\n", _Generic(18446744073709551615,
            __int128_t: "__int128_t",
            default:    "something else")
        );
}
</code>```

In contrast, Clang 13.0.0 uses unsigned long long.](https://godbolt.org/z/a5Y3h5Wbo)

Thus, GCC’s error message that states “integer constant is so large that it is unsigned” is incorrect. GCC uses a different type than its error message states, so this is a bug in GCC.

Given that the type is __int128_t, −1 and 18,446,744,073,709,551,615 are both representable in the type, so evaluation of the expression converts −1 to __int128_t with no change in value, the values are unequal, and the comparison produces 0.

(Since Clang uses unsigned long long, it produces 1.)

For confirmation, we see that printf("%d\n", -18446744073709551615 < 0); prints “1” in GCC, showing the comparison was performed with a signed type, whereas Clang prints “0”.

Finally, in -1 == 18446744073709551615UL, the usual arithmetic conversions convert −1 to unsigned long, which wraps modulo 264, producing 18,446,744,073,709,551,615. Then the two operands are equal, and the comparison produces 1.

Body:
I have a misunderstanding about the following statements:

printf("%d\n", -1 == 65535);
printf("%d\n", -1 == 4294967295UL);
printf("%d\n", -1 == 18446744073709551615);
printf("%d\n", -1 == 18446744073709551615UL);

The output is:

0
0
0
1

If if don't add the UL suffixes the compiler gives the following warning: main.c:36:28: warning: integer constant is so large that it is unsigned

Can someone explain this to me please? Why for 18446744073709551615 the result is 0 but for 18446744073709551615UL the results is 1? It's ok not to add that suffix?

Thanks

Body:
Case 3 exhibits a bug in GCC.

In GCC 11.2 for x86_64, the signed and unsigned int types are 32 bits, the signed and unsigned long and long long types are 64 bits, and there are also extended types __int128_t and __uint128_t with width 128.

In -1 == 65535, -1 and 65535 are both int. They are unequal, so the comparison produces 0.

In -1 == 4294967295UL, -1 is an int, and 4294967295UL is an unsigned long. Per the usual arithmetic conversions, −1 is converted to unsigned long, which wraps modulo 264, producing 18,446,744,073,709,551,615. That does not equal 4,294,967,295, so the comparison produces 0.

In -1 == 18446744073709551615, 18446744073709551615 is too large for the normal types. C 2018 6.4.4.1 5 says the type of an unsuffixed decimal integer constant is the first of int, long int, or long long int that can represent it. Since none of those can represent it in this C implementation, paragraph 6 applies:

If an integer constant cannot be represented by any type in its list, it may have an extended integer type, if the extended integer type can represent its value. If all of the types in the list for the constant are signed, the extended integer type shall be signed…

From this, we see the type of 18446744073709551615 should be __int128_t. This is confirmed by using _Generic to reveal the type; the following program prints “__int128_t”:

#include <stdio.h>

int main(void)
{
    printf("%s\n", _Generic(18446744073709551615,
            __int128_t: "__int128_t",
            default:    "something else")
        );
}

In contrast, Clang 13.0.0 uses unsigned long long.](https://godbolt.org/z/a5Y3h5Wbo)

Thus, GCC’s error message that states “integer constant is so large that it is unsigned” is incorrect. GCC uses a different type than its error message states, so this is a bug in GCC.

Given that the type is __int128_t, −1 and 18,446,744,073,709,551,615 are both representable in the type, so evaluation of the expression converts −1 to __int128_t with no change in value, the values are unequal, and the comparison produces 0.

(Since Clang uses unsigned long long, it produces 1.)

For confirmation, we see that printf("%d\n", -18446744073709551615 < 0); prints “1” in GCC, showing the comparison was performed with a signed type, whereas Clang prints “0”.

Finally, in -1 == 18446744073709551615UL, the usual arithmetic conversions convert −1 to unsigned long, which wraps modulo 264, producing 18,446,744,073,709,551,615. Then the two operands are equal, and the comparison produces 1.


问:
Sorting a vector of objects in C++
say I have a class "Information" and it stores the Name and Age of people in a vector.

so...

```<code>class Information {

private:
int age;
string name;

//etc, etc...
};
</code>```

How would I sort the vector in either ascending/descending order with respect to age?

I believe you use something like this.

```<code>sort(listOfPeople.begin(), listOfPeople.end(), greater<Information>());
</code>```

listOfPeople would be the vector.

Any help would be greatly appreciated.

答:
I would  overload operator < and then sort using greater. Greater essentially means rhs < lhs. You then sort using sort(listOfPeople.begin(), listOfPeople.end(), greater<Information>());

If you decide to add operator< your class would play nicely with std::set and as a key in std::map in addition to allowing sort.

```<code>class Information {

private:
int age;
string name;

friend bool operator< (Information const& lhs, Information const& rhs){
    return lhs.age < rhs.age;
}

//etc, etc...
};
</code>```

Title: Sorting a vector of objects in C++

Body:
say I have a class "Information" and it stores the Name and Age of people in a vector.

so...

class Information {

private:
int age;
string name;

//etc, etc...
};

How would I sort the vector in either ascending/descending order with respect to age?

I believe you use something like this.

sort(listOfPeople.begin(), listOfPeople.end(), greater<Information>());

listOfPeople would be the vector.

Any help would be greatly appreciated.

Body:
I would  overload operator < and then sort using greater. Greater essentially means rhs < lhs. You then sort using sort(listOfPeople.begin(), listOfPeople.end(), greater<Information>());

If you decide to add operator< your class would play nicely with std::set and as a key in std::map in addition to allowing sort.

class Information {

private:
int age;
string name;

friend bool operator< (Information const& lhs, Information const& rhs){
    return lhs.age < rhs.age;
}

//etc, etc...
};


问:
RecyclerView RTL some items not adjusted
I'm using a RecyclerView to show a list of country codes, countries and flags respecively. The app is supporting RTL, so the layout of item is a simple Constraintlayout with 3 elements:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/selectable_background">

    <ImageView
        android:id="@+id/countryFlag"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:scaleType="centerInside"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/countryName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textAlignment="viewStart"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/countryCode"
        app:layout_constraintStart_toEndOf="@+id/countryFlag"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/countryCode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

But sometimes I get this visual representation in RTL (Arabic) like this, where some items are not aligned properly. See Angola and Anguilla country items:

答:
There is no reason for countryName to fill the entire width, the constraint layout's width is already match_parent and countryName's start already aligned to the flag's end.

Align using constraints is much more stable then android:textAlignment attribute.

Edit it as follows

```<code><TextView
        android:id="@+id/countryName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/countryCode"
        app:layout_constraintStart_toEndOf="@+id/countryFlag"
        app:layout_constraintTop_toTopOf="parent" />
</code>```

Happy to help

Body:
I'm using a RecyclerView to show a list of country codes, countries and flags respecively. The app is supporting RTL, so the layout of item is a simple Constraintlayout with 3 elements:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/selectable_background">

    <ImageView
        android:id="@+id/countryFlag"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:scaleType="centerInside"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/countryName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textAlignment="viewStart"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/countryCode"
        app:layout_constraintStart_toEndOf="@+id/countryFlag"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/countryCode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

But sometimes I get this visual representation in RTL (Arabic) like this, where some items are not aligned properly. See Angola and Anguilla country items:

Body:
There is no reason for countryName to fill the entire width, the constraint layout's width is already match_parent and countryName's start already aligned to the flag's end.

Align using constraints is much more stable then android:textAlignment attribute.

Edit it as follows

<TextView
        android:id="@+id/countryName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/countryCode"
        app:layout_constraintStart_toEndOf="@+id/countryFlag"
        app:layout_constraintTop_toTopOf="parent" />

Happy to help


问:
sum of duplicates data list on java
I have this code

```<code>    ... some code here

    while (iterator.hasNext()) {
      Document next = iterator.next();

      projectNumber = new NpoProjectNumberVM();
      localDate = new java.sql.Date(((Date) next.get("_id")).getTime()).toLocalDate();
      projectNumber.setDay(localDate);
      projectNumber.setNumber(((Long) next.get("number")).intValue());
      projectNumberList.add(projectNumber);
    }

    return projectNumberList;
</code>```

which displays this result

```<code> "projectNumber": [
        {
            "day": "2022-02-07",
            "number": 2
        },
        {
            "day": "2022-02-07",
            "number": 1
        },
        {
            "day": "2022-02-07",
            "number": 4
        },
    ]
</code>```

My request is: I want to have the sum of the numbers for the same date like this

```<code> "projectNumber": [
        {
            "day": "2022-02-07",
            "number": 7
        },
    ]
</code>```

答:
Java 8 streams: GroupingBy

Use Java 8 streaming with some of the Collectors like groupingBy for the key and summingLong for the aggregate-function to return a Map<?, Long> (where ? stands for the key, here LocalDate):

Map<LocalDate, Long> sumByDay = projectNumberList.stream().collect(
    groupingBy(
        ProjectNumber::getDay,
        summingLong(ProjectNumber::getNumber)
    )
);
```
<p>See also:</p>
<ul>
<li>Baeldung: Guide to Java 8 groupingBy Collector, 2.7. Getting the Sum from Grouped Results
</li>
</ul>
<h3>JSON output</h3>
<p>To produce some JSON output like</p>
<pre class="lang-json prettyprint-override"><code>"projectNumber": [
        {
            "day": "2022-02-07",
            "number": 7
        },
        {
            "day": "2022-02-01",
            "number": 1
        }
]
</code>```

you could use Jackson with a custom Map-serializer.

Title: sum of duplicates data list on java

Body:
I have this code

    ... some code here

    while (iterator.hasNext()) {
      Document next = iterator.next();

      projectNumber = new NpoProjectNumberVM();
      localDate = new java.sql.Date(((Date) next.get("_id")).getTime()).toLocalDate();
      projectNumber.setDay(localDate);
      projectNumber.setNumber(((Long) next.get("number")).intValue());
      projectNumberList.add(projectNumber);
    }

    return projectNumberList;

which displays this result

 "projectNumber": [
        {
            "day": "2022-02-07",
            "number": 2
        },
        {
            "day": "2022-02-07",
            "number": 1
        },
        {
            "day": "2022-02-07",
            "number": 4
        },
    ]

My request is: I want to have the sum of the numbers for the same date like this

 "projectNumber": [
        {
            "day": "2022-02-07",
            "number": 7
        },
    ]

Body:
Java 8 streams: GroupingBy

Use Java 8 streaming with some of the Collectors like groupingBy for the key and summingLong for the aggregate-function to return a Map<?, Long> (where ? stands for the key, here LocalDate):

Map<LocalDate, Long> sumByDay = projectNumberList.stream().collect(
    groupingBy(
        ProjectNumber::getDay,
        summingLong(ProjectNumber::getNumber)
    )
);

See also:

Baeldung: Guide to Java 8 groupingBy Collector, 2.7. Getting the Sum from Grouped Results

JSON output

To produce some JSON output like

"projectNumber": [
        {
            "day": "2022-02-07",
            "number": 7
        },
        {
            "day": "2022-02-01",
            "number": 1
        }
]

you could use Jackson with a custom Map-serializer.


问:
UITableView image on the left hand side

Possible Duplicate:

  adding images to UItableView

I want to add image in UITableView in the left hand side how could I add it?

答:
Either you can add UIImageView to the desired position by setting its frame...

```<code>    UIImageView *postImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 34, 300, 225)];
    postImage.image = [UIImage imageWithData:data];
    [postImage setContentMode:UIViewContentModeScaleAspectFill];
    postImage.clipsToBounds = YES;
    [cell addSubview:postImage];
    [postImage release];
</code>```

or you can go with following code too...

```<code>    cell.myImageView.image = [UIImage imageNamed:@"image.png"];
    cell.imageView.contentMode = UIViewContentModeCenter;
</code>```

Title: UITableView image on the left hand side

Body:
Either you can add UIImageView to the desired position by setting its frame...

    UIImageView *postImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 34, 300, 225)];
    postImage.image = [UIImage imageWithData:data];
    [postImage setContentMode:UIViewContentModeScaleAspectFill];
    postImage.clipsToBounds = YES;
    [cell addSubview:postImage];
    [postImage release];

or you can go with following code too...

    cell.myImageView.image = [UIImage imageNamed:@"image.png"];
    cell.imageView.contentMode = UIViewContentModeCenter;


问:
Plotly's interactive charts in PyCharm's SciView
PyCharm's SciView is by default able to show only static charts.

A plugin however exists, called lets-plot, allowing it to display interactive charts. Unfortunately this works by default with the python homonymous library lets-plot.

Nonetheless, the very fact that the plugin is able to display interactive charts would make me believe there must be a way to direct plotly's output to that renderer. What I can see available in plotly (plotly.io.renderers) are:

```<code>Default renderer: 'browser'
    Available renderers:
        ['plotly_mimetype', 'jupyterlab', 'nteract', 'vscode',
         'notebook', 'notebook_connected', 'kaggle', 'azure', 'colab',
         'json', 'png', 'jpeg', 'jpg', 'svg', 'pdf', 'browser',
         'firefox', 'chrome', 'chromium', 'iframe', 'iframe_connected',
         'sphinx_gallery']
</code>```

Question: does anyone know if this issue can somehow be circumvented allowing to display plotly's output in the embedded sciview?

What am I not looking for: I am aware of the alternatives, including rendering in browser, and rendering in jupyter notebooks.

答:
No, at the moment there is no way of displaying HTML/JS interactive chart in PyCharm' SciView.

Lets-plot among others also supports Java Swing frontend (see: Lets-Plot in JVM and Kotlin/JS application). This is what make its interactive charts possible in PyCharm.

Body:
PyCharm's SciView is by default able to show only static charts.

A plugin however exists, called lets-plot, allowing it to display interactive charts. Unfortunately this works by default with the python homonymous library lets-plot.

Nonetheless, the very fact that the plugin is able to display interactive charts would make me believe there must be a way to direct plotly's output to that renderer. What I can see available in plotly (plotly.io.renderers) are:

Default renderer: 'browser'
    Available renderers:
        ['plotly_mimetype', 'jupyterlab', 'nteract', 'vscode',
         'notebook', 'notebook_connected', 'kaggle', 'azure', 'colab',
         'json', 'png', 'jpeg', 'jpg', 'svg', 'pdf', 'browser',
         'firefox', 'chrome', 'chromium', 'iframe', 'iframe_connected',
         'sphinx_gallery']

Question: does anyone know if this issue can somehow be circumvented allowing to display plotly's output in the embedded sciview?

What am I not looking for: I am aware of the alternatives, including rendering in browser, and rendering in jupyter notebooks.


问:
Checking if key exists in Presto value map
I am new to Presto, and can't quite figure out how to check if a key is present in a map. When I run a SELECT query, this error message is returned:

Key not present in map: element

```<code>SELECT value_map['element'] FROM
mytable
WHERE name = 'foobar'
</code>```

Adding AND contains(value_map, 'element') does not work

The data type is a string array

```<code>SELECT typeof('value_map') FROM mytable
</code>```

returns varchar(9)

How would I only select records where 'element' is present in the value_map?

答: element_at is ambiguous in that case -- it'll return NULL when either there's no such key or the key does exist and has NULL associated with it. A guaranteed approach is contains(map_keys(my_map), 'mykey'), which admittedly should be a bit slower than the original variant.

Body:
I am new to Presto, and can't quite figure out how to check if a key is present in a map. When I run a SELECT query, this error message is returned:

Key not present in map: element

SELECT value_map['element'] FROM
mytable
WHERE name = 'foobar'

Adding AND contains(value_map, 'element') does not work

The data type is a string array

SELECT typeof('value_map') FROM mytable

returns varchar(9)

How would I only select records where 'element' is present in the value_map?


问:
save() prohibited [...] due to unsaved related object, but related object already saved
I'm working with Django 4.0.1.

I'm having having "save() prohibited to prevent data loss due to unsaved related object 'page'" even if the 'page' object is saved one line before.

Here is the code:

```<code># Upload entity data
u = Upload(
    message=request.POST["upload_msg"]
)
# saving u here to be able to use u.datetime later
u.save()
# new page for the upload entity
page = Page(
    title="notes for Upload " + str(u.datetime),
    content="This page is empty..."
)
page.save()
u.page = page
u.save()
</code>```

The last line (u.save()) is the one causing the error.
Am I having some kind of race condition here? Isn't it assured that the previous db operations are complete before trying to run the next?
Any other ideas?

Thank you.

UPDATE

I can see from the admin panel that the Upload and Page instance are both created correctly but the Upload instance does not have a Page id set.
Unless I'm misunderstanding the error message the Page instance does not result saved (or updated inside the python 'page' variable) when the last u.save() call is invoked. Any way to solve this?

UPDATE 2

Looks like this problem arises only if I explicitly define the primary key as follows:

```<code>id = models.IntegerField(primary_key=True, null=False)
</code>```

Shouldn't this automatically create the entities' ids on .save()?

答:
You're trying to call save() but not storing instance of it in u and use commit=False this will not hit database it will store instance in memory after your proccess is finished you can save it. check more info about save() method.

```<code># Upload entity data
u = Upload(
    message=request.POST["upload_msg"]
)
# saving u here to be able to use u.datetime later
u = u.save(commit=False)
# new page for the upload entity
page = Page(
    title="notes for Upload " + str(u.datetime),
    content="This page is empty..."
)
page.save()
u.page = page
u.save()
</code>```

Body:
I'm working with Django 4.0.1.

I'm having having "save() prohibited to prevent data loss due to unsaved related object 'page'" even if the 'page' object is saved one line before.

Here is the code:

# Upload entity data
u = Upload(
    message=request.POST["upload_msg"]
)
# saving u here to be able to use u.datetime later
u.save()
# new page for the upload entity
page = Page(
    title="notes for Upload " + str(u.datetime),
    content="This page is empty..."
)
page.save()
u.page = page
u.save()

The last line (u.save()) is the one causing the error.
Am I having some kind of race condition here? Isn't it assured that the previous db operations are complete before trying to run the next?
Any other ideas?

Thank you.

UPDATE

I can see from the admin panel that the Upload and Page instance are both created correctly but the Upload instance does not have a Page id set.
Unless I'm misunderstanding the error message the Page instance does not result saved (or updated inside the python 'page' variable) when the last u.save() call is invoked. Any way to solve this?

UPDATE 2

Looks like this problem arises only if I explicitly define the primary key as follows:

id = models.IntegerField(primary_key=True, null=False)

Shouldn't this automatically create the entities' ids on .save()?

Body:
You're trying to call save() but not storing instance of it in u and use commit=False this will not hit database it will store instance in memory after your proccess is finished you can save it. check more info about save() method.

# Upload entity data
u = Upload(
    message=request.POST["upload_msg"]
)
# saving u here to be able to use u.datetime later
u = u.save(commit=False)
# new page for the upload entity
page = Page(
    title="notes for Upload " + str(u.datetime),
    content="This page is empty..."
)
page.save()
u.page = page
u.save()


问:
How to disable blueprint view on Android Studio permanently?
When editing layouts, my computer lags a lot when it shows both the Design and Blueprint views like so :

I can press that blue icon at the top left to disable Blueprint but I have to do it for every layout. Is there a way to permanently disable it for Android Studio?

答:
Yes, you can do this just click on blue print design and press 'B' button and it will hide and you want it again then press "B" again and again.
hope it works..</p>


答:
just use :

if you are using UITableViewCellStyleDefault then you don't need to customize the look of of tableviewcells.

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    // Configure the cell...

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }

cell.imageView.image=[UIImage imageNamed:@"ImageName.png"];
cell.textLabel.text=@"Text";
return cell;
}
</code>```

Title: UITableView image on the left hand side

Body:
Possible Duplicate:

  adding images to UItableView

I want to add image in UITableView in the left hand side how could I add it?

Body:
just use :

if you are using UITableViewCellStyleDefault then you don't need to customize the look of of tableviewcells.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    // Configure the cell...

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }

cell.imageView.image=[UIImage imageNamed:@"ImageName.png"];
cell.textLabel.text=@"Text";
return cell;
}


问:
Inter-column padding in Bootstrap 4 without side margins
I'm using Bootstrap 4.1. I'd like to have a grid of cells (Box A-E) with some spacing in between them. If I set padding on each column, I also get padding on the left and right side that breaks alignment with other elements; I would like Box A and Box D to align with the left edge of Top Box, for example.

The documentation talks about using a negative margin to offset this but I couldn't figure out where to put it.

The set of boxes is dynamic (there could be dozens) and I'd like to apply consistent styling to all of them, rather than make modifications to specific boxes.

I also want to avoid making modifications to Top Box, which is a stand-in for many existing UI elements in my real page that cannot easily be changed.

Here's a JSFiddle:
https://jsfiddle.net/u5094cjb/2/

body {
  margin: 1rem;
}

.box {
  border: 1px solid black;
  background-color: white;
  margin-bottom: 0.1rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>

<div class="container">

  <!-- ideally don't change this part -->
  <div class="row">
    <div class="col">
      <div class="box">Top Box</div>
    </div>
  </div>

  <!-- change this part only -->
  <div class="row">
    <div class="col">
      <div class="container">
        <div class="row">
          <div class="col-4 px-1">
            <div class="box">Box A</div>
          </div>
          <div class="col-4 px-1">
            <div class="box">Box B</div>
          </div>
          <div class="col-4 px-1">
            <div class="box">Box C</div>
          </div>
          <div class="col-4 px-1">
            <div class="box">Box D</div>
          </div>
          <div class="col-4 px-1">
            <div class="box">Box E</div>
          </div>
        </div>
      </div>
    </div>
  </div>

</div></code>```

答:
For what you're trying to accomplish it seems like you're using a bit "too much" code. I cleaned it up a bit so now that you only have two rows and added px-1 to your first col

body {
  margin: 1rem;
}

.box {
  border: 1px solid black;
  background-color: white;
  margin-bottom: 0.1rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<div class="container">
   <div class="row">
        <div class="col px-1">
            <div class="box">Top Box</div>
        </div>
    </div>
</div>
<div class="container">
    <div class="row">
        <div class="col-4 px-1">
            <div class="box">Box A</div>
        </div>
        <div class="col-4 px-1">
            <div class="box">Box B</div>
        </div>
        <div class="col-4 px-1">
            <div class="box">Box C</div>
        </div>
        <div class="col-4 px-1">
            <div class="box">Box D</div>
        </div>
        <div class="col-4 px-1">
            <div class="box">Box E</div>
        </div>
    </div>
</div></code>```

Body:
I'm using Bootstrap 4.1. I'd like to have a grid of cells (Box A-E) with some spacing in between them. If I set padding on each column, I also get padding on the left and right side that breaks alignment with other elements; I would like Box A and Box D to align with the left edge of Top Box, for example.

The documentation talks about using a negative margin to offset this but I couldn't figure out where to put it.

The set of boxes is dynamic (there could be dozens) and I'd like to apply consistent styling to all of them, rather than make modifications to specific boxes.

I also want to avoid making modifications to Top Box, which is a stand-in for many existing UI elements in my real page that cannot easily be changed.

Here's a JSFiddle:
https://jsfiddle.net/u5094cjb/2/

body {
  margin: 1rem;
}

.box {
  border: 1px solid black;
  background-color: white;
  margin-bottom: 0.1rem;
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

Top Box

Box A

Box B

Box C

Box D

Box E

Body:
For what you're trying to accomplish it seems like you're using a bit "too much" code. I cleaned it up a bit so now that you only have two rows and added px-1 to your first col

body {
  margin: 1rem;
}

.box {
  border: 1px solid black;
  background-color: white;
  margin-bottom: 0.1rem;
}

<head>
   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<div class="container">
   <div class="row">
        <div class="col px-1">
            <div class="box">Top Box</div>
        </div>
    </div>
</div>
<div class="container">
    <div class="row">
        <div class="col-4 px-1">
            <div class="box">Box A</div>
        </div>
        <div class="col-4 px-1">
            <div class="box">Box B</div>
        </div>
        <div class="col-4 px-1">
            <div class="box">Box C</div>
        </div>
        <div class="col-4 px-1">
            <div class="box">Box D</div>
        </div>
        <div class="col-4 px-1">
            <div class="box">Box E</div>
        </div>
    </div>
</div>


问:
Strapi v4 sanitizeEntity
I'm trying out the new strapi v4 right now (4.0.0) community edition. I've got a custom controller which queries for the current user and (in the future) fetches related objects.

When I did this with strapi v3 I used the built-in sanititzeEntitiy - helper function to remove sensitive fields from the user instance. In v4 however, this function appears to not exist anymore and I can't figure out how to achieve this.

Is there anyone that can help me with this? My code so far is:

module.exports = {
  currentUser: async(ctx, next) => {
    let user = ctx.state.user;
    // TODO: sanitize this
  }
}
```

In v3 I just did return sanitizeEntity(user); which would have the desired effect. I just can't figure out how to do this in v4 and I can't find anything related to that in the docs.

答:
So I simultaneously posted this question on the strapi community forums. A user named JustJerem got me an answer to this question which looks like this:

```<code>**const { sanitizeEntity } = require("strapi-utils/lib");**

module.exports = (plugin) => {

  plugin.controllers.user.deleteMe = async (ctx) => {
    const entity = await strapi.entityService.delete('plugin::users-permissions.user', user.id)
    var result = **sanitizeEntity(entity, { model: strapi.getModel('plugin::users-permissions.user') })**
    return result
  };
//...
};
</code>```

The original answer in the strapi forums can be found here:

https://forum.strapi.io/t/v4-0-0-sanitize-user-data/13326/4?u=derelektrischemoench

All credits to this solution go out to JustJerem on the strapi boards.
Doing it like this worked for me. Hopefully this can help someone else, too.

Greetings,
derelektrischemoench

Title: Strapi v4 sanitizeEntity

Body:
I'm trying out the new strapi v4 right now (4.0.0) community edition. I've got a custom controller which queries for the current user and (in the future) fetches related objects.

When I did this with strapi v3 I used the built-in sanititzeEntitiy - helper function to remove sensitive fields from the user instance. In v4 however, this function appears to not exist anymore and I can't figure out how to achieve this.

Is there anyone that can help me with this? My code so far is:

module.exports = {
  currentUser: async(ctx, next) => {
    let user = ctx.state.user;
    // TODO: sanitize this
  }
}

In v3 I just did return sanitizeEntity(user); which would have the desired effect. I just can't figure out how to do this in v4 and I can't find anything related to that in the docs.

Body:
So I simultaneously posted this question on the strapi community forums. A user named JustJerem got me an answer to this question which looks like this:

**const { sanitizeEntity } = require("strapi-utils/lib");**

module.exports = (plugin) => {

  plugin.controllers.user.deleteMe = async (ctx) => {
    const entity = await strapi.entityService.delete('plugin::users-permissions.user', user.id)
    var result = **sanitizeEntity(entity, { model: strapi.getModel('plugin::users-permissions.user') })**
    return result
  };
//...
};

The original answer in the strapi forums can be found here:

https://forum.strapi.io/t/v4-0-0-sanitize-user-data/13326/4?u=derelektrischemoench

All credits to this solution go out to JustJerem on the strapi boards.
Doing it like this worked for me. Hopefully this can help someone else, too.

Greetings,
derelektrischemoench


问:
Can I use std::next on user defined class
If I have a user-defined class :

```<code>class MyColl {
     int *data ;
     public :
     class Itr {
              int operator*() {}
              void operator++()
              bool operator != (const Itr &oth)
     } ;
     Itr begin() {}
     Itr end() {}
} ;
</code>```

Can I use std::next on objects of MyColl
If yes, then what needs to be done

答:
```<code>// How to implement a forward iterator for your collection class

template <typename T>
class MyCollection
{
public:

  struct MyCollectionIterator
  {
    // These five typedefs tell other things about your iterator

    using iterator_category = std::forward_iterator_tag;
    using value_type        = T;
    using difference_type   = std::ptrdiff_t;
    using pointer           = T*;
    using reference         = T&;

    explicit MyCollectionIterator( ... ) ... {}

    // These five methods implement the minimum required behavior of a forward iterator

    reference  operator *  () const {...}
    iterator & operator ++ ()       {...}
    iterator   operator ++ (int)    {...}

    bool operator == ( iterator that ) {...}
    bool operator != ( iterator that ) {...}
  };

  MyCollectionIterator begin() { return MyCollectionIterator(...); }
  MyCollectionIterator end()   { return MyCollectionIterator(...); }
};
</code>```

There are other iterator types beyond a forward iterator. If possible, you should implement the most capable iterator type you can: if not random access, then bidirectional, and if not bidirectional, then forward.

Iterators have been an increasingly frightening thing to look at in C++ (see docs here), but the basic idea is simply a class that knows how to pretend to be a pointer sufficient to access your collection’s data. To do that it must provide certain kinds of information and capabilities.

That little table of iterator types in the linked docs will help you when adding the required functionality to your iterator class.

Body:
If I have a user-defined class :

class MyColl {
     int *data ;
     public :
     class Itr {
              int operator*() {}
              void operator++()
              bool operator != (const Itr &oth)
     } ;
     Itr begin() {}
     Itr end() {}
} ;

Can I use std::next on objects of MyColl
If yes, then what needs to be done

Body:
// How to implement a forward iterator for your collection class

template <typename T>
class MyCollection
{
public:

  struct MyCollectionIterator
  {
    // These five typedefs tell other things about your iterator

    using iterator_category = std::forward_iterator_tag;
    using value_type        = T;
    using difference_type   = std::ptrdiff_t;
    using pointer           = T*;
    using reference         = T&;

    explicit MyCollectionIterator( ... ) ... {}

    // These five methods implement the minimum required behavior of a forward iterator

    reference  operator *  () const {...}
    iterator & operator ++ ()       {...}
    iterator   operator ++ (int)    {...}

    bool operator == ( iterator that ) {...}
    bool operator != ( iterator that ) {...}
  };

  MyCollectionIterator begin() { return MyCollectionIterator(...); }
  MyCollectionIterator end()   { return MyCollectionIterator(...); }
};

There are other iterator types beyond a forward iterator. If possible, you should implement the most capable iterator type you can: if not random access, then bidirectional, and if not bidirectional, then forward.

Iterators have been an increasingly frightening thing to look at in C++ (see docs here), but the basic idea is simply a class that knows how to pretend to be a pointer sufficient to access your collection’s data. To do that it must provide certain kinds of information and capabilities.

That little table of iterator types in the linked docs will help you when adding the required functionality to your iterator class.


问:
Getting Firefox's history
I am making a windows application to get a list of accessed website addresses of Firefox browser. I have no idea how to achieve this ? I am thinking accessing cache may be fine but computer cache contains more information than those I actually need. Would you please recommend a COM or method used to get this done ? I am grateful for your help.

Thank you.

答:
History is stored in a SQLLIte database and can be accessed using the API: https://developer.mozilla.org/en/Using_the_Places_history_service

See also: https://developer.mozilla.org/En/Places

Title: Getting Firefox's history