问:
Actionscript 2: Event Cue Points: findNearestCuePoint
Hello everyone and anyone!

Ok... I have been banging my head against the wall with this issue for literally weeks, but I still cannot find an answer that has successfully resolved the issue.

I created an FLA and placed a FLV component with the instance name of videoPlay on the stage.

videoPlay is pathed to a streaming FLV with embedded event cue points. The cue points are numbered sequentially from narration1 to narration16.

I established a listener object:

```<code>     var videoPlayCuePointListener:Object = new Object();
</code>```

The event listener for the cue points:

```<code>   videoPlayCuePointListener.cuePoint = function(eventObject:Object):Void{
   if(eventObject.info.name == "narration1"){_root.cc_box.cc_txt.htmlText = cueTxt1);}
   else if(eventObject.info.name == "narration2"){_root.cc_box.cc_txt.htmlText = cueTxt2);}
   etc, through narration16 }
</code>```

and so on through narration16.

Then I attached the event listener to the FLV component on stage:

```<code>   videoPlay.addEventListener("cuePoint", videoPlayCuePointListener);
</code>```

All of this works very well. As the FLV plays, each event cue point fires off the correct text to the cc_txt dynamic text box.

The issue I am having is that I cannot find the nearest cue point to the FLV playhead so that I can fire events when the user scrubs the timeline.

I have researched this as thoroughly as I possibly could before finally deciding to post the issue, but although the documentation and various postings regarding findNearestCuePoint discovered throughout the web have provided numerous examples, not a single one has been successful.

I have attempted to add a listener to videoPlay that creates an object (nearestCue) and gives nearestCue the value of videoPlay.findNearestCuePoint(videoPlay.playheadTime), then read out nearestCue's name, label, etc. No dice.

Nothing suggested in any posts I have reviewed (many, many posts) has provided an answer.

This seems like it would be the easiest thing to accomplish but I have not been successful a single time.

Any suggestions or assistance would be much appreciated.

Thank you for your time!

答:
George,

I believe I discovered the issue, and I think it was something that you covered in your previous post, but I glossed over it by accident.

The F4V I was working with had the cue points embedded using Adobe Media Encoder... and that was the entire issue.

I went back and exported the cue points out to XML, then stripped them out of the F4V and re-encoded it without them. Then I edited the XML to change all of the event cue point to actionscript and imported them into the FLA file using the FLV component properties dialogue.

Presto, amazingly enough, I had no issues finding the cue points, tracing them, and using them for any purpose.

So in the future, I just need to remember to set up the cue points in the Properties dialogue and set them to actionscript and I should be golden. So far, it has worked flawlessly with all of the F4V files since making the change.

Thank you very much for your detailed response and your follow up!

Body:
Hello everyone and anyone!

Ok... I have been banging my head against the wall with this issue for literally weeks, but I still cannot find an answer that has successfully resolved the issue.

I created an FLA and placed a FLV component with the instance name of videoPlay on the stage.

videoPlay is pathed to a streaming FLV with embedded event cue points. The cue points are numbered sequentially from narration1 to narration16.

I established a listener object:

     var videoPlayCuePointListener:Object = new Object();

The event listener for the cue points:

   videoPlayCuePointListener.cuePoint = function(eventObject:Object):Void{
   if(eventObject.info.name == "narration1"){_root.cc_box.cc_txt.htmlText = cueTxt1);}
   else if(eventObject.info.name == "narration2"){_root.cc_box.cc_txt.htmlText = cueTxt2);}
   etc, through narration16 }

and so on through narration16.

Then I attached the event listener to the FLV component on stage:

   videoPlay.addEventListener("cuePoint", videoPlayCuePointListener);

All of this works very well. As the FLV plays, each event cue point fires off the correct text to the cc_txt dynamic text box.

The issue I am having is that I cannot find the nearest cue point to the FLV playhead so that I can fire events when the user scrubs the timeline.

I have researched this as thoroughly as I possibly could before finally deciding to post the issue, but although the documentation and various postings regarding findNearestCuePoint discovered throughout the web have provided numerous examples, not a single one has been successful.

I have attempted to add a listener to videoPlay that creates an object (nearestCue) and gives nearestCue the value of videoPlay.findNearestCuePoint(videoPlay.playheadTime), then read out nearestCue's name, label, etc. No dice.

Nothing suggested in any posts I have reviewed (many, many posts) has provided an answer.

This seems like it would be the easiest thing to accomplish but I have not been successful a single time.

Any suggestions or assistance would be much appreciated.

Thank you for your time!


来源: stackexchange

问:
Flutter: ListView not rebuilding after parent changes state
By using ListView i came into a problem i don't understand what is going on. I got one ListView with a list of Task and a second with a list of TaskTile (stateless widget with ListTile in build method).

With the first List i map the tasks into TaskTile, the rebuild works as expected but in the second it works only if i scroll the list and not when the state changes.

Here is the code for the two lists and a gif representing the problem:

```<code>import 'package:flutter/material.dart';
import 'package:todo/screens/task/task_screen.dart';

void main() {
 runApp(const MyApp());
}

class MyApp extends StatelessWidget {
 const MyApp({Key? key}) : super(key: key);

 @override
 Widget build(BuildContext context) {
   return MaterialApp(
     title: 'Flutter Demo',
     theme: ThemeData(
       primarySwatch: Colors.blue,
     ),
     home: const TaskScreen(),
   );
 }
}

class Task {
 String title;
 bool completed;

 Task({required this.title, this.completed = false});

 void toggleCompleted() {
   completed = !completed;
 }
}

class TaskScreen extends StatefulWidget {
 const TaskScreen({Key? key}) : super(key: key);

 @override
 State<TaskScreen> createState() => _TaskScreenState();
}

class _TaskScreenState extends State<TaskScreen> {
 List<Task> tasks = [
   Task(title: "task1"),
   Task(title: "task2"),
   Task(title: "task3"),
 ];

 List<TaskTile> taskTiles = [
   TaskTile(task: Task(title: "tile1")),
   TaskTile(task: Task(title: "tile2")),
   TaskTile(task: Task(title: "tile3")),
 ];

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
       title: const Text("Tasks"),
     ),
     body: SafeArea(
       child: Column(
         children: [
           Expanded(
               child: TasksList(
             tasks: tasks,
           )),
           const Divider(
             thickness: 10,
             color: Colors.blue,
           ),
           Expanded(
               child: TaskTilesList(
             tasks: taskTiles,
           )),
           Row(
             mainAxisAlignment: MainAxisAlignment.spaceEvenly,
             children: [
               ElevatedButton(
                   onPressed: () {
                     setState(() {
                       tasks.add(Task(title: "Task"));
                     });
                   },
                   child: const Text("Add Task")),
               ElevatedButton(
                   onPressed: () {
                     setState(() {
                       taskTiles.add(TaskTile(task: Task(title: "Tile")));
                     });
                   },
                   child: const Text("Add Task Tile")),
             ],
           ),
         ],
       ),
     ),
   );
 }
}

class TasksList extends StatelessWidget {
 const TasksList({Key? key, required this.tasks}) : super(key: key);

 final List<Task> tasks;

 @override
 Widget build(BuildContext context) {
   //************* List of Task mapped to TaskTile *******************
   return ListView(children: tasks.map((e) => TaskTile(task: e)).toList());
 }
}

class TaskTilesList extends StatelessWidget {
 const TaskTilesList({Key? key, required this.tasks}) : super(key: key);

 final List<TaskTile> tasks;

 @override
 Widget build(BuildContext context) {

   //************ List of TaskTile *************
   return ListView(
     children: tasks,
   );
 }
}

class TaskTile extends StatefulWidget {
 const TaskTile({Key? key, required this.task}) : super(key: key);

 final Task task;

 @override
 State<TaskTile> createState() => _TaskTileState();
}

class _TaskTileState extends State<TaskTile> {
 bool checkBoxValue = false;

 @override
 Widget build(BuildContext context) {
   print("Task: ${widget.task.title}");
   return ListTile(
     title: Text(
       widget.task.title,
       style: TextStyle(color: checkBoxValue ? Colors.black : Colors.black),
     ),
     trailing: TileCheckbox(
         checkBoxValue: checkBoxValue,
         callback: (val) {
           setState(() {
             checkBoxValue = val;
           });
         }),
     onTap: () {
       print("tile tapped");
       setState(() {});
     },
   );
 }
}

class TileCheckbox extends StatelessWidget {
 const TileCheckbox(
     {Key? key, required this.checkBoxValue, required this.callback})
     : super(key: key);

 final bool checkBoxValue;
 final Function callback;

 @override
 Widget build(BuildContext context) {
   return Checkbox(
     value: checkBoxValue,
     onChanged: (bool? value) {
       callback(value);
     },
   );
}
}
</code>```

When i replace ListView with ListView.builder in the problematic list it works but i don't understand why it does not work without the builder constructor. I tried to understand it with prints when i add the new TaskTile, in console the two lists are rebuild i can even see the newly added TaskTile but it does not appear in UI without scrolling the list. Is it supposed to work like this? What is the difference when passing a list of TaskTile instead of a mapped list of TaskTile?

答:
By definition ListView requires you to create all items at once, while the builder constructor creates a lazy list which loads the itens on demand

from the oficial docs:

ListView: Creates a scrollable, linear array of widgets from an
explicit List. This constructor is appropriate for list views with a
small number of children because constructing the List requires doing
work for every child that could possibly be displayed in the list view
instead of just those children that are actually visible.

ListView.builder Creates a scrollable, linear array of widgets that
are created on demand. This constructor is appropriate for list views
with a large (or infinite) number of children because the builder is
called only for those children that are actually visible.

ContentLicense: CC BY-SA 4.0

Body:
By using ListView i came into a problem i don't understand what is going on. I got one ListView with a list of Task and a second with a list of TaskTile (stateless widget with ListTile in build method).

With the first List i map the tasks into TaskTile, the rebuild works as expected but in the second it works only if i scroll the list and not when the state changes.

Here is the code for the two lists and a gif representing the problem:

import 'package:flutter/material.dart';
import 'package:todo/screens/task/task_screen.dart';

void main() {
 runApp(const MyApp());
}

class MyApp extends StatelessWidget {
 const MyApp({Key? key}) : super(key: key);

 @override
 Widget build(BuildContext context) {
   return MaterialApp(
     title: 'Flutter Demo',
     theme: ThemeData(
       primarySwatch: Colors.blue,
     ),
     home: const TaskScreen(),
   );
 }
}

class Task {
 String title;
 bool completed;

 Task({required this.title, this.completed = false});

 void toggleCompleted() {
   completed = !completed;
 }
}

class TaskScreen extends StatefulWidget {
 const TaskScreen({Key? key}) : super(key: key);

 @override
 State<TaskScreen> createState() => _TaskScreenState();
}

class _TaskScreenState extends State<TaskScreen> {
 List<Task> tasks = [
   Task(title: "task1"),
   Task(title: "task2"),
   Task(title: "task3"),
 ];

 List<TaskTile> taskTiles = [
   TaskTile(task: Task(title: "tile1")),
   TaskTile(task: Task(title: "tile2")),
   TaskTile(task: Task(title: "tile3")),
 ];

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
       title: const Text("Tasks"),
     ),
     body: SafeArea(
       child: Column(
         children: [
           Expanded(
               child: TasksList(
             tasks: tasks,
           )),
           const Divider(
             thickness: 10,
             color: Colors.blue,
           ),
           Expanded(
               child: TaskTilesList(
             tasks: taskTiles,
           )),
           Row(
             mainAxisAlignment: MainAxisAlignment.spaceEvenly,
             children: [
               ElevatedButton(
                   onPressed: () {
                     setState(() {
                       tasks.add(Task(title: "Task"));
                     });
                   },
                   child: const Text("Add Task")),
               ElevatedButton(
                   onPressed: () {
                     setState(() {
                       taskTiles.add(TaskTile(task: Task(title: "Tile")));
                     });
                   },
                   child: const Text("Add Task Tile")),
             ],
           ),
         ],
       ),
     ),
   );
 }
}

class TasksList extends StatelessWidget {
 const TasksList({Key? key, required this.tasks}) : super(key: key);

 final List<Task> tasks;

 @override
 Widget build(BuildContext context) {
   //************* List of Task mapped to TaskTile *******************
   return ListView(children: tasks.map((e) => TaskTile(task: e)).toList());
 }
}

class TaskTilesList extends StatelessWidget {
 const TaskTilesList({Key? key, required this.tasks}) : super(key: key);

 final List<TaskTile> tasks;

 @override
 Widget build(BuildContext context) {

   //************ List of TaskTile *************
   return ListView(
     children: tasks,
   );
 }
}

class TaskTile extends StatefulWidget {
 const TaskTile({Key? key, required this.task}) : super(key: key);

 final Task task;

 @override
 State<TaskTile> createState() => _TaskTileState();
}

class _TaskTileState extends State<TaskTile> {
 bool checkBoxValue = false;

 @override
 Widget build(BuildContext context) {
   print("Task: ${widget.task.title}");
   return ListTile(
     title: Text(
       widget.task.title,
       style: TextStyle(color: checkBoxValue ? Colors.black : Colors.black),
     ),
     trailing: TileCheckbox(
         checkBoxValue: checkBoxValue,
         callback: (val) {
           setState(() {
             checkBoxValue = val;
           });
         }),
     onTap: () {
       print("tile tapped");
       setState(() {});
     },
   );
 }
}

class TileCheckbox extends StatelessWidget {
 const TileCheckbox(
     {Key? key, required this.checkBoxValue, required this.callback})
     : super(key: key);

 final bool checkBoxValue;
 final Function callback;

 @override
 Widget build(BuildContext context) {
   return Checkbox(
     value: checkBoxValue,
     onChanged: (bool? value) {
       callback(value);
     },
   );
}
}

When i replace ListView with ListView.builder in the problematic list it works but i don't understand why it does not work without the builder constructor. I tried to understand it with prints when i add the new TaskTile, in console the two lists are rebuild i can even see the newly added TaskTile but it does not appear in UI without scrolling the list. Is it supposed to work like this? What is the difference when passing a list of TaskTile instead of a mapped list of TaskTile?


问:
How to secure an HTTP based API Gateway in AWS
There are two versions of the AWS API Gateway:

REST version

HTTP version (v2)

I am using the newer HTTP version with a lambda authorizer and would like to protect my staging/test environments from outside requests.  One idea is to put a WAF in front of the API gateway, but unfortunately only the REST version of the gateway supports a WAF.

Any suggestions for how to protect these resources so they can only be accessed from a specific IP range? (Company VPN)

答:
You can create private Api Gateways using the tags aws:SourceVpc and aws:SourceVpce in the Api resource policy.

link to aws official documentation


问:
Create new boolean fields based on specific terms appearing in a tokenized pandas dataframe
Looping over a list of terms to search for, I need to create a boolean field for each term according to whether or not it is present in a tokenized pandas series.

List of search terms:

```<code>terms = ['innovative', 'data', 'rf']
</code>```

Dataframe:

```<code>df = pd.DataFrame(data={'job_description': [['innovative', 'data', 'science'],
                                            ['scientist', 'have', 'a', 'masters'],
                                            ['database', 'rf', 'innovative'],
                                            ['sciencedata', 'data', 'performance']]})
</code>```

Desired output for df:

```<code>                     job_description  innovative   data     rf
0        [innovative, data, science]        True   True  False
1      [scientist, have, a, masters]       False  False  False
2         [database, rf, innovative]        True  False   True
3  [sciencedata, data, performance]        False   True  False
</code>```

Criteria:

Only exact matches should be replaced (for example, flagging for 'rf' should return True for 'rf' but False for 'performance')

each search term should get it's own field and be concatenated to the original df

What I've tried:
Failed, as it creates a boolean for each term in the series:

```<code>df['innovative'] = df['job_description'].explode().str.contains(r'innovative').groupby(level=-1).agg(list)
</code>```

Failed:

```<code>df['innovative'] = df['job_description'].str.contains('innovative').astype(int, errors='ignore')
</code>```

Failed:

```<code>df.loc[df['job_description'].str.contains(terms)] = 1
</code>```

Failed: I tried implementing what was documented here (See if item in each row of pandas series), but could not adapt it to create new fields or flag properly

Thanks for any help you can provide!

答:
This should be pretty fast:

```<code>e = df['job_description'].explode()
new_df[terms] = pd.concat([e.eq(t).rename(t) for t in terms], axis=1).groupby(level=0).any()
</code>```

Output:

```<code>>>> new_df
                    job_description  innovative   data     rf
0       [innovative, data, science]        True   True  False
1     [scientist, have, a, masters]       False  False  False
2        [database, rf, innovative]        True  False   True
3  [sciencedata, data, performance]       False   True  False
</code>```

Body:
Looping over a list of terms to search for, I need to create a boolean field for each term according to whether or not it is present in a tokenized pandas series.

List of search terms:

terms = ['innovative', 'data', 'rf']

Dataframe:

df = pd.DataFrame(data={'job_description': [['innovative', 'data', 'science'],
                                            ['scientist', 'have', 'a', 'masters'],
                                            ['database', 'rf', 'innovative'],
                                            ['sciencedata', 'data', 'performance']]})

Desired output for df:

                     job_description  innovative   data     rf
0        [innovative, data, science]        True   True  False
1      [scientist, have, a, masters]       False  False  False
2         [database, rf, innovative]        True  False   True
3  [sciencedata, data, performance]        False   True  False

Criteria:

Only exact matches should be replaced (for example, flagging for 'rf' should return True for 'rf' but False for 'performance')

each search term should get it's own field and be concatenated to the original df

What I've tried:
Failed, as it creates a boolean for each term in the series:

df['innovative'] = df['job_description'].explode().str.contains(r'innovative').groupby(level=-1).agg(list)

Failed:

df['innovative'] = df['job_description'].str.contains('innovative').astype(int, errors='ignore')

Failed:

df.loc[df['job_description'].str.contains(terms)] = 1

Failed: I tried implementing what was documented here (See if item in each row of pandas series), but could not adapt it to create new fields or flag properly

Thanks for any help you can provide!

Body:
This should be pretty fast:

e = df['job_description'].explode()
new_df[terms] = pd.concat([e.eq(t).rename(t) for t in terms], axis=1).groupby(level=0).any()

Output:

>>> new_df
                    job_description  innovative   data     rf
0       [innovative, data, science]        True   True  False
1     [scientist, have, a, masters]       False  False  False
2        [database, rf, innovative]        True  False   True
3  [sciencedata, data, performance]       False   True  False


问:
Xcode 12.0 not showing variable when debugging
I have projects that I have created with earlier releases of Xcode. I was forced to upgrade to Xcode 12.0.
When I run my old projects, not tried all of them, I am not getting any variable declared outside of the current routine, the variables within the current routine do not show any value. I have created a new project and the same thing applies. I have checked old reports and all my optimization settings are none, and I have debug for my Build configuration along with many of the other suggestions on earlier versions of Xcode with the same problem. So there's probably something very simple that I need to do but I can't find it. Hope somebody has the solution.</p>

答:
I had the same problem, using Xcode 12.5.1, and eventually solved it by changing my default interactive shell to zsh, then closing and reopening Xcode.

To change the default interactive shell to zsh, use this command in a terminal (command line) window:

```<code>chsh -s /bin/zsh
</code>```

I had already ensured that both Objective C and Swift were being compiled with no optimisation in debug mode, and that I was running a debug build of my app.

Before I made the change I couldn't see any variables, and no lldb commands worked. The change fixed both those problems.

Body:
I had the same problem, using Xcode 12.5.1, and eventually solved it by changing my default interactive shell to zsh, then closing and reopening Xcode.

To change the default interactive shell to zsh, use this command in a terminal (command line) window:

chsh -s /bin/zsh

I had already ensured that both Objective C and Swift were being compiled with no optimisation in debug mode, and that I was running a debug build of my app.

Before I made the change I couldn't see any variables, and no lldb commands worked. The change fixed both those problems.


问:
Black / white theme, how to add fontawesome icon (JavaScript)
I don't really know JavaScript. My goal is to add the icons to the  white /  dark button. If you know javascript please help me.
What I want:

If you press the button it is white = moon.

If you press the button it is dark = sun.

My fontawesome icons:

CDN Font awesome:

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">

if (!localStorage.theme) localStorage.theme = "light"
document.body.className = localStorage.theme
toggleThemeBtn.innerText = document.body.classList.contains("dark") ? "white" : "dark"

toggleThemeBtn.onclick = () => {
    document.body.classList.toggle("dark")
    toggleThemeBtn.innerText = document.body.classList.contains("dark") ? "white" : "dark"
    localStorage.theme = document.body.className || "light"
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}
body {
    min-height: calc(100vh - 100px);
    margin-top: 100px;
}
body.dark {
    background: #303133;
    color: #fff;
}
body.dark .content {
    box-shadow: 0 0 5px #1d2225;
}
body.dark button {
    box-shadow: 0 0 5px #1d2225;
    color: #fff;
}
body.dark button:hover {
    box-shadow: 0 0 10px #1d2225;
}
body.dark button:active {
    box-shadow: inset 0 0 5px #1d2225;
}
.content {
    width: 55%;
    margin: auto;
    box-shadow: 0 0 3px silver;
    padding: 20px;
    height: calc(100vh - 100px - 40px);
}
section:not(:first-child) {
    margin-top: 30px;
}
.desc {
    margin: 10px 0;
    opacity: .7;
}
button {
    padding: 10px 20px;
    border: none;
    background: transparent;
    box-shadow: 0 0 5px silver;
    cursor: pointer;
    outline: none;
}
button:hover {
    box-shadow: 0 0 10px silver;
}
button:active {
    box-shadow: inset 0 0 5px silver;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <link href="style.css" rel="stylesheet">
    <title></title>

BLock

Lorem ipsum dolor sit amet consectetur adipisicing elit. Officiis quod porro voluptate minima quasi a mollitia dicta corrupti nesciunt! Corrupti, quis at? Perspiciatis voluptatibus provident laboriosam vitae voluptatem autem, cupiditate esse nihil est! Ducimus non, corrupti totam quisquam quod et!
<button id="toggleThemeBtn">Сменить тему на тёмную</button>

```
</div>
</div>
</p>
<p>I don't know why but my HTML / CSS / js snippet doesn't work on StackOverflow, especially for this I created a page on CodePen
codepen url
or <code>https://codepen.io/SergiuC121/pen/dyZWjOd</code></p>
<p>I don't know if it makes sense, but before I changed my code the following way and it practically worked but it displayed true and false after which I deleted the white/dark text.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var i = document.createElement("i");
var t = document.createElement("i");
t.className = "fa-solid fa-moon nav-li-icon-bottom";
i.className = "fa-solid fa-sun nav-li-icon-bottom";
if (!localStorage.theme) localStorage.theme = "backgroundthemelight";
document.body.className = localStorage.theme;

    if (toggleThemeBtn.innerText = document.body.classList.contains("dark")) {
        document.getElementById('toggleThemeBtn').appendChild(i);
    } else {
        document.getElementById('toggleThemeBtn').appendChild(t);
    }

toggleThemeBtn.onclick = () => {
    document.body.classList.toggle("dark");
    var i = document.createElement("i");
    i.className = "fa-solid fa-sun nav-li-icon-bottom";
    var t = document.createElement("i");
    t.className = "fa-solid fa-moon nav-li-icon-bottom";
    if (toggleThemeBtn.innerText = document.body.classList.contains("dark")) {
        document.getElementById('toggleThemeBtn').appendChild(i);
    } else {
        document.getElementById('toggleThemeBtn').appendChild(t);
    }
    localStorage.theme = document.body.className || "backgroundthemelight"
}</code>```

* {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}

body {
    min-height: calc(100vh - 100px);
    margin-top: 100px;
}

body.dark {
    background: #303133;
    color: #fff;
}

body.dark .content {
    box-shadow: 0 0 5px #1d2225;
}

body.dark button {
    box-shadow: 0 0 5px #1d2225;
    color: #fff;
}

body.dark button:hover {
    box-shadow: 0 0 10px #1d2225;
}

body.dark button:active {
    box-shadow: inset 0 0 5px #1d2225;
}

.content {
    width: 55%;
    margin: auto;
    box-shadow: 0 0 3px silver;
    padding: 20px;
    height: calc(100vh - 100px - 40px);
}

section:not(:first-child) {
    margin-top: 30px;
}

.desc {
    margin: 10px 0;
    opacity: .7;
}

button {
    padding: 10px 20px;
    border: none;
    background: transparent;
    box-shadow: 0 0 5px silver;
    cursor: pointer;
    outline: none;
}

button:hover {
    box-shadow: 0 0 10px silver;
}

button:active {
    box-shadow: inset 0 0 5px silver;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <main class="content">
                <i class="fa-solid fa-sun nav-li-icon-bottom" id="moodBW"></i>
                <i class="fa-solid fa-moon nav-li-icon-bottom"></i>
        <section>
            <h1>BLock</h1>
            <p class="desc">
                Lorem ipsum dolor sit amet consectetur adipisicing elit. Officiis quod porro voluptate minima quasi a mollitia dicta corrupti nesciunt! Corrupti, quis at? Perspiciatis voluptatibus provident laboriosam vitae voluptatem autem, cupiditate esse nihil est! Ducimus non, corrupti totam quisquam quod et!
            </p>
            <button id="toggleThemeBtn">Сменить тему на тёмную</button>
        </section>
    </main>

    <script src="script.js"></script>
</body>
</html></code>```

Upstairs I presented my old code but here it doesn't work again I don't know why I attach a link to CodePen
url codepen or https://codepen.io/SergiuC121/pen/zYPwLRz

IMG result:
(suddenly the first button after pressing the 2nd button)

The theme is saved in local storage because I can't execute my snippet here.

Any advice?

p.s: I translated it into English with google translate if anyone finds mistakes please correct them so that others understand, thanks..

答:
For me both the code pen examples are working fine and thus I am unable to propose a fix in Javascript. Though if your requirement is just to toggle between the btns and have the theme switched based on the same then you can make use of css to hide/show buttons and js can be used just to toggle body class.

I have created a codepen example for the same.

The js in the pen is only for toggling the body class based on button clicked.
while css is doing the job of showing and hiding the buttons.

The JS is as follows:

```<code>document.getElementById("lightThemeBtn")?.addEventListener('click', (e) => {
    const body = document.querySelector("body");

    body.classList.add('dark');
});
document.getElementById("darkThemeBtn")?.addEventListener('click', (e) => {
    const body = document.querySelector("body");

    body.classList.remove('dark');
});
</code>```

I have used all your css (except the padding on button) and added the following at the bottom:

```<code>.toggleThemeBtn > div > i {
  margin-right: 5px;
}

.toggleThemeBtn #darkThemeBtn {
  display:none;
}

body.dark #lightThemeBtn {
  display: none;
}

body.dark #darkThemeBtn {
  display: block;
}

.toggleThemeBtn > div {
  padding: 10px 20px;
}
</code>```

Inside the HTML, in the button, I am rendering 2 div which contain the sun and the moon icon and text.

```<code>  <button class="toggleThemeBtn" id="toggleThemeBtn">
          <div id="lightThemeBtn"><i class="fa-solid fa-sun"></i>Light</div>
          <div id="darkThemeBtn"><i class="fa-solid fa-moon" ></i>Dark</div>
        </button>
</code>```

These changes are giving me the desired result. Hopefully it answers your question in a different way.

Body:
I don't really know JavaScript. My goal is to add the icons to the  white /  dark button. If you know javascript please help me.
What I want:

If you press the button it is white = moon.

If you press the button it is dark = sun.

My fontawesome icons:

CDN Font awesome:

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">

if (!localStorage.theme) localStorage.theme = "light"
document.body.className = localStorage.theme
toggleThemeBtn.innerText = document.body.classList.contains("dark") ? "white" : "dark"

toggleThemeBtn.onclick = () => {
    document.body.classList.toggle("dark")
    toggleThemeBtn.innerText = document.body.classList.contains("dark") ? "white" : "dark"
    localStorage.theme = document.body.className || "light"
}

* {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}
body {
    min-height: calc(100vh - 100px);
    margin-top: 100px;
}
body.dark {
    background: #303133;
    color: #fff;
}
body.dark .content {
    box-shadow: 0 0 5px #1d2225;
}
body.dark button {
    box-shadow: 0 0 5px #1d2225;
    color: #fff;
}
body.dark button:hover {
    box-shadow: 0 0 10px #1d2225;
}
body.dark button:active {
    box-shadow: inset 0 0 5px #1d2225;
}
.content {
    width: 55%;
    margin: auto;
    box-shadow: 0 0 3px silver;
    padding: 20px;
    height: calc(100vh - 100px - 40px);
}
section:not(:first-child) {
    margin-top: 30px;
}
.desc {
    margin: 10px 0;
    opacity: .7;
}
button {
    padding: 10px 20px;
    border: none;
    background: transparent;
    box-shadow: 0 0 5px silver;
    cursor: pointer;
    outline: none;
}
button:hover {
    box-shadow: 0 0 10px silver;
}
button:active {
    box-shadow: inset 0 0 5px silver;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <link href="style.css" rel="stylesheet">
    <title></title>

BLock

Lorem ipsum dolor sit amet consectetur adipisicing elit. Officiis quod porro voluptate minima quasi a mollitia dicta corrupti nesciunt! Corrupti, quis at? Perspiciatis voluptatibus provident laboriosam vitae voluptatem autem, cupiditate esse nihil est! Ducimus non, corrupti totam quisquam quod et!
<button id="toggleThemeBtn">Сменить тему на тёмную</button>

I don't know why but my HTML / CSS / js snippet doesn't work on StackOverflow, especially for this I created a page on CodePen
codepen url
or https://codepen.io/SergiuC121/pen/dyZWjOd

I don't know if it makes sense, but before I changed my code the following way and it practically worked but it displayed true and false after which I deleted the white/dark text.

var i = document.createElement("i");
var t = document.createElement("i");
t.className = "fa-solid fa-moon nav-li-icon-bottom";
i.className = "fa-solid fa-sun nav-li-icon-bottom";
if (!localStorage.theme) localStorage.theme = "backgroundthemelight";
document.body.className = localStorage.theme;

    if (toggleThemeBtn.innerText = document.body.classList.contains("dark")) {
        document.getElementById('toggleThemeBtn').appendChild(i);
    } else {
        document.getElementById('toggleThemeBtn').appendChild(t);
    }

toggleThemeBtn.onclick = () => {
    document.body.classList.toggle("dark");
    var i = document.createElement("i");
    i.className = "fa-solid fa-sun nav-li-icon-bottom";
    var t = document.createElement("i");
    t.className = "fa-solid fa-moon nav-li-icon-bottom";
    if (toggleThemeBtn.innerText = document.body.classList.contains("dark")) {
        document.getElementById('toggleThemeBtn').appendChild(i);
    } else {
        document.getElementById('toggleThemeBtn').appendChild(t);
    }
    localStorage.theme = document.body.className || "backgroundthemelight"
}

* {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}

body {
    min-height: calc(100vh - 100px);
    margin-top: 100px;
}

body.dark {
    background: #303133;
    color: #fff;
}

body.dark .content {
    box-shadow: 0 0 5px #1d2225;
}

body.dark button {
    box-shadow: 0 0 5px #1d2225;
    color: #fff;
}

body.dark button:hover {
    box-shadow: 0 0 10px #1d2225;
}

body.dark button:active {
    box-shadow: inset 0 0 5px #1d2225;
}

.content {
    width: 55%;
    margin: auto;
    box-shadow: 0 0 3px silver;
    padding: 20px;
    height: calc(100vh - 100px - 40px);
}

section:not(:first-child) {
    margin-top: 30px;
}

.desc {
    margin: 10px 0;
    opacity: .7;
}

button {
    padding: 10px 20px;
    border: none;
    background: transparent;
    box-shadow: 0 0 5px silver;
    cursor: pointer;
    outline: none;
}

button:hover {
    box-shadow: 0 0 10px silver;
}

button:active {
    box-shadow: inset 0 0 5px silver;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="style.css">

BLock

                Lorem ipsum dolor sit amet consectetur adipisicing elit. Officiis quod porro voluptate minima quasi a mollitia dicta corrupti nesciunt! Corrupti, quis at? Perspiciatis voluptatibus provident laboriosam vitae voluptatem autem, cupiditate esse nihil est! Ducimus non, corrupti totam quisquam quod et!

            <button id="toggleThemeBtn">Сменить тему на тёмную</button>

Upstairs I presented my old code but here it doesn't work again I don't know why I attach a link to CodePen
url codepen or https://codepen.io/SergiuC121/pen/zYPwLRz

IMG result:
(suddenly the first button after pressing the 2nd button)

The theme is saved in local storage because I can't execute my snippet here.

Any advice?

p.s: I translated it into English with google translate if anyone finds mistakes please correct them so that others understand, thanks..

Body:
For me both the code pen examples are working fine and thus I am unable to propose a fix in Javascript. Though if your requirement is just to toggle between the btns and have the theme switched based on the same then you can make use of css to hide/show buttons and js can be used just to toggle body class.

I have created a codepen example for the same.

The js in the pen is only for toggling the body class based on button clicked.
while css is doing the job of showing and hiding the buttons.

The JS is as follows:

document.getElementById("lightThemeBtn")?.addEventListener('click', (e) => {
    const body = document.querySelector("body");

    body.classList.add('dark');
});
document.getElementById("darkThemeBtn")?.addEventListener('click', (e) => {
    const body = document.querySelector("body");

    body.classList.remove('dark');
});

I have used all your css (except the padding on button) and added the following at the bottom:

.toggleThemeBtn > div > i {
  margin-right: 5px;
}

.toggleThemeBtn #darkThemeBtn {
  display:none;
}

body.dark #lightThemeBtn {
  display: none;
}

body.dark #darkThemeBtn {
  display: block;
}

.toggleThemeBtn > div {
  padding: 10px 20px;
}

Inside the HTML, in the button, I am rendering 2 div which contain the sun and the moon icon and text.

  <button class="toggleThemeBtn" id="toggleThemeBtn">
          <div id="lightThemeBtn"><i class="fa-solid fa-sun"></i>Light</div>
          <div id="darkThemeBtn"><i class="fa-solid fa-moon" ></i>Dark</div>
        </button>

These changes are giving me the desired result. Hopefully it answers your question in a different way.


问:
Swagger Summary for Enum not showing
I am using xml annotations on my API endpoints which contain information about the endpoint responses as well as a summary for that endpoint.

On my request model, each property has a  describing the property. This all works fine except for when I try to add a summary to an Enum.

For example, I have the following property in my class:

```<code>/// <summary>
/// Domain Model Class
/// </summary>
public DomainModelClass? AssetDomainModelClass { get; set; }
</code>```

And DomainModelClass is an Enum

When I go to the swagger page, there is no description on AssetDomainModelClass

Additionally I looked at the json that is created, and it does not contain a description for the Enum field

But the summary works for all non Enum properties, such as the AssetId one right above my example. How can I get a summary to attach to Enum values?

I am using Swashbuckle.AspNetCore (6.0.7)

答:
I hope you found this when you needed it, but for people like me:</p>
```<code>services.AddSwaggerGen(options =>
{
    options.UseInlineDefinitionsForEnums();
}
</code>```

Title: Swagger Summary for Enum not showing

Body:
I am using xml annotations on my API endpoints which contain information about the endpoint responses as well as a summary for that endpoint.

On my request model, each property has a  describing the property. This all works fine except for when I try to add a summary to an Enum.

For example, I have the following property in my class:

///
/// Domain Model Class
///
public DomainModelClass? AssetDomainModelClass { get; set; }

And DomainModelClass is an Enum

When I go to the swagger page, there is no description on AssetDomainModelClass

Additionally I looked at the json that is created, and it does not contain a description for the Enum field

But the summary works for all non Enum properties, such as the AssetId one right above my example. How can I get a summary to attach to Enum values?

I am using Swashbuckle.AspNetCore (6.0.7)

Body:
I hope you found this when you needed it, but for people like me:

services.AddSwaggerGen(options =>
{
    options.UseInlineDefinitionsForEnums();
}


问:
I'm trying to store ID of three employees using Dynamic Memory Allocation
Code -

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

int main()
{
    char *e;
    int len;

    for (int i = 1; i < 4; i++)
    {
        printf("Enter the size of the ID of the Employee %d\n", i);
        scanf("%d", &len);

        printf("Enter Employee ID of Employee %d\n", i);
        scanf("%s", &e);
    }

    e = (char *)malloc((len + 1) * sizeof(char));

    for (int i = 1; i < 4; i++)
    {
        printf("ID of Employee %d is %s\n", i, e);
    }

    return 0;
}
</code>```

Terminal -

```<code>Enter the size of the ID of the Employee 1
2
Enter Employee ID of Employee 1
A2
Enter the size of the ID of the Employee 2
2
Enter Employee ID of Employee 2
A7
Enter the size of the ID of the Employee 3
3
Enter Employee ID of Employee 3
AA1
</code>```

Expected Output -

```<code>ID of Employee 1 is A2
ID of Employee 2 is A7
ID of Employee 3 is AA1
</code>```

Output I am getting -

```<code>»D of Employee 1 is Φ
»D of Employee 2 is Φ
»D of Employee 3 is Φ
</code>```

Here, »D and Φ refers to Garbage Value that changes every time when I run it in another terminal

I'm just learning the basics of Dynamic Memory Allocation but getting problems even in that

Pls Help

答:
you need to store the data for every employee (probably in an array)

in scanf("%s", something) something must be of type char *. In your code it is char **.

don't use scanf %s because it assumes the buffer is large enough for the input. Use fgets or scanf %ms

in new versions there is also scanf("%ms", something) where something is char **. It allocates the string and stores the pointer to it in *something

having i start at 0 is easier when working with arrays

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

int main()
{
    char *ids[3];   // store the id for every employee, no need to store the length

    for (int i = 0; i < 3; i++)
    {
        printf("Enter the size of the ID of the Employee %d\n", i + 1);
        int len;
        scanf("%d", &len);
        ids[i] = malloc(len + 1);   // no need to cast the pointer, sizeof(char) is always 1

        printf("Enter Employee ID of Employee %d\n", i + 1);
        scanf("%s", ids[i]);   // use fgets here
    }

    for (int i = 0; i < 3; i++)
    {
        printf("ID of Employee %d is %s\n", i + 1, ids[i]);
        free(ids[i]);   // free it when you are done with it
    }

    return 0;
}
</code>```

Body:
Code -

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

int main()
{
    char *e;
    int len;

    for (int i = 1; i < 4; i++)
    {
        printf("Enter the size of the ID of the Employee %d\n", i);
        scanf("%d", &len);

        printf("Enter Employee ID of Employee %d\n", i);
        scanf("%s", &e);
    }

    e = (char *)malloc((len + 1) * sizeof(char));

    for (int i = 1; i < 4; i++)
    {
        printf("ID of Employee %d is %s\n", i, e);
    }

    return 0;
}

Terminal -

Enter the size of the ID of the Employee 1
2
Enter Employee ID of Employee 1
A2
Enter the size of the ID of the Employee 2
2
Enter Employee ID of Employee 2
A7
Enter the size of the ID of the Employee 3
3
Enter Employee ID of Employee 3
AA1

Expected Output -

ID of Employee 1 is A2
ID of Employee 2 is A7
ID of Employee 3 is AA1

Output I am getting -

»D of Employee 1 is Φ
»D of Employee 2 is Φ
»D of Employee 3 is Φ

Here, »D and Φ refers to Garbage Value that changes every time when I run it in another terminal

I'm just learning the basics of Dynamic Memory Allocation but getting problems even in that

Pls Help

Body:
you need to store the data for every employee (probably in an array)

in scanf("%s", something) something must be of type char *. In your code it is char **.

don't use scanf %s because it assumes the buffer is large enough for the input. Use fgets or scanf %ms

in new versions there is also scanf("%ms", something) where something is char **. It allocates the string and stores the pointer to it in *something

having i start at 0 is easier when working with arrays

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

int main()
{
    char *ids[3];   // store the id for every employee, no need to store the length

    for (int i = 0; i < 3; i++)
    {
        printf("Enter the size of the ID of the Employee %d\n", i + 1);
        int len;
        scanf("%d", &len);
        ids[i] = malloc(len + 1);   // no need to cast the pointer, sizeof(char) is always 1

        printf("Enter Employee ID of Employee %d\n", i + 1);
        scanf("%s", ids[i]);   // use fgets here
    }

    for (int i = 0; i < 3; i++)
    {
        printf("ID of Employee %d is %s\n", i + 1, ids[i]);
        free(ids[i]);   // free it when you are done with it
    }

    return 0;
}


问:
ERC721 NFT creating a function to buy/sell NFTs that have been preminted by the contract owner, security question
I came across this answer while researching creating a function for someone to buy an NFT:

https://stackoverflow.com/a/67384225/1414721

The relevant lines are

```<code>            IERC20 tokenContract = IERC20(tokenAddress);
            require(tokenContract.transferFrom(msg.sender, address(this), price),
                "buy: payment failed");
</code>```

I don't want people to be able to buy my NFTs in anything other than Ethereum, although the author here says:

prevent an edge case where if gas runs out during execution, the buyer could end up with their NFT for free

This caught my eye and from reading the code it seems the check that is being done here is to prevent this edge case.

What I'm not sure of is how the applies when the currency the NFT is being bought in is Ethereum.

I have adjusted my buy function to look like

```<code>    function buy(uint256 _tokenId) external payable {
        uint256 price = tokenIdToPrice[_tokenId];
        require(price > 0, 'This token is not for sale');
        require(msg.value == price, 'Incorrect value');
        address seller = ownerOf(_tokenId);
        IERC20 tokenContract = IERC20(address(0));
        require(tokenContract.transferFrom(msg.sender, address(this), price), "buy: payment failed");
        payable(seller).transfer(msg.value);
        _transfer(seller, msg.sender, _tokenId);
        tokenIdToPrice[_tokenId] = 0;
        emit NftBought(seller, msg.sender, msg.value);
    }
</code>```

which I believe a) incorporates the token Contract from being the Ethereum token (IERC20(address(0)) - I understand address(0) is the Ethereum token address?) and b

```<code>require(tokenContract.transferFrom(msg.sender, address(this), price), "buy: payment failed");
</code>```

makes sure the gas limit edge case mentioned is handled.

Is this correct, Googling this was quite hard.

One last question (unrelated, I hope that's OK) - when a market displays all the NFTs available for a collection, i assume that the way they are doing that is the contract has a function that returns the NFT IDs and the Token URIs? Is that correct, or does OpenZeppelin provide this functionality and I don't have to concern myself with adding this function?

答: i think the gas edge case was solved by changing the order of operations. first pay then transfer the token.</p>

Body:
I came across this answer while researching creating a function for someone to buy an NFT:

https://stackoverflow.com/a/67384225/1414721

The relevant lines are

            IERC20 tokenContract = IERC20(tokenAddress);
            require(tokenContract.transferFrom(msg.sender, address(this), price),
                "buy: payment failed");

I don't want people to be able to buy my NFTs in anything other than Ethereum, although the author here says:

prevent an edge case where if gas runs out during execution, the buyer could end up with their NFT for free

This caught my eye and from reading the code it seems the check that is being done here is to prevent this edge case.

What I'm not sure of is how the applies when the currency the NFT is being bought in is Ethereum.

I have adjusted my buy function to look like

    function buy(uint256 _tokenId) external payable {
        uint256 price = tokenIdToPrice[_tokenId];
        require(price > 0, 'This token is not for sale');
        require(msg.value == price, 'Incorrect value');
        address seller = ownerOf(_tokenId);
        IERC20 tokenContract = IERC20(address(0));
        require(tokenContract.transferFrom(msg.sender, address(this), price), "buy: payment failed");
        payable(seller).transfer(msg.value);
        _transfer(seller, msg.sender, _tokenId);
        tokenIdToPrice[_tokenId] = 0;
        emit NftBought(seller, msg.sender, msg.value);
    }

which I believe a) incorporates the token Contract from being the Ethereum token (IERC20(address(0)) - I understand address(0) is the Ethereum token address?) and b

require(tokenContract.transferFrom(msg.sender, address(this), price), "buy: payment failed");

makes sure the gas limit edge case mentioned is handled.

Is this correct, Googling this was quite hard.

One last question (unrelated, I hope that's OK) - when a market displays all the NFTs available for a collection, i assume that the way they are doing that is the contract has a function that returns the NFT IDs and the Token URIs? Is that correct, or does OpenZeppelin provide this functionality and I don't have to concern myself with adding this function?


问:
Google Sheets Extracting Digits with Regex
I've been stuck on this for a while now. I want to extract only digits (numeric values) from the cell, but for some reason, it does not extract if it contains a single digit. See below for more details:

String
End Result

$8 - added to cart
8

Formula used: =REGEXEXTRACT(J92,"\d+.?\d+")

The formula would also grab digits that contain decimals. For some reason, this formula works if the string was "$81 - added to cart". Can someone help me fix this so it would work on strings with a single digit?

答:
This should do what you're expecting:

=IFERROR(REGEXEXTRACT(J92,"[\d\.,]+")*1)

Note that I've included both decimal points and commas here and then multiplied by 1 to convert the extracted string to a real value. If the source string has no matches, IFERROR will return null.

However, I'll note that doing this cell by cell is inefficient when an array formula could likely process the entire range. If you're interested in such an approach, share a link to the spreadsheet (or to a copy of it) below.


问:
How to join same table on multiple columns?
What would be the best way to JOIN a table based on whether join column is NULL or not.

I need to JOIN table #main with table #sub.

For example:

if ID column in table #main is NULL then join on column LocationID = #sub.LocationID

if ID and LocationID columns in table #main is NULLs then join on column UserID = #sub.UserID

```<code>create table #main (ID int, locationID varchar(50), UserID varchar(50))
insert into #main values (1,'Loc1',NULL),
                         (2,NULL,'User1'),
                         (NULL,'Loc1','User1'),
                         (4,'Loc1',NULL),
                         (5,NULL,'User1'),
                         (NULL,'Loc1','User1')
--select * from #main

select *
from #main m
-- if m.ID is not null then join on m.ID
-- OR if m.ID is null then join on m.locationID = s.LocationID
-- OR if m.ID is null and m.LocationID is null then join on  m.UserID = s.UserID
    left join #sub s ON  m.ID = s.ID OR m.locationID = s.LocationID OR m.UserID = s.UserID
</code>```

Thank you

答:
Something like this should work.  Not sure about performance...</p>
```<code>Select * From #Main m
    left Join #sub s on
    (m.id is null and m.locationid is null and m.userId = s.userID)
    or (m.id is not null and m.locationid is null and m.locationid = s.locationId)
    or (m.id is not null and m.locationid is not  null and m.id = s.id)
</code>```

Body:
What would be the best way to JOIN a table based on whether join column is NULL or not.

I need to JOIN table #main with table #sub.

For example:

if ID column in table #main is NULL then join on column LocationID = #sub.LocationID

if ID and LocationID columns in table #main is NULLs then join on column UserID = #sub.UserID

create table #main (ID int, locationID varchar(50), UserID varchar(50))
insert into #main values (1,'Loc1',NULL),
                         (2,NULL,'User1'),
                         (NULL,'Loc1','User1'),
                         (4,'Loc1',NULL),
                         (5,NULL,'User1'),
                         (NULL,'Loc1','User1')
--select * from #main

select *
from #main m
-- if m.ID is not null then join on m.ID
-- OR if m.ID is null then join on m.locationID = s.LocationID
-- OR if m.ID is null and m.LocationID is null then join on  m.UserID = s.UserID
    left join #sub s ON  m.ID = s.ID OR m.locationID = s.LocationID OR m.UserID = s.UserID

Thank you

Body:
Something like this should work.  Not sure about performance...

Select * From #Main m
    left Join #sub s on
    (m.id is null and m.locationid is null and m.userId = s.userID)
    or (m.id is not null and m.locationid is null and m.locationid = s.locationId)
    or (m.id is not null and m.locationid is not  null and m.id = s.id)


问:
how to not have the flask server break when an error occurs?
I have made an API app using flask, that takes a number(decimal) as input and returns some string. This app breaks if I send a string and works fine after re-starting it. I don't want to restart every time some error happens during processing. How do i do this?

Here is my code:

```<code>from flask import Flask, request, jsonify

# initiating the app
flask_api_app = Flask(__name__)

# the app accepts requests via "GET" and "POST" methods
@flask_api_app.route("/", methods=["GET", "POST"])
def output_risk_and_report():
    # getting json data from api call
    json_data = request.get_json(force=True)

    # now the processing part
    if json_data['number'] < 2:
        return jsonify(["the number is less than two"])
    else:
        return jsonify(["the number is not less than two"])

# main function, in which app will be run
if __name__ == "__main__":
    # running the app on local host
    flask_api_app.run(debug=True, host='127.0.0.1', port='8080')
</code>```

example of call which doesn't break the app: {"number":4}

example of call which breaks the app: {"number":"adfa"}

What changes do I make in my code to accomplish this?

EDIT 1:
i was naive to give that example in my question. in my original program, i may get an error when inserting data into database or may get an error with some arithmetic calculation or something. So, is there any way to tell flask to keep serving for new api requests and not break when an error occurs with only one api call.

答:
your problem is caused because your program runs in debug mode.
for linux there is a tool called gunicorn. you should set up gunicorn and it will run again your flask app every time it crashes so you wont need to restart by yourself.
i dont know if there is a tool for windows.</p>

Body:
I have made an API app using flask, that takes a number(decimal) as input and returns some string. This app breaks if I send a string and works fine after re-starting it. I don't want to restart every time some error happens during processing. How do i do this?

Here is my code:

from flask import Flask, request, jsonify

# initiating the app
flask_api_app = Flask(__name__)

# the app accepts requests via "GET" and "POST" methods
@flask_api_app.route("/", methods=["GET", "POST"])
def output_risk_and_report():
    # getting json data from api call
    json_data = request.get_json(force=True)

    # now the processing part
    if json_data['number'] < 2:
        return jsonify(["the number is less than two"])
    else:
        return jsonify(["the number is not less than two"])

# main function, in which app will be run
if __name__ == "__main__":
    # running the app on local host
    flask_api_app.run(debug=True, host='127.0.0.1', port='8080')

example of call which doesn't break the app: {"number":4}

example of call which breaks the app: {"number":"adfa"}

What changes do I make in my code to accomplish this?

EDIT 1:
i was naive to give that example in my question. in my original program, i may get an error when inserting data into database or may get an error with some arithmetic calculation or something. So, is there any way to tell flask to keep serving for new api requests and not break when an error occurs with only one api call.


问:
connection times out when trying to connect to mongodb atlas with python
I'm trying to connect to my mongodb atlas cluster but i keep getting timed out as soon as i try to do something with my db.

The db i use was created in mongoshell and also the collection i checked their existence in mongodb compass

ERROR

```<code>pymongo.errors.ServerSelectionTimeoutError: projekt-shard-00-01-rk7ft.mongodb.net:27017: timed out,projekt-shard-00-00-rk7ft.mongodb.net:27017: timed out,projekt-shard-00-02-rk7ft.mongodb.net:27017: timed out
</code>```

CODE

```<code>client = MongoClient("""mongodb://user:password@projekt-shard-00-00-rk7ft.mongodb.net:27017,projekt-shard-00-01-rk7ft.mongodb.net:27017,projekt-shard-00-02-rk7ft.mongodb.net:27017/projekt?ssl=true&replicaSet=projekt-shard-0&authSource=admin""")

    client.projekt.category.insert_one({type : "pants"}).inserted_id
</code>```

答: Anybody looking for a solution, if you are trying to access Atlas instance from out in the wild, check the "Network Access" tab, as i think you have to whitelist either all, or specific IP addresses</p>

Body:
I'm trying to connect to my mongodb atlas cluster but i keep getting timed out as soon as i try to do something with my db.

The db i use was created in mongoshell and also the collection i checked their existence in mongodb compass

ERROR

pymongo.errors.ServerSelectionTimeoutError: projekt-shard-00-01-rk7ft.mongodb.net:27017: timed out,projekt-shard-00-00-rk7ft.mongodb.net:27017: timed out,projekt-shard-00-02-rk7ft.mongodb.net:27017: timed out

CODE

client = MongoClient("""mongodb://user:password@projekt-shard-00-00-rk7ft.mongodb.net:27017,projekt-shard-00-01-rk7ft.mongodb.net:27017,projekt-shard-00-02-rk7ft.mongodb.net:27017/projekt?ssl=true&replicaSet=projekt-shard-0&authSource=admin""")

    client.projekt.category.insert_one({type : "pants"}).inserted_id


问:
URL component encoding in Node.js
I want to send http request using node.js. I do:

```<code>http = require('http');

var options = {
    host: 'www.mainsms.ru',
    path: '/api/mainsms/message/send?project='+project+'&sender='+sender+'&message='+message+'&recipients='+from+'&sign='+sign
    };

    http.get(options, function(res) {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    }).on('error', function(e) {
    console.log('ERROR: ' + e.message);
    });
</code>```

When my path like this:

```<code>/api/mainsms/message/send?project=geoMessage&sender=gis&message=tester_response&recipients=79089145***&sign=2c4135e0f84d2c535846db17b1cec3c6
</code>```

Its work. But when message parameter contains any spaces for example tester response all broke. And in console i see that http use this url:

```<code>  /api/mainsms/message/send?project=geoMessage&sender=gis&message=tester
</code>```

How to send spaces. Or i just can't use spaces in url?

答:
TLDR: Use fixedEncodeURI() and fixedEncodeURIComponent()

MDN encodeURI() Documentation...

```<code>function fixedEncodeURI(str) {
   return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');
}
</code>```

MDN encodeURIComponent() Documentation...

```<code>function fixedEncodeURIComponent(str) {
 return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
   return '%' + c.charCodeAt(0).toString(16);
 });
}
</code>```

Why to Not Use encodeURI() and encodeURIComponent()

It is really not recommended to use encodeURI() and encodeURIComponent(), as they are insufficient to properly handle URI or URL encoding directly.  Just like at this piece...

```<code>'&message=' + encodeURIComponent(message) +
</code>```

Let's say that the message var is set to this: "Hello, world! (Really hello!)".  So what is that evaluated to?

console.log('&message=' + encodeURIComponent("Hello, world! (Really hello!)"));```

Output:

&message=Hello%2C%20world!%20(Really%20hello!)

That's not right!  Why weren't ( and ) encoded?  After all, according to RFC3986, Section 2.2: Reserved Characters...

If data for a URI component would conflict with a reserved character's purpose as a delimiter, then the conflicting data must be percent-encoded before the URI is formed.

sub-delims  = "!" / "$" / "&" / "'" / "(" / ")"  / "*" / "+" / "," / ";" / "="

Parens are a sub-delim, but they are not being escaped by encodeURI() or encodeURIComponent().

ContentLicense: CC BY-SA 3.0

Title: URL component encoding in Node.js

Body:
I want to send http request using node.js. I do:

http = require('http');

var options = {
    host: 'www.mainsms.ru',
    path: '/api/mainsms/message/send?project='+project+'&sender='+sender+'&message='+message+'&recipients='+from+'&sign='+sign
    };

    http.get(options, function(res) {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    }).on('error', function(e) {
    console.log('ERROR: ' + e.message);
    });

When my path like this:

/api/mainsms/message/send?project=geoMessage&sender=gis&message=tester_response&recipients=79089145***&sign=2c4135e0f84d2c535846db17b1cec3c6

Its work. But when message parameter contains any spaces for example tester response all broke. And in console i see that http use this url:

  /api/mainsms/message/send?project=geoMessage&sender=gis&message=tester

How to send spaces. Or i just can't use spaces in url?

Body:
TLDR: Use fixedEncodeURI() and fixedEncodeURIComponent()

MDN encodeURI() Documentation...

function fixedEncodeURI(str) {
   return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');
}

MDN encodeURIComponent() Documentation...

function fixedEncodeURIComponent(str) {
 return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
   return '%' + c.charCodeAt(0).toString(16);
 });
}

Why to Not Use encodeURI() and encodeURIComponent()

It is really not recommended to use encodeURI() and encodeURIComponent(), as they are insufficient to properly handle URI or URL encoding directly.  Just like at this piece...

'&message=' + encodeURIComponent(message) +

Let's say that the message var is set to this: "Hello, world! (Really hello!)".  So what is that evaluated to?

console.log('&message=' + encodeURIComponent("Hello, world! (Really hello!)"));

Output:

&message=Hello%2C%20world!%20(Really%20hello!)

That's not right!  Why weren't ( and ) encoded?  After all, according to RFC3986, Section 2.2: Reserved Characters...

If data for a URI component would conflict with a reserved character's purpose as a delimiter, then the conflicting data must be percent-encoded before the URI is formed.

sub-delims  = "!" / "$" / "&" / "'" / "(" / ")"  / "*" / "+" / "," / ";" / "="

Parens are a sub-delim, but they are not being escaped by encodeURI() or encodeURIComponent().


问:
openssl_cipher_iv_length error on php 7.4
how to fix openssl_cipher_iv_length error on php 7.4 its working normally on php 7.2?

```<code>    $key = pack('H*','5e4888f3b85db60b53303483581c2b42112788e5e1b2d18c45cf70b867ca0721');
    $method = 'aes-256-ecb';
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
    $encrypted = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
    $encrypted = strtoupper(implode(null, unpack('H*', $encrypted)));
    return $encrypted;
</code>```

in PHP 7.4 i get this error Fatal error: Uncaught Error: Length must be greater than 0

In Php 7.2 Everything is work

答:
We need add a condition in order to find out if $ivSize is greater than zero. If $ivSize will be return zero $iv will stay empty.

Here is fixed code for PHP 7.4 and newer.

```<code>$key = pack('H*','5e4888f3b85db60b53303483581c2b42112788e5e1b2d18c45cf70b867ca0721');
$method = 'aes-256-ecb';
$ivSize = openssl_cipher_iv_length($method);
$iv = '';
if ($ivSize > 0) {
    $iv = openssl_random_pseudo_bytes($ivSize);
}
$encrypted = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
$encrypted = strtoupper(implode(null, unpack('H*', $encrypted)));
return $encrypted;
</code>```

Body:
how to fix openssl_cipher_iv_length error on php 7.4 its working normally on php 7.2?

    $key = pack('H*','5e4888f3b85db60b53303483581c2b42112788e5e1b2d18c45cf70b867ca0721');
    $method = 'aes-256-ecb';
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
    $encrypted = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
    $encrypted = strtoupper(implode(null, unpack('H*', $encrypted)));
    return $encrypted;

in PHP 7.4 i get this error Fatal error: Uncaught Error: Length must be greater than 0

In Php 7.2 Everything is work

Body:
We need add a condition in order to find out if $ivSize is greater than zero. If $ivSize will be return zero $iv will stay empty.

Here is fixed code for PHP 7.4 and newer.

$key = pack('H*','5e4888f3b85db60b53303483581c2b42112788e5e1b2d18c45cf70b867ca0721');
$method = 'aes-256-ecb';
$ivSize = openssl_cipher_iv_length($method);
$iv = '';
if ($ivSize > 0) {
    $iv = openssl_random_pseudo_bytes($ivSize);
}
$encrypted = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
$encrypted = strtoupper(implode(null, unpack('H*', $encrypted)));
return $encrypted;


问:
createlink and unlink in contenteditable div
I am trying to create a text/html editor in javascript/Angular in which I am trying to create link and unlink a selected text from the contenteditable div.

here is my JSFiddle

function saveSelection() {
  if (window.getSelection) {
    const sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      var ranges = [];
      for (var i = 0, len = sel.rangeCount; i < len; ++i) {
        ranges.push(sel.getRangeAt(i));
      }
      return ranges;
    }
    return null;
  }
}

function restoreSelection(savedSel) {
  if (savedSel) {
    if (window.getSelection) {
      const sel = window.getSelection();
      sel.removeAllRanges();
      for (var i = 0, len = savedSel.length; i < len; ++i) {
        sel.addRange(savedSel[i]);
      }
    }
  }
}

function insertLink() {
  var savedSel = saveSelection();
  var url = document.getElementById("url").value;
  restoreSelection(savedSel);
  document.execCommand("createLink", false, url);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.editor {
  border: 2px solid black;
  width: 200px;
  height: 50px;
}</code>```

<input type="text" id="url" style="border: solid blue 1px" value=" http://" onblur="insertLink()" />```

I am trying to createlink on blur of input but document.execCommand not running in the input .

答:
let savedSel=''
function saveSelection() {
  if (window.getSelection) {
    const sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      var ranges = [];
      for (var i = 0, len = sel.rangeCount; i < len; ++i) {
        ranges.push(sel.getRangeAt(i));
      }
      savedSel=ranges;
      return;
    }
    savedSel=null;
  }
}

function restoreSelection() {
  if (savedSel) {
    if (window.getSelection) {
      const sel = window.getSelection();
      sel.removeAllRanges();
      for (var i = 0, len = savedSel.length; i < len; ++i) {
        sel.addRange(savedSel[i]);
      }
    }
  }
}
function insertLink(){
  var url = document.getElementById("url").value;
  restoreSelection(savedSel);
  document.execCommand("createLink", false, url);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.editor {
  border: 2px solid black;
  width: 200px;
  height: 50px;
}</code>```

<input type="text" id="url" style="border: solid blue 1px" value=" http://" onblur="insertLink()" />```

Body:
I am trying to create a text/html editor in javascript/Angular in which I am trying to create link and unlink a selected text from the contenteditable div.

here is my JSFiddle

function saveSelection() {
  if (window.getSelection) {
    const sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      var ranges = [];
      for (var i = 0, len = sel.rangeCount; i < len; ++i) {
        ranges.push(sel.getRangeAt(i));
      }
      return ranges;
    }
    return null;
  }
}

function restoreSelection(savedSel) {
  if (savedSel) {
    if (window.getSelection) {
      const sel = window.getSelection();
      sel.removeAllRanges();
      for (var i = 0, len = savedSel.length; i < len; ++i) {
        sel.addRange(savedSel[i]);
      }
    }
  }
}

function insertLink() {
  var savedSel = saveSelection();
  var url = document.getElementById("url").value;
  restoreSelection(savedSel);
  document.execCommand("createLink", false, url);
}

.editor {
  border: 2px solid black;
  width: 200px;
  height: 50px;
}

<input type="text" id="url" style="border: solid blue 1px" value=" http://" onblur="insertLink()" />

I am trying to createlink on blur of input but document.execCommand not running in the input .

Body:
let savedSel=''
function saveSelection() {
  if (window.getSelection) {
    const sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      var ranges = [];
      for (var i = 0, len = sel.rangeCount; i < len; ++i) {
        ranges.push(sel.getRangeAt(i));
      }
      savedSel=ranges;
      return;
    }
    savedSel=null;
  }
}

function restoreSelection() {
  if (savedSel) {
    if (window.getSelection) {
      const sel = window.getSelection();
      sel.removeAllRanges();
      for (var i = 0, len = savedSel.length; i < len; ++i) {
        sel.addRange(savedSel[i]);
      }
    }
  }
}
function insertLink(){
  var url = document.getElementById("url").value;
  restoreSelection(savedSel);
  document.execCommand("createLink", false, url);
}

.editor {
  border: 2px solid black;
  width: 200px;
  height: 50px;
}

<div contenteditable="true" class="editor" onblur="saveSelection()"></div>
<input type="text" id="url" style="border: solid blue 1px" value=" http://" onblur="insertLink()" />


问:
DDD Repository vs Factory, Am I rehydrating or creating?
We have an externally-owned SQL server with data that needs to be in our periodically ported into our team-owned (SQL) server.

The external and internal server share the same domain concepts but exist in very distinct forms. Transforming the object from its external form into our own domain form is a complicated process.

currently this is done like so:

Adapter queries External Db, use Automapper to map to DTO (Adapter lives in infra layer)

Adapter returns DTO to application layer (DTO defined in the app layer)

Factory constructs domain object from DTO and factory loads related domain aggregates to set navigation IDs + other properties (Factory lives in app layer)

Is it proper to consider the work here by the factory as really building a new object since it's really hydrating an object from an external source, and we add further (required) decorations? The Entity ID stays the same as its transformed.

However calling this a repository also feels wrong as there is more work than just a simple hydration from a single DB?

I'm still new to DDD so any and all inputs are appreciated!

答:
Your process is basically missing a layer and having an excessive mapping. What you should have is only 3 data models :

The source database model

The domain model

The destination database model

Your source and destination database models are entities (in the sense of EF, not DDD). They already are POCO/DTO, you don't need to map them to an intermediate model before converting them to domain model.

What your application should be doing is this :

Reading from the source database

Converting EF-entities to domain model

Validating some business rules

Converting domain model to destination EF-entities

Writing to the destination database

In order to do that, what I suggest you do is create an additional "contract" layer, in which you put assemblies for your EF models. You should have a single assembly for each database. I strongly suggest that these be generated using EF database-first tools. These assemblies will only contain EF models with db contexts used for databse read/write operations, and can be considered as an external service contract.

Your adapter layer will now basically act as a conversion layer between domain layer and contract layer. They will mainly consist of maps or factories, and repositories. In case of change in any database, you can simply regenerate the associated contract assembly and update any impacted adapter assembly (unless that change implies evolution in the domain model of course).

You entrypoint will be able to import your data by calling the source adapters repositories, which will query the source database and automap results to domain objects, then validate your business rules, and finally calling the destination adapters repositories, which will write into destination database after having automap domain objects to the destination EF-entities.


问:
flutter doctor is ok but this " No devices found with name or id matching 'emulator-5554' " show at my console
No devices found with name or id matching 'emulator-5554'
idk how to fix it ,flutter doctor is ok,but when I run my program on emulator at console show this " No devices found with name or id matching 'emulator-5554' "

```<code>C:\Users\athir>flutter doctor -v
[√] Flutter (Channel stable, 2.2.1, on Microsoft Windows [Version 10.0.19043.928], locale en-
US)
• Flutter version 2.2.1 at C:\flutter
• Framework revision 02c026b03c (2 weeks ago), 2021-05-27 12:24:44 -0700
• Engine revision 0fdb562ac8
• Dart version 2.13.1

[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
• Android SDK at \Users\athir\AppData\Local\Android\Sdk
• Platform android-30, build-tools 30.0.3
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6842174)
• All Android licenses accepted.

[√] Chrome - develop for the web
• Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe

[√] Android Studio
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin can be installed from:
   https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
   https://plugins.jetbrains.com/plugin/6351-dart
• android-studio-dir = C:\Program Files\Android\Android Studio
• Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6842174)

[√] Connected device (3 available)
• sdk gphone x86 arm (mobile) • emulator-5554 • android-x86    • Android 11 (API 30)
(emulator)
• Chrome (web)                • chrome        • web-javascript • Google Chrome 91.0.4472.101
• Edge (web)                  • edge          • web-javascript • Microsoft Edge 91.0.864.41

• No issues found!
</code>```

enter image description here

答:
Had a similar problem after updating iOS physical device.
Updating MacOS and XCode solved the problem</p>

Body:
No devices found with name or id matching 'emulator-5554'
idk how to fix it ,flutter doctor is ok,but when I run my program on emulator at console show this " No devices found with name or id matching 'emulator-5554' "

C:\Users\athir>flutter doctor -v
[√] Flutter (Channel stable, 2.2.1, on Microsoft Windows [Version 10.0.19043.928], locale en-
US)
• Flutter version 2.2.1 at C:\flutter
• Framework revision 02c026b03c (2 weeks ago), 2021-05-27 12:24:44 -0700
• Engine revision 0fdb562ac8
• Dart version 2.13.1

[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
• Android SDK at \Users\athir\AppData\Local\Android\Sdk
• Platform android-30, build-tools 30.0.3
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6842174)
• All Android licenses accepted.

[√] Chrome - develop for the web
• Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe

[√] Android Studio
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin can be installed from:
   https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
   https://plugins.jetbrains.com/plugin/6351-dart
• android-studio-dir = C:\Program Files\Android\Android Studio
• Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6842174)

[√] Connected device (3 available)
• sdk gphone x86 arm (mobile) • emulator-5554 • android-x86    • Android 11 (API 30)
(emulator)
• Chrome (web)                • chrome        • web-javascript • Google Chrome 91.0.4472.101
• Edge (web)                  • edge          • web-javascript • Microsoft Edge 91.0.864.41

• No issues found!

enter image description here


问:
Github workflow excluding paths does not work
I cannot get the Github workflow feature to exclude paths to work properly and could not find a similar problem on stack overflow. The most similar case is Github workflow does not trigger on push for path based filtering but it has not helped me.

I have the workflow for PRs below:

```<code>name: Build For PRs

on:
  pull_request:
    types: [opened, synchronize, ready_for_review]
    paths:
      - 'src/**'
      - '!src/abc/**'
      - '!src/def/**'
      - '!src/ghi/**'
      - '!src/docker-compose*.yml'
      - '!**.md'
</code>```

I want it to run on PR's when any file under "src" changes, except when one of the negative filters is a match.

Even changing a .md file triggers this WF. How can I achieve the logic above?

答:
The problem is that excluding paths doesn't work as you want by design.

When all the path names match patterns in paths-ignore, the workflow will not run, but if you have at least one file that doesn't fall under negations - workflow will still run.

So there is no way to stop workflow by this feature the way you want to do - to stop workflow when at least 1 file belong to excluded list.

I would recommend filtering changed files and then stopping workflow if you find any files matching your criteria and use https://github.com/tj-actions/changed-files/ instead.
With that action you will be able to check if any files are fitting your criteria and then you just stop the workflow.
Unfortunately it will start full workflow, create a runner and execute workflow itself.

Body:
I cannot get the Github workflow feature to exclude paths to work properly and could not find a similar problem on stack overflow. The most similar case is Github workflow does not trigger on push for path based filtering but it has not helped me.

I have the workflow for PRs below:

name: Build For PRs

on:
  pull_request:
    types: [opened, synchronize, ready_for_review]
    paths:
      - 'src/**'
      - '!src/abc/**'
      - '!src/def/**'
      - '!src/ghi/**'
      - '!src/docker-compose*.yml'
      - '!**.md'

I want it to run on PR's when any file under "src" changes, except when one of the negative filters is a match.

Even changing a .md file triggers this WF. How can I achieve the logic above?


问:
Python wordlist creation
So far I am creating a world based game the only thing I need help with is creating a wordlist without having to type each word or re formate hundreds into the correct formatting. Any tips?

so far I have this:

```<code>fiveLetterWords = ["abuse", "adult", "drama", "drain", "enemy", "entry", "catch", "could", "would", "track", "train", "plain", "plane"]
sixLetterWords = ["people", "things", "really", "abroad", "accept", "belief", "scraps", "trashy", "camera", "create"]
</code>```

I would like to have a few more words than this and if there's a site that has this listed in this format comment it thanks!

答:
These files are from the wordle game therefore only have 5 letter words.

Download the files from allowed guess list and
allowed answer list (by clicking download zip)
then unzipping them and putting them into the same directory as your script. You can run this to read in those words and use them as part of your wordle game.

```<code>def read_from_txt_file(filename):
    with open('wordle-allowed-guesses.txt', 'r') as file:
        file_list = [item[:-1] for item in file] # using [:-1] to get rid of the newline character
    return file_list

guess_list = read_from_txt_file('wordle-allowed-guesses.txt')
answer_list = read_from_txt_file('wordle-answers-alphabetical.txt')
</code>```

Title: Python wordlist creation

Body:
So far I am creating a world based game the only thing I need help with is creating a wordlist without having to type each word or re formate hundreds into the correct formatting. Any tips?

so far I have this:

fiveLetterWords = ["abuse", "adult", "drama", "drain", "enemy", "entry", "catch", "could", "would", "track", "train", "plain", "plane"]
sixLetterWords = ["people", "things", "really", "abroad", "accept", "belief", "scraps", "trashy", "camera", "create"]

I would like to have a few more words than this and if there's a site that has this listed in this format comment it thanks!

Body:
These files are from the wordle game therefore only have 5 letter words.

Download the files from allowed guess list and
allowed answer list (by clicking download zip)
then unzipping them and putting them into the same directory as your script. You can run this to read in those words and use them as part of your wordle game.

def read_from_txt_file(filename):
    with open('wordle-allowed-guesses.txt', 'r') as file:
        file_list = [item[:-1] for item in file] # using [:-1] to get rid of the newline character
    return file_list

guess_list = read_from_txt_file('wordle-allowed-guesses.txt')
answer_list = read_from_txt_file('wordle-answers-alphabetical.txt')


问:
GAS-built telegram bot: catching replies to bot
I wrote an bot on GAS to read from / write to a google sheet from telegram. I use the webhook method. I can address the bot with /read <args> and /write <args>. However, the less tech-savvy are not able to understand the principle of arguments...
So I want to make a conversational bot, like botfather. eg, if /read or /write are sent, then the bot ask in pm for the arguments, one by one.
The "reply in PM" part is easy, but I don't see how I can catch replies for arguments?

As far as I understand, the function doPost is called each time a command is sent to the bot which poses issues of interactivity, and requiring a slash-something command to run the script instead of a plain text reply (and as the GAS data is volatile, the ugly work-around of storing a variable to know the bot should do the 2nd action is impossible too).

Is it feasible with webhook method?

Should I switch to polling / getUpdates method? I'm guessing it could work that way,  with a time-out to exit the script in case of no reply, but I'm also guessing the PM chat should be set to 'no privacy' mode. or maybe it is intrinsic to the bot?

Any help appreciated!

答:
So, GAS does offer a not-so volatile storage: CacheService.getScriptCache() (see also https://developers.google.com/apps-script/reference/cache/cache)

The principle is simple: store the variable you want persistent in the cache (optionally, set a time out too - the default is 10min), and get the values when the script is called again. I found out that project that helped me understand how to use it: https://github.com/Milleus/tessara/blob/master/Code.gs

In a few words: the syntax is cache.put(key, value) to store the value, and value=cache.get(key) to fetch it back.

The beauty of it is that all required variables (if more than one) can be stored in an object, the key can be a unique identifier for the "user", and the value is the stringified object.

In my case, I was able to build a fully conversational telegram bot (exactly like BotFather, but for my usage). Using the id from the person sending messages to the bot as the key, the script can run in "parallel" for multiple users at once.


问:
The Uninstall section of my .INF
I'm working on extending an existing USB device driver, and have been struggling learn how the .INF file works.  I believe that I have it right now, the driver installs and works.  It also shows up in the "Add/Remove Programs" list.

I find that when I uninstall the driver from Add/Remove, it seems to do little if anything.  This was in the .INF as I inherited it:

```<code>[myUninstall]
DelReg = myDelReg

[MyDelReg]
HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\myName"
</code>```

I can find no other references, not even where "myName" is installed in the registry Uninstall.

I've changed the .INF to have this:

```<code>[DefaultUninstall]
myUninstall

[myUninstall]
DelFiles = ... a list of files ...
DelDirs  = UNINST.Dirs
DelReg   = UNINST.Regs
Cleanup  = 1

[UNINST.Dirs]
%16422%\%InstallDir%

[UNINST.Regs]
myDev.AddReg
myDev.CommonRegs

[myDev.AddReg]      ; same definition used for installing
HKR,,Drivers,Subclasses,,"wave,midi,mixer,aux"
...

[myDev,CommonRegs]  ; same definition used for installing
HKR, Parameters, BufferSize, 0x0010001, 256
...
</code>```

Still, whether I uninstall from the Control Panel Add/Remove programs or do it from the device manager, the system doesn't complain and nothing seems to happen.  I've looked at the output of "dpinst /c" and the setupapi.log, and neither tell me much.  dpinst shows no error but is clearly not even trying to execute my uninstall section.

I find a lot of verbiage online and examples of uninstall sections, but very little in the way of explanation.  I did stumble across one sentence in 1 forum today that implied that PnP device .INF's don't use Uninstall.  Perhaps this is my issue?

am I wrong in thinking that I can have Uninstall in this .INF?

is there some other way to tell what is happening?

is my only recourse to write a separate uninstaller?

答:
I don't think DefaultUninstall is a standard section in the way DefaultInstall is. Often you will see the UninstallString ARP entry just calling DefaultUninstall by name.

The documentation in this area is pretty bad and there is a split between the basic SetupAPI/SetupX INF files and the Advanced INF files (AdvPack).

The only 3rd-party exception I know of is TweakUI.inf from the Windows 95 PowerToys.

It has parts that look like this:

```<code>...

[Optional Components]
TweakUIInstall

[TweakUIInstall]
CopyFiles = ...
AddReg    = ...
Ini2Reg   = ...
...
InstallType    = 10 ;Typical, Custom.
Uninstall      = DefaultUnInstall

[DefaultUnInstall]
DelFiles  = ...
DelReg    = ...
</code>```

But I think that only works with the optional components feature, not basic uninstallation. TweakUI v1.33 (Tweakui.exe SFX archive) has some more NT related entries and I believe the way it writes the UninstallString for NT even writes the wrong INF section. Wrong or not, it manually has to specify a INF section for normal uninstall.

Title: The Uninstall section of my .INF

Body:
I'm working on extending an existing USB device driver, and have been struggling learn how the .INF file works.  I believe that I have it right now, the driver installs and works.  It also shows up in the "Add/Remove Programs" list.

I find that when I uninstall the driver from Add/Remove, it seems to do little if anything.  This was in the .INF as I inherited it:

[myUninstall]
DelReg = myDelReg

[MyDelReg]
HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\myName"

I can find no other references, not even where "myName" is installed in the registry Uninstall.

I've changed the .INF to have this:

[DefaultUninstall]
myUninstall

[myUninstall]
DelFiles = ... a list of files ...
DelDirs  = UNINST.Dirs
DelReg   = UNINST.Regs
Cleanup  = 1

[UNINST.Dirs]
%16422%\%InstallDir%

[UNINST.Regs]
myDev.AddReg
myDev.CommonRegs

[myDev.AddReg]      ; same definition used for installing
HKR,,Drivers,Subclasses,,"wave,midi,mixer,aux"
...

[myDev,CommonRegs]  ; same definition used for installing
HKR, Parameters, BufferSize, 0x0010001, 256
...

Still, whether I uninstall from the Control Panel Add/Remove programs or do it from the device manager, the system doesn't complain and nothing seems to happen.  I've looked at the output of "dpinst /c" and the setupapi.log, and neither tell me much.  dpinst shows no error but is clearly not even trying to execute my uninstall section.

I find a lot of verbiage online and examples of uninstall sections, but very little in the way of explanation.  I did stumble across one sentence in 1 forum today that implied that PnP device .INF's don't use Uninstall.  Perhaps this is my issue?

am I wrong in thinking that I can have Uninstall in this .INF?

is there some other way to tell what is happening?

is my only recourse to write a separate uninstaller?

Body:
I don't think DefaultUninstall is a standard section in the way DefaultInstall is. Often you will see the UninstallString ARP entry just calling DefaultUninstall by name.

The documentation in this area is pretty bad and there is a split between the basic SetupAPI/SetupX INF files and the Advanced INF files (AdvPack).

The only 3rd-party exception I know of is TweakUI.inf from the Windows 95 PowerToys.

It has parts that look like this:

...

[Optional Components]
TweakUIInstall

[TweakUIInstall]
CopyFiles = ...
AddReg    = ...
Ini2Reg   = ...
...
InstallType    = 10 ;Typical, Custom.
Uninstall      = DefaultUnInstall

[DefaultUnInstall]
DelFiles  = ...
DelReg    = ...

But I think that only works with the optional components feature, not basic uninstallation. TweakUI v1.33 (Tweakui.exe SFX archive) has some more NT related entries and I believe the way it writes the UninstallString for NT even writes the wrong INF section. Wrong or not, it manually has to specify a INF section for normal uninstall.


问:
How to do a OR in a c:if statement in jsp
How do I properly declare a or statement i try this without success:

<c:forEach var="route" items="${map.street}">
<c:if test="${route.value.type == 'road' || route.value.type == 'street'}">

答:
Bitwise inclusive OR  --> |

Logical OR --> ||

So...

```<code>if ( true || false )
{
    /* the first expression is evaluated, it is true, we enter the 'if' block */
}

int i = 1 | 0;  /* i == 1 */
</code>```

OwnerDisplayName: JorgeO

ContentLicense: CC BY-SA 2.5

Body:
Bitwise inclusive OR  --> |

Logical OR --> ||

So...

if ( true || false )
{
    /* the first expression is evaluated, it is true, we enter the 'if' block */
}

int i = 1 | 0;  /* i == 1 */

OwnerDisplayName: Ed Swangren

LastEditorDisplayName: Ed Swangren


问:
select * only return one value
I want select multiple (all) values from table Account.

```<code>string query = "SELECT * FROM Account";
        SqlConnection connection = new SqlConnection(connectionString);
        SqlCommand command = new SqlCommand(query, connection);
        SqlDataReader reader;
        connection.Open();
        reader = command.ExecuteReader();
        reader.Read();
        label1.Text = reader["PasswordHash"].ToString();
        connection.Close();
</code>```

Why is this always returning only the first row. Actually it return one row, because if I set in where clause something like where id = 2 and id = 3 it still returns only one value.
Table have more than one value i checked form Management Studio, there query run as they should.

Thanks in advance.

答:
The reader only advances one record at a time. You'd need to iterate through the result set in a loop:

```<code>while (reader.Read()) {
    // do something with the current row by accessing reader[]
}
reader.Close();
</code>```

There are better ways to structure your code but this illustrates the point you were missing and requires the least changes.

Title: select * only return one value

Body:
I want select multiple (all) values from table Account.

string query = "SELECT * FROM Account";
        SqlConnection connection = new SqlConnection(connectionString);
        SqlCommand command = new SqlCommand(query, connection);
        SqlDataReader reader;
        connection.Open();
        reader = command.ExecuteReader();
        reader.Read();
        label1.Text = reader["PasswordHash"].ToString();
        connection.Close();

Why is this always returning only the first row. Actually it return one row, because if I set in where clause something like where id = 2 and id = 3 it still returns only one value.
Table have more than one value i checked form Management Studio, there query run as they should.

Thanks in advance.

Body:
The reader only advances one record at a time. You'd need to iterate through the result set in a loop:

while (reader.Read()) {
    // do something with the current row by accessing reader[]
}
reader.Close();

There are better ways to structure your code but this illustrates the point you were missing and requires the least changes.


问:
xdpoffload attach failed: Invalid argument
When I try to attach a BPF program in XDP offload mode, I get Invalid argument. I get the same error if attach through code or by using bpftool. Here's how I'm attaching using netlink:

```<code>err = netlink.LinkSetXdpFdWithFlags(link, objects.CollectIpsProg.FD(), 8)
</code>```

And from using bpftool:

```<code># bpftool prog loadall collect_ips.o /sys/fs/bpf/collect_ips type xdp
# bpftool net attach xdpoffload id 106 dev public
Error: interface xdpoffload attach failed: Invalid argument
</code>```

I don't have any issues loading the program in driver mode, where 4 is passed to LinkSetXdpFdWithFlags.

My NIC, Mellanox MT28800 Family [ConnectX-5 Ex], should support HW offload.

My main XDP program makes calls to two different tail programs. I use BPF_MAP_TYPE_RINGBUF, BPF_MAP_TYPE_PROG_ARRAY, and BPF_MAP_TYPE_ARRAY.

答:
Mellanox cards support some hardware offload (e.g., flow control rules), but not the offload of BPF programs as far as I know. The only Ethernet adapters out there that support BPF offloading are Netronome's cards.

One way to check this is to grep for the XDP_SETUP_PROG_HW BPF netdev command in the Linux source code:

```<code>$ git grep XDP_SETUP_PROG_HW
drivers/net/ethernet/netronome/nfp/nfp_net_common.c:    case XDP_SETUP_PROG_HW:
drivers/net/netdevsim/bpf.c:    if (bpf->command == XDP_SETUP_PROG_HW && !ns->bpf_xdpoffload_accept) {
drivers/net/netdevsim/bpf.c:    if (bpf->command == XDP_SETUP_PROG_HW) {
drivers/net/netdevsim/bpf.c:    case XDP_SETUP_PROG_HW:
include/linux/netdevice.h:      XDP_SETUP_PROG_HW,
net/core/dev.c: xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
</code>```

That command is used to tell the driver to offload the BPF program to the hardware, via the ndo_bpf callback function.

Body:
When I try to attach a BPF program in XDP offload mode, I get Invalid argument. I get the same error if attach through code or by using bpftool. Here's how I'm attaching using netlink:

err = netlink.LinkSetXdpFdWithFlags(link, objects.CollectIpsProg.FD(), 8)

And from using bpftool:

# bpftool prog loadall collect_ips.o /sys/fs/bpf/collect_ips type xdp
# bpftool net attach xdpoffload id 106 dev public
Error: interface xdpoffload attach failed: Invalid argument

I don't have any issues loading the program in driver mode, where 4 is passed to LinkSetXdpFdWithFlags.

My NIC, Mellanox MT28800 Family [ConnectX-5 Ex], should support HW offload.

My main XDP program makes calls to two different tail programs. I use BPF_MAP_TYPE_RINGBUF, BPF_MAP_TYPE_PROG_ARRAY, and BPF_MAP_TYPE_ARRAY.

Body:
Mellanox cards support some hardware offload (e.g., flow control rules), but not the offload of BPF programs as far as I know. The only Ethernet adapters out there that support BPF offloading are Netronome's cards.

One way to check this is to grep for the XDP_SETUP_PROG_HW BPF netdev command in the Linux source code:

$ git grep XDP_SETUP_PROG_HW
drivers/net/ethernet/netronome/nfp/nfp_net_common.c:    case XDP_SETUP_PROG_HW:
drivers/net/netdevsim/bpf.c:    if (bpf->command == XDP_SETUP_PROG_HW && !ns->bpf_xdpoffload_accept) {
drivers/net/netdevsim/bpf.c:    if (bpf->command == XDP_SETUP_PROG_HW) {
drivers/net/netdevsim/bpf.c:    case XDP_SETUP_PROG_HW:
include/linux/netdevice.h:      XDP_SETUP_PROG_HW,
net/core/dev.c: xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;

That command is used to tell the driver to offload the BPF program to the hardware, via the ndo_bpf callback function.


问:
Android. Repository with global lifecycle
I have a repository where a chain of network requests is calling. The repository is accessed from the interactor. And interactor is accessed from  viewModel. The view model is attached to activity A. If I go to activity B, which has its own viewModel, then the request chain in the repository of activity A does not complete its execution.

Is it possible to make a repository whose life cycle will be equal to the life cycle of the application. I need all requests to complete even if I go to a new activity.

Please, help me.

答:
You should create a singleton Repository class, then access its instance anywhere you want.

```<code>object Repository {
    val instance: Repository
        get() {
            return this
        }
}
</code>```

You can create create its object in ViewModel for A and create object in ViewModel for B.
Both will have same instance for Repository class, so in this way you can achieve what you need.

Body:
You should create a singleton Repository class, then access its instance anywhere you want.

object Repository {
    val instance: Repository
        get() {
            return this
        }
}

You can create create its object in ViewModel for A and create object in ViewModel for B.
Both will have same instance for Repository class, so in this way you can achieve what you need.