问:
How to close react-burger-menu when link click in a component?
i am working with negomi/react-burger-menu. i want to close my sidebar menu when a link is click not outside or cross button click just link click then my sidebar menu automatically close itself. But problem is my link is under another component , Suppose my component <ShipForMe/> and my link is under <ShipForMe/> like <NavLink to="/dashboard/ship-for-me/my-request/pending">My Request</NavLink>

Sidebar.js

```<code><div className="sidebar-wrap " id="outer-container">
                <div className="dashboard-menu rounded">
                    <ShipForMe/>
                    <MyWallet/>
                    <Profiles/>
                    <div className="sidebar-item ds-item">
                        <div className="sidebar-item__title">
                            <NavLink to="">VIP Center</NavLink>
                        </div>
                    </div>
                </div>
                <div className="dashboard-responsive rounded">
                    <Menu pageWrapId={ "page-wrap" } outerContainerId={ "outer-container" } isOpen={false}>
                            <div id="page-wrap" style={{marginTop: '-25%'}}>
                                <ShipForMe handleUrl={handleUrl}/>
                                <MyWallet/>
                                <Profiles/>
                                <div className="sidebar-item ds-item">
                                    <div className="sidebar-item__title">
                                        <NavLink to="">VIP Center</NavLink>
                                    </div>
                                </div>
                            </div>
                    </Menu>
                </div>
            </div>
</code>```

ShipForMe.js

```<code><div className="ship-wrap ds-item">
         <div className="sidebar-item">
            <div className="sidebar-item__title">
               Ship for me
            </div>
            <ul className="sidebar-item__lists">
               <li>
                  <NavLink to="/dashboard/ship-for-me/my-request/pending">My Request</NavLink>
               </li>
               <li>
                  <NavLink to="/dashboard/ship-for-me/forwarding-parcel/abroad-to-bd">My Forwarding Parcel</NavLink>
               </li>
            </ul>
         </div>
      </div>
</code>```

Note: isOpen{flase} is not working, it is only working when link is physical there.

答:
Have spent a lot of time fiddling with problem. One critical part of the solution is to pass the appropriate callback function as a prop to the < Menu > component:

```<code>onStateChange={handleStateChange}
</code>```

where handleStateChange is defined as:

```<code>const handleStateChange = (state) => {
  setMenuOpen(state.isOpen);
};
</code>```

where setMenuOpen is state setter as defined in:

```<code>const [isMenuOpen, setIsMenuOpen] = React.useState(false);
</code>```

you also need a handleCloseMenu function that calls your setter:

```<code>const handleCloseMenu = () => {
  setIsMenuOpen(false);
};
</code>```

you can then pass handleCloseMenu to an onclick of a button in your sidebar / burger menu.

all together you have:

```<code>const [isMenuOpen, setIsMenuOpen] = React.useState(false);
const handleCloseMenu = () => {
  setIsMenuOpen(false);
};
const handleStateChange = (state) => {
  setIsMenuOpen(state.isOpen);
};

return (
  <Menu isOpen={isMenuOpen} onStateChange={handleStateChange}>
     ... Link 1
     <button onClick = {()=>handleCloseMenu}/>
     ....
  </Menu>
)
</code>```

Here is a working sandbox example I found on the github repo:

And here is the github repo. There's an Issue posted about streamlining it further. But once you pass the correct callback, onStateChange={handleStateChange}, you should be good.

Body:
i am working with negomi/react-burger-menu. i want to close my sidebar menu when a link is click not outside or cross button click just link click then my sidebar menu automatically close itself. But problem is my link is under another component , Suppose my component <ShipForMe/> and my link is under <ShipForMe/> like <NavLink to="/dashboard/ship-for-me/my-request/pending">My Request</NavLink>

Sidebar.js

                    <ShipForMe/>
                    <MyWallet/>
                    <Profiles/>

                            <NavLink to="">VIP Center</NavLink>

                    <Menu pageWrapId={ "page-wrap" } outerContainerId={ "outer-container" } isOpen={false}>

                                <ShipForMe handleUrl={handleUrl}/>
                                <MyWallet/>
                                <Profiles/>

                                        <NavLink to="">VIP Center</NavLink>

                    </Menu>

ShipForMe.js

               Ship for me

                  <NavLink to="/dashboard/ship-for-me/my-request/pending">My Request</NavLink>

                  <NavLink to="/dashboard/ship-for-me/forwarding-parcel/abroad-to-bd">My Forwarding Parcel</NavLink>

Note: isOpen{flase} is not working, it is only working when link is physical there.

Body:
Have spent a lot of time fiddling with problem. One critical part of the solution is to pass the appropriate callback function as a prop to the < Menu > component:

onStateChange={handleStateChange}

where handleStateChange is defined as:

const handleStateChange = (state) => {
  setMenuOpen(state.isOpen);
};

where setMenuOpen is state setter as defined in:

const [isMenuOpen, setIsMenuOpen] = React.useState(false);

you also need a handleCloseMenu function that calls your setter:

const handleCloseMenu = () => {
  setIsMenuOpen(false);
};

you can then pass handleCloseMenu to an onclick of a button in your sidebar / burger menu.

all together you have:

const [isMenuOpen, setIsMenuOpen] = React.useState(false);
const handleCloseMenu = () => {
  setIsMenuOpen(false);
};
const handleStateChange = (state) => {
  setIsMenuOpen(state.isOpen);
};

return (
  <Menu isOpen={isMenuOpen} onStateChange={handleStateChange}>
     ... Link 1
     <button onClick = {()=>handleCloseMenu}/>
     ....
  </Menu>
)

Here is a working sandbox example I found on the github repo:

And here is the github repo. There's an Issue posted about streamlining it further. But once you pass the correct callback, onStateChange={handleStateChange}, you should be good.


来源: stackexchange

问:
Angular *ngFor Howto stack element tag with left and right on respective sides?
Expected left to be stacked top left and right top right

[Need to stack elements with name left in left side and right in right side
Using single *ngFor div/ ul /table any means .....
Sample play around provided below]
https://stackblitz.com/edit/ngfor-index-example-wntaie?file=app%2Fapp.component.html

答:
Try this

https://stackblitz.com/edit/ngfor-index-example-jkkeue?file=app/app.component.html

You had the right idea with using display: flex and flex-direction: row

I added a getter for leftCourses and rightCourses to clean up the code a bit.

ContentLicense: CC BY-SA 4.0


问:
How to apply different free trials for different recurring items in the same order - Stripe
Let's say I have 2 items in the order, and both items are subscriptions. I want to create a checkout session and give free trial for both subscriptions, but the period of free trial should be different for each subscription.

After checking the docs, I was able to set free trial to the whole order by specifying subscription_data.trial_period_days property on the order itself. But that will apply the same free trial to all subscriptions. I want to give a different free trial period to each subscription.

答:
The trial_peroid_days is a property you specify when creating a Subscription object, and it would apply to all line items in the subscription.

If you want to apply a different trial period for an item, you can create another subscription for that particular item with a different trial period.


问:
EF Core : migration failed, prompting that there is no TOOLS package
In my ASP.NET Core 3.1 project, I am using EF Core for code migration. But when I use the add-migration MyProject command to operate, I get an error.

Your startup project 'MyProject' doesn't reference Microsoft.EntityFrameworkCore.Design. This package is required for the Entity Framework Core Tools to work. Ensure your startup project is correct, install the package, and try again.

But I'm sure I downloaded the Entity Framework Core Tools package, I hope you can give me some advice, thank you.

答:
Can you show all your EFCORE dependencies?

I have a successful case of migration here, you can refer to：

Model:

```<code>public class TestModel
{

    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public string pwd { get; set; }
}
</code>```

DBContext:

```<code> public class TestContext: DbContext
    {
        public TestContext(DbContextOptions<TestContext> options) : base(options) { }
        public DbSet<TestModel> Users { get; set; }
    }
</code>```

appsettings.json:

```<code>  "ConnectionStrings": {
    "DefaultConnection": "your db"
  }
</code>```

Startup.cs:

```<code> public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<TestContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddControllersWithViews();
        }
</code>```

Here are the required dependencies：

```<code><Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.14">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.14" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.14">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>

</Project>
</code>```

Migration ：

Body:
Can you show all your EFCORE dependencies?

I have a successful case of migration here, you can refer to：

Model:

public class TestModel
{

    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public string pwd { get; set; }
}

DBContext:

 public class TestContext: DbContext
    {
        public TestContext(DbContextOptions<TestContext> options) : base(options) { }
        public DbSet<TestModel> Users { get; set; }
    }

appsettings.json:

  "ConnectionStrings": {
    "DefaultConnection": "your db"
  }

Startup.cs:

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<TestContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddControllersWithViews();
        }

Here are the required dependencies：

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.14">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.14" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.14">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>

</Project>

Migration ：


问:
how can I recommend a method in java?
how can I recommend a method in java? example, in this image
image

"System.out.println", there is a star in front of method "println", I don't know how to mark my customize method a star method?

答:
I don't think you can do so.
Why are there stars? The explanation is here:

Title: how can I recommend a method in java?


问:
Unusual way of using java constructor
At some part of the code that I've been working on I am tempted to use the constructor in an unusual way. The goal is to have minimal to none sensitive values inside string pool.

public class MyClass{
    private String mySafeString;

    public MyClass(char[] aCharArray, String salt) {
         this.mySafeString = Encrypt.encrypt(new String(aCharArray), salt);
    }

    public String getMySafeString(){
         return this.mySafeString;
    }
}

...
public static void main(String[] args){
    String salt = getSaltFromSomewhere();
    char[] someKey = new char[]{'c', 'x'};
    var myObject = new MyClass(someKey, salt);
    var encryptedSafeString = myObject.getMySafeString();
}
```

By creating the String object like that I am avoiding the value's presence inside the string pool. Thereby, intending to leave it to GC to perish the object.

However, I fail to find any resource that forbids the usage of constructor like the way I used it. I am keen to know if it is a bad practice in any way?

Could you please be so kind and advise me on my approach?

答:
The goal is to have minimal to none sensitive values inside string pool.

That's a non-goal.  Strings only get placed in the string pool if they are either compile time constants OR if some code explicitly calls String.intern to put them in the string pool.

Your real goal is to avoid leaving sensitive information somewhere in memory ... or in a swap file ... where a bad guy may be able to retrieve it.

However, I fail to find any resource that forbids the usage of constructor like the way I used it. I am keen to know if it is a bad practice in any way?

I doubt that you will find anything that forbids this1.

However, it is not clear from the code what it achieves and how you intend to use it.

Is it your intention that the "safe" string be decryptable or not?

If Yes, you have a big problem.  In order to decrypt, you need the decryption key in memory at some time.  If the cipher algorithm is symmetric, that means that salt is the decryption key.  But you have already put that onto the heap as a String object.  (Ooops!)

And if you avoid that oops, the next problem is that the bad guy will be able to reverse engineer getSaltFromSomewhere() or the equivalent that generates the decryption key in the case of an asymmetric cipher.  They may then be able to recover the key.  Note that in order to successfully decrypt, your application must be able to obtain the correct key ... in memory ... to do the decryption.

If No, then it strikes me that the "safe" string could actually be replaced with a cryptographic hash of the original string.  You don't necessarily need a salt for that.  And if you do need one, you don't need the seed to be generated securely.

Also, it is not sufficient to just use a char[] to avoid storing the unencrypted (etc) secret in a String.  The char[] is also in the heap.  So it is also imperative that you overwrite the char[] when you are finished with it.  A secret in a char[] or byte[] or Buffer, etc can be found just as easily as a secret in a String.

Finally, you probably should be doing a thorough risk assessment to decide whether the effort of protecting strings in the heap is actually going to be worth it.  What is the chance that the bad guys can get in to capture a heap dump?  If they can get in that way, can they intercept the secrets some other way; e.g. by surreptitiously replacing some of your Java app code, attaching a debugger, stealing keys out of config files, etc.

1 - Normal Java coding standards don't concern themselves with protecting secrets, and security standards don't concern themselves with Java style, etc issues.

In short, there is nothing wrong with the constructor per se, but the chances are that it doesn't solve the real problem.

Title: Unusual way of using java constructor

Body:
At some part of the code that I've been working on I am tempted to use the constructor in an unusual way. The goal is to have minimal to none sensitive values inside string pool.

public class MyClass{
    private String mySafeString;

    public MyClass(char[] aCharArray, String salt) {
         this.mySafeString = Encrypt.encrypt(new String(aCharArray), salt);
    }

    public String getMySafeString(){
         return this.mySafeString;
    }
}

...
public static void main(String[] args){
    String salt = getSaltFromSomewhere();
    char[] someKey = new char[]{'c', 'x'};
    var myObject = new MyClass(someKey, salt);
    var encryptedSafeString = myObject.getMySafeString();
}

By creating the String object like that I am avoiding the value's presence inside the string pool. Thereby, intending to leave it to GC to perish the object.

However, I fail to find any resource that forbids the usage of constructor like the way I used it. I am keen to know if it is a bad practice in any way?

Could you please be so kind and advise me on my approach?


问:
Cannot retrive UUID from RNTwilioPhone.calls after CallConnected was fired
I'm developing the React Native Android mobile apps with outbound calls feature,
at the current state, it is able to make an outbound call to PSTN but cannot hang up.
I tried to find the UUID after CallConnected according to the following quote, to use for RNCallKeep.endCall(uuid) , but still no luck.

Hi, you should see it in RNTwilioPhone.calls when CallConnected event is triggered.

Originally posted by @MrHertal in https://github.com/MrHertal/react-native-twilio-phone/issues/54#issuecomment-902481675

Event Listener

```<code>twilioPhoneEmitter.addListener(EventType.CallConnected, ({callSid}) => {
  console.log('CallConnected');
  console.log('callSid');
  console.log(callSid);
  console.log('RNTwilioPhone.calls');
  console.log(RNTwilioPhone.calls);
}),
</code>```

Console.log

```<code> LOG  CallConnected
 LOG  callSid
 LOG  CAfcd9ea923d640be2bf37b24ade18f642
 LOG  RNTwilioPhone.calls
 LOG  []
</code>```

Code snippet

```<code>const HandleHangUp = () => {
    RNCallKeep.endAllCalls(); // Not working
    navigate.goBack();
};

const callKeepOptions = {
    ios: {
        appName: 'TwilioPhone Example',
        supportsVideo: false,
    },
    android: {
        alertTitle: 'Permissions required',
        alertDescription: 'This application needs to access your phone accounts',
        cancelButton: 'Cancel',
        okButton: 'OK',
        additionalPermissions: [],
        selfManaged: true,
        foregroundService: {
            channelId: 'io.wazo.callkeep.VoiceConnectionService',
            channelName: 'Foreground service for my app',
            notificationTitle: 'My app is running on background',
        },
    },
};

useEffect(() => {
    const unsubscribeRNTTwilio = RNTwilioPhone.initializeCallKeep(callKeepOptions, fetchAccessToken);
    const unsubscribeTwilioPhone = listenTwilioPhone();
    RNTwilioPhone.startCall(userPhone);
    return () => {
        unsubscribeRNTTwilio();
        unsubscribeTwilioPhone();
    };
}, []);

const listenTwilioPhone = () => {
    const subscriptions = [
        twilioPhoneEmitter.addListener(EventType.CallConnected, ({callSid}) => {
            console.log('CallConnected');
            console.log('callSid');
            console.log(callSid);
            console.log('RNTwilioPhone.calls');
            console.log(RNTwilioPhone.calls);
        }),
        twilioPhoneEmitter.addListener(EventType.CallDisconnected, () => {
            console.log('CallDisconnected');
            setCallInProgress(RNTwilioPhone.calls.length > 0);
            navigate.goBack();
        }),
        twilioPhoneEmitter.addListener(EventType.CallDisconnectedError, (error) => {
            console.log('CallDisconnectedError');
            console.log(error);
            setCallInProgress(RNTwilioPhone.calls.length > 0);
            navigate.goBack();
        }),
    ];

    return () => {
        subscriptions.map((subscription) => {
            subscription.remove();
        });
    };
};
</code>```

答:
Twilio developer evangelist here.

While you do seem to be having a problem with the currently connected calls when calling RNTwilioPhone.calls that might not stop this working for you right now.

From what I can see in the source code, the TwilioPhone.endCall method takes the callSid as an argument. So, you should be able to keep the active callSid in the state and then use that to hang up.

So, you should keep callSid in state:

const [callSid, setCallSid] = useState(null);
```
<p>When a call is connected, set the <code>callSid</code> in the state.</p>
<pre class="lang-js prettyprint-override"><code>twilioPhoneEmitter.addListener(EventType.CallConnected, ({callSid}) => {
  setCallSid(callSid);
});

</code>```

And then when you want to hangup, use the callSid to end the call and set the state back to null:

const HandleHangUp = () => {
  TwilioPhone.endCall(callSid);
  setCallSid(null);
  navigate.goBack();
};
```

Body:
I'm developing the React Native Android mobile apps with outbound calls feature,
at the current state, it is able to make an outbound call to PSTN but cannot hang up.
I tried to find the UUID after CallConnected according to the following quote, to use for RNCallKeep.endCall(uuid) , but still no luck.

Hi, you should see it in RNTwilioPhone.calls when CallConnected event is triggered.

Originally posted by @MrHertal in https://github.com/MrHertal/react-native-twilio-phone/issues/54#issuecomment-902481675

Event Listener

twilioPhoneEmitter.addListener(EventType.CallConnected, ({callSid}) => {
  console.log('CallConnected');
  console.log('callSid');
  console.log(callSid);
  console.log('RNTwilioPhone.calls');
  console.log(RNTwilioPhone.calls);
}),

Console.log

 LOG  CallConnected
 LOG  callSid
 LOG  CAfcd9ea923d640be2bf37b24ade18f642
 LOG  RNTwilioPhone.calls
 LOG  []

Code snippet

const HandleHangUp = () => {
    RNCallKeep.endAllCalls(); // Not working
    navigate.goBack();
};

const callKeepOptions = {
    ios: {
        appName: 'TwilioPhone Example',
        supportsVideo: false,
    },
    android: {
        alertTitle: 'Permissions required',
        alertDescription: 'This application needs to access your phone accounts',
        cancelButton: 'Cancel',
        okButton: 'OK',
        additionalPermissions: [],
        selfManaged: true,
        foregroundService: {
            channelId: 'io.wazo.callkeep.VoiceConnectionService',
            channelName: 'Foreground service for my app',
            notificationTitle: 'My app is running on background',
        },
    },
};

useEffect(() => {
    const unsubscribeRNTTwilio = RNTwilioPhone.initializeCallKeep(callKeepOptions, fetchAccessToken);
    const unsubscribeTwilioPhone = listenTwilioPhone();
    RNTwilioPhone.startCall(userPhone);
    return () => {
        unsubscribeRNTTwilio();
        unsubscribeTwilioPhone();
    };
}, []);

const listenTwilioPhone = () => {
    const subscriptions = [
        twilioPhoneEmitter.addListener(EventType.CallConnected, ({callSid}) => {
            console.log('CallConnected');
            console.log('callSid');
            console.log(callSid);
            console.log('RNTwilioPhone.calls');
            console.log(RNTwilioPhone.calls);
        }),
        twilioPhoneEmitter.addListener(EventType.CallDisconnected, () => {
            console.log('CallDisconnected');
            setCallInProgress(RNTwilioPhone.calls.length > 0);
            navigate.goBack();
        }),
        twilioPhoneEmitter.addListener(EventType.CallDisconnectedError, (error) => {
            console.log('CallDisconnectedError');
            console.log(error);
            setCallInProgress(RNTwilioPhone.calls.length > 0);
            navigate.goBack();
        }),
    ];

    return () => {
        subscriptions.map((subscription) => {
            subscription.remove();
        });
    };
};

Body:
Twilio developer evangelist here.

While you do seem to be having a problem with the currently connected calls when calling RNTwilioPhone.calls that might not stop this working for you right now.

From what I can see in the source code, the TwilioPhone.endCall method takes the callSid as an argument. So, you should be able to keep the active callSid in the state and then use that to hang up.

So, you should keep callSid in state:

const [callSid, setCallSid] = useState(null);

When a call is connected, set the callSid in the state.

twilioPhoneEmitter.addListener(EventType.CallConnected, ({callSid}) => {
  setCallSid(callSid);
});

And then when you want to hangup, use the callSid to end the call and set the state back to null:

const HandleHangUp = () => {
  TwilioPhone.endCall(callSid);
  setCallSid(null);
  navigate.goBack();
};


问:
Is there a way to tell if the search bar is active with the .searchable modifier?
Given an example as below, I would like to be able to tell if the user has clicked the search bar and it is active. I'm wanting to do this for performance reasons, SwiftUI lists are horribly laggy when the first character is entered on a huge list (yes, I already know the .id(UUID()) trick, still laggy). I would like the list to be empty as soon as the search becomes active.

For the iPhone that would typically mean the keyboard is visible, but that's not reliable, the keyboard could be active for another reason or we could be on an iPad with a physical keyboard.

The EditMode has an environment variable to tell if the user is currently editing the list but I can't find anything similar for the search bar. Does something like that exist or is there a workaround to detect it?

```<code>import SwiftUI
import LoremSwiftum

let words = Lorem.words(50000).components(separatedBy: " ")

struct ContentView: View {

    @State var searchText = ""

    var searchedWords: [String] {
        //I would like something like !searchActive ? words : ...
        searchText.isEmpty ? [] : Array(words.filter { $0.localizedCaseInsensitiveContains(searchText) }.prefix(50))
    }

    var body: some View {
        NavigationView {
            List {
                ForEach(searchedWords.indices, id:\.self) { i in
                    Text(searchedWords[i])
                }
            }
            .id(UUID())
            .searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always))
        }
    }
}
</code>```

答: So the environment value is isSearching. Not exactly easy to use since the declaration of the property must be in a subview of the view that is searchable.</p>

Body:
Given an example as below, I would like to be able to tell if the user has clicked the search bar and it is active. I'm wanting to do this for performance reasons, SwiftUI lists are horribly laggy when the first character is entered on a huge list (yes, I already know the .id(UUID()) trick, still laggy). I would like the list to be empty as soon as the search becomes active.

For the iPhone that would typically mean the keyboard is visible, but that's not reliable, the keyboard could be active for another reason or we could be on an iPad with a physical keyboard.

The EditMode has an environment variable to tell if the user is currently editing the list but I can't find anything similar for the search bar. Does something like that exist or is there a workaround to detect it?

import SwiftUI
import LoremSwiftum

let words = Lorem.words(50000).components(separatedBy: " ")

struct ContentView: View {

    @State var searchText = ""

    var searchedWords: [String] {
        //I would like something like !searchActive ? words : ...
        searchText.isEmpty ? [] : Array(words.filter { $0.localizedCaseInsensitiveContains(searchText) }.prefix(50))
    }

    var body: some View {
        NavigationView {
            List {
                ForEach(searchedWords.indices, id:\.self) { i in
                    Text(searchedWords[i])
                }
            }
            .id(UUID())
            .searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always))
        }
    }
}


问:
404 Error Contact Form 7 ajax form submitting
The contact form does not work, and affects loading after one try. The chrome console shows the error message:

```<code>POST http://example.com/wp-json/contact-form-7/v1/contact-forms/50/feedback 404 (Not Found)
send @ jquery.js?ver=1.12.4:4
ajax @ jquery.js?ver=1.12.4:4
wpcf7.submit @ scripts.js?ver=5.0.3:346
(anonymous) @ scripts.js?ver=5.0.3:53
dispatch @ jquery.js?ver=1.12.4:3
r.handle @ jquery.js?ver=1.12.4:3
</code>```

How to solve this issue? thanks in advance

答:
downgraded to version 7.4.7
https://downloads.wordpress.org/plugin/contact-form-7.4.7.zip

kredit to https://wordpress.org/support/topic/wp-json-contact-form-7-v1-contact-forms-3453-feedback-404-not-found/

thank you so much ! to vesylivskyy (@vesylivskyy).

Body:
The contact form does not work, and affects loading after one try. The chrome console shows the error message:

POST http://example.com/wp-json/contact-form-7/v1/contact-forms/50/feedback 404 (Not Found)
send @ jquery.js?ver=1.12.4:4
ajax @ jquery.js?ver=1.12.4:4
wpcf7.submit @ scripts.js?ver=5.0.3:346
(anonymous) @ scripts.js?ver=5.0.3:53
dispatch @ jquery.js?ver=1.12.4:3
r.handle @ jquery.js?ver=1.12.4:3

How to solve this issue? thanks in advance


问:
React-Native another VirtualizedList-backed container
After upgrading to react-native 0.61 i get a lot of warnings like that:

```<code>VirtualizedLists should never be nested inside plain ScrollViews with the same orientation - use another VirtualizedList-backed container instead.
</code>```

What is the other VirtualizedList-backed container that i should use, and why is it now advised not to use like that?

答:
You can add horizontal=True and contentContainerStyle={{ width: '100%' }} to the ScrollView parent.

```<code><ScrollView
  style={styles.collaborators}
  contentContainerStyle={{ width: '100%' }} <--
  horizontal <--
>
  <FlatList
    data={list?.slice(0, 10) || []}
    keyExtractor={item => item.cc}
    ItemSeparatorComponent={Separator}
    renderItem={({ item }) => (
      <Collaborator name={item.name} cc={item.cc} />
    )}
  />
</ScrollView>
</code>```

Body:
After upgrading to react-native 0.61 i get a lot of warnings like that:

VirtualizedLists should never be nested inside plain ScrollViews with the same orientation - use another VirtualizedList-backed container instead.

What is the other VirtualizedList-backed container that i should use, and why is it now advised not to use like that?

Body:
You can add horizontal=True and contentContainerStyle={{ width: '100%' }} to the ScrollView parent.

<ScrollView
  style={styles.collaborators}
  contentContainerStyle={{ width: '100%' }} <--
  horizontal <--
>
  <FlatList
    data={list?.slice(0, 10) || []}
    keyExtractor={item => item.cc}
    ItemSeparatorComponent={Separator}
    renderItem={({ item }) => (
      <Collaborator name={item.name} cc={item.cc} />
    )}
  />
</ScrollView>


问:
How to iterate through the infinite Cartesian product of infinite generator functions in python?
I want a generator function product that generates the Cartesian product of any two given generator functions f and g (i.e. if x can found in f() in finite time and y can be found in g() in finite time, then (x,y) should be produced from product(f, g) in finite time).

For example, I might want a generator function to iterate through (x,y) satisfying x in itertools.count() and y in itertools.count(-1, -1).

What is a good way to do this? Any order is fine.

答:
Based on Gavin's earlier self-product solution, this progresses by expanding the "square" of visited pairs (if you imagine them laid out in 2D, one axis for the first generator and the other for the other).

```<code>from itertools import count, repeat

def product(f, g):
    for i, x, y in zip(count(), f(), g()):
        yield from zip(repeat(x, i), g())
        yield from zip(f(), repeat(y, i+1))
</code>```

Demo, the product of the positive ints and the negative ints:

```<code>for p in product(lambda: count(1), lambda: count(-1, -1)):
    print(p)
</code>```

Output (Try it online!):

```<code>(1, -1)
(2, -1)
(1, -2)
(2, -2)
(3, -1)
(3, -2)
(1, -3)
(2, -3)
(3, -3)
(4, -1)
(4, -2)
(4, -3)
(1, -4)
(2, -4)
(3, -4)
(4, -4)
(5, -1)
...
</code>```

Body:
Based on Gavin's earlier self-product solution, this progresses by expanding the "square" of visited pairs (if you imagine them laid out in 2D, one axis for the first generator and the other for the other).

from itertools import count, repeat

def product(f, g):
    for i, x, y in zip(count(), f(), g()):
        yield from zip(repeat(x, i), g())
        yield from zip(f(), repeat(y, i+1))

Demo, the product of the positive ints and the negative ints:

for p in product(lambda: count(1), lambda: count(-1, -1)):
    print(p)

Output (Try it online!):

(1, -1)
(2, -1)
(1, -2)
(2, -2)
(3, -1)
(3, -2)
(1, -3)
(2, -3)
(3, -3)
(4, -1)
(4, -2)
(4, -3)
(1, -4)
(2, -4)
(3, -4)
(4, -4)
(5, -1)
...


问:
Unexpected symbol 'dim' with a OLEDB connection
How do I fix this error? I'm using asp.net

Compilation Error

Description: Error compiling a resource required to service this request. Review your source file and modify it to fix this error.

Compiler Error Message: CS1519: Unexpected symbol `Dim' in class, struct, or interface member declaration

Source code:

```<code><%@ Import Namespace="System.Data.OleDb" %>

<script runat="server">
sub Page_Load
Dim dbconn As OleDbConnection
dbconn=New OleDbConnection("Provider=SQLOLEDB;
Data source='http://localhost';
User Id='90782';
Password='@ER#82L(*&!';")
dbconn.Open()
end sub
</script>
</code>```

PS: Double quote added, but this didn't fix the problem.

答: you have not closed your double quotes (")</p>

ContentLicense: CC BY-SA 3.0

Body:
How do I fix this error? I'm using asp.net

Compilation Error

Description: Error compiling a resource required to service this request. Review your source file and modify it to fix this error.

Compiler Error Message: CS1519: Unexpected symbol `Dim' in class, struct, or interface member declaration

Source code:

<%@ Import Namespace="System.Data.OleDb" %>

PS: Double quote added, but this didn't fix the problem.


问:
SwiftUI List: Prevent Empty Selection
I have a SwiftUI list, defined in a typical fashion:

```<code>struct SettingsView: View
{
    @State private var selectedCategory: SettingsCategory? = .general

    List(SettingsCategory.allCases, id: \.self, selection: $selectedCategory) { category in
        [...]
    }
}
</code>```

In this case, the List is a table of "categories" for a settings area in my UI. The SettingsCategory is an enum that defines these categories, and the UI ends up looking like this:

It is not appropriate for this list to have an empty selection; a category should always be selected. In AppKit, it was trivially easy to disable an empty selection on NSTableView. But in SwiftUI, I've been unable to find a way to disable it. Anytime I click in the empty area of the list, the selection is cleared. How can I stop that?

selectedCategory must be an Optional or the compiler vomits all over itself.

I can't use willSet/didSet on selectedCategory because of the @State property wrapper. And I can't use a computed property that never returns nil because the List's selection has to be bound.

I also tried this approach: SwiftUI DatePicker Binding optional Date, valid nil

So, what magical incantation is required to disable empty selection in List?

答:
One solution would be to set the selection back to the original one if the selection becomes nil.

Code:

```<code>struct ContentView: View {
    @State private var selectedCategory: SettingsCategory = .general

    var body: some View {
        NavigationView {
            SettingsView(selectedCategory: $selectedCategory)

            Text("Category: \(selectedCategory.rawValue.capitalized)")
                .navigationTitle("App")
        }
    }
}
</code>```
```<code>enum SettingsCategory: String, CaseIterable, Identifiable {
    case destination
    case general
    case speed
    case schedule
    case advanced
    case scripts

    var id: String { rawValue }
}
</code>```
```<code>struct SettingsView: View {
    @Binding private var selectedCategory: SettingsCategory
    @State private var selection: SettingsCategory?

    init(selectedCategory: Binding<SettingsCategory>) {
        _selectedCategory = Binding<SettingsCategory>(
            get: { selectedCategory.wrappedValue },
            set: { newCategory in
                selectedCategory.wrappedValue = newCategory
            }
        )
    }

    var body: some View {
        List(SettingsCategory.allCases, selection: $selection) { category in
            Text(category.rawValue.capitalized)
                .tag(category)
        }
        .onChange(of: selection) { [oldCategory = selection] newCategory in
            if let newCategory = newCategory {
                selection = newCategory
                selectedCategory = newCategory
            } else {
                selection = oldCategory
            }
        }
    }
}
</code>```

Title: SwiftUI List: Prevent Empty Selection

Body:
I have a SwiftUI list, defined in a typical fashion:

struct SettingsView: View
{
    @State private var selectedCategory: SettingsCategory? = .general

    List(SettingsCategory.allCases, id: \.self, selection: $selectedCategory) { category in
        [...]
    }
}

In this case, the List is a table of "categories" for a settings area in my UI. The SettingsCategory is an enum that defines these categories, and the UI ends up looking like this:

It is not appropriate for this list to have an empty selection; a category should always be selected. In AppKit, it was trivially easy to disable an empty selection on NSTableView. But in SwiftUI, I've been unable to find a way to disable it. Anytime I click in the empty area of the list, the selection is cleared. How can I stop that?

selectedCategory must be an Optional or the compiler vomits all over itself.

I can't use willSet/didSet on selectedCategory because of the @State property wrapper. And I can't use a computed property that never returns nil because the List's selection has to be bound.

I also tried this approach: SwiftUI DatePicker Binding optional Date, valid nil

So, what magical incantation is required to disable empty selection in List?

Body:
One solution would be to set the selection back to the original one if the selection becomes nil.

Code:

struct ContentView: View {
    @State private var selectedCategory: SettingsCategory = .general

    var body: some View {
        NavigationView {
            SettingsView(selectedCategory: $selectedCategory)

            Text("Category: \(selectedCategory.rawValue.capitalized)")
                .navigationTitle("App")
        }
    }
}

enum SettingsCategory: String, CaseIterable, Identifiable {
    case destination
    case general
    case speed
    case schedule
    case advanced
    case scripts

    var id: String { rawValue }
}

struct SettingsView: View {
    @Binding private var selectedCategory: SettingsCategory
    @State private var selection: SettingsCategory?

    init(selectedCategory: Binding<SettingsCategory>) {
        _selectedCategory = Binding<SettingsCategory>(
            get: { selectedCategory.wrappedValue },
            set: { newCategory in
                selectedCategory.wrappedValue = newCategory
            }
        )
    }

    var body: some View {
        List(SettingsCategory.allCases, selection: $selection) { category in
            Text(category.rawValue.capitalized)
                .tag(category)
        }
        .onChange(of: selection) { [oldCategory = selection] newCategory in
            if let newCategory = newCategory {
                selection = newCategory
                selectedCategory = newCategory
            } else {
                selection = oldCategory
            }
        }
    }
}


问:
Encrypting a string by replacing letters between two strings
I want to create a function which will receive two strings as parameters. One will be the the phrase to be encrypted and the other one will be some sort of index used to encrypt. The process is based on a alphabet 'abcdefghijklmnopqrstuvwxyz .'. Each letter in the first string will have its corresponding letter found in the second string. Its position number will determine which letter of 'abcdefghijklmnopqrstuvwxyz .' will be used at the result. For example:

```<code>>>> func('hello world', '. zyxwvutsrqponmlkjihgfedcba')
    'uxqqnbfnkqy'
</code>```

While searching, I found out some methods to do it, but they used external libraries. Is there a way to do it without them?

Thanks in advance for any help.

答:
Python's builtin translate() function does exactly what you want out of the box and it's orders of magnitude faster on larger strings than looping:

```<code>def f(s, key):
    alphabet = 'abcdefghijklmnopqrstuvwxyz .'
    trans = str.maketrans(alphabet, key)
    return s.translate(trans)

f('hello world', '. zyxwvutsrqponmlkjihgfedcba')
# 'uxqqnbfnkqy'
</code>```

You just need to make sure the alphabet and key code are the same length.

Body:
I want to create a function which will receive two strings as parameters. One will be the the phrase to be encrypted and the other one will be some sort of index used to encrypt. The process is based on a alphabet 'abcdefghijklmnopqrstuvwxyz .'. Each letter in the first string will have its corresponding letter found in the second string. Its position number will determine which letter of 'abcdefghijklmnopqrstuvwxyz .' will be used at the result. For example:

>>> func('hello world', '. zyxwvutsrqponmlkjihgfedcba')
    'uxqqnbfnkqy'

While searching, I found out some methods to do it, but they used external libraries. Is there a way to do it without them?

Thanks in advance for any help.

Body:
Python's builtin translate() function does exactly what you want out of the box and it's orders of magnitude faster on larger strings than looping:

def f(s, key):
    alphabet = 'abcdefghijklmnopqrstuvwxyz .'
    trans = str.maketrans(alphabet, key)
    return s.translate(trans)

f('hello world', '. zyxwvutsrqponmlkjihgfedcba')
# 'uxqqnbfnkqy'

You just need to make sure the alphabet and key code are the same length.


问:
Stripe.js detect user changes to element fields
I have a kiosk application where the kiosk software wraps a registration website where the user pays at the end of the process.

As with many of these types of applications, there is a need after a certain period of inactivity, to redirect to the starting page and/or clear user data.

Since stripe.js "elements" payments fields load in an iFrame, I am not able to detect changes and when users fumble for with typing in their cards (especially older users that are easily frustrated by technology), the system times out and sends them back to the beginning, losing not only their card input, but everything else they've done.   Obviously this causes a lot of hate and discontent.

The solution seemed to be easy, hook to the "change" event for the element (provided by stripe.js), however, it appears to only fire when some major payload change occurs (i.e. first digit or two of the card, anything in the postal field, nothing in the exp fields, and nothing in the CVV field).

Anyone come up another option to be notified when the user interacts with the element?  Seems like this would be a common use case that the developers have overlooked (or maybe I'm just not seeing the solution to).  If it provides other options, I'm using a UWP webview as my kiosk application software.

答:
have you tried registering events on the other elements? Stripe also provides a set of individual elements that you can integrate.

For instance, you can create a cardCvcElement and register a onChange listener to get notified for the cvc input events. See https://stripe.com/docs/js/element/events/on_change?type=cardCvcElement


问:
Issues I have with making a navbar in CSS
I tried adding a navbar, and I use this.

.topnav {
  background-color: rgb(0, 0, 0);
  overflow: hidden;
  width: 1920;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.topnav a {
  position: relative;
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 7px 16px;
  text-decoration: none;
  font-size: 17px;
  transition: .5s;
  border-radius: 30px;
}

.topnav a:hover {
  background-color: #b0fcbd;
  color: black;
  border-radius: 30px;
  padding: 7px 16px;
  opacity: 70%;
}

.topnav a.active {
  background-color: #21ff46;
  color: black;
  border-radius: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="topnav">
  Home
  News
  Contact
  About
</div></code>```

Yet, the navbar (the blackest part - the background is a bit lighter) starts out a few pixels below and to the right of when the page starts. Also, the Links are in the complete middle. I just want them centered at the top. Hope someone can help.

答:
To fix your positioning issue, just set margin: 0; on body.

To align the navbar items at the top, you can set align-items: start; on .topnav.

body {
  margin: 0;
}

.topnav {
  background-color: rgb(0, 0, 0);
  overflow: hidden;
  width: 1920;
  height: 200px;
  display: flex;
  align-items: start;
  justify-content: center;
}

.topnav a {
  position: relative;
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 7px 16px;
  text-decoration: none;
  font-size: 17px;
  transition: .5s;
  border-radius: 30px;
}

.topnav a:hover {
  background-color: #b0fcbd;
  color: black;
  border-radius: 30px;
  padding: 7px 16px;
  opacity: 70%;
}

.topnav a.active {
  background-color: #21ff46;
  color: black;
  border-radius: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="topnav">
  Home
  News
  Contact
  About
</div></code>```

Body:
I tried adding a navbar, and I use this.

.topnav {
  background-color: rgb(0, 0, 0);
  overflow: hidden;
  width: 1920;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.topnav a {
  position: relative;
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 7px 16px;
  text-decoration: none;
  font-size: 17px;
  transition: .5s;
  border-radius: 30px;
}

.topnav a:hover {
  background-color: #b0fcbd;
  color: black;
  border-radius: 30px;
  padding: 7px 16px;
  opacity: 70%;
}

.topnav a.active {
  background-color: #21ff46;
  color: black;
  border-radius: 30px;
}

  Home
  News
  Contact
  About

Yet, the navbar (the blackest part - the background is a bit lighter) starts out a few pixels below and to the right of when the page starts. Also, the Links are in the complete middle. I just want them centered at the top. Hope someone can help.

Body:
To fix your positioning issue, just set margin: 0; on body.

To align the navbar items at the top, you can set align-items: start; on .topnav.

body {
  margin: 0;
}

.topnav {
  background-color: rgb(0, 0, 0);
  overflow: hidden;
  width: 1920;
  height: 200px;
  display: flex;
  align-items: start;
  justify-content: center;
}

.topnav a {
  position: relative;
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 7px 16px;
  text-decoration: none;
  font-size: 17px;
  transition: .5s;
  border-radius: 30px;
}

.topnav a:hover {
  background-color: #b0fcbd;
  color: black;
  border-radius: 30px;
  padding: 7px 16px;
  opacity: 70%;
}

.topnav a.active {
  background-color: #21ff46;
  color: black;
  border-radius: 30px;
}

<div class="topnav">
  <a class="active" href="#home">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
  <a href="#about">About</a>
</div>


问:
How to create "read more" button for a text without having the text content?
I am building a website that fetches images from NASA's API. Now, I would like to add description to those images but I don't want all the description to be shown. Thus, I want to add a read more button/link to it. The text content(or description of the image) will change every day. And so I don't know at which word to put the button. Is there any way that I can put button after certain number of rows?

Any help or input is highly appreciated, thanks.

答:
You can store the full text content in a data attribute then display it once the button is clicked.

Just base whether or not there is a read more button on the length of the description string given back by the API.

```

Body:
You can store the full text content in a data attribute then display it once the button is clicked.

Just base whether or not there is a read more button on the length of the description string given back by the API.

<div id="main"></div>

<script>
    const main = document.querySelector('#main');

    const posts = [
        {
            image: 'https://www.mobiltech.cz/wp-content/uploads/2021/04/placeholder-2.png',
            description:
                'Long description lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tristique, augue ac feugiat venenatis, eros tortor fringilla leo, quis posuere dui lectus in velit. Suspendisse consectetur orci quis elit congue mollis. Cras eget lorem faucibus, dictum nisi eget, elementum velit. Integer imperdiet hendrerit velit, id porttitor nunc vestibulum vel. Integer ut congue lectus, id ullamcorper neque. Curabitur non pharetra urna, ac euismod magna. Proin sit amet mollis leo. Vestibulum in nunc sed mi feugiat pellentesque. Donec vel molestie lacus. Nam dictum imperdiet tortor pellentesque posuere. Nullam arcu nisl, rhoncus hendrerit condimentum et, bibendum porta sapien.',
        },
        {
            image: 'https://www.mobiltech.cz/wp-content/uploads/2021/04/placeholder-2.png',
            description: 'Short description.',
        },
        {
            image: 'https://www.mobiltech.cz/wp-content/uploads/2021/04/placeholder-2.png',
            description:
                'Medium description length. lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tristique, augue ac feugiat venenatis,',
        },
    ];

    const createPost = ({ image, description }) => {
        const div = document.createElement('div');

        const img = document.createElement('img');
        img.setAttribute('src', image);
        img.style.maxWidth = 200 + 'px';

        const text = document.createElement('p');

        div.appendChild(img);

        if (description.length > 50) {
            text.innerText = `${description.slice(0, 50)}...`;
            text.setAttribute('data-full', description);

            const btn = document.createElement('button');
            btn.innerText = 'Read more...';
            btn.setAttribute('onclick', 'displayPost(this)');

            div.appendChild(text);
            div.appendChild(btn);
            return div;
        }

        text.innerText = description;
        div.appendChild(text);
        return div;
    };

    posts.forEach((post) => {
        const element = createPost(post);
        main.appendChild(element);
    });

    const displayPost = (elem) => {
        elem.previousSibling.innerText = elem.previousSibling.getAttribute('data-full');
        elem.remove();
    };
</script>


答:
You need to add reset css to your page. Glad it help!

/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

#app {
 min-height: 100vh;
 width: 100vw;
 background: #0f1114;
}

.topnav {
  background-color: rgb(0, 0, 0);
  overflow: hidden;
  width: 1920;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.topnav a {
  position: relative;
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 7px 16px;
  text-decoration: none;
  font-size: 17px;
  transition: 0.5s;
  border-radius: 30px;
}

.topnav a:hover {
  background-color: #b0fcbd;
  color: black;
  border-radius: 30px;
  padding: 7px 16px;
  opacity: 70%;
}

.topnav a.active {
  background-color: #21ff46;
  color: black;
  border-radius: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="app">
  <div class="topnav">
    Home
    News
    Contact
    About
  </div>
</div></code>```

Title: Issues I have with making a navbar in CSS

Body:
You need to add reset css to your page. Glad it help!

/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

#app {
 min-height: 100vh;
 width: 100vw;
 background: #0f1114;
}

.topnav {
  background-color: rgb(0, 0, 0);
  overflow: hidden;
  width: 1920;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.topnav a {
  position: relative;
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 7px 16px;
  text-decoration: none;
  font-size: 17px;
  transition: 0.5s;
  border-radius: 30px;
}

.topnav a:hover {
  background-color: #b0fcbd;
  color: black;
  border-radius: 30px;
  padding: 7px 16px;
  opacity: 70%;
}

.topnav a.active {
  background-color: #21ff46;
  color: black;
  border-radius: 30px;
}

<div id="app">
  <div class="topnav">
    <a class="active" href="#home">Home</a>
    <a href="#news">News</a>
    <a href="#contact">Contact</a>
    <a href="#about">About</a>
  </div>
</div>


问:
laravel how to show one to many data in view (fetch ) in view
hello I'm trying to fetch one to many data in view like post with this feast comment shooed be show in view

iam able to get value in array now i what to show in view

my array controller

```<code>public function data($id)
{

 $post= User::with(['Comments'=>function($query){
    $query->first();
}])->find($id);

 dd($post->toArray());
</code>```

}

array data

```<code>array:53 [▼
  "id" => 39
  "name" => "KUMAR"
  "post" => "hello word "
  "created_at" => "2022-02-11T02:38:51.000000Z"
  "updated_at" => "2022-02-11T10:05:26.000000Z"
  "comments" => array:1 [▼
    0 => array:13 [▼
      "id" => 6
      "user_id" => "39"
      "comment" => "good post"
      "created_at" => "2022-02-11T15:13:51.000000Z"
      "updated_at" => "2022-02-11T15:13:51.000000Z"
    ]
  ]
]
</code>```

my view Controller

```<code>public function data($id)
{

 $post= User::with(['Comments'=>function($query){
    $query->first();
}])->find($id);

 return view('user.post',compact('post'));
</code>```

}

答:
Try this</p>
```<code>public function data($id)
{

 $post= User::wherehas('Comments', function($query){
    $query->where('user_id',$id);
})->get();

 return view('user.post',compact('post'));
}
</code>```

Body:
hello I'm trying to fetch one to many data in view like post with this feast comment shooed be show in view

iam able to get value in array now i what to show in view

my array controller

public function data($id)
{

 $post= User::with(['Comments'=>function($query){
    $query->first();
}])->find($id);

 dd($post->toArray());

}

array data

array:53 [▼
  "id" => 39
  "name" => "KUMAR"
  "post" => "hello word "
  "created_at" => "2022-02-11T02:38:51.000000Z"
  "updated_at" => "2022-02-11T10:05:26.000000Z"
  "comments" => array:1 [▼
    0 => array:13 [▼
      "id" => 6
      "user_id" => "39"
      "comment" => "good post"
      "created_at" => "2022-02-11T15:13:51.000000Z"
      "updated_at" => "2022-02-11T15:13:51.000000Z"
    ]
  ]
]

my view Controller

public function data($id)
{

 $post= User::with(['Comments'=>function($query){
    $query->first();
}])->find($id);

 return view('user.post',compact('post'));

}

Body:
Try this

public function data($id)
{

 $post= User::wherehas('Comments', function($query){
    $query->where('user_id',$id);
})->get();

 return view('user.post',compact('post'));
}


问:
Is deleting old branches in Git submodules safe w.r.t. usable history of 'supermodules'?
If I use a workflow like this:

app_repo and app2_repo have a common submodule, library_repo.

In library_repo, I make a library_feature branch to work on a new feature while leaving master stable.

app2_repo needs the new feature, so I track the submodule development in it (i.e. I update the submodule reference as commits are made to library_repo).  In tandem to this, changes are being made to the app2_repo source too (the app is under development also).

After the feature is finished, I merge the library_feature branch in library_repo back into  library_repo's master branch.

Deveopment continues, with app2_repo now inluding library_repo's master again.

I delete library_repo's library_feature branch, now that the history is merged into master, to keep things 'clean'.

Have I just lost the ability to check out historic app2_repo SHAs and have 'submodule update' update correctly with the relevant historical commits from library_repo, because I deleted the library_feature branch that they were in, or will all the relevent commits still be there, because the history is now shared with master now it's merged?

答:
All the relevant commits will still be there.

When you create a commit with a submodule at a particular version, the only information stored in the tree of the "supermodule" is the object name (i.e. SHA1sum) of the commit that the submodule should be at.  So, deleting the branch once it's been merged into master will make no difference - all your old commits in the supermodule will point to the object names of commits that are still in the history of master in the submodule.

If you had deleted a branch which isn't merged into some other branch, the unmerged commits on that branch would eventually be garbage collected and that might create the problem you're worried about, but you've explicitly said here that everything was merged before deleting the branch.


问:
How to use JFXBadge
I'm developing a Java application, with a GUI based on JavaFX and JFoenix. Based on information from the database, I want to add a badge showing the number of issues I have with data from the database (looks like number of unread messages in a mail application).

I have been looking for hours to find an example showing me how to use JFXbadge, but did not find anything. Is there anybody who can give me an example in FXML ?

答:
I scoured the intarwebs and this is the only one I found ...but basically you use it like a Pane.

<JFXBadge fx:id="badge1" position="TOP_RIGHT" text="1" styleClass="icons-badge">
  <StackPane style="-fx-padding: 10;">
    <FontAwesomeIconView glyphName="STAR" size="2em" styleClass="icon"/>
  </StackPane>
</JFXBadge>
```

The catch here is that it seems that the the library is not loading its .css stylesheets by default...at least for the JFXBadge.  so in the above example icons-badge is not going to be resolved unless you "load" the corresponding stylesheet css by specifying stylesheets attribute or assign the css definition in style attribute.

Title: How to use JFXBadge

Body:
I scoured the intarwebs and this is the only one I found ...but basically you use it like a Pane.

<JFXBadge fx:id="badge1" position="TOP_RIGHT" text="1" styleClass="icons-badge">
  <StackPane style="-fx-padding: 10;">
    <FontAwesomeIconView glyphName="STAR" size="2em" styleClass="icon"/>
  </StackPane>
</JFXBadge>

The catch here is that it seems that the the library is not loading its .css stylesheets by default...at least for the JFXBadge.  so in the above example icons-badge is not going to be resolved unless you "load" the corresponding stylesheet css by specifying stylesheets attribute or assign the css definition in style attribute.


问:
How can I dynamically generate pytest parametrized fixtures from imported helper methods?
What I want to achieve is basically this but with a class scoped, parametrized fixture.

The problem is that if I import the methods (generate_fixture and inject_fixture) from a helper file the inject fixture code seems to be getting called too late. Here is a complete, working code sample:

# all of the code in one file
import pytest
import pytest_check as check

def generate_fixture(params):
    @pytest.fixture(scope='class', params=params)
    def my_fixture(request, session):
        request.cls.param = request.param
        print(params)

    return my_fixture

def inject_fixture(name, someparam):
    globals()[name] = generate_fixture(someparam)

inject_fixture('myFixture', 'cheese')

@pytest.mark.usefixtures('myFixture')
class TestParkingInRadius:

    def test_custom_fixture(self):
        check.equal(True, self.param, 'Sandwhich')
```
<p>If I move the generate and inject helpers into their own file (without changing them at all) I get a fixture not found error i.e. if the test file looks like this instead:</p>
<pre class="lang-py prettyprint-override"><code>import pytest
import pytest_check as check

from .helpers import inject_fixture

inject_fixture('myFixture', 'cheese')

@pytest.mark.usefixtures('myFixture')
class TestParkingInRadius:

    def test_custom_fixture(self):
        check.equal(True, self.param, 'Sandwhich')

</code>```

The I get an error at setup: E fixture 'myFixture' not found followed by a list of available fixtures (which doesn't include the injected fixture).

Could someone help explain why this is happening? Having to define those functions in every single test file sort of defeats the whole point of doing this (keeping things DRY).

答:
I figured out the problem.

Placing the inject fixture method in a different file changes the global scope of that method. The reason it works inside the same file is both the caller and inject fixture method share the same global scope.

Using the native inspect package and getting the scope of the caller solved the issue, here it is with full boiler plate working code including class introspection via the built in request fixture:

import inspect
import pytest

def generate_fixture(scope, params):
    @pytest.fixture(scope=scope, params=params)
    def my_fixture(request):
        request.cls.param = request.param
        print(request.param)

    return my_fixture

def inject_fixture(name, scope, params):
    """Dynamically inject a fixture at runtime"""
    # we need the caller's global scope for this hack to work hence the use of the inspect module
    caller_globals = inspect.stack()[1][0].f_globals
    # for an explanation of this trick and why it works go here: https://github.com/pytest-dev/pytest/issues/2424
    caller_globals[name] = generate_fixture(scope, params)
```

Body:
What I want to achieve is basically this but with a class scoped, parametrized fixture.

The problem is that if I import the methods (generate_fixture and inject_fixture) from a helper file the inject fixture code seems to be getting called too late. Here is a complete, working code sample:

# all of the code in one file
import pytest
import pytest_check as check

def generate_fixture(params):
    @pytest.fixture(scope='class', params=params)
    def my_fixture(request, session):
        request.cls.param = request.param
        print(params)

    return my_fixture

def inject_fixture(name, someparam):
    globals()[name] = generate_fixture(someparam)

inject_fixture('myFixture', 'cheese')

@pytest.mark.usefixtures('myFixture')
class TestParkingInRadius:

    def test_custom_fixture(self):
        check.equal(True, self.param, 'Sandwhich')

If I move the generate and inject helpers into their own file (without changing them at all) I get a fixture not found error i.e. if the test file looks like this instead:

import pytest
import pytest_check as check

from .helpers import inject_fixture

inject_fixture('myFixture', 'cheese')

@pytest.mark.usefixtures('myFixture')
class TestParkingInRadius:

    def test_custom_fixture(self):
        check.equal(True, self.param, 'Sandwhich')

The I get an error at setup: E fixture 'myFixture' not found followed by a list of available fixtures (which doesn't include the injected fixture).

Could someone help explain why this is happening? Having to define those functions in every single test file sort of defeats the whole point of doing this (keeping things DRY).


问:
How to connect to a Mongo Standalone ReplicaSet, running in Docker, with Mongoose 6.0.8?
Connecting to a MongoDB (with ReplicaSet) running in Docker worked in 5.13.9 but fails in 6.0.8

docker-compose.yml for the database:

This is the docker-compose.yml file for the Database:

version: '3.9'

services:

  loggerdb:
    image: mongo
    container_name: loggerdb
    command: ["--replSet", "rs0", "--bind_ip_all", ]
    restart: always
    ports:
      - "27017:27017"
    volumes:
      - ./data:/data/db
    environment:
      MONGO_INITDB_DATABASE: logger

networks:
  default:
    external: true
    name: logger-network
```
<p>As you see, there is no Authentication and the database is listening to 27017 on localhost.</p>
<p>The database is running in the Docker Container:</p>
<pre class="lang-sh prettyprint-override"><code>$ docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED       STATUS       PORTS                                           NAMES
b42adb1e26ec   0bcbeb494bed   "docker-entrypoint.s…"   3 hours ago   Up 3 hours   0.0.0.0:27017->27017/tcp, :::27017->27017/tcp   loggerdb
</code>```

Code to connect (5.13.9)

The code is in Typescript, and for the version 5.13.9 Mongoose I use the following:

mongoose.connect('mongodb://localhost:27017/logger', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
        app.listen(PORT, () => {
            console.log(`Listening on ${PORT} for Log Messages`);
        });
    });
```
<p>It is necessary to specify useNewUrlParser and useUnifiedTopology here, otherwise you'll get an error.</p>
<p>The result is that this is working correctly. The program is connecting to the database and I can write stuff to it.</p>
<h3>Code to connect (6.0.8)</h3>
<p>The code for 6.0.8 is slightly different:</p>
<pre class="lang-js prettyprint-override"><code>mongoose.connect('mongodb://localhost:27017/logger?replicaSet=rs0')
    .then(() => {
        app.listen(PORT, () => {
            console.log(`Listening on ${PORT} for Log Messages`);
        });
    });
</code>```

The useNewUrlParser and useUnifiedTopology are obsolete now, and the docs show you need to specify the ReplicaSet as a param.

The result of connecting with this code to 6.0.8 Mongoose is as follows:

[INFO] 14:33:33 ts-node-dev ver. 1.1.8 (using ts-node ver. 9.1.1, typescript ver. 4.3.5)
MongooseServerSelectionError: getaddrinfo ENOTFOUND b42adb1e26ec
   [[ Removed the StackTrace ]]
[ERROR] 14:34:05 MongooseServerSelectionError: getaddrinfo ENOTFOUND b42adb1e26ec
```

Question

What is the correct to connect to a Mongo Standalone ReplicaSet, running in Docker, with Mongoose 6.0.8 ?

答:
I had this exact problem when trying to connect to a single node replica set inside docker from localhost (I was also upgrading mongoose from v5 to v6.)

I solved the issue by changing my connection string from

mongodb://admin:pass@127.0.0.1:27017/testdb

to

mongodb://admin:pass@127.0.0.1:27017/testdb?directConnection=true

It looks like mongoose is forcefully using the docker hostname which would only work if your code was running inside of docker.

directConnection - Specifies whether to force dispatch all operations to the host specified in the connection URI.

Body:
Connecting to a MongoDB (with ReplicaSet) running in Docker worked in 5.13.9 but fails in 6.0.8

docker-compose.yml for the database:

This is the docker-compose.yml file for the Database:

version: '3.9'

services:

  loggerdb:
    image: mongo
    container_name: loggerdb
    command: ["--replSet", "rs0", "--bind_ip_all", ]
    restart: always
    ports:
      - "27017:27017"
    volumes:
      - ./data:/data/db
    environment:
      MONGO_INITDB_DATABASE: logger

networks:
  default:
    external: true
    name: logger-network

As you see, there is no Authentication and the database is listening to 27017 on localhost.

The database is running in the Docker Container:

$ docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED       STATUS       PORTS                                           NAMES
b42adb1e26ec   0bcbeb494bed   "docker-entrypoint.s…"   3 hours ago   Up 3 hours   0.0.0.0:27017->27017/tcp, :::27017->27017/tcp   loggerdb

Code to connect (5.13.9)

The code is in Typescript, and for the version 5.13.9 Mongoose I use the following:

mongoose.connect('mongodb://localhost:27017/logger', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
        app.listen(PORT, () => {
            console.log(`Listening on ${PORT} for Log Messages`);
        });
    });

It is necessary to specify useNewUrlParser and useUnifiedTopology here, otherwise you'll get an error.

The result is that this is working correctly. The program is connecting to the database and I can write stuff to it.

Code to connect (6.0.8)

The code for 6.0.8 is slightly different:

mongoose.connect('mongodb://localhost:27017/logger?replicaSet=rs0')
    .then(() => {
        app.listen(PORT, () => {
            console.log(`Listening on ${PORT} for Log Messages`);
        });
    });

The useNewUrlParser and useUnifiedTopology are obsolete now, and the docs show you need to specify the ReplicaSet as a param.

The result of connecting with this code to 6.0.8 Mongoose is as follows:

[INFO] 14:33:33 ts-node-dev ver. 1.1.8 (using ts-node ver. 9.1.1, typescript ver. 4.3.5)
MongooseServerSelectionError: getaddrinfo ENOTFOUND b42adb1e26ec
   [[ Removed the StackTrace ]]
[ERROR] 14:34:05 MongooseServerSelectionError: getaddrinfo ENOTFOUND b42adb1e26ec

Question

What is the correct to connect to a Mongo Standalone ReplicaSet, running in Docker, with Mongoose 6.0.8 ?


问:
Align input text fields in R Shiny
I have multiple text input fields that I would like to display in 2 columns. My basic example uses, splitLayout to do this.

The names of each text input field (ie, AAA, BBBBBBB...) are fixed and known in advance. I would like:

The text input fields themselves to align

The second column of text input fields to be closer to the first column

More space between the first and second row

Something close to:

How can that be done in R Shiny?

Basic Example

```<code># Form fields displayed in two columns with Shiny

library("shiny")
library("shinydashboard")

ui <- fluidRow(
  box(width = 12, title = "Here is a Title",
      splitLayout(
        textInput("a", "AAA"),
        textInput("b", "BBBBBBB")
      ),
      splitLayout(
        textInput("c", "CCCCCCCCC"),
        textInput("d", "SSSSSSSSS")
      )
  )
)

server <- function(input, output) {
}

shinyApp(ui, server)
</code>```

答:
You can use tags$table.

library("shiny")
library("shinydashboard")

ui <- fluidRow(
  box(width = 12, title = "Here is a Title",
    tags$table(
      tags$tr(
        tags$td("AAA"),
        tags$td(textInput("a", NULL)),
        tags$td("BBBBBBB"),
        tags$td(textInput("b", NULL))
      ),
      tags$tr(
        tags$td("CCCCCCCCC"),
        tags$td(textInput("c", NULL)),
        tags$td("SSSSSSSSS"),
        tags$td(textInput("d", NULL))
      )
    )
  )
)

server <- function(input, output) {
}

shinyApp(ui, server)
```

Title: Align input text fields in R Shiny

Body:
I have multiple text input fields that I would like to display in 2 columns. My basic example uses, splitLayout to do this.

The names of each text input field (ie, AAA, BBBBBBB...) are fixed and known in advance. I would like:

The text input fields themselves to align

The second column of text input fields to be closer to the first column

More space between the first and second row

Something close to:

How can that be done in R Shiny?

Basic Example

# Form fields displayed in two columns with Shiny

library("shiny")
library("shinydashboard")

ui <- fluidRow(
  box(width = 12, title = "Here is a Title",
      splitLayout(
        textInput("a", "AAA"),
        textInput("b", "BBBBBBB")
      ),
      splitLayout(
        textInput("c", "CCCCCCCCC"),
        textInput("d", "SSSSSSSSS")
      )
  )
)

server <- function(input, output) {
}

shinyApp(ui, server)


问:
How to see several lines under one grep line
I want to see the logs where log level is ERROR
and I want to see the stackTrace
but when I input like below
cat app.log | grep ERROR
I can't see the stackTrace
Is there a way to see several lines under the greped line?

答:
```<code>grep -A 3 app.log
</code>```

-A 3 ("after") prints matching line, and 3 more below (4 lines total)

-B 3 ("before") prints matching line, and 3 more before (4 lines total)

-C 3 ("context") prints matching line, and 3 above and 3 below (7 lines total)

Body:
grep -A 3 app.log

-A 3 ("after") prints matching line, and 3 more below (4 lines total)

-B 3 ("before") prints matching line, and 3 more before (4 lines total)

-C 3 ("context") prints matching line, and 3 above and 3 below (7 lines total)


问:
faster way for moving large amounts data in oracle to external database
I have a java program that compares and moves data from a local Oracle database to an external MS SQL data base hosted by an online vendor.

Currently the program connects to the MS SQL database doing a SELECT * FROM myTABLE and putting the results in a two-dimensional array.  A temp table is then created in Oracle and the data is inserted into the temp table using a for loop:

```<code>for (int ii = 0; ii < arr.length(); ii++){
    query = "insert into myTable_temp values "+values_from_array;
    stmt.executeQuery();
}
</code>```

A MINUS statement is used find the differences:

```<code>query = "select * from ora_table minus select * from myTable_temp";
rs = stmt.executeQuery();
</code>```

and the result is then inserted back into the MS SQL table using a insert_into_mssql() method:

```<code>while (rs.next()){
    query = "insert into myTable values "+ values_from_rs
    insert_into_mssql(query);
}
</code>```

This works fine except a table I am using has 220,000 rows.  So it takes a long time to load the array, insert into temp table, run the minus statement, then insert everything back into the mssql table.

Is there a more efficient way to do this? or a way to make this faster?
(a dblink or any direct connection wont work bc of security restrictions)

答: Yes, What version of MS SQL Server are you using? Depending on that, you can look into SSIS or other DTS software. It allows you to do excactly what you want very quickly.</p>

Body:
I have a java program that compares and moves data from a local Oracle database to an external MS SQL data base hosted by an online vendor.

Currently the program connects to the MS SQL database doing a SELECT * FROM myTABLE and putting the results in a two-dimensional array.  A temp table is then created in Oracle and the data is inserted into the temp table using a for loop:

for (int ii = 0; ii < arr.length(); ii++){
    query = "insert into myTable_temp values "+values_from_array;
    stmt.executeQuery();
}

A MINUS statement is used find the differences:

query = "select * from ora_table minus select * from myTable_temp";
rs = stmt.executeQuery();

and the result is then inserted back into the MS SQL table using a insert_into_mssql() method:

while (rs.next()){
    query = "insert into myTable values "+ values_from_rs
    insert_into_mssql(query);
}

This works fine except a table I am using has 220,000 rows.  So it takes a long time to load the array, insert into temp table, run the minus statement, then insert everything back into the mssql table.

Is there a more efficient way to do this? or a way to make this faster?
(a dblink or any direct connection wont work bc of security restrictions)


问:
Understanding const reference returned from a function
I have a function

```<code>const std::string& getRecordingJobToken() { return getToken(); }
const std::string& getToken() const { return m_Token;  }
std::string m_Token;
</code>```

I am able to call it as below

```<code>const std::string jobToken = getRecordingJobToken();
</code>```

However when I do this,

```<code>const std::string jobToken;
jobToken = getRecordingJobToken();
</code>```

It throws me this error -

error: passing ‘const string’ {aka ‘const std::__cxx11::basic_string’} as ‘this’ argument discards qualifiers [-fpermissive]

What is the difference ?
I know that a reference variable has to be initialized immediately.

std::string &ref = a;

Is it some similiar logic ? The reason i am confused is that though getRecordingJobToken() returns a const reference, the variable jobToken that I have is not a reference variable. It is a variable that is used to take a string reference being returned from the getRecordingJobToken() function.

答:
I am able to call it as below

const std::string jobToken = getRecordingJobToken();
```
<p>However when I do this,</p>
<pre class="lang-cpp prettyprint-override"><code>const std::string jobToken;
jobToken = getRecordingJobToken();
</code>```

error ...

Yes, you can initialize a const object (which is what you do in the first example), but you can't assign to it/change it afterwards (which is what you try doing in the second example).

Note that you don't have to though. The function getRecordingJobToken() returns a const std::string& which is "cheap" with regards to resources. It's just a refrence to an internal std::string that the class or function keeps - but doesn't let anyone modify from the outside. If you only need to read the value, take it by const reference instead:

```<code>const std::string& jobToken = getRecordingJobToken();
</code>```

If you on the other hand would like to modify the returned value, take it by value (and get a copy of whatever is returned). Your jobToken does not need to be const in this situation:

```<code>std::string jobToken = getRecordingJobToken();
jobToken += "foo"; // ok now since it's not `const`
</code>```

Body:
I have a function

const std::string& getRecordingJobToken() { return getToken(); }
const std::string& getToken() const { return m_Token;  }
std::string m_Token;

I am able to call it as below

const std::string jobToken = getRecordingJobToken();

However when I do this,

const std::string jobToken;
jobToken = getRecordingJobToken();

It throws me this error -

error: passing ‘const string’ {aka ‘const std::__cxx11::basic_string’} as ‘this’ argument discards qualifiers [-fpermissive]

What is the difference ?
I know that a reference variable has to be initialized immediately.

std::string &ref = a;

Is it some similiar logic ? The reason i am confused is that though getRecordingJobToken() returns a const reference, the variable jobToken that I have is not a reference variable. It is a variable that is used to take a string reference being returned from the getRecordingJobToken() function.

Body:
I am able to call it as below

const std::string jobToken = getRecordingJobToken();

However when I do this,

const std::string jobToken;
jobToken = getRecordingJobToken();

error ...

Yes, you can initialize a const object (which is what you do in the first example), but you can't assign to it/change it afterwards (which is what you try doing in the second example).

Note that you don't have to though. The function getRecordingJobToken() returns a const std::string& which is "cheap" with regards to resources. It's just a refrence to an internal std::string that the class or function keeps - but doesn't let anyone modify from the outside. If you only need to read the value, take it by const reference instead:

const std::string& jobToken = getRecordingJobToken();

If you on the other hand would like to modify the returned value, take it by value (and get a copy of whatever is returned). Your jobToken does not need to be const in this situation:

std::string jobToken = getRecordingJobToken();
jobToken += "foo"; // ok now since it's not `const`