问:
Python library function to approximate a set of 2D points with a straight line
Given an array with [x, y] points, e.g.:

```<code>p0 = np.random.rand(21, 2)
p1 = np.array([[0, 0], [0, 1], [0, 2], [0, 3]])
</code>```

I would like to get a straight line [segment] approximation of these points. Least squares method is acceptable, other error functions may be fine too. Note that the set of points in general is not a function, i.e. as shown above in p1, there are multiple y values associated with x = 0.

There is no slope, intercept solution for a vertical set of points, e.g. p1, therefore np.polyfit, scipy.stats.linregress are not solutions I'm looking for. Think geometry, not statistics.

答:
Maybe I'm missing something, but since you're already using Numpy, why not just use its polyfit function?

```<code>def fit_line(points):
    r = np.polyfit([p[0] for p in points], [p[1] for p in points], 1)
    print(f"y = {r[0]:.2f}x + {r[1]:.2f}")

fit_line(np.random.rand(21, 2))
# fit_line(np.array([[0, 0], [0, 1], [0, 2], [0, 3]]))
fit_line(np.array([[0, 3], [1, 4], [2, 5], [3, 6]]))
</code>```

Result:

```<code>y = 0.20x + 0.51  (different each run)
y = 1.00x + 3.00
</code>```

As you note, the second example is a degenerate case with no slope-intercept form and so polyfit throws an exception.  You could catch the exception to deal with that case.  Unfortunately, the library also outputs a bunch of crap to stdout in the degenerate case, making catching the exception less than ideal by itself.  For this reason, I chose to not demonstrate catching the exception but instead just commented out that case.

Body:
Given an array with [x, y] points, e.g.:

p0 = np.random.rand(21, 2)
p1 = np.array([[0, 0], [0, 1], [0, 2], [0, 3]])

I would like to get a straight line [segment] approximation of these points. Least squares method is acceptable, other error functions may be fine too. Note that the set of points in general is not a function, i.e. as shown above in p1, there are multiple y values associated with x = 0.

There is no slope, intercept solution for a vertical set of points, e.g. p1, therefore np.polyfit, scipy.stats.linregress are not solutions I'm looking for. Think geometry, not statistics.

Body:
Maybe I'm missing something, but since you're already using Numpy, why not just use its polyfit function?

def fit_line(points):
    r = np.polyfit([p[0] for p in points], [p[1] for p in points], 1)
    print(f"y = {r[0]:.2f}x + {r[1]:.2f}")

fit_line(np.random.rand(21, 2))
# fit_line(np.array([[0, 0], [0, 1], [0, 2], [0, 3]]))
fit_line(np.array([[0, 3], [1, 4], [2, 5], [3, 6]]))

Result:

y = 0.20x + 0.51  (different each run)
y = 1.00x + 3.00

As you note, the second example is a degenerate case with no slope-intercept form and so polyfit throws an exception.  You could catch the exception to deal with that case.  Unfortunately, the library also outputs a bunch of crap to stdout in the degenerate case, making catching the exception less than ideal by itself.  For this reason, I chose to not demonstrate catching the exception but instead just commented out that case.


来源: stackexchange

问:
Decode a prepended VarInt from a byte stream of unknown size in javascript/Nodejs
I am writing a small utility library for me to request server status of a given minecraft host in js on node. I am using the Server List Ping Protocol as outlined here (https://wiki.vg/Server_List_Ping) and got it mostly working as expected, albeit having big trouble working with unsupported Data Types (VarInt) and had to scour the internet to find a way of converting js nums into VarInts in order to craft the necessary packet buffers:

```<code>function toVarIntBuffer(integer) {
    let buffer = Buffer.alloc(0);
    while (true) {
        let tmp = integer & 0b01111111;
        integer >>>= 7;
        if (integer != 0) {
            tmp |= 0b10000000;
        }
        buffer = Buffer.concat([buffer, Buffer.from([tmp])]);
        if (integer <= 0) break;
    }
    return buffer;
}
</code>```

Right now I am able to request a server status by sending the handshake packet and then the query packet and do receive a JSON response with the length of the response prepended as a VarInt.

However the issue is here, where I simply don't know how to safely identify the VarInt from the beginning of the JSON response (as it can be anywhere up to 5 byte) and decode it back to a readable num so I can get the proper length of the response byte stream.

[...] as with all strings this is prefixed by its length as a VarInt

(from the protocol documentation)

My current super hacky workaround is to concatenate the chunks as String until the concatenated string contains the same count of '{'s and '}'s (meaning a full json object) and slice the json response at the first '{' before parsing it.

However I am very unhappy with this hacky, inefficient, unelegant and possibly unreliable way of solving the issue and would rather decode the VarInt in front of the JSON response in order to get a proper length to compare against.

答:
Thanks to the reference material that @thst pointed me to, I was able to slap together a working way of reading VarInts in javascript.

```<code>function readVarInt(buffer) {
    let value = 0;
    let length = 0;
    let currentByte;

    while (true) {
        currentByte = buffer[length];
        value |= (currentByte & 0x7F) << (length * 7);
        length += 1;
        if (length > 5) {
            throw new Error('VarInt exceeds allowed bounds.');
        }
        if ((currentByte & 0x80) != 0x80) break;
    }
    return value;
}
</code>```

buffer must be a byte stream starting with the VarInt, ideally using the std Buffer class.

ContentLicense: CC BY-SA 4.0

Body:
I am writing a small utility library for me to request server status of a given minecraft host in js on node. I am using the Server List Ping Protocol as outlined here (https://wiki.vg/Server_List_Ping) and got it mostly working as expected, albeit having big trouble working with unsupported Data Types (VarInt) and had to scour the internet to find a way of converting js nums into VarInts in order to craft the necessary packet buffers:

function toVarIntBuffer(integer) {
    let buffer = Buffer.alloc(0);
    while (true) {
        let tmp = integer & 0b01111111;
        integer >>>= 7;
        if (integer != 0) {
            tmp |= 0b10000000;
        }
        buffer = Buffer.concat([buffer, Buffer.from([tmp])]);
        if (integer <= 0) break;
    }
    return buffer;
}

Right now I am able to request a server status by sending the handshake packet and then the query packet and do receive a JSON response with the length of the response prepended as a VarInt.

However the issue is here, where I simply don't know how to safely identify the VarInt from the beginning of the JSON response (as it can be anywhere up to 5 byte) and decode it back to a readable num so I can get the proper length of the response byte stream.

[...] as with all strings this is prefixed by its length as a VarInt

(from the protocol documentation)

My current super hacky workaround is to concatenate the chunks as String until the concatenated string contains the same count of '{'s and '}'s (meaning a full json object) and slice the json response at the first '{' before parsing it.

However I am very unhappy with this hacky, inefficient, unelegant and possibly unreliable way of solving the issue and would rather decode the VarInt in front of the JSON response in order to get a proper length to compare against.

Body:
Thanks to the reference material that @thst pointed me to, I was able to slap together a working way of reading VarInts in javascript.

function readVarInt(buffer) {
    let value = 0;
    let length = 0;
    let currentByte;

    while (true) {
        currentByte = buffer[length];
        value |= (currentByte & 0x7F) << (length * 7);
        length += 1;
        if (length > 5) {
            throw new Error('VarInt exceeds allowed bounds.');
        }
        if ((currentByte & 0x80) != 0x80) break;
    }
    return value;
}

buffer must be a byte stream starting with the VarInt, ideally using the std Buffer class.


问:
Trouble debugging - VSCode - configuring JSON - Program path is missing or invalid
I am having trouble getting the F5 debugger to work properly.

I have been trying to follow the Microsoft tutorial to get things going, but after building successfully the debugging process never really works out the way it should.

When I use the Ctrl + Shift + B command to build, it successfully creates a main.exe file, but I cannot change the launch.json file in a way that works hand-in-hand.

While tasks.json has this
"-o","${fileDirname}\\${fileBasenameNoExtension}.exe" as the object path/name, 'main.cpp' is compiled into main.exe.

So, initially, I had tried to set launch.json to have program": ${fileDirname}\\${fileBasenameNoExtension}.exe.  Which would be neat and effective, matching the build file that would be produced.

I get this error:

Next, I tried to change launch.json to run as a.exe hardcoded. In the PS terminal within VSCode, I ran g++ .\main.cpp and produced an a.exe file.  Which successfully allows F5 debugging giving me an exit code '0' in the debug console when I changed launch.json to have "program": "${workspaceFolder}\\a.exe".

I have also tried to use ${workspaceFolder}\\${fileBasenameNoExtension}.exe with no luck.

It makes no logical sense to me that the same parameters for cwd with the same object name in tasks won't run successfully for debugging in launch.

The entire tasks.json:

```<code>{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: cpp.exe build active file",
            "command": "C:\\msys64\\mingw64\\bin\\cpp.exe",
            "args": [
                "-fdiagnostics-color=always",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "compiler: C:\\msys64\\mingw64\\bin\\cpp.exe"
        }
    ]
}
</code>```

The entire launch.json:

```<code>{
    "configurations": [
    {
        "name": "(gdb) Launch",
        "type": "cppdbg",
        "request": "launch",
        "program": "${workspaceFolder}\\a.exe",
        "args": [],
        "stopAtEntry": false,
        "cwd": "${fileDirname}",
        "environment": [],
        "externalConsole": false,
        "MIMode": "gdb",
        "miDebuggerPath": "C:\\msys64\\mingw64\\bin\\gdb.exe",
        "setupCommands": [
            {
                "description": "Enable pretty-printing for gdb",
                "text": "-enable-pretty-printing",
                "ignoreFailures": true
            },
            {
                "description":  "Set Disassembly Flavor to Intel",
                "text": "-gdb-set disassembly-flavor intel",
                "ignoreFailures": true
            }
        ]
    }
    ]
}
</code>```

Could someone please take a look for me?  This is infuriating..  Thanks in advance!

答:
I figured out the problem. Hopefully will help someone else, too.

First I updated the architecture portion of the options for launch.json - not relevant to the file-path issue, but figured I would mention.  Add "targetArchitecture": "x64"(or the 32bit option if necessary) to the tasks.json file.

==================================================================

Solution: After fiddling around a bit I have found that tasks.json was the issue, not launch.json. After a good amount of confusion I took a break and came back to the problem and noticed that tasks was running cpp.exe to build the file. Out of curiosity I replaced it with g++.exe and voilà - it works.

So, if you have issues with using F5 in VSCode with MinGW for compiling/debugging - ensure that g++.exe is compiling. At least from my limited knowledge, that should fix the issue if you are running VSCode and using MinGW for building/debugging.

Body:
I am having trouble getting the F5 debugger to work properly.

I have been trying to follow the Microsoft tutorial to get things going, but after building successfully the debugging process never really works out the way it should.

When I use the Ctrl + Shift + B command to build, it successfully creates a main.exe file, but I cannot change the launch.json file in a way that works hand-in-hand.

While tasks.json has this
"-o","${fileDirname}\\${fileBasenameNoExtension}.exe" as the object path/name, 'main.cpp' is compiled into main.exe.

So, initially, I had tried to set launch.json to have program": ${fileDirname}\\${fileBasenameNoExtension}.exe.  Which would be neat and effective, matching the build file that would be produced.

I get this error:

Next, I tried to change launch.json to run as a.exe hardcoded. In the PS terminal within VSCode, I ran g++ .\main.cpp and produced an a.exe file.  Which successfully allows F5 debugging giving me an exit code '0' in the debug console when I changed launch.json to have "program": "${workspaceFolder}\\a.exe".

I have also tried to use ${workspaceFolder}\\${fileBasenameNoExtension}.exe with no luck.

It makes no logical sense to me that the same parameters for cwd with the same object name in tasks won't run successfully for debugging in launch.

The entire tasks.json:

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: cpp.exe build active file",
            "command": "C:\\msys64\\mingw64\\bin\\cpp.exe",
            "args": [
                "-fdiagnostics-color=always",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "compiler: C:\\msys64\\mingw64\\bin\\cpp.exe"
        }
    ]
}

The entire launch.json:

{
    "configurations": [
    {
        "name": "(gdb) Launch",
        "type": "cppdbg",
        "request": "launch",
        "program": "${workspaceFolder}\\a.exe",
        "args": [],
        "stopAtEntry": false,
        "cwd": "${fileDirname}",
        "environment": [],
        "externalConsole": false,
        "MIMode": "gdb",
        "miDebuggerPath": "C:\\msys64\\mingw64\\bin\\gdb.exe",
        "setupCommands": [
            {
                "description": "Enable pretty-printing for gdb",
                "text": "-enable-pretty-printing",
                "ignoreFailures": true
            },
            {
                "description":  "Set Disassembly Flavor to Intel",
                "text": "-gdb-set disassembly-flavor intel",
                "ignoreFailures": true
            }
        ]
    }
    ]
}

Could someone please take a look for me?  This is infuriating..  Thanks in advance!


问:
Using Dynamically-Sizing Tab View Nested in Scrollview in Flutter
I'm trying to nest a tabview in a Scrollview, and can't find a good way to accomplish the task.

A diagram is included below:

The desired functionality is to have a normal scrollable page, where one of the slivers is a tab view with different sized (and dynamically resizing) tabs.

Unfortunately, despite looking at several resources and the flutter docs, I haven't come across any good solutions.

Here is what I have tried:

SingleChildScrollView with a column child, with the TabBarView wrapped in an IntrinsicHeight widget (Unbound constraints)

CustomScrollView variations, with the TabBarView wrapped in a SliverFillRemaining and the header and footer each wrapped with a SliverToBoxAdapter. In all cases, the content is forced to expand to the full size of the viewport (as if using a SliverFillViewport Sliver with a viewport fraction of 1.0) if smaller, or a nested scroll/overflow is created within the space if larger (see below)

If the children of the TabBarView are scrollable widgets, the sliver with the tab bar is given a height equal to the ViewPort (1.0) and any leftover space is empty.

If the children are not scrollable, they are force-expanded to fit if smaller, or give an overflow error if larger.

NestedScrollView comes closest but still suffers the ill effects of the previous implementation (see below for code example)

Various other unorthodox approaches (such as removing the TabBarView and trying to use an AnimatedSwitcher in conjunction with a listener on the TabBar to animate between the "tabs" but this wasn't swipable and the animation janked and the switched widgets overlapped)

The thus-far "best" implementation's code is given below, but it is not ideal.

Does anyone know of any way(s) to accomplish this?

Thank you in advance.

// best (more "Least-bad") solution code
import 'package:flutter/material.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: 'Demo',
      routes: {
        'root': (context) => const Scaffold(
              body: ExamplePage(),
            ),
      },
      initialRoute: 'root',
    );
  }
}

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

  @override
  State<ExamplePage> createState() => _ExamplePageState();
}

class _ExamplePageState extends State<ExamplePage>
    with TickerProviderStateMixin {
  late TabController tabController;

  @override
  void initState() {
    super.initState();
    tabController = TabController(length: 2, vsync: this);
    tabController.addListener(() {
      setState(() {});
    });
  }

  @override
  void dispose() {
    tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        resizeToAvoidBottomInset: true,
        backgroundColor: Colors.grey[100],
        appBar: AppBar(),
        body: NestedScrollView(
          floatHeaderSlivers: false,
          physics: const AlwaysScrollableScrollPhysics(),
          headerSliverBuilder: (BuildContext context, bool value) => [
            SliverToBoxAdapter(
              child: Padding(
                padding: const EdgeInsets.only(
                  left: 16.0,
                  right: 16.0,
                  bottom: 24.0,
                  top: 32.0,
                ),
                child: Column(
                  children: [
                    // TODO: Add scan tab thing
                    Container(
                      height: 94.0,
                      width: double.infinity,
                      color: Colors.blueGrey,
                      alignment: Alignment.center,
                      child: Text('A widget with information'),
                    ),
                    const SizedBox(height: 24.0),
                    GenaricTabBar(
                      controller: tabController,
                      tabStrings: const [
                        'Tab 1',
                        'Tab 2',
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
          body: CustomScrollView(
            slivers: [
              SliverFillRemaining(
                child: TabBarView(
                  physics: const AlwaysScrollableScrollPhysics(),
                  controller: tabController,
                  children: [
                    // Packaging Parts
                    SingleChildScrollView(
                      child: Container(
                        height: 200,
                        color: Colors.black,
                      ),
                    ),
                    // Symbols
                    SingleChildScrollView(
                      child: Column(
                        children: [
                          Container(
                            color: Colors.red,
                            height: 200.0,
                          ),
                          Container(
                            color: Colors.orange,
                            height: 200.0,
                          ),
                          Container(
                            color: Colors.amber,
                            height: 200.0,
                          ),
                          Container(
                            color: Colors.green,
                            height: 200.0,
                          ),
                          Container(
                            color: Colors.blue,
                            height: 200.0,
                          ),
                          Container(
                            color: Colors.purple,
                            height: 200.0,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              SliverToBoxAdapter(
                child: ElevatedButton(
                  child: Text('Button'),
                  onPressed: () => print('pressed'),
                ),
              ),
            ],
          ),
        ),
      );
}

class GenaricTabBar extends StatelessWidget {
  final TabController? controller;
  final List<String> tabStrings;

  const GenaricTabBar({
    Key? key,
    this.controller,
    required this.tabStrings,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) => Container(
        decoration: BoxDecoration(
          color: Colors.grey,
          borderRadius: BorderRadius.circular(8.0),
        ),
        padding: const EdgeInsets.all(4.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // if want tab-bar, uncomment
            TabBar(
              controller: controller,
              indicator: ShapeDecoration.fromBoxDecoration(
                BoxDecoration(
                  borderRadius: BorderRadius.circular(6.0),
                  color: Colors.white,
                ),
              ),
              tabs: tabStrings
                  .map((String s) => _GenaricTab(tabString: s))
                  .toList(),
            ),
          ],
        ),
      );
}

class _GenaricTab extends StatelessWidget {
  final String tabString;

  const _GenaricTab({
    Key? key,
    required this.tabString,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) => Container(
        child: Text(
          tabString,
          style: const TextStyle(
            color: Colors.black,
          ),
        ),
        height: 32.0,
        alignment: Alignment.center,
      );
}
```

The above works in Dartpad (dartpad.dev) and doesn't require any external libraries

答:
Ideally, there is a better answer out there somewhere. BUT, until it arrives, this is how I got around the issue:

import 'package:flutter/material.dart';
import 'package:flutter/rendering.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: 'Demo',
      // darkTheme: Themes.darkTheme,
      // Language support
      // Routes will keep track of all of the possible places to go.
      routes: {
        'root': (context) => const Scaffold(
              body: ExamplePage(),
            ),
      },
      initialRoute: 'root', // See below.
    );
  }
}

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

  @override
  State<ExamplePage> createState() => _ExamplePageState();
}

class _ExamplePageState extends State<ExamplePage>
    with TickerProviderStateMixin {
  late TabController tabController;
  late PageController scrollController;
  late int _pageIndex;

  @override
  void initState() {
    super.initState();
    _pageIndex = 0;
    tabController = TabController(length: 2, vsync: this);
    scrollController = PageController();
    tabController.addListener(() {
      if (_pageIndex != tabController.index) {
        animateToPage(tabController.index);
      }
    });
  }

  void animateToPage([int? target]) {
    if (target == null || target == _pageIndex) return;
    scrollController.animateToPage(
      target,
      duration: const Duration(milliseconds: 250),
      curve: Curves.easeInOut,
    );
    setState(() {
      _pageIndex = target;
    });
  }

  void animateTabSelector([int? target]) {
    if (target == null || target == tabController.index) return;
    tabController.animateTo(
      target,
      duration: const Duration(
        milliseconds: 100,
      ),
    );
  }

  @override
  void dispose() {
    tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        resizeToAvoidBottomInset: true,
        backgroundColor: Colors.grey[100],
        appBar: AppBar(),
        body: CustomScrollView(
          slivers: [
            SliverToBoxAdapter(
              child: Padding(
                padding: const EdgeInsets.only(
                  left: 16.0,
                  right: 16.0,
                  bottom: 24.0,
                  top: 32.0,
                ),
                child: Column(
                  children: [
                    // TODO: Add scan tab thing
                    Container(
                      height: 94.0,
                      width: double.infinity,
                      color: Colors.blueGrey,
                      alignment: Alignment.center,
                      child: Text('A widget with information'),
                    ),
                    const SizedBox(height: 24.0),
                    GenaricTabBar(
                      controller: tabController,
                      tabStrings: const [
                        'Tab 1',
                        'Tab 2',
                      ],
                    ),
                  ],
                ),
              ),
            ),
            SliverToBoxAdapter(
              child: Container(
                height: 200,
                color: Colors.black,
              ),
            ),
            SliverToBoxAdapter(
              child: NotificationListener<ScrollNotification>(
                onNotification: (ScrollNotification notification) {
                  // if page more than 50% to other page, animate tab controller
                  double diff = notification.metrics.extentBefore -
                      notification.metrics.extentAfter;
                  if (diff.abs() < 50 && !tabController.indexIsChanging) {
                    animateTabSelector(diff >= 0 ? 1 : 0);
                  }
                  if (notification.metrics.atEdge) {
                    if (notification.metrics.extentBefore == 0.0) {
                      // Page 0 (1)
                      if (_pageIndex != 0) {
                        setState(() {
                          _pageIndex = 0;
                        });
                        animateTabSelector(_pageIndex);
                      }
                    } else if (notification.metrics.extentAfter == 0.0) {
                      // Page 1 (2)
                      if (_pageIndex != 1) {
                        setState(() {
                          _pageIndex = 1;
                        });
                        animateTabSelector(_pageIndex);
                      }
                    }
                  }
                  return false;
                },
                child: SingleChildScrollView(
                  controller: scrollController,
                  scrollDirection: Axis.horizontal,
                  physics: const PageScrollPhysics(),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 1. Parts
                      SizedBox(
                        width: MediaQuery.of(context).size.width,
                        child: Container(
                          color: Colors.teal,
                          height: 50,
                        ),
                      ),
                      // 2. Symbols
                      SizedBox(
                        width: MediaQuery.of(context).size.width,
                        child: Container(
                          color: Colors.orange,
                          height: 10000,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            SliverToBoxAdapter(
              child: Column(
                children: [
                  Container(
                    color: Colors.red,
                    height: 200.0,
                  ),
                  Container(
                    color: Colors.orange,
                    height: 200.0,
                  ),
                  Container(
                    color: Colors.amber,
                    height: 200.0,
                  ),
                  Container(
                    color: Colors.green,
                    height: 200.0,
                  ),
                  Container(
                    color: Colors.blue,
                    height: 200.0,
                  ),
                  Container(
                    color: Colors.purple,
                    height: 200.0,
                  ),
                ],
              ),
            ),
          ],
        ),
      );
}

class GenaricTabBar extends StatelessWidget {
  final TabController? controller;
  final List<String> tabStrings;

  const GenaricTabBar({
    Key? key,
    this.controller,
    required this.tabStrings,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) => Container(
        decoration: BoxDecoration(
          color: Colors.grey,
          borderRadius: BorderRadius.circular(8.0),
        ),
        padding: const EdgeInsets.all(4.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // if want tab-bar, uncomment
            TabBar(
              controller: controller,
              indicator: ShapeDecoration.fromBoxDecoration(
                BoxDecoration(
                  borderRadius: BorderRadius.circular(6.0),
                  color: Colors.white,
                ),
              ),
              tabs: tabStrings
                  .map((String s) => _GenaricTab(tabString: s))
                  .toList(),
            ),
          ],
        ),
      );
}

class _GenaricTab extends StatelessWidget {
  final String tabString;

  const _GenaricTab({
    Key? key,
    required this.tabString,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) => Container(
        child: Text(
          tabString,
          style: const TextStyle(
            color: Colors.black,
          ),
        ),
        height: 32.0,
        alignment: Alignment.center,
      );
}
```

(Dartpad ready)

The basic idea is to not use a Tabview at all and instead use a horizontal scroll view nested in our scrollable area.

By using page physics for the horizontal scroll and using a PageController instead of a normal ScrollController, we can achieve a a scroll effect between the two widgets in the horizontal area that snap to whichever page is correct.

By using a notification listener, we can listen for changes in the scrollview and update the tab view accordingly.

LIMITATIONS:

The above code assumes only two tabs, so would require more thought to optimize for more tabs, particularly in the NotificationListener function.

This also may not be performant for large tabs since both tabs are being built, even if one is out of view.

Finally, the vertical height of each tab is the same; so a tab that is much larger will cause the other tab to have a lot of empty vertical space.

Hope this helps anyone in a similar boat, and am open to suggestions to improve.

Body:
I'm trying to nest a tabview in a Scrollview, and can't find a good way to accomplish the task.

A diagram is included below:

The desired functionality is to have a normal scrollable page, where one of the slivers is a tab view with different sized (and dynamically resizing) tabs.

Unfortunately, despite looking at several resources and the flutter docs, I haven't come across any good solutions.

Here is what I have tried:

SingleChildScrollView with a column child, with the TabBarView wrapped in an IntrinsicHeight widget (Unbound constraints)

CustomScrollView variations, with the TabBarView wrapped in a SliverFillRemaining and the header and footer each wrapped with a SliverToBoxAdapter. In all cases, the content is forced to expand to the full size of the viewport (as if using a SliverFillViewport Sliver with a viewport fraction of 1.0) if smaller, or a nested scroll/overflow is created within the space if larger (see below)

If the children of the TabBarView are scrollable widgets, the sliver with the tab bar is given a height equal to the ViewPort (1.0) and any leftover space is empty.

If the children are not scrollable, they are force-expanded to fit if smaller, or give an overflow error if larger.

NestedScrollView comes closest but still suffers the ill effects of the previous implementation (see below for code example)

Various other unorthodox approaches (such as removing the TabBarView and trying to use an AnimatedSwitcher in conjunction with a listener on the TabBar to animate between the "tabs" but this wasn't swipable and the animation janked and the switched widgets overlapped)

The thus-far "best" implementation's code is given below, but it is not ideal.

Does anyone know of any way(s) to accomplish this?

Thank you in advance.

// best (more "Least-bad") solution code
import 'package:flutter/material.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: 'Demo',
      routes: {
        'root': (context) => const Scaffold(
              body: ExamplePage(),
            ),
      },
      initialRoute: 'root',
    );
  }
}

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

  @override
  State<ExamplePage> createState() => _ExamplePageState();
}

class _ExamplePageState extends State<ExamplePage>
    with TickerProviderStateMixin {
  late TabController tabController;

  @override
  void initState() {
    super.initState();
    tabController = TabController(length: 2, vsync: this);
    tabController.addListener(() {
      setState(() {});
    });
  }

  @override
  void dispose() {
    tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        resizeToAvoidBottomInset: true,
        backgroundColor: Colors.grey[100],
        appBar: AppBar(),
        body: NestedScrollView(
          floatHeaderSlivers: false,
          physics: const AlwaysScrollableScrollPhysics(),
          headerSliverBuilder: (BuildContext context, bool value) => [
            SliverToBoxAdapter(
              child: Padding(
                padding: const EdgeInsets.only(
                  left: 16.0,
                  right: 16.0,
                  bottom: 24.0,
                  top: 32.0,
                ),
                child: Column(
                  children: [
                    // TODO: Add scan tab thing
                    Container(
                      height: 94.0,
                      width: double.infinity,
                      color: Colors.blueGrey,
                      alignment: Alignment.center,
                      child: Text('A widget with information'),
                    ),
                    const SizedBox(height: 24.0),
                    GenaricTabBar(
                      controller: tabController,
                      tabStrings: const [
                        'Tab 1',
                        'Tab 2',
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
          body: CustomScrollView(
            slivers: [
              SliverFillRemaining(
                child: TabBarView(
                  physics: const AlwaysScrollableScrollPhysics(),
                  controller: tabController,
                  children: [
                    // Packaging Parts
                    SingleChildScrollView(
                      child: Container(
                        height: 200,
                        color: Colors.black,
                      ),
                    ),
                    // Symbols
                    SingleChildScrollView(
                      child: Column(
                        children: [
                          Container(
                            color: Colors.red,
                            height: 200.0,
                          ),
                          Container(
                            color: Colors.orange,
                            height: 200.0,
                          ),
                          Container(
                            color: Colors.amber,
                            height: 200.0,
                          ),
                          Container(
                            color: Colors.green,
                            height: 200.0,
                          ),
                          Container(
                            color: Colors.blue,
                            height: 200.0,
                          ),
                          Container(
                            color: Colors.purple,
                            height: 200.0,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              SliverToBoxAdapter(
                child: ElevatedButton(
                  child: Text('Button'),
                  onPressed: () => print('pressed'),
                ),
              ),
            ],
          ),
        ),
      );
}

class GenaricTabBar extends StatelessWidget {
  final TabController? controller;
  final List<String> tabStrings;

  const GenaricTabBar({
    Key? key,
    this.controller,
    required this.tabStrings,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) => Container(
        decoration: BoxDecoration(
          color: Colors.grey,
          borderRadius: BorderRadius.circular(8.0),
        ),
        padding: const EdgeInsets.all(4.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // if want tab-bar, uncomment
            TabBar(
              controller: controller,
              indicator: ShapeDecoration.fromBoxDecoration(
                BoxDecoration(
                  borderRadius: BorderRadius.circular(6.0),
                  color: Colors.white,
                ),
              ),
              tabs: tabStrings
                  .map((String s) => _GenaricTab(tabString: s))
                  .toList(),
            ),
          ],
        ),
      );
}

class _GenaricTab extends StatelessWidget {
  final String tabString;

  const _GenaricTab({
    Key? key,
    required this.tabString,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) => Container(
        child: Text(
          tabString,
          style: const TextStyle(
            color: Colors.black,
          ),
        ),
        height: 32.0,
        alignment: Alignment.center,
      );
}

The above works in Dartpad (dartpad.dev) and doesn't require any external libraries

Body:
Ideally, there is a better answer out there somewhere. BUT, until it arrives, this is how I got around the issue:

import 'package:flutter/material.dart';
import 'package:flutter/rendering.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: 'Demo',
      // darkTheme: Themes.darkTheme,
      // Language support
      // Routes will keep track of all of the possible places to go.
      routes: {
        'root': (context) => const Scaffold(
              body: ExamplePage(),
            ),
      },
      initialRoute: 'root', // See below.
    );
  }
}

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

  @override
  State<ExamplePage> createState() => _ExamplePageState();
}

class _ExamplePageState extends State<ExamplePage>
    with TickerProviderStateMixin {
  late TabController tabController;
  late PageController scrollController;
  late int _pageIndex;

  @override
  void initState() {
    super.initState();
    _pageIndex = 0;
    tabController = TabController(length: 2, vsync: this);
    scrollController = PageController();
    tabController.addListener(() {
      if (_pageIndex != tabController.index) {
        animateToPage(tabController.index);
      }
    });
  }

  void animateToPage([int? target]) {
    if (target == null || target == _pageIndex) return;
    scrollController.animateToPage(
      target,
      duration: const Duration(milliseconds: 250),
      curve: Curves.easeInOut,
    );
    setState(() {
      _pageIndex = target;
    });
  }

  void animateTabSelector([int? target]) {
    if (target == null || target == tabController.index) return;
    tabController.animateTo(
      target,
      duration: const Duration(
        milliseconds: 100,
      ),
    );
  }

  @override
  void dispose() {
    tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        resizeToAvoidBottomInset: true,
        backgroundColor: Colors.grey[100],
        appBar: AppBar(),
        body: CustomScrollView(
          slivers: [
            SliverToBoxAdapter(
              child: Padding(
                padding: const EdgeInsets.only(
                  left: 16.0,
                  right: 16.0,
                  bottom: 24.0,
                  top: 32.0,
                ),
                child: Column(
                  children: [
                    // TODO: Add scan tab thing
                    Container(
                      height: 94.0,
                      width: double.infinity,
                      color: Colors.blueGrey,
                      alignment: Alignment.center,
                      child: Text('A widget with information'),
                    ),
                    const SizedBox(height: 24.0),
                    GenaricTabBar(
                      controller: tabController,
                      tabStrings: const [
                        'Tab 1',
                        'Tab 2',
                      ],
                    ),
                  ],
                ),
              ),
            ),
            SliverToBoxAdapter(
              child: Container(
                height: 200,
                color: Colors.black,
              ),
            ),
            SliverToBoxAdapter(
              child: NotificationListener<ScrollNotification>(
                onNotification: (ScrollNotification notification) {
                  // if page more than 50% to other page, animate tab controller
                  double diff = notification.metrics.extentBefore -
                      notification.metrics.extentAfter;
                  if (diff.abs() < 50 && !tabController.indexIsChanging) {
                    animateTabSelector(diff >= 0 ? 1 : 0);
                  }
                  if (notification.metrics.atEdge) {
                    if (notification.metrics.extentBefore == 0.0) {
                      // Page 0 (1)
                      if (_pageIndex != 0) {
                        setState(() {
                          _pageIndex = 0;
                        });
                        animateTabSelector(_pageIndex);
                      }
                    } else if (notification.metrics.extentAfter == 0.0) {
                      // Page 1 (2)
                      if (_pageIndex != 1) {
                        setState(() {
                          _pageIndex = 1;
                        });
                        animateTabSelector(_pageIndex);
                      }
                    }
                  }
                  return false;
                },
                child: SingleChildScrollView(
                  controller: scrollController,
                  scrollDirection: Axis.horizontal,
                  physics: const PageScrollPhysics(),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 1. Parts
                      SizedBox(
                        width: MediaQuery.of(context).size.width,
                        child: Container(
                          color: Colors.teal,
                          height: 50,
                        ),
                      ),
                      // 2. Symbols
                      SizedBox(
                        width: MediaQuery.of(context).size.width,
                        child: Container(
                          color: Colors.orange,
                          height: 10000,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            SliverToBoxAdapter(
              child: Column(
                children: [
                  Container(
                    color: Colors.red,
                    height: 200.0,
                  ),
                  Container(
                    color: Colors.orange,
                    height: 200.0,
                  ),
                  Container(
                    color: Colors.amber,
                    height: 200.0,
                  ),
                  Container(
                    color: Colors.green,
                    height: 200.0,
                  ),
                  Container(
                    color: Colors.blue,
                    height: 200.0,
                  ),
                  Container(
                    color: Colors.purple,
                    height: 200.0,
                  ),
                ],
              ),
            ),
          ],
        ),
      );
}

class GenaricTabBar extends StatelessWidget {
  final TabController? controller;
  final List<String> tabStrings;

  const GenaricTabBar({
    Key? key,
    this.controller,
    required this.tabStrings,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) => Container(
        decoration: BoxDecoration(
          color: Colors.grey,
          borderRadius: BorderRadius.circular(8.0),
        ),
        padding: const EdgeInsets.all(4.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // if want tab-bar, uncomment
            TabBar(
              controller: controller,
              indicator: ShapeDecoration.fromBoxDecoration(
                BoxDecoration(
                  borderRadius: BorderRadius.circular(6.0),
                  color: Colors.white,
                ),
              ),
              tabs: tabStrings
                  .map((String s) => _GenaricTab(tabString: s))
                  .toList(),
            ),
          ],
        ),
      );
}

class _GenaricTab extends StatelessWidget {
  final String tabString;

  const _GenaricTab({
    Key? key,
    required this.tabString,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) => Container(
        child: Text(
          tabString,
          style: const TextStyle(
            color: Colors.black,
          ),
        ),
        height: 32.0,
        alignment: Alignment.center,
      );
}

(Dartpad ready)

The basic idea is to not use a Tabview at all and instead use a horizontal scroll view nested in our scrollable area.

By using page physics for the horizontal scroll and using a PageController instead of a normal ScrollController, we can achieve a a scroll effect between the two widgets in the horizontal area that snap to whichever page is correct.

By using a notification listener, we can listen for changes in the scrollview and update the tab view accordingly.

LIMITATIONS:

The above code assumes only two tabs, so would require more thought to optimize for more tabs, particularly in the NotificationListener function.

This also may not be performant for large tabs since both tabs are being built, even if one is out of view.

Finally, the vertical height of each tab is the same; so a tab that is much larger will cause the other tab to have a lot of empty vertical space.

Hope this helps anyone in a similar boat, and am open to suggestions to improve.


问:
Nested array data transformation with Mule 3
I am trying to transform data in Mule 3 (DataWeave 1.0) but I am not getting the desire result.

This is the input payload:

```<code>[
  "https://scrum-caller.com/repo/v1/inside#Changes",
  [
    {
      "id": "8db55441-6255-4d24-8d39-658536985214",
      "number": "0w-30",
      "Desc": "maintain"
    }
  ],
  "https://scrum-caller.com/repo/v1/inside#Changes",
  [
    {
      "id": "11111111-6666-2222-3g3g-854712547412",
      "number": "5w-40",
      "Desc": "on prod"
    }
  ],
  "https://scrum-caller.com/repo/v1/inside#Changes",
  [
    {
      "id": "1ab32c5b-ffs3-3243-74fv-3376218042bb",
      "number": "5w-30",
      "Desc": "on test"
    }
  ]
]
</code>```

And my desire output need to be like the one below

```<code>{
    "@odata.context": "https://scrum-caller.com/repo/v1/inside#Changes",
    "value": [
        {
      "id": "8db55441-6255-4d24-8d39-658536985214",
      "number": "0w-30",
      "Desc": "maintain"
    },
    {
      "id": "11111111-6666-2222-3g3g-854712547412",
      "number": "5w-40",
      "Desc": "on prod"
    },
    {
      "id": "1ab32c5b-ffs3-3243-74fv-3376218042bb",
      "number": "5w-30",
      "Desc": "on test"
    }
    ]
}
</code>```

Thanks for helping guys.

答:
Assuming all the URLs are the same, since the question doesn't provide details only an example, I just take the first element as the value of the input for "@odata.context", the the value is just filtering out the non-array elements and use the reduce operator to get a single array of the other elements.

%dw 1.0
%output application/json
---
{
  "@odata.context" : payload[0],
  value : payload filter ($ is :array) reduce ($ ++ $$)
}
```

Body:
I am trying to transform data in Mule 3 (DataWeave 1.0) but I am not getting the desire result.

This is the input payload:

[
  "https://scrum-caller.com/repo/v1/inside#Changes",
  [
    {
      "id": "8db55441-6255-4d24-8d39-658536985214",
      "number": "0w-30",
      "Desc": "maintain"
    }
  ],
  "https://scrum-caller.com/repo/v1/inside#Changes",
  [
    {
      "id": "11111111-6666-2222-3g3g-854712547412",
      "number": "5w-40",
      "Desc": "on prod"
    }
  ],
  "https://scrum-caller.com/repo/v1/inside#Changes",
  [
    {
      "id": "1ab32c5b-ffs3-3243-74fv-3376218042bb",
      "number": "5w-30",
      "Desc": "on test"
    }
  ]
]

And my desire output need to be like the one below

{
    "@odata.context": "https://scrum-caller.com/repo/v1/inside#Changes",
    "value": [
        {
      "id": "8db55441-6255-4d24-8d39-658536985214",
      "number": "0w-30",
      "Desc": "maintain"
    },
    {
      "id": "11111111-6666-2222-3g3g-854712547412",
      "number": "5w-40",
      "Desc": "on prod"
    },
    {
      "id": "1ab32c5b-ffs3-3243-74fv-3376218042bb",
      "number": "5w-30",
      "Desc": "on test"
    }
    ]
}

Thanks for helping guys.


问:
GET request from local server using live-server
I am trying to fetch data from my local server and here is my server and how I handled GET requests:

```<code>const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());

app.listen(port, () => {
  console.log(`app running on port: ${port}...`);
});

const responseToClient = (req, res) => {
  res.status(200).json({
    status: 'success',
    body: 'Hello from the server!',
  });
};

app.get('/api', responseToClient);
</code>```

When I run my server and send a GET request to this address: 127.0.0.1:3000/api with Postman, it works perfectly.

The thing is I created a html page along with a js file and want to fetch data from my local server by it. Here is my fetch request on my js file:

```<code>const url = '/api';

const fetchData = async () => {
  try {
    const response = await fetch(url);
    const body = await response.json();
    alert(body);
  } catch (error) {
    alert(error);
  }
};
fetchData();
</code>```

I run my html file with live-server (extension) which runs on port 5500 by default , so the address my fetch request goes to will be 127.0.0.1:5500/api (instead of 127.0.0.1:3000/api), so it does not exists and I get an error message.

I tried to change the port of my server and set it to 5500 (the same as live-server) but it did not work.

How can I run my local server and send requests to it with live-server and my html file?

答:
Solved by using:

```<code> const url = 'http://localhost:3000/api';
</code>```

instead of the ip address and installing cors middle ware.

Body:
I am trying to fetch data from my local server and here is my server and how I handled GET requests:

const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());

app.listen(port, () => {
  console.log(`app running on port: ${port}...`);
});

const responseToClient = (req, res) => {
  res.status(200).json({
    status: 'success',
    body: 'Hello from the server!',
  });
};

app.get('/api', responseToClient);

When I run my server and send a GET request to this address: 127.0.0.1:3000/api with Postman, it works perfectly.

The thing is I created a html page along with a js file and want to fetch data from my local server by it. Here is my fetch request on my js file:

const url = '/api';

const fetchData = async () => {
  try {
    const response = await fetch(url);
    const body = await response.json();
    alert(body);
  } catch (error) {
    alert(error);
  }
};
fetchData();

I run my html file with live-server (extension) which runs on port 5500 by default , so the address my fetch request goes to will be 127.0.0.1:5500/api (instead of 127.0.0.1:3000/api), so it does not exists and I get an error message.

I tried to change the port of my server and set it to 5500 (the same as live-server) but it did not work.

How can I run my local server and send requests to it with live-server and my html file?

Body:
Solved by using:

 const url = 'http://localhost:3000/api';

instead of the ip address and installing cors middle ware.


问:
Software composition using "components" - Clarification needed
I read a nice definition for software composition here. It says

Software composition is the construction of software applications from components that implement abstractions pertaining to a particular problem domain

Is it the construction of these abstractions where design patterns fit in?

答:
That's a higher level abstraction.  Patterns solve common object-oriented problems.

Abstraction, encapsulation, and information hiding are pertinent at the level of individual components.  You can do the latter without ever employing patterns.

ContentLicense: CC BY-SA 3.0


问:
npm --save-dev not updating node_modules
I am new to nodejs and am having trouble with npm.

Whenever I try to install something with 'npm install  --save-dev', it shows up in my devDependencies in my package.json but it never gets added to my node_modules folder.

This is what I tried:

Create new folder

npm init -y

npm install typescript --save-dev

Result:
In package.json I see "typescript": "^3.1.6" in my devDependencies.
No node_modules is even created.

For everyone else it does show up. Can someone help me out here?

答: If anyone else is having this issue, make sure your $NODE_ENV wasn't accidentally set to production.


问:
assign a value from a list to corresponding string on terminal
I am trying to do create a list with assigning the corresponding values from another list.

I have a file like this(list.txt);

```<code>.
.
ak_1002
ak_1002
ak_1014
ak_1017
ak_1017
ak_1239
ak_1246
ak_1284
ak_1286
ak_1320
ak_138
ak_139
.
.
</code>```

And another file with the corresponding values (ref.txt)

```<code>.
.
ak_1     39,877
ak_10    75,636
ak_100   32,936
ak_1000  81,609
ak_1002  30,946
ak_1003  40,862
ak_1004  96,566
ak_1005  50,778
ak_1006  62,698
ak_1007  47,8
ak_1008  37,895
ak_1009  126,501
ak_101   45,829
ak_1011  33,925
ak_1012  50,778
ak_1013  43,842
ak_1014  65,676
ak_1015  161,859
ak_1016  70,652
ak_1017  32,933
.
.
</code>```

I am trying to obtain a result file should be looking like this:

```<code>.
.
ak_1002 30,946
ak_1002 30,946
ak_1014 65,676
ak_1017 32,933
ak_1017 32,933
.
.
</code>```

Actually, I was using this code with other datasets and it was working perfectly, but right now it is returning no result.

```<code>awk 'FNR==NR{ arr[NR]=$0 }
    NR!=FNR{ for(i in arr){
      if(arr[i]==$1){ print arr[i],$2 } } }' list.txt ref.txt > result.txt
</code>```

PS: I am sure that there is only one corresponding value to every unique string, and also sure that all of the strings in the list.txt exist in ref.txt, because list.txt is a subset of ref.txt.

I could not figure out the reason. If you have any idea thank you in advance.

答:
Using GNU awk,</p>
```<code>awk -v RS='\r?\n' 'FNR==NR{ arr[$1]=$2 }
     FNR!=NR{ if ($1 in arr) print $1, arr[$1]; }' ref.txt list.txt
</code>```

Body:
I am trying to do create a list with assigning the corresponding values from another list.

I have a file like this(list.txt);

.
.
ak_1002
ak_1002
ak_1014
ak_1017
ak_1017
ak_1239
ak_1246
ak_1284
ak_1286
ak_1320
ak_138
ak_139
.
.

And another file with the corresponding values (ref.txt)

.
.
ak_1     39,877
ak_10    75,636
ak_100   32,936
ak_1000  81,609
ak_1002  30,946
ak_1003  40,862
ak_1004  96,566
ak_1005  50,778
ak_1006  62,698
ak_1007  47,8
ak_1008  37,895
ak_1009  126,501
ak_101   45,829
ak_1011  33,925
ak_1012  50,778
ak_1013  43,842
ak_1014  65,676
ak_1015  161,859
ak_1016  70,652
ak_1017  32,933
.
.

I am trying to obtain a result file should be looking like this:

.
.
ak_1002 30,946
ak_1002 30,946
ak_1014 65,676
ak_1017 32,933
ak_1017 32,933
.
.

Actually, I was using this code with other datasets and it was working perfectly, but right now it is returning no result.

awk 'FNR==NR{ arr[NR]=$0 }
    NR!=FNR{ for(i in arr){
      if(arr[i]==$1){ print arr[i],$2 } } }' list.txt ref.txt > result.txt

PS: I am sure that there is only one corresponding value to every unique string, and also sure that all of the strings in the list.txt exist in ref.txt, because list.txt is a subset of ref.txt.

I could not figure out the reason. If you have any idea thank you in advance.

Body:
Using GNU awk,

awk -v RS='\r?\n' 'FNR==NR{ arr[$1]=$2 }
     FNR!=NR{ if ($1 in arr) print $1, arr[$1]; }' ref.txt list.txt


问:
Understanding the Domain object + Data mapper pattern?
I've always worked with various ORM's in the past and placed all my logic inside my models regardless of it's nature - SQL, MongoDB queries & even fetching of remote JSON objects.
But when it's necessary to ensure loose couplings to allow a high level of testability, the issues of this methodology quickly appears.

Today I've read about separating models into two parts, Domain objects & Data mappers.

If I understood it completely, Domain objects are completely unaware of the storage used, and instead exists to handle business logic. Data mappers on the other hand takes care of storing the data set in the Domain objects to a set data storage.

I do however find it a bit hard to find a good, easy-to-understand example online on how to work with the DomainObjects & DataMappers in a real world example.

Would this (below shown code) be the appropriate way to work with DomainObjects & DataMappers in my code to store Users or have I gotten it all wrong in my head?

```<code>$user = new User_DO;
$userSave = new User_DM;
$userSave->store( $user->add(array('name' => 'John Doe')) );

class User_DO {

    function add($array) {
        if(!isset($array['name'])) {
            throw new Exception("Name must be set");
        }

        return $array;

    }

}

class User_DM {

    function store($array) {
        MyDatabase::execute("INSERT INTO...");
    }

}
</code>```

答:
The idea behind this is to have a standard object, that represents the current state in real life or in other words, in the domain. This domain model is usually a collection of data without logic.

```<code>class person_DO {
    public $id;
    public $firstname;
    public $lastname;
    public $addresses;
}
</code>```

The loading of instances of this domain model (domain objects) and the persistence is handled through data mappers - e.g. the address of the above person might be located in another table via a 1:n relationship, as such:

```<code>TABLE person {
    id        INTEGER PRIMARY KEY,
    firstname VARCHAR(32),
    lastname  VARCHAR(32)
}

TABLE addresses {
    id INTEGER PRIMARY KEY,
    person_id  INTEGER FOREIGN KEY ON person.id, --Reference on person-row
    street     VARCHAR(64),
    ...
}
</code>```

The person_DO does not need to know about that, but the datamapper does, as it has to aggregate the data during loading and separate during persisting:

```<code>class person_DM {
    /**
     * @param  [integer] $id
     * @return [person_DO] an instance of a person or null, if no person
     *                     with that id was found.
     */
    public function findById ($id) {...}

    /**
     * @return [array of person_DO]
     */
    public function fetchAll() {...}

    /**
     * persists a person object
     * @param [person_DO] an instance of a person
     */
    public function saveOrUpdate(person_DO $person) {...}
}
</code>```

In order to decouple the different parts even more, the DataMappers usually use the DbTable Gateway or a similar pattern to allow the use of different databases or similar actions. That way, I can have several databases with the same schemas, but e.g. in different organizations to build a data warehouse with the same code, only different database objects.

As a practical example, I would suggest looking at the Quickstart Tutorial of the Zend Framework, which does exactly what I just explained briefly.

Body:
I've always worked with various ORM's in the past and placed all my logic inside my models regardless of it's nature - SQL, MongoDB queries & even fetching of remote JSON objects.
But when it's necessary to ensure loose couplings to allow a high level of testability, the issues of this methodology quickly appears.

Today I've read about separating models into two parts, Domain objects & Data mappers.

If I understood it completely, Domain objects are completely unaware of the storage used, and instead exists to handle business logic. Data mappers on the other hand takes care of storing the data set in the Domain objects to a set data storage.

I do however find it a bit hard to find a good, easy-to-understand example online on how to work with the DomainObjects & DataMappers in a real world example.

Would this (below shown code) be the appropriate way to work with DomainObjects & DataMappers in my code to store Users or have I gotten it all wrong in my head?

$user = new User_DO;
$userSave = new User_DM;
$userSave->store( $user->add(array('name' => 'John Doe')) );

class User_DO {

    function add($array) {
        if(!isset($array['name'])) {
            throw new Exception("Name must be set");
        }

        return $array;

    }

}

class User_DM {

    function store($array) {
        MyDatabase::execute("INSERT INTO...");
    }

}

Body:
The idea behind this is to have a standard object, that represents the current state in real life or in other words, in the domain. This domain model is usually a collection of data without logic.

class person_DO {
    public $id;
    public $firstname;
    public $lastname;
    public $addresses;
}

The loading of instances of this domain model (domain objects) and the persistence is handled through data mappers - e.g. the address of the above person might be located in another table via a 1:n relationship, as such:

TABLE person {
    id        INTEGER PRIMARY KEY,
    firstname VARCHAR(32),
    lastname  VARCHAR(32)
}

TABLE addresses {
    id INTEGER PRIMARY KEY,
    person_id  INTEGER FOREIGN KEY ON person.id, --Reference on person-row
    street     VARCHAR(64),
    ...
}

The person_DO does not need to know about that, but the datamapper does, as it has to aggregate the data during loading and separate during persisting:

class person_DM {
    /**
     * @param  [integer] $id
     * @return [person_DO] an instance of a person or null, if no person
     *                     with that id was found.
     */
    public function findById ($id) {...}

    /**
     * @return [array of person_DO]
     */
    public function fetchAll() {...}

    /**
     * persists a person object
     * @param [person_DO] an instance of a person
     */
    public function saveOrUpdate(person_DO $person) {...}
}

In order to decouple the different parts even more, the DataMappers usually use the DbTable Gateway or a similar pattern to allow the use of different databases or similar actions. That way, I can have several databases with the same schemas, but e.g. in different organizations to build a data warehouse with the same code, only different database objects.

As a practical example, I would suggest looking at the Quickstart Tutorial of the Zend Framework, which does exactly what I just explained briefly.


问:
Recharts join disconnected lines
When there is null in the time-series data, Recharts is not joining the dots and considering it as an independent point in the Line chart.

I want to join the disconnected points. How can I achieve that?

```<code>const data = [
  {
    ts: 1641275508,
    uv: 4000,
    pv: null,
    amt: 2400
  },
  {
    ts: 1641275608,
    uv: null,
    pv: 1398,
    amt: 2210
  },
  {
    ts: 1641275708,
    uv: 2000,
    pv: 9800,
    amt: 2290
  },
  {
    ts: 1641275808,
    uv: null,
    pv: 3908,
    amt: 2000
  },
  {
    ts: 1641275908,
    uv: 1890,
    pv: null,
    amt: 2181
  },
  {
    ts: 1641276008,
    uv: 2390,
    pv: 3800,
    amt: 2500
  },
  {
    ts: 1641276108,
    uv: null,
    pv: 4300,
    amt: 2100
  }
];
</code>```

Current Result

Expected Result

https://codesandbox.io/s/simple-line-chart-forked-mozqo?file=/src/App.tsx

答:
It can be achieved using connectNulls props by components like Line, Area etc.

    <LineChart
      width={500}
      height={300}
      data={data}
      margin={{
        top: 5,
        right: 30,
        left: 20,
        bottom: 5
      }}
    >
      <CartesianGrid strokeDasharray="3 3" />
      <XAxis dataKey="ts" type={"number"} domain={["dataMin", "dataMax"]} />
      <YAxis />
      <Tooltip />
      <Legend />
      <Line type="monotone" connectNulls dataKey="pv" stroke="#8884d8" />
      <Line type="monotone" connectNulls dataKey="uv" stroke="#82ca9d" />
    </LineChart>
```

Solution:

https://codesandbox.io/s/simple-line-chart-forked-mdkeb?file=/src/App.tsx

Title: Recharts join disconnected lines

Body:
When there is null in the time-series data, Recharts is not joining the dots and considering it as an independent point in the Line chart.

I want to join the disconnected points. How can I achieve that?

const data = [
  {
    ts: 1641275508,
    uv: 4000,
    pv: null,
    amt: 2400
  },
  {
    ts: 1641275608,
    uv: null,
    pv: 1398,
    amt: 2210
  },
  {
    ts: 1641275708,
    uv: 2000,
    pv: 9800,
    amt: 2290
  },
  {
    ts: 1641275808,
    uv: null,
    pv: 3908,
    amt: 2000
  },
  {
    ts: 1641275908,
    uv: 1890,
    pv: null,
    amt: 2181
  },
  {
    ts: 1641276008,
    uv: 2390,
    pv: 3800,
    amt: 2500
  },
  {
    ts: 1641276108,
    uv: null,
    pv: 4300,
    amt: 2100
  }
];

Current Result

Expected Result

https://codesandbox.io/s/simple-line-chart-forked-mozqo?file=/src/App.tsx

Body:
It can be achieved using connectNulls props by components like Line, Area etc.

    <LineChart
      width={500}
      height={300}
      data={data}
      margin={{
        top: 5,
        right: 30,
        left: 20,
        bottom: 5
      }}
    >
      <CartesianGrid strokeDasharray="3 3" />
      <XAxis dataKey="ts" type={"number"} domain={["dataMin", "dataMax"]} />
      <YAxis />
      <Tooltip />
      <Legend />
      <Line type="monotone" connectNulls dataKey="pv" stroke="#8884d8" />
      <Line type="monotone" connectNulls dataKey="uv" stroke="#82ca9d" />
    </LineChart>

Solution:

https://codesandbox.io/s/simple-line-chart-forked-mdkeb?file=/src/App.tsx


问:
#line keyword in C
I am trying to understand some code and I've come across a keyword that I've never seen before. I tried to google it, but haven't found anything regarding it as well.

```<code>char *valtext;
#line 1 "Values.l"
#define INITIAL 0
#line 2 "Values.l"
int reserve(char *s);
#line 388 "lex.val.c"
</code>```

I've included the entire block hoping that perhaps someone can help me understand this chunk of code. I can't find any files on my system named "Values.l" and this chunk of code is located in the "lex.val.c" file.

Thanks in advance.

答:
That code has gone through the pre-processor and as such is marked up by one stage of a compiler, intended to be consumed by another stage of the same compiler. The features that it uses aren't intended for your use.

The files that it references may be temporary files created by the compiler as it runs.

Title: #line keyword in C

Body:
I am trying to understand some code and I've come across a keyword that I've never seen before. I tried to google it, but haven't found anything regarding it as well.

char *valtext;
#line 1 "Values.l"
#define INITIAL 0
#line 2 "Values.l"
int reserve(char *s);
#line 388 "lex.val.c"

I've included the entire block hoping that perhaps someone can help me understand this chunk of code. I can't find any files on my system named "Values.l" and this chunk of code is located in the "lex.val.c" file.

Thanks in advance.


问:
do not output specific div if something is null using jquery
I am making database query.

```<code>let link = something from the database;
let output = `
   <div>
      ...
   <div>
   <div>
      ...
   <div>
   <div>
      <iframe src="${link}"></iframe>
   </div>
   <div>
      <div>
         ...
      </div>
   <div>
`;
$('#table').html(output);
</code>```

The link could be empty then I do not want to output the highlighted div. I do not know a "cool" way of doing that.

答:
If I understand your question correctly, you don't want to display the iframe, if link is set to null.

This is one of many ways how you could do it:

let link = 'Change me to null';
link ??= `

`;

let output = `

      ...

      ...

`;
output += link;
output += `

         ...

`;
$('#table').html(output);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="table"></div></code>```

Body:
I am making database query.

let link = something from the database;
let output = `

      ...

      ...

         ...

`;
$('#table').html(output);

The link could be empty then I do not want to output the highlighted div. I do not know a "cool" way of doing that.

Body:
If I understand your question correctly, you don't want to display the iframe, if link is set to null.

This is one of many ways how you could do it:

let link = 'Change me to null';
link ??= `
   <div>
      <iframe src="${link}"></iframe>
   </div>
`;

let output = `
   <div>
      ...
   <div>
   <div>
      ...
   <div>
`;
output += link;
output += `
   <div>
      <div>
         ...
      </div>
   <div>
`;
$('#table').html(output);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="table"></div>


问:
How to load infinite scroll pages faster?
https://immutascan.io/address/0xac98d8d1bb27a94e79fbf49198210240688bb1ed

This URL has 100k+ rows that I'm trying to scrape. They go back about a month (1/10/2022 I believe) but load in badges of 7-8.

Right now I have a macro slowly scrolling down the page, which is working, but takes about 8-10 hours per day's worth of rows.

As of now, when new rows load there are 2-3 items that load immediately and then a few that load over time. I don't need the parts that load slowly and would like them to load faster or not at all.

Is there a way that I can prevent elements from loading to speed up the loading of additional rows?

I'm using an autohotkey script that scrolls down with the mouse-wheel and that's been working best.

I've also tried a Chrome extension but that was slower.

I found a python script at one point but it wasn't any faster than autohotkey.

Answer: Immutable X has an API so I'm using that instead of this site that does the same thing. Here's the working code:

```<code>import requests
import time
import pandas as pd
import time

URL = "https://api.x.immutable.com/v1/orders"
bg_output = []
params = {'status': 'filled',
          'sell_token_address': '0xac98d8d1bb27a94e79fbf49198210240688bb1ed'}

with requests.Session() as session:
    while True:
        (r := session.get(URL, params=params)).raise_for_status()
        data = r.json()
        for value in data['result']:
            orderID = value['order_id']
            info = value["sell"]["data"]["properties"]["name"]
            wei = value["buy"]["data"]["quantity"]
            decimals = value["buy"]["data"]["decimals"]
            spacer = "."
            eth = float(wei[decimals:] + spacer + wei[:decimals])
            print(f'Count={len(bg_output)},Order ID={orderID}, Info={info}, Eth={eth}')
            bg_output.append(f'Count={len(bg_output)},Order ID={orderID}, Info={info}, Eth={eth}')
            timestr = time.strftime("%Y%m%d")
            pd.DataFrame(bg_output).to_csv('bg_output' + timestr + '.csv')
            #print(len(bg_output))
        time.sleep(1)
        if (cursor := data.get('cursor')):
            params['cursor'] = cursor
        else:
            print(bg_output)
            break

print(bg_output)
print("END")
</code>```

答:
Have you considered using their API directly? When you scroll the page, have a look at your browser’s dev tools “network” tab. There you can see the actual call to their API. Look at all POST requests to the URL

```<code>https://3vkyshzozjep5ciwsh2fvgdxwy.appsync-api.us-west-2.amazonaws.com/graphql
</code>```

Try adapting these API calls so that you can get the data right via their GraphQL-API and without having to scroll the actual page.

Body:
https://immutascan.io/address/0xac98d8d1bb27a94e79fbf49198210240688bb1ed

This URL has 100k+ rows that I'm trying to scrape. They go back about a month (1/10/2022 I believe) but load in badges of 7-8.

Right now I have a macro slowly scrolling down the page, which is working, but takes about 8-10 hours per day's worth of rows.

As of now, when new rows load there are 2-3 items that load immediately and then a few that load over time. I don't need the parts that load slowly and would like them to load faster or not at all.

Is there a way that I can prevent elements from loading to speed up the loading of additional rows?

I'm using an autohotkey script that scrolls down with the mouse-wheel and that's been working best.

I've also tried a Chrome extension but that was slower.

I found a python script at one point but it wasn't any faster than autohotkey.

Answer: Immutable X has an API so I'm using that instead of this site that does the same thing. Here's the working code:

import requests
import time
import pandas as pd
import time

URL = "https://api.x.immutable.com/v1/orders"
bg_output = []
params = {'status': 'filled',
          'sell_token_address': '0xac98d8d1bb27a94e79fbf49198210240688bb1ed'}

with requests.Session() as session:
    while True:
        (r := session.get(URL, params=params)).raise_for_status()
        data = r.json()
        for value in data['result']:
            orderID = value['order_id']
            info = value["sell"]["data"]["properties"]["name"]
            wei = value["buy"]["data"]["quantity"]
            decimals = value["buy"]["data"]["decimals"]
            spacer = "."
            eth = float(wei[decimals:] + spacer + wei[:decimals])
            print(f'Count={len(bg_output)},Order ID={orderID}, Info={info}, Eth={eth}')
            bg_output.append(f'Count={len(bg_output)},Order ID={orderID}, Info={info}, Eth={eth}')
            timestr = time.strftime("%Y%m%d")
            pd.DataFrame(bg_output).to_csv('bg_output' + timestr + '.csv')
            #print(len(bg_output))
        time.sleep(1)
        if (cursor := data.get('cursor')):
            params['cursor'] = cursor
        else:
            print(bg_output)
            break

print(bg_output)
print("END")

Body:
Have you considered using their API directly? When you scroll the page, have a look at your browser’s dev tools “network” tab. There you can see the actual call to their API. Look at all POST requests to the URL

https://3vkyshzozjep5ciwsh2fvgdxwy.appsync-api.us-west-2.amazonaws.com/graphql

Try adapting these API calls so that you can get the data right via their GraphQL-API and without having to scroll the actual page.


问:
align div horizontally after screen resize using css
I'm trying to align div horizontally as the browser resizes, currently, I have 3 divs. As per the requirement, I can add an additional div. My problem is as soon I increase the window size above 2500, the right side of the screen becomes empty & all the divs are floating to left. As I cannot set the div width to 30-33% as per the requirement. Below is my code. kindly help.

div.box-container {
  mc-grid-row: true;
  margin-left: auto;
  margin-right: auto;
  float: left;
  display: flex;
  width: 100%
}

div.box {
  float: left;
  background-color: #ffffff;
  position: relative;
  padding: 10px;
  box-sizing: border-box;
  height: 326px;
  margin-left: 20px;
  margin-bottom: 0;
  top: 55px;
  border-top-right-radius: 0px;
  width: 30%;
  border: 1px solid #cccccc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-container">

  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
</div></code>```

答:
Use justify-content: center; when you are using flex. This means the flexed contents will always be centered on all screen types.

div.box-container {
  mc-grid-row: true;
  margin-left: auto;
  margin-right: auto;
  display: flex;
  gap: 10px;
  justify-content: center;
  width: 100%
}

div.box {
  background-color: #ffffff;
  position: relative;
  padding: 10px;
  box-sizing: border-box;
  height: 326px;
  margin-bottom: 0;
  top: 55px;
  border-top-right-radius: 0px;
  width: 33.33%;
  border: 1px solid #cccccc;
}

body {
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-container">

  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
</div></code>```

Edit ~ add another div, reduce the % the div covers. Demonstrate min-width responsiveness.

div.box-container {
  mc-grid-row: true;
  margin-left: auto;
  margin-right: auto;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
  width: 100%
}

div.box {
  background-color: #ffffff;
  position: relative;
  padding: 10px;
  box-sizing: border-box;
  height: 326px;
  margin-bottom: 0;
  top: 55px;
  border-top-right-radius: 0px;
  width: 24%;
  min-width: 300px;
  border: 1px solid #cccccc;
}

body {
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-container">

  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
</div></code>```

Body:
I'm trying to align div horizontally as the browser resizes, currently, I have 3 divs. As per the requirement, I can add an additional div. My problem is as soon I increase the window size above 2500, the right side of the screen becomes empty & all the divs are floating to left. As I cannot set the div width to 30-33% as per the requirement. Below is my code. kindly help.

div.box-container {
  mc-grid-row: true;
  margin-left: auto;
  margin-right: auto;
  float: left;
  display: flex;
  width: 100%
}

div.box {
  float: left;
  background-color: #ffffff;
  position: relative;
  padding: 10px;
  box-sizing: border-box;
  height: 326px;
  margin-left: 20px;
  margin-bottom: 0;
  top: 55px;
  border-top-right-radius: 0px;
  width: 30%;
  border: 1px solid #cccccc;
}

jfn,mnfngf,mn,mgfnbgnkjdkjgkdg

jfn,mnfngf,mn,mgfnbgnkjdkjgkdg

jfn,mnfngf,mn,mgfnbgnkjdkjgkdg

Body:
Use justify-content: center; when you are using flex. This means the flexed contents will always be centered on all screen types.

div.box-container {
  mc-grid-row: true;
  margin-left: auto;
  margin-right: auto;
  display: flex;
  gap: 10px;
  justify-content: center;
  width: 100%
}

div.box {
  background-color: #ffffff;
  position: relative;
  padding: 10px;
  box-sizing: border-box;
  height: 326px;
  margin-bottom: 0;
  top: 55px;
  border-top-right-radius: 0px;
  width: 33.33%;
  border: 1px solid #cccccc;
}

body {
  margin: 0;
}

<div class="box-container">

  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
</div>

Edit ~ add another div, reduce the % the div covers. Demonstrate min-width responsiveness.

div.box-container {
  mc-grid-row: true;
  margin-left: auto;
  margin-right: auto;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
  width: 100%
}

div.box {
  background-color: #ffffff;
  position: relative;
  padding: 10px;
  box-sizing: border-box;
  height: 326px;
  margin-bottom: 0;
  top: 55px;
  border-top-right-radius: 0px;
  width: 24%;
  min-width: 300px;
  border: 1px solid #cccccc;
}

body {
  margin: 0;
}

<div class="box-container">

  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
  <div class="box">
    <p>jfn,mnfngf,mn,mgfnbgnkjdkjgkdg</p>
  </div>
</div>


问:
How to access WEB API on .NET Core from the outside network?
I want to access my API from the outside ?

On the local machine I access my API like this:

```<code>https://localhost:44377/api/stations
</code>```

So my IP address for example is: 186.143.119.43

What do I need to change to see it through external networks?

This is my launchSettings.json file:

```<code>    {
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:51429",
      "sslPort": 44377
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "WebAPI": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
</code>```

How to access this API from outside network ?

答: If its for testing purposes consider using an service like ngrok.com</p>

Body:
I want to access my API from the outside ?

On the local machine I access my API like this:

https://localhost:44377/api/stations

So my IP address for example is: 186.143.119.43

What do I need to change to see it through external networks?

This is my launchSettings.json file:

    {
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:51429",
      "sslPort": 44377
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "WebAPI": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

How to access this API from outside network ?


问:
Swift DiffableDataSource Snapshot Not Updating
I am working with DiffableDataSource inside of a collection view for the first time, but I am running into an error while trying to update a view.

So I am working with 2 custom cells. CustomCell1 is a cell that has a Label on the left and a UITextField on the right. CustomCell2 is a cell that has 2 column UIPickerView inside of it. CustomCell2 has a delegate that will let my main view controller know when it has been updated. This is all working fine.

So the problem is coming when I am trying to update the textfield in CustomCell1 with the value selected in the UIPickerView from CustomCell2. As a note, the textfield is being used for text entry in rows of the page. And the picker view is shown when a cell is clicked, and hidden when the cell is clicked again.

So in my delegate to update the cell, I have this code:

```<code>func updateSelectedCharacter(withCharacter character: String, indexPath: IndexPath) {
        print(character)
        DispatchQueue.main.async {
            guard let charItem = self.dataSource.itemIdentifier(for: IndexPath(row: indexPath.row - 1, section: indexPath.section)), let parentId = charItem.parentId else { return }
            self.updatePlayerData(forPlayerIndex: parentId, character: character)
            var snap = self.dataSource.snapshot()
            snap.reloadItems([charItem])
            self.dataSource.apply(snap)
        }
    }
</code>```

And in my cellForRowAt, I have the following code to update the text field in the character cell (CustomCell1). The gameInfo object is a struct that has information, including the character name I am trying to display, that I will eventually store off into CoreData from the entries in the cells.

```<code>guard let parentId = info.parentId else { return UICollectionViewListCell() }
let playerData = self.gameInfo.playerData[parentId]
var obj = TextEntryCellInformation(title: rowTitle, rowType: info.rowType)
obj.value = obj.value = playerData?.character
obj.isSelectable = false
return collectionView.dequeueConfiguredReusableCell(using: textEntryCell, for: indexPath, item: obj)
</code>```

And here is the cell registration for that cell, where TextEntryCellInformation holds the row type, title for the label, and an optional value that can set textfield's text:

```<code>private func createTextEntryListCellRegistration() -> UICollectionView.CellRegistration<TextEntryCollectionViewCell, TextEntryCellInformation> {
        return UICollectionView.CellRegistration<TextEntryCollectionViewCell, TextEntryCellInformation> { cell, indexPath, data in
            var config = TextEntryContentConfiguration()
            config.title = data.title
            config.tag = data.rowType.rawValue
            config.textChangedDelegate = self
            config.isSelectable = data.isSelectable
            config.customPlaceholder = "required"
            if let val = data.value {
                config.textValue = val
            }
            cell.contentConfiguration = config
        }
    }
</code>```

So now, I think I have explained most of the code. Whenever I select the value in the picker view, the first time it will show the value correctly in the character cell. But if I change the value, the text seems to disappear from the character cell. However, I am getting the correct value from the picker view, verified with the print call at the start of the delegate function. I am also verifying that after I apply in the update delegate function, I am running through the cell registration and the correct value is being assigned to the config.textValue. I am not sure why then, if the config is being data is being set as expected with the correct character name, why the UI is not updating to show that information.

I included what I think is the relevant code and information. However, if more is needed, I will definitely update.

Thanks in advance for any help given!

答:
Turns out I found the answer. When setting the configuration on the content view of the textfield custom cell (CustomCell1), I was doing  check to conform to equatable:

```<code>static func == (lhs: TextEntryContentConfiguration, rhs: TextEntryContentConfiguration) -> Bool {
        return lhs.title == rhs.title
    }
</code>```

I needed to be doing:

```<code>static func == (lhs: TextEntryContentConfiguration, rhs: TextEntryContentConfiguration) -> Bool {
        return lhs.textValue == rhs.textValue
    }
</code>```

This checks the difference to know if I should be updating the config values or not.

Body:
I am working with DiffableDataSource inside of a collection view for the first time, but I am running into an error while trying to update a view.

So I am working with 2 custom cells. CustomCell1 is a cell that has a Label on the left and a UITextField on the right. CustomCell2 is a cell that has 2 column UIPickerView inside of it. CustomCell2 has a delegate that will let my main view controller know when it has been updated. This is all working fine.

So the problem is coming when I am trying to update the textfield in CustomCell1 with the value selected in the UIPickerView from CustomCell2. As a note, the textfield is being used for text entry in rows of the page. And the picker view is shown when a cell is clicked, and hidden when the cell is clicked again.

So in my delegate to update the cell, I have this code:

func updateSelectedCharacter(withCharacter character: String, indexPath: IndexPath) {
        print(character)
        DispatchQueue.main.async {
            guard let charItem = self.dataSource.itemIdentifier(for: IndexPath(row: indexPath.row - 1, section: indexPath.section)), let parentId = charItem.parentId else { return }
            self.updatePlayerData(forPlayerIndex: parentId, character: character)
            var snap = self.dataSource.snapshot()
            snap.reloadItems([charItem])
            self.dataSource.apply(snap)
        }
    }

And in my cellForRowAt, I have the following code to update the text field in the character cell (CustomCell1). The gameInfo object is a struct that has information, including the character name I am trying to display, that I will eventually store off into CoreData from the entries in the cells.

guard let parentId = info.parentId else { return UICollectionViewListCell() }
let playerData = self.gameInfo.playerData[parentId]
var obj = TextEntryCellInformation(title: rowTitle, rowType: info.rowType)
obj.value = obj.value = playerData?.character
obj.isSelectable = false
return collectionView.dequeueConfiguredReusableCell(using: textEntryCell, for: indexPath, item: obj)

And here is the cell registration for that cell, where TextEntryCellInformation holds the row type, title for the label, and an optional value that can set textfield's text:

private func createTextEntryListCellRegistration() -> UICollectionView.CellRegistration<TextEntryCollectionViewCell, TextEntryCellInformation> {
        return UICollectionView.CellRegistration<TextEntryCollectionViewCell, TextEntryCellInformation> { cell, indexPath, data in
            var config = TextEntryContentConfiguration()
            config.title = data.title
            config.tag = data.rowType.rawValue
            config.textChangedDelegate = self
            config.isSelectable = data.isSelectable
            config.customPlaceholder = "required"
            if let val = data.value {
                config.textValue = val
            }
            cell.contentConfiguration = config
        }
    }

So now, I think I have explained most of the code. Whenever I select the value in the picker view, the first time it will show the value correctly in the character cell. But if I change the value, the text seems to disappear from the character cell. However, I am getting the correct value from the picker view, verified with the print call at the start of the delegate function. I am also verifying that after I apply in the update delegate function, I am running through the cell registration and the correct value is being assigned to the config.textValue. I am not sure why then, if the config is being data is being set as expected with the correct character name, why the UI is not updating to show that information.

I included what I think is the relevant code and information. However, if more is needed, I will definitely update.

Thanks in advance for any help given!

Body:
Turns out I found the answer. When setting the configuration on the content view of the textfield custom cell (CustomCell1), I was doing  check to conform to equatable:

static func == (lhs: TextEntryContentConfiguration, rhs: TextEntryContentConfiguration) -> Bool {
        return lhs.title == rhs.title
    }

I needed to be doing:

static func == (lhs: TextEntryContentConfiguration, rhs: TextEntryContentConfiguration) -> Bool {
        return lhs.textValue == rhs.textValue
    }

This checks the difference to know if I should be updating the config values or not.


问:
Calculate walking times across route
I am trying to calculate travel distances across a walkable street network I've downloaded using OSMNX. I have generated a route from an origin to a destination using NetworkX's nx.shortest_path function. However, whenever I calculate my route setting "travel_time" as weight, I get inaccurate results. I was wondering if this might have to do with the "speed_kph" attribute in the network. Is there a way to manually set speeds to equate walking speeds (e.g. 5 kph?)?

答:
You are using the nx.shortest_path_length function and the travel_time attribute. Note the travel_time attribute is not present by default in your graph. In order to add it you need to use ox.add_edge_travel_times.

The Networkx function shortest_path_length states in it's documentation:

weight -
If None, every edge has weight/distance/cost 1. If a string, use this edge attribute as the edge weight. Any edge attribute not present defaults to 1.

Since the travel_time is not present you get the shortest path which has the minimum edges.

This can be verified by trying:

```<code>weight = nx.shortest_path_length(walk_network, origin_nn, destination_nn, weight = 'fake_key')
</code>```

Since usually in walking you assume a constant speed, a possible solution would be to use the edge length and calculate the speed separately.

For example:

```<code>import osmnx as ox
import networkx as nx

WALKING_SPEED = 1.4 # m/s average walkihg speed

walk_network = ox.graph.graph_from_address('Piccadilly Circus, London', dist = 1000, network_type = 'walk')

origin = (-0.13492669985021463, 51.51016491413415)
destination = (-0.12516, 51.51112)

origin_nn = ox.distance.nearest_nodes(walk_network, origin[0], origin[1])
destination_nn = ox.distance.nearest_nodes(walk_network, destination[0], destination[1])

length = nx.shortest_path_length(walk_network, origin_nn, destination_nn, weight = 'length')
duration = length / WALKING_SPEED / 60
print('The shortest walking route is {:.2f} meters and will take {:.2f} minutes'.format(length, duration))
</code>```

Title: Calculate walking times across route

Body:
You are using the nx.shortest_path_length function and the travel_time attribute. Note the travel_time attribute is not present by default in your graph. In order to add it you need to use ox.add_edge_travel_times.

The Networkx function shortest_path_length states in it's documentation:

weight -
If None, every edge has weight/distance/cost 1. If a string, use this edge attribute as the edge weight. Any edge attribute not present defaults to 1.

Since the travel_time is not present you get the shortest path which has the minimum edges.

This can be verified by trying:

weight = nx.shortest_path_length(walk_network, origin_nn, destination_nn, weight = 'fake_key')

Since usually in walking you assume a constant speed, a possible solution would be to use the edge length and calculate the speed separately.

For example:

import osmnx as ox
import networkx as nx

WALKING_SPEED = 1.4 # m/s average walkihg speed

walk_network = ox.graph.graph_from_address('Piccadilly Circus, London', dist = 1000, network_type = 'walk')

origin = (-0.13492669985021463, 51.51016491413415)
destination = (-0.12516, 51.51112)

origin_nn = ox.distance.nearest_nodes(walk_network, origin[0], origin[1])
destination_nn = ox.distance.nearest_nodes(walk_network, destination[0], destination[1])

length = nx.shortest_path_length(walk_network, origin_nn, destination_nn, weight = 'length')
duration = length / WALKING_SPEED / 60
print('The shortest walking route is {:.2f} meters and will take {:.2f} minutes'.format(length, duration))