问:
The following assertion was thrown during performLayout():
I'm new to flutter and I'm following up with this Udemy course but I face this error when I run the app on Android emulater on windows machine it shows the button on the whole screen

the app simple I'm just trying to get data from the user to store it in s file then print it in the console

My Result

Expected result

My code:-

main.dart

```<code>import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

void main() async{

  var data = await readData();
  if(data != null){
    print(data);
  }

  runApp(
      MaterialApp(
        title: "IO",
        home: Home(),
      )
  );
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  var _enterDataField = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Read/Write"),
        centerTitle: true,
        backgroundColor: Colors.greenAccent,
      ),
      body: new Container(
        padding: EdgeInsets.all(13.4),
        alignment: Alignment.topCenter,
        child: ListTile(
          title: TextField(
            controller: _enterDataField,
            decoration: InputDecoration(
                labelText: "Input Something"
            ),
          ),
          subtitle: FlatButton(
            color: Colors.redAccent,
            onPressed: (){
              print("Flat button");
              writeData(_enterDataField.text);
            },
            child: new Column(
              children: <Widget>[
                Text("Save Data"),
                Padding(padding: EdgeInsets.all(14.5)),
                Text("Save data goes all"),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Future<String> get _localPath async {
  final directory = await getApplicationDocumentsDirectory();
  return directory.path; // /home/directory/
}

Future<File> get _localFile async {
  final path = await _localPath;
  return File("$path/data.txt"); // /home/directory/data.txt
}

Future<File> writeData(String message) async {
  final file = await _localFile;
  return file.writeAsString("$message");
}

Future<String> readData() async{
  try{
    final file = await _localFile;
    String data = await file.readAsString();
    return data;
  }catch(e){
    return "Nothing has been saved yet!";
  }
}
</code>```

pubspec.yaml

```<code>version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  path_provider: ^1.1.0
</code>```

Error during run:

```<code>Launching lib\main.dart on Android SDK built for x86 in debug mode...
Initializing gradle...
Resolving dependencies...
Gradle task 'assembleDebug'...
Built build\app\outputs\apk\debug\app-debug.apk.
I/flutter ( 4904): Nothing has been saved yet!
I/Choreographer( 4904): Skipped 105 frames!  The application may be doing too much work on its main thread.
Syncing files to device Android SDK built for x86...
D/EGL_emulation( 4904): eglMakeCurrent: 0xe7085900: ver 3 1 (tinfo 0xe70839b0)
I/flutter ( 4904): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 4904): The following assertion was thrown during performLayout():
I/flutter ( 4904): not implemented
I/flutter ( 4904): 'package:flutter/src/material/input_decorator.dart': Failed assertion: line 977 pos 12: 'false'
I/flutter ( 4904):
I/flutter ( 4904): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter ( 4904): more information in this error message to help you determine and fix the underlying cause.
I/flutter ( 4904): In either case, please report this assertion by filing a bug on GitHub:
I/flutter ( 4904):   https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 4904):
I/flutter ( 4904): When the exception was thrown, this was the stack:
I/flutter ( 4904): #2      _RenderDecoration.computeDistanceToActualBaseline (package:flutter/src/material/input_decorator.dart:977:12)
I/flutter ( 4904): #3      RenderBox.getDistanceToActualBaseline.<anonymous closure> (package:flutter/src/rendering/box.dart:1672:50)
I/flutter ( 4904): #4      __InternalLinkedHashMap&_HashVMBase&MapMixin&_LinkedHashMapMixin.putIfAbsent (dart:collection/runtime/libcompact_hash.dart:281:23)
I/flutter ( 4904): #5      RenderBox.getDistanceToActualBaseline (package:flutter/src/rendering/box.dart:1672:22)
I/flutter ( 4904): #6      _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.computeDistanceToActualBaseline (package:flutter/src/rendering/proxy_box.dart:97:20)
I/flutter ( 4904): #7      RenderBox.getDistanceToActualBaseline.<anonymous closure> (package:flutter/src/rendering/box.dart:1672:50)
I/flutter ( 4904): #8      __InternalLinkedHashMap&_HashVMBase&MapMixin&_LinkedHashMapMixin.putIfAbsent (dart:collection/runtime/libcompact_hash.dart:281:23)
I/flutter ( 4904): #9      RenderBox.getDistanceToActualBaseline (package:flutter/src/rendering/box.dart:1672:22)
I/flutter ( 4904): #10     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.computeDistanceToActualBaseline (package:flutter/src/rendering/proxy_box.dart:97:20)
I/flutter ( 4904): #11     RenderBox.getDistanceToActualBaseline.<anonymous closure> (package:flutter/src/rendering/box.dart:1672:50)
I/flutter ( 4904): #12     __InternalLinkedHashMap&_HashVMBase&MapMixin&_LinkedHashMapMixin.putIfAbsent (dart:collection/runtime/libcompact_hash.dart:281:23)
I/flutter ( 4904): #13     RenderBox.getDistanceToActualBaseline (package:flutter/src/rendering/box.dart:1672:22)
I/flutter ( 4904): #14     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.computeDistanceToActualBaseline (package:flutter/src/rendering/proxy_box.dart:97:20)
I/flutter ( 4904): #15     RenderBox.getDistanceToActualBaseline.<anonymous closure> (package:flutter/src/rendering/box.dart:1672:50)
I/flutter ( 4904): #16     __InternalLinkedHashMap&_HashVMBase&MapMixin&_LinkedHashMapMixin.putIfAbsent (dart:collection/runtime/libcompact_hash.dart:281:23)
I/flutter ( 4904): #17     RenderBox.getDistanceToActualBaseline (package:flutter/src/rendering/box.dart:1672:22)
I/flutter ( 4904): #18     RenderBox.getDistanceToBaseline (package:flutter/src/rendering/box.dart:1655:27)
I/flutter ( 4904): #19     _RenderListTile._boxBaseline (package:flutter/src/material/list_tile.dart:886:16)
I/flutter ( 4904): #20     _RenderListTile.performLayout (package:flutter/src/material/list_tile.dart:945:32)
I/flutter ( 4904): #21     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #22     RenderPadding.performLayout (package:flutter/src/rendering/shifted_box.dart:199:11)
I/flutter ( 4904): #23     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #24     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #25     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #26     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #27     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #28     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #29     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #30     RenderPositionedBox.performLayout (package:flutter/src/rendering/shifted_box.dart:385:13)
I/flutter ( 4904): #31     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #32     RenderPadding.performLayout (package:flutter/src/rendering/shifted_box.dart:199:11)
I/flutter ( 4904): #33     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #34     MultiChildLayoutDelegate.layoutChild (package:flutter/src/rendering/custom_layout.dart:142:11)
I/flutter ( 4904): #35     _ScaffoldLayout.performLayout (package:flutter/src/material/scaffold.dart:339:7)
I/flutter ( 4904): #36     MultiChildLayoutDelegate._callPerformLayout (package:flutter/src/rendering/custom_layout.dart:212:7)
I/flutter ( 4904): #37     RenderCustomMultiChildLayoutBox.performLayout (package:flutter/src/rendering/custom_layout.dart:356:14)
I/flutter ( 4904): #38     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #39     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #40     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #41     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #42     _RenderCustomClip.performLayout (package:flutter/src/rendering/proxy_box.dart:1203:11)
I/flutter ( 4904): #43     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #44     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #45     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #46     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #47     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #48     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #49     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #50     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #51     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #52     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #53     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #54     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #55     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #56     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #57     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #58     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #59     RenderOffstage.performLayout (package:flutter/src/rendering/proxy_box.dart:2900:13)
I/flutter ( 4904): #60     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #61     RenderStack.performLayout (package:flutter/src/rendering/stack.dart:510:15)
I/flutter ( 4904): #62     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #63     __RenderTheatre&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #64     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #65     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #66     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #67     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #68     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #69     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #70     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #71     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #72     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #73     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #74     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #75     RenderView.performLayout (package:flutter/src/rendering/view.dart:147:13)
I/flutter ( 4904): #76     RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:1509:7)
I/flutter ( 4904): #77     PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:768:18)
I/flutter ( 4904): #78     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:281:19)
I/flutter ( 4904): #79     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:686:13)
I/flutter ( 4904): #80     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:219:5)
I/flutter ( 4904): #81     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)
I/flutter ( 4904): #82     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9)
I/flutter ( 4904): #83     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:751:7)
I/flutter ( 4904): #85     _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19)
I/flutter ( 4904): #86     _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
I/flutter ( 4904): #87     _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
I/flutter ( 4904): (elided 3 frames from class _AssertionError and package dart:async)
I/flutter ( 4904):
I/flutter ( 4904): The following RenderObject was being processed when the exception was fired:
I/flutter ( 4904):   _RenderListTile#c955b relayoutBoundary=up7 NEEDS-LAYOUT NEEDS-PAINT
I/flutter ( 4904):   creator: _ListTile ← MediaQuery ← Padding ← SafeArea ← Semantics ← Listener ← _GestureSemantics ←
I/flutter ( 4904):   RawGestureDetector ← GestureDetector ← InkWell ← ListTile ← Align ← ⋯
I/flutter ( 4904):   parentData: offset=Offset(0.0, 0.0) (can use size)
I/flutter ( 4904):   constraints: BoxConstraints(0.0<=w<=352.6, 0.0<=h<=668.1)
I/flutter ( 4904):   size: MISSING
I/flutter ( 4904): This RenderObject had the following descendants (showing up to depth 5):
I/flutter ( 4904):   RenderSemanticsAnnotations#30cbc relayoutBoundary=up8 NEEDS-PAINT
I/flutter ( 4904):     RenderIgnorePointer#d2ac5 relayoutBoundary=up9 NEEDS-PAINT
I/flutter ( 4904):       RenderPointerListener#95c88 relayoutBoundary=up10 NEEDS-PAINT
I/flutter ( 4904):         _RenderDecoration#d39f5 relayoutBoundary=up11 NEEDS-PAINT
I/flutter ( 4904):           RenderRepaintBoundary#7e8a4 relayoutBoundary=up12 NEEDS-PAINT
I/flutter ( 4904):           RenderTransform#6a1d0 relayoutBoundary=up12 NEEDS-PAINT
I/flutter ( 4904):           RenderConstrainedBox#bd9be relayoutBoundary=up12 NEEDS-PAINT
I/flutter ( 4904):           RenderCustomPaint#862dd NEEDS-PAINT
I/flutter ( 4904):   RenderSemanticsAnnotations#103e3 relayoutBoundary=up8 NEEDS-PAINT
I/flutter ( 4904):     _RenderInputPadding#ab3b4 relayoutBoundary=up9 NEEDS-PAINT
I/flutter ( 4904):       RenderConstrainedBox#39a4f relayoutBoundary=up10 NEEDS-PAINT
I/flutter ( 4904):         RenderPhysicalShape#32f8b relayoutBoundary=up11 NEEDS-PAINT
I/flutter ( 4904):           RenderCustomPaint#5950d relayoutBoundary=up12 NEEDS-PAINT
I/flutter ( 4904): ════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter ( 4904): Another exception was thrown: RenderBox was not laid out: _RenderListTile#c955b relayoutBoundary=up7 NEEDS-PAINT
I/flutter ( 4904): Another exception was thrown: RenderBox was not laid out: RenderPadding#a1895 relayoutBoundary=up6 NEEDS-PAINT
I/flutter ( 4904): Another exception was thrown: RenderBox was not laid out: RenderSemanticsAnnotations#9585a relayoutBoundary=up5 NEEDS-PAINT
I/flutter ( 4904): Another exception was thrown: RenderBox was not laid out: RenderPointerListener#867ef relayoutBoundary=up4 NEEDS-PAINT
I/flutter ( 4904): Another exception was thrown: 'package:flutter/src/rendering/shifted_box.dart': Failed assertion: line 314 pos 12: 'child.hasSize': is not true.
D/        ( 4904): HostConnection::get() New Host Connection established 0xce8870c0, tid 4923
D/EGL_emulation( 4904): eglMakeCurrent: 0xe569c960: ver 3 1 (tinfo 0xe447f500)
</code>```

答:
I had to edit the code to be like this in order to work</p>

```<code>FlatButton(
              color: Colors.redAccent,
              onPressed: (){
                print("Flat button ${_enterDataField.text}");
                writeData(_enterDataField.text.toString());
              },
              child: new Column(
                children: <Widget>[
                  Text("Save Data"),
                  Padding(padding: EdgeInsets.all(14.5)),
                  FutureBuilder(
                    future: readData(),
                    builder: (BuildContext context, AsyncSnapshot<String> data){
                      if(data.hasData != null){
                        return Text(
                          data.data.toString(),
                          style: TextStyle(
                            color: Colors.white70,
                          ),
                        );
                      }else{
                        return Text("No data has been saved");
                      }
                    },
                  ),
                ],
              ),
            )
</code>```

Body:
I'm new to flutter and I'm following up with this Udemy course but I face this error when I run the app on Android emulater on windows machine it shows the button on the whole screen

the app simple I'm just trying to get data from the user to store it in s file then print it in the console

My Result

Expected result

My code:-

main.dart

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

void main() async{

  var data = await readData();
  if(data != null){
    print(data);
  }

  runApp(
      MaterialApp(
        title: "IO",
        home: Home(),
      )
  );
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  var _enterDataField = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Read/Write"),
        centerTitle: true,
        backgroundColor: Colors.greenAccent,
      ),
      body: new Container(
        padding: EdgeInsets.all(13.4),
        alignment: Alignment.topCenter,
        child: ListTile(
          title: TextField(
            controller: _enterDataField,
            decoration: InputDecoration(
                labelText: "Input Something"
            ),
          ),
          subtitle: FlatButton(
            color: Colors.redAccent,
            onPressed: (){
              print("Flat button");
              writeData(_enterDataField.text);
            },
            child: new Column(
              children: <Widget>[
                Text("Save Data"),
                Padding(padding: EdgeInsets.all(14.5)),
                Text("Save data goes all"),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Future<String> get _localPath async {
  final directory = await getApplicationDocumentsDirectory();
  return directory.path; // /home/directory/
}

Future<File> get _localFile async {
  final path = await _localPath;
  return File("$path/data.txt"); // /home/directory/data.txt
}

Future<File> writeData(String message) async {
  final file = await _localFile;
  return file.writeAsString("$message");
}

Future<String> readData() async{
  try{
    final file = await _localFile;
    String data = await file.readAsString();
    return data;
  }catch(e){
    return "Nothing has been saved yet!";
  }
}

pubspec.yaml

version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  path_provider: ^1.1.0

Error during run:

Launching lib\main.dart on Android SDK built for x86 in debug mode...
Initializing gradle...
Resolving dependencies...
Gradle task 'assembleDebug'...
Built build\app\outputs\apk\debug\app-debug.apk.
I/flutter ( 4904): Nothing has been saved yet!
I/Choreographer( 4904): Skipped 105 frames!  The application may be doing too much work on its main thread.
Syncing files to device Android SDK built for x86...
D/EGL_emulation( 4904): eglMakeCurrent: 0xe7085900: ver 3 1 (tinfo 0xe70839b0)
I/flutter ( 4904): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 4904): The following assertion was thrown during performLayout():
I/flutter ( 4904): not implemented
I/flutter ( 4904): 'package:flutter/src/material/input_decorator.dart': Failed assertion: line 977 pos 12: 'false'
I/flutter ( 4904):
I/flutter ( 4904): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter ( 4904): more information in this error message to help you determine and fix the underlying cause.
I/flutter ( 4904): In either case, please report this assertion by filing a bug on GitHub:
I/flutter ( 4904):   https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 4904):
I/flutter ( 4904): When the exception was thrown, this was the stack:
I/flutter ( 4904): #2      _RenderDecoration.computeDistanceToActualBaseline (package:flutter/src/material/input_decorator.dart:977:12)
I/flutter ( 4904): #3      RenderBox.getDistanceToActualBaseline.<anonymous closure> (package:flutter/src/rendering/box.dart:1672:50)
I/flutter ( 4904): #4      __InternalLinkedHashMap&_HashVMBase&MapMixin&_LinkedHashMapMixin.putIfAbsent (dart:collection/runtime/libcompact_hash.dart:281:23)
I/flutter ( 4904): #5      RenderBox.getDistanceToActualBaseline (package:flutter/src/rendering/box.dart:1672:22)
I/flutter ( 4904): #6      _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.computeDistanceToActualBaseline (package:flutter/src/rendering/proxy_box.dart:97:20)
I/flutter ( 4904): #7      RenderBox.getDistanceToActualBaseline.<anonymous closure> (package:flutter/src/rendering/box.dart:1672:50)
I/flutter ( 4904): #8      __InternalLinkedHashMap&_HashVMBase&MapMixin&_LinkedHashMapMixin.putIfAbsent (dart:collection/runtime/libcompact_hash.dart:281:23)
I/flutter ( 4904): #9      RenderBox.getDistanceToActualBaseline (package:flutter/src/rendering/box.dart:1672:22)
I/flutter ( 4904): #10     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.computeDistanceToActualBaseline (package:flutter/src/rendering/proxy_box.dart:97:20)
I/flutter ( 4904): #11     RenderBox.getDistanceToActualBaseline.<anonymous closure> (package:flutter/src/rendering/box.dart:1672:50)
I/flutter ( 4904): #12     __InternalLinkedHashMap&_HashVMBase&MapMixin&_LinkedHashMapMixin.putIfAbsent (dart:collection/runtime/libcompact_hash.dart:281:23)
I/flutter ( 4904): #13     RenderBox.getDistanceToActualBaseline (package:flutter/src/rendering/box.dart:1672:22)
I/flutter ( 4904): #14     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.computeDistanceToActualBaseline (package:flutter/src/rendering/proxy_box.dart:97:20)
I/flutter ( 4904): #15     RenderBox.getDistanceToActualBaseline.<anonymous closure> (package:flutter/src/rendering/box.dart:1672:50)
I/flutter ( 4904): #16     __InternalLinkedHashMap&_HashVMBase&MapMixin&_LinkedHashMapMixin.putIfAbsent (dart:collection/runtime/libcompact_hash.dart:281:23)
I/flutter ( 4904): #17     RenderBox.getDistanceToActualBaseline (package:flutter/src/rendering/box.dart:1672:22)
I/flutter ( 4904): #18     RenderBox.getDistanceToBaseline (package:flutter/src/rendering/box.dart:1655:27)
I/flutter ( 4904): #19     _RenderListTile._boxBaseline (package:flutter/src/material/list_tile.dart:886:16)
I/flutter ( 4904): #20     _RenderListTile.performLayout (package:flutter/src/material/list_tile.dart:945:32)
I/flutter ( 4904): #21     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #22     RenderPadding.performLayout (package:flutter/src/rendering/shifted_box.dart:199:11)
I/flutter ( 4904): #23     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #24     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #25     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #26     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #27     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #28     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #29     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #30     RenderPositionedBox.performLayout (package:flutter/src/rendering/shifted_box.dart:385:13)
I/flutter ( 4904): #31     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #32     RenderPadding.performLayout (package:flutter/src/rendering/shifted_box.dart:199:11)
I/flutter ( 4904): #33     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #34     MultiChildLayoutDelegate.layoutChild (package:flutter/src/rendering/custom_layout.dart:142:11)
I/flutter ( 4904): #35     _ScaffoldLayout.performLayout (package:flutter/src/material/scaffold.dart:339:7)
I/flutter ( 4904): #36     MultiChildLayoutDelegate._callPerformLayout (package:flutter/src/rendering/custom_layout.dart:212:7)
I/flutter ( 4904): #37     RenderCustomMultiChildLayoutBox.performLayout (package:flutter/src/rendering/custom_layout.dart:356:14)
I/flutter ( 4904): #38     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #39     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #40     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #41     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #42     _RenderCustomClip.performLayout (package:flutter/src/rendering/proxy_box.dart:1203:11)
I/flutter ( 4904): #43     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #44     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #45     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #46     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #47     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #48     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #49     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #50     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #51     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #52     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #53     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #54     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #55     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #56     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #57     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #58     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #59     RenderOffstage.performLayout (package:flutter/src/rendering/proxy_box.dart:2900:13)
I/flutter ( 4904): #60     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #61     RenderStack.performLayout (package:flutter/src/rendering/stack.dart:510:15)
I/flutter ( 4904): #62     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #63     __RenderTheatre&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #64     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #65     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #66     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #67     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #68     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #69     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #70     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #71     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #72     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #73     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:104:13)
I/flutter ( 4904): #74     RenderObject.layout (package:flutter/src/rendering/object.dart:1634:7)
I/flutter ( 4904): #75     RenderView.performLayout (package:flutter/src/rendering/view.dart:147:13)
I/flutter ( 4904): #76     RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:1509:7)
I/flutter ( 4904): #77     PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:768:18)
I/flutter ( 4904): #78     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:281:19)
I/flutter ( 4904): #79     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:686:13)
I/flutter ( 4904): #80     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:219:5)
I/flutter ( 4904): #81     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)
I/flutter ( 4904): #82     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9)
I/flutter ( 4904): #83     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:751:7)
I/flutter ( 4904): #85     _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19)
I/flutter ( 4904): #86     _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
I/flutter ( 4904): #87     _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
I/flutter ( 4904): (elided 3 frames from class _AssertionError and package dart:async)
I/flutter ( 4904):
I/flutter ( 4904): The following RenderObject was being processed when the exception was fired:
I/flutter ( 4904):   _RenderListTile#c955b relayoutBoundary=up7 NEEDS-LAYOUT NEEDS-PAINT
I/flutter ( 4904):   creator: _ListTile ← MediaQuery ← Padding ← SafeArea ← Semantics ← Listener ← _GestureSemantics ←
I/flutter ( 4904):   RawGestureDetector ← GestureDetector ← InkWell ← ListTile ← Align ← ⋯
I/flutter ( 4904):   parentData: offset=Offset(0.0, 0.0) (can use size)
I/flutter ( 4904):   constraints: BoxConstraints(0.0<=w<=352.6, 0.0<=h<=668.1)
I/flutter ( 4904):   size: MISSING
I/flutter ( 4904): This RenderObject had the following descendants (showing up to depth 5):
I/flutter ( 4904):   RenderSemanticsAnnotations#30cbc relayoutBoundary=up8 NEEDS-PAINT
I/flutter ( 4904):     RenderIgnorePointer#d2ac5 relayoutBoundary=up9 NEEDS-PAINT
I/flutter ( 4904):       RenderPointerListener#95c88 relayoutBoundary=up10 NEEDS-PAINT
I/flutter ( 4904):         _RenderDecoration#d39f5 relayoutBoundary=up11 NEEDS-PAINT
I/flutter ( 4904):           RenderRepaintBoundary#7e8a4 relayoutBoundary=up12 NEEDS-PAINT
I/flutter ( 4904):           RenderTransform#6a1d0 relayoutBoundary=up12 NEEDS-PAINT
I/flutter ( 4904):           RenderConstrainedBox#bd9be relayoutBoundary=up12 NEEDS-PAINT
I/flutter ( 4904):           RenderCustomPaint#862dd NEEDS-PAINT
I/flutter ( 4904):   RenderSemanticsAnnotations#103e3 relayoutBoundary=up8 NEEDS-PAINT
I/flutter ( 4904):     _RenderInputPadding#ab3b4 relayoutBoundary=up9 NEEDS-PAINT
I/flutter ( 4904):       RenderConstrainedBox#39a4f relayoutBoundary=up10 NEEDS-PAINT
I/flutter ( 4904):         RenderPhysicalShape#32f8b relayoutBoundary=up11 NEEDS-PAINT
I/flutter ( 4904):           RenderCustomPaint#5950d relayoutBoundary=up12 NEEDS-PAINT
I/flutter ( 4904): ════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter ( 4904): Another exception was thrown: RenderBox was not laid out: _RenderListTile#c955b relayoutBoundary=up7 NEEDS-PAINT
I/flutter ( 4904): Another exception was thrown: RenderBox was not laid out: RenderPadding#a1895 relayoutBoundary=up6 NEEDS-PAINT
I/flutter ( 4904): Another exception was thrown: RenderBox was not laid out: RenderSemanticsAnnotations#9585a relayoutBoundary=up5 NEEDS-PAINT
I/flutter ( 4904): Another exception was thrown: RenderBox was not laid out: RenderPointerListener#867ef relayoutBoundary=up4 NEEDS-PAINT
I/flutter ( 4904): Another exception was thrown: 'package:flutter/src/rendering/shifted_box.dart': Failed assertion: line 314 pos 12: 'child.hasSize': is not true.
D/        ( 4904): HostConnection::get() New Host Connection established 0xce8870c0, tid 4923
D/EGL_emulation( 4904): eglMakeCurrent: 0xe569c960: ver 3 1 (tinfo 0xe447f500)

Body:
I had to edit the code to be like this in order to work

FlatButton(
              color: Colors.redAccent,
              onPressed: (){
                print("Flat button ${_enterDataField.text}");
                writeData(_enterDataField.text.toString());
              },
              child: new Column(
                children: <Widget>[
                  Text("Save Data"),
                  Padding(padding: EdgeInsets.all(14.5)),
                  FutureBuilder(
                    future: readData(),
                    builder: (BuildContext context, AsyncSnapshot<String> data){
                      if(data.hasData != null){
                        return Text(
                          data.data.toString(),
                          style: TextStyle(
                            color: Colors.white70,
                          ),
                        );
                      }else{
                        return Text("No data has been saved");
                      }
                    },
                  ),
                ],
              ),
            )


来源: stackexchange

问:
File has two parts - 1st is text 2nd is CSV. How to parse only the CSV part with python
I have a text file which contains text in the first 20 or so lines, followed by CSV data.  Some of the text in the text section contains commas and so trying csv.reader or csv.dictreader doesn't work well.

I want to skip past the text section and only then start to parse the CSV data.

Searches don't yield much other than instructions to either use csv.reader/csv.dictreader and iterate through the rows that are returned (which doesn't work because of the commas in the text), or to read the file line-by-line and split the lines using ',' as the delimiter.

The latter works up to a point, but it produces strings, not numbers.   I could convert the strings to numbers but I'm hoping that there's a simple way to do this either with the csv or numpy libraries.

As requested - Sample data:

```
This is the first line. This is all just text to be skipped.
The first line doesn't always have a comma - maybe it's in the third line
Still no commas, or was there?
Yes, there was. And there it is again.
and so on
There are more lines but they finally stop when you get to
EndOfHeader
1,2,3,4,5
8,9,10,11,12
3, 6, 9, 12, 15
```

Thanks for the help.

Edit#2
A suggested answer gave the following link entitled Read file from line 2...
That's kind of what I'm looking for, but I want to be able to read through the lines until I find the "EndOfHeader"  and then call on the CSV library to handle the remainder of the file.
The reply by saimadhu.polamuri is part of what I've tried, specifically

with open(filename , 'r') as f:
    first_line = f.readline()
    for line in f:
            #test if line equals EndOfHeader. If true then parse as CSV
```

But that's where it comes apart - I can't see how to have CSV work with the data from this point forward.

答:
With thanks to @Mike for the suggestion, the code is actually reasonably straightforward.

with open('data.csv') as f:                # open the file
    for i in range(7):                     # Loop over first 7 lines
        str=f.readline()                   # just read them. Could also do f.next()
    r = csv.reader(f, delimiter=',')       # Now pass the file handle to a csv reader
    for row in r:                          # and loop over the resulting rows
        print(row)                         # Print the row. Or do something else.
```

In my actual code, it will search for the EndOfHeader line and use that to decide where to start parsing the CSV

I'm posting this as an answer, as the question that this one supposedly duplicates doesn't explicitly consider this issue of the file handle and how it can be passed to a CSV reader, and so it may help someone else.

Thanks to all who took time to help.

ContentLicense: CC BY-SA 4.0

Body:
I have a text file which contains text in the first 20 or so lines, followed by CSV data.  Some of the text in the text section contains commas and so trying csv.reader or csv.dictreader doesn't work well.

I want to skip past the text section and only then start to parse the CSV data.

Searches don't yield much other than instructions to either use csv.reader/csv.dictreader and iterate through the rows that are returned (which doesn't work because of the commas in the text), or to read the file line-by-line and split the lines using ',' as the delimiter.

The latter works up to a point, but it produces strings, not numbers.   I could convert the strings to numbers but I'm hoping that there's a simple way to do this either with the csv or numpy libraries.

As requested - Sample data:

This is the first line. This is all just text to be skipped.
The first line doesn't always have a comma - maybe it's in the third line
Still no commas, or was there?
Yes, there was. And there it is again.
and so on
There are more lines but they finally stop when you get to
EndOfHeader
1,2,3,4,5
8,9,10,11,12
3, 6, 9, 12, 15

Thanks for the help.

Edit#2
A suggested answer gave the following link entitled Read file from line 2...
That's kind of what I'm looking for, but I want to be able to read through the lines until I find the "EndOfHeader"  and then call on the CSV library to handle the remainder of the file.
The reply by saimadhu.polamuri is part of what I've tried, specifically

with open(filename , 'r') as f:
    first_line = f.readline()
    for line in f:
            #test if line equals EndOfHeader. If true then parse as CSV

But that's where it comes apart - I can't see how to have CSV work with the data from this point forward.

Body:
With thanks to @Mike for the suggestion, the code is actually reasonably straightforward.

with open('data.csv') as f:                # open the file
    for i in range(7):                     # Loop over first 7 lines
        str=f.readline()                   # just read them. Could also do f.next()
    r = csv.reader(f, delimiter=',')       # Now pass the file handle to a csv reader
    for row in r:                          # and loop over the resulting rows
        print(row)                         # Print the row. Or do something else.

In my actual code, it will search for the EndOfHeader line and use that to decide where to start parsing the CSV

I'm posting this as an answer, as the question that this one supposedly duplicates doesn't explicitly consider this issue of the file handle and how it can be passed to a CSV reader, and so it may help someone else.

Thanks to all who took time to help.


问:
Need to add multiple elements to search for a particular class with jQuery
I am using jQuery and am currently looking in one type of element for a particular class. I need to update it to look in three different elements, but am not sure how to do this since I assume I will need to use an array?

Here's my current code:

```<code>$findRed = $("p.red", "#main");

if ( $findRed.length >= 1 ) {
    greater or equal to one
}
</code>```

I need to change it so it will look for .red in either a p, div, or span tag.

Any help would be appreciate.

答:
Your selector can simply be .red.  That will match any element type with that class.  Or if you just want those specific elements, your selector could look like this:

```<code>$findRed = $("p.red, div.red, span.red", "#main");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using jQuery and am currently looking in one type of element for a particular class. I need to update it to look in three different elements, but am not sure how to do this since I assume I will need to use an array?

Here's my current code:

$findRed = $("p.red", "#main");

if ( $findRed.length >= 1 ) {
    greater or equal to one
}

I need to change it so it will look for .red in either a p, div, or span tag.

Any help would be appreciate.

Body:
Your selector can simply be .red.  That will match any element type with that class.  Or if you just want those specific elements, your selector could look like this:

$findRed = $("p.red, div.red, span.red", "#main");


问:
what condition will cause while loop stop in itertools.groupby() source code
I saw this code in here: https://docs.python.org/3/library/itertools.html?highlight=groupby#itertools.groupby

```<code>class groupby:
    # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
    # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
    def __init__(self, iterable, key=None):
        if key is None:
            key = lambda x: x
        self.keyfunc = key
        self.it = iter(iterable)
        self.tgtkey = self.currkey = self.currvalue = object()
    def __iter__(self):
        return self
    def __next__(self):
        self.id = object()
        while self.currkey == self.tgtkey:
            self.currvalue = next(self.it)    # Exit on StopIteration
            self.currkey = self.keyfunc(self.currvalue)
        self.tgtkey = self.currkey
        return (self.currkey, self._grouper(self.tgtkey, self.id))
    def _grouper(self, tgtkey, id):
        while self.id is id and self.currkey == tgtkey:
            yield self.currvalue
            try:
                self.currvalue = next(self.it)
            except StopIteration:
                return
            self.currkey = self.keyfunc(self.currvalue)
</code>```

In the condition of while self.id is id and self.currkey == tgtkey:, I want know what kind of condition will cause self.id is id to become False?

答:
The condition while self.id is id and self.currkey == tgtkey: reads roughly as "while the user hasn't called next again, and we are in the same group:". self.id is an attribute set by __next__. The local reference id is the reference in _grouper to what self.id was when it got called. Since every call to next generates a new object, the check is equivalent to asking if __next__ has been called since grouper started.

Remember that the groupby object does not have to operate on stored sequences. The input can be a lazy generator. Notice that the functions always read ahead to ensure that the next item is in the current group, and only yield it if it is. The first part of __next__ consumes the remainer of the iterator until the next group starts, to fulfill exactly that part of the contract in case you ask for the next group before the current one is consumed.

Body:
I saw this code in here: https://docs.python.org/3/library/itertools.html?highlight=groupby#itertools.groupby

class groupby:
    # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
    # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
    def __init__(self, iterable, key=None):
        if key is None:
            key = lambda x: x
        self.keyfunc = key
        self.it = iter(iterable)
        self.tgtkey = self.currkey = self.currvalue = object()
    def __iter__(self):
        return self
    def __next__(self):
        self.id = object()
        while self.currkey == self.tgtkey:
            self.currvalue = next(self.it)    # Exit on StopIteration
            self.currkey = self.keyfunc(self.currvalue)
        self.tgtkey = self.currkey
        return (self.currkey, self._grouper(self.tgtkey, self.id))
    def _grouper(self, tgtkey, id):
        while self.id is id and self.currkey == tgtkey:
            yield self.currvalue
            try:
                self.currvalue = next(self.it)
            except StopIteration:
                return
            self.currkey = self.keyfunc(self.currvalue)

In the condition of while self.id is id and self.currkey == tgtkey:, I want know what kind of condition will cause self.id is id to become False?


问:
Using pandas to combine csv by comparing a key ("id")
I have two CSVs with basically the same content, but spelling mistakes are removed from one, fileA.csv, and fileB.csv gets updated (as in new rows are added) from upstream (a limesurvey installation). How do I "combine" these two files using Pandas by checking the "id" column?

I have tried to iterate over both files using Python csv module, but it didn't ended successfully. I managed to combine the two CSVs using the code below, but it just added the same columns ending with "_x" and "_y" ...

```<code>import pandas as pd

fileA = pd.read_csv("new_data.csv_corrected",sep=";")
fileB = pd.read_csv("new_data.csv",sep=";")

merged = pd.merge(fileB, fileA, on='id')

print(merged.to_csv())
</code>```

Body:
I have two CSVs with basically the same content, but spelling mistakes are removed from one, fileA.csv, and fileB.csv gets updated (as in new rows are added) from upstream (a limesurvey installation). How do I "combine" these two files using Pandas by checking the "id" column?

I have tried to iterate over both files using Python csv module, but it didn't ended successfully. I managed to combine the two CSVs using the code below, but it just added the same columns ending with "_x" and "_y" ...

import pandas as pd

fileA = pd.read_csv("new_data.csv_corrected",sep=";")
fileB = pd.read_csv("new_data.csv",sep=";")

merged = pd.merge(fileB, fileA, on='id')

print(merged.to_csv())

Body:
I'm presuming spelling mistakes being removed from fileA.csv means you want to keep row in fileA.csv, but add any rows in fileB.csv that do not exist in fileA.csv.

As a general rule you should read in your DataFrames so the index is set to your primary key. Having done that, I think the simple way to do what you want is combine_first():

Example:

> cat FileA.csv
id,0,  1,  2,  3,  4
A,1.000,1.000,1.000,1.000,1.000
B,1.000,1.000,1.000,1.000,1.000
C,1.000,1.000,1.000,1.000,1.000
D,1.000,1.000,1.000,1.000,1.000
> cat FileB.csv
id,0,  1,  2,  3,  4
A,0.000,0.000,0.000,0.000,0.000
B,0.000,0.000,0.000,0.000,0.000
E,0.000,0.000,0.000,0.000,0.000
F,0.000,0.000,0.000,0.000,0.000
> dfA = pd.read_csv('FileA.csv', header=0, index_col='id')
> dfB = pd.read_csv('FileB.csv', header=0, index_col='id')
> dfA.combine_first(dfB)

Gives:

           0         1         2         3         4
id
A  +1.000000 +1.000000 +1.000000 +1.000000 +1.000000
B  +1.000000 +1.000000 +1.000000 +1.000000 +1.000000
C  +1.000000 +1.000000 +1.000000 +1.000000 +1.000000
D  +1.000000 +1.000000 +1.000000 +1.000000 +1.000000
E  +0.000000 +0.000000 +0.000000 +0.000000 +0.000000
F  +0.000000 +0.000000 +0.000000 +0.000000 +0.000000

There is also DataFrame.update() but annoyingly, its behavior is inconsistent with dict.update(), as won't add new "keys" (index items).


问:
S3 Bucket Endpoint for Static Website Hosting
I've hosted a static website on S3 bucket in US East (N. Virginia) region. The endpoint is something like this

http:// BucketName .s3-website-us-east-1.amazonaws.com

This region has also a valid endpoint name

s3.amazonaws.com

I want change mine to something like
http://s3.amazonaws.com/ BucketName /

Is there a way I can do so?

答:
You can point to an Amazon S3 bucket using the s3.amazonaws.com/bucketname method, however:

This does not enable the Static Website Hosting features (such as using default index and error pages)

It is being deprecated. See: Amazon S3 Path Deprecation Plan – The Rest of the Story | AWS News Blog


问:
Printing struct to a file printing all empty elements of a char array
I am trying to create a program to create a text file, write an unknown amount of structures and other files contents into one main file. When I write a structure to a text file, it writes all the empty elements of a character array, and I want to avoid this. Any idea on how to prevent these elements from being written? I am at a beginning part of the program and am working on building it.

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
struct hdr
{
  int file_size;
  char deleted[1];
  char file_name[256];
};

int main()
{

  //Open the main file, check if the main header exists
  FILE *fp;
  int exists = 0;
  fp = fopen("CS3411TAR.txt","a+b");

  //Check if exists
  char* buf[100];
  while(fscanf(fp," %*s %*s %s ",buf) >0){
    exists = 1;
  }

  if(exists == 0){
    //file header DNE
    struct  hdr create = {atoi("-10"),"0","CS3411 TAR"};
    fwrite( &create, sizeof(struct hdr),1,fp);

  }
  //To-Do  open file arguments names create headers and write

  fclose(fp);

  return 0;
}

```

<p>This is the file output, some elements have been removed as it just continues 200+ odd times</p>

<pre class="lang-c prettyprint-override"><code>öÿÿÿ0CS3411 TAR^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@
</code>```

Im hoping for an output of

-10
0
CS3411 TAR
```

答:
Please remember that the if clause needs an expression to evaluate.

Your expression exists = 0 always results in the value of exists which is 0.

Correct the if expression to !exists which is a boolean expression to compare exists against the value zero.

If exists has a value not equal to 0, you write to the file, otherwise you skip the write statement.

That's what you meant.

Add a fread statement instead of fscanf to check if the header exists in the file you just opened.

You write binary, so read binary, too.

The real problem appears, when all simple issues are fixed, is: the file opened for appending is positioned at the end of file.

Use fseekto position the file pointer everytime you want to read the header or a record from the file.

Here ist my working version:

```<code>#include <string.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct hdr
{
  int file_size;
  char deleted;
  char file_name[256];
} Header;

const Header defaultHeader = {-10, 0, "CS3411 TAR"};

int main()
{
  //Open the main file, check if the main header exists
  FILE *fp;
  int exists = 0;
  fp = fopen("CS3411TAR.txt", "a+");
  if (!fp)
  {

    perror("Couldn't open file");
    return EXIT_FAILURE;
  }
  Header header;

  //Check if exists
  fseek(fp, 0, SEEK_SET);
  int bytesRead = fread(&header, sizeof(Header), 1, fp);
  printf("bytesRead: %d\n", bytesRead);
  if (bytesRead == 1)
  {
    printf("Header found!\n");
  }
  else
  {
    fseek(fp, 0, SEEK_SET);
    //file header DNE
    fwrite(&defaultHeader, sizeof(Header), 1, fp);

    printf("Header written.\n");
  }

  //To-Do  open file arguments names create headers and write

  fclose(fp);

  return EXIT_SUCCESS;
}
</code>```

Body:
I am trying to create a program to create a text file, write an unknown amount of structures and other files contents into one main file. When I write a structure to a text file, it writes all the empty elements of a character array, and I want to avoid this. Any idea on how to prevent these elements from being written? I am at a beginning part of the program and am working on building it.

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
struct hdr
{
  int file_size;
  char deleted[1];
  char file_name[256];
};

int main()
{

  //Open the main file, check if the main header exists
  FILE *fp;
  int exists = 0;
  fp = fopen("CS3411TAR.txt","a+b");

  //Check if exists
  char* buf[100];
  while(fscanf(fp," %*s %*s %s ",buf) >0){
    exists = 1;
  }

  if(exists == 0){
    //file header DNE
    struct  hdr create = {atoi("-10"),"0","CS3411 TAR"};
    fwrite( &create, sizeof(struct hdr),1,fp);

  }
  //To-Do  open file arguments names create headers and write

  fclose(fp);

  return 0;
}

This is the file output, some elements have been removed as it just continues 200+ odd times

öÿÿÿ0CS3411 TAR^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@

Im hoping for an output of

-10
0
CS3411 TAR

Body:
Please remember that the if clause needs an expression to evaluate.

Your expression exists = 0 always results in the value of exists which is 0.

Correct the if expression to !exists which is a boolean expression to compare exists against the value zero.

If exists has a value not equal to 0, you write to the file, otherwise you skip the write statement.

That's what you meant.

Add a fread statement instead of fscanf to check if the header exists in the file you just opened.

You write binary, so read binary, too.

The real problem appears, when all simple issues are fixed, is: the file opened for appending is positioned at the end of file.

Use fseekto position the file pointer everytime you want to read the header or a record from the file.

Here ist my working version:

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct hdr
{
  int file_size;
  char deleted;
  char file_name[256];
} Header;

const Header defaultHeader = {-10, 0, "CS3411 TAR"};

int main()
{
  //Open the main file, check if the main header exists
  FILE *fp;
  int exists = 0;
  fp = fopen("CS3411TAR.txt", "a+");
  if (!fp)
  {

    perror("Couldn't open file");
    return EXIT_FAILURE;
  }
  Header header;

  //Check if exists
  fseek(fp, 0, SEEK_SET);
  int bytesRead = fread(&header, sizeof(Header), 1, fp);
  printf("bytesRead: %d\n", bytesRead);
  if (bytesRead == 1)
  {
    printf("Header found!\n");
  }
  else
  {
    fseek(fp, 0, SEEK_SET);
    //file header DNE
    fwrite(&defaultHeader, sizeof(Header), 1, fp);

    printf("Header written.\n");
  }

  //To-Do  open file arguments names create headers and write

  fclose(fp);

  return EXIT_SUCCESS;
}


问:
Calling Check Names from plugin
I was wondering if there is a way to call the Check Names function from my Outlook plugin so i can avoid unresolved names which will not be send. My problem is when a user enters an email address which has not been checked / underlined and it calls my plugin i do not get the address in the TO, or CC box which is a big problem. If i go and press check names. the new email is underlined and will be sent. So trying to find a way to automate this process.
So i am looking for some code example or docs which shows how to call the check names function from an plugin</p>

答: Sure, use Recipient.Resolve. Recipient object can be retrieved either from the MailItem.Recipients collection or from Namespace.CreateRecipient.

Title: Calling Check Names from plugin


问:
React hooks warn me for missing dependencies
Suppose I am using useEffect to prefetch data on initial rendering:

```<code>function myComponent(props) {
    const { fetchSomething } = props;
    ...
    ...
    useEffect(() => {
        fetchSomething();
    }, []);
    ...
    ...
}
</code>```

My linter warn me for "React Hook useCallback has missing dependencies". It wants me to put fetchSomething inside the dependencies array.

The issue is that even it fetchSomething is going to be changed, I don't want the component to refetch the data. And as I see it, most of the situations where useEffect uses a function, it doesn't really care whether the function is changed.

I don't want to turn off that warning and doesn't like to spread // eslint-disable-next-line react-hooks/exhaustive-deps all over my code.

What is the rational behind such behavior?

It makes me feel insecure while using hooks, as if I am doing something incorrect.

答:
I agree with you that useRef is hacky solution that adds unnecessary complexity. Honestly the best solution I found is to use a conditional inside of useEffect()

```<code>function myComponent(props) {
    const { fetchSomething } = props;
    const [fetched, setFetched] = useState(false)
    ...
    ...
    useEffect(() => {
       if(!fetched) {
        fetchSomething();
        setFetched(true)
       }
    }, [fetched, fetchSomething]);
    ...
    ...
}
</code>```

using the useEffect hook properly is a very complex topic. You can read this very long article about it

https://overreacted.io/a-complete-guide-to-useeffect/

useEffect is still fairly new so there are still competing best practices. I wouldnt recommend useRef tho.

Body:
Suppose I am using useEffect to prefetch data on initial rendering:

function myComponent(props) {
    const { fetchSomething } = props;
    ...
    ...
    useEffect(() => {
        fetchSomething();
    }, []);
    ...
    ...
}

My linter warn me for "React Hook useCallback has missing dependencies". It wants me to put fetchSomething inside the dependencies array.

The issue is that even it fetchSomething is going to be changed, I don't want the component to refetch the data. And as I see it, most of the situations where useEffect uses a function, it doesn't really care whether the function is changed.

I don't want to turn off that warning and doesn't like to spread // eslint-disable-next-line react-hooks/exhaustive-deps all over my code.

What is the rational behind such behavior?

It makes me feel insecure while using hooks, as if I am doing something incorrect.

Body:
I agree with you that useRef is hacky solution that adds unnecessary complexity. Honestly the best solution I found is to use a conditional inside of useEffect()

function myComponent(props) {
    const { fetchSomething } = props;
    const [fetched, setFetched] = useState(false)
    ...
    ...
    useEffect(() => {
       if(!fetched) {
        fetchSomething();
        setFetched(true)
       }
    }, [fetched, fetchSomething]);
    ...
    ...
}

using the useEffect hook properly is a very complex topic. You can read this very long article about it

https://overreacted.io/a-complete-guide-to-useeffect/

useEffect is still fairly new so there are still competing best practices. I wouldnt recommend useRef tho.


问:
How to limit a users integer input?
I want the user to input an integer from 1000 to 25000 but I don't want the user to input an integer that passes the 25000 and at the same time want the user to try it again without having to restart the program.

```<code>while True:
    try:
        loan_amount= int(input("How much do you want to borrow?(1000-25000)"))
    except ValueError:
        print("Sorry, I didn't understand that.")
        continue
    else:
        break
if loan_amount > 25000:
    print("Sorry, We only lend up to $25,000. Please try again!")
</code>```

I expect that when a user inputs an integer that is greater than 25,000 they will be told that "we can't lend that much try again" and then repeats the question again.

答:
You should try to include the if else statements inside the try block with a break statement to exit the while loop if a correct amount is entered.

```<code>while True:
    try:
        loan_amount= int(input("How much do you want to borrow?(1000-25000) "))
        if loan_amount > 25000:
            print("Sorry, We only lend up to $25,000. Please try again!")
        else:
            print ("Amount loaned")
            break
    except ValueError:
        print("Sorry, I didn't understand that. Please try again")
</code>```

Output

Try 1

```<code>How much do you want to borrow?(1000-25000) 24999
Amount loaned
</code>```

Try 2

```<code>How much do you want to borrow?(1000-25000) Donald Trump
Sorry, I didn't understand that. Please try again
How much do you want to borrow?(1000-25000) 23000
Amount loaned
</code>```

Try 3

```<code>How much do you want to borrow?(1000-25000) 27000
Sorry, We only lend up to $25,000. Please try again!
How much do you want to borrow?(1000-25000) 23000
Amount loaned
</code>```

Title: How to limit a users integer input?

Body:
I want the user to input an integer from 1000 to 25000 but I don't want the user to input an integer that passes the 25000 and at the same time want the user to try it again without having to restart the program.

while True:
    try:
        loan_amount= int(input("How much do you want to borrow?(1000-25000)"))
    except ValueError:
        print("Sorry, I didn't understand that.")
        continue
    else:
        break
if loan_amount > 25000:
    print("Sorry, We only lend up to $25,000. Please try again!")

I expect that when a user inputs an integer that is greater than 25,000 they will be told that "we can't lend that much try again" and then repeats the question again.

Body:
You should try to include the if else statements inside the try block with a break statement to exit the while loop if a correct amount is entered.

while True:
    try:
        loan_amount= int(input("How much do you want to borrow?(1000-25000) "))
        if loan_amount > 25000:
            print("Sorry, We only lend up to $25,000. Please try again!")
        else:
            print ("Amount loaned")
            break
    except ValueError:
        print("Sorry, I didn't understand that. Please try again")

Output

Try 1

How much do you want to borrow?(1000-25000) 24999
Amount loaned

Try 2

How much do you want to borrow?(1000-25000) Donald Trump
Sorry, I didn't understand that. Please try again
How much do you want to borrow?(1000-25000) 23000
Amount loaned

Try 3

How much do you want to borrow?(1000-25000) 27000
Sorry, We only lend up to $25,000. Please try again!
How much do you want to borrow?(1000-25000) 23000
Amount loaned


问:
Creating MySQL query from access query
I'm trying to convert an Access query to MySQL. I'm decent with MySQL but I am unsure of how to incorporate this. I think the 2nd query from Access needs to become a sub-query for MySQL in the 1st query, I just don't know where to place it. This query will be ran as an event on the MySQL server.

The access query is ran as two, the first one, which determines the transaction ID of the determining transaction. I have converted already to MySQL and works correctly is:

```<code>SELECT DISTINCT t.patient_id, MAX(t.id) AS MaxOfid
FROM transactions AS t
INNER JOIN disposition_transaction_type AS dt
    ON t.disposition_transaction_type_id = dt.id
INNER JOIN dispositions AS d
    ON dt.disposition_id = d.id
WHERE (d.member_status = "Unenrolled" AND (t.created_at BETWEEN '2019-05-01' AND '2019-05-31')) OR ((t.created_at BETWEEN '2019-05-01' AND '2019-05-31') AND (t.disposition_transaction_type_id = 24))
GROUP BY t.patient_id;
</code>```

which producers the correct return

```<code>+------------+---------+
| patient_id | MaxOfid |
+------------+---------+
|         10 |       8 |
+------------+---------+
|        112 |    4321 |
+------------+---------+
</code>```

The 2nd query, which determines the determining disposition and status for the patient:

```<code>SELECT qryAgreedToServiceOrUnenrolled.patient_id, dispositions.description, dispositions.member_status
FROM ((qryAgreedToServiceOrUnenrolled
INNER JOIN transactions ON qryAgreedToServiceOrUnenrolled.MaxOfid = transactions.id)
INNER JOIN disposition_transaction_type ON transactions.disposition_transaction_type_id = disposition_transaction_type.id)
INNER JOIN dispositions ON disposition_transaction_type.disposition_id = dispositions.id;
</code>```

答:
Assuming the first query to run is named qryAgreedToServiceOrUnenrolled. Try nesting the first SQL in the second's FROM clause. Can replace qryAgreedToServiceOrUnenrolled with some other alias everywhere it is referenced.

```<code>SELECT qryAgreedToServiceOrUnenrolled.patient_id, dispositions.description, dispositions.member_status
FROM ((

    (SELECT DISTINCT t.patient_id, MAX(t.id) AS MaxOfid
    FROM transactions AS t
    INNER JOIN disposition_transaction_type AS dt
        ON t.disposition_transaction_type_id = dt.id
    INNER JOIN dispositions AS d
        ON dt.disposition_id = d.id
    WHERE (d.member_status = "Unenrolled" AND (t.created_at BETWEEN '2019-05-01' AND '2019-05-31')) OR ((t.created_at BETWEEN '2019-05-01' AND '2019-05-31') AND (t.disposition_transaction_type_id = 24))
    GROUP BY t.patient_id) AS qryAgreedToServiceOrUnenrolled

INNER JOIN transactions ON qryAgreedToServiceOrUnenrolled.MaxOfid = transactions.id)
INNER JOIN disposition_transaction_type ON transactions.disposition_transaction_type_id = disposition_transaction_type.id)
INNER JOIN dispositions ON disposition_transaction_type.disposition_id = dispositions.id;
</code>```

I agree that DISTINCT is probably not needed.

Title: Creating MySQL query from access query

Body:
I'm trying to convert an Access query to MySQL. I'm decent with MySQL but I am unsure of how to incorporate this. I think the 2nd query from Access needs to become a sub-query for MySQL in the 1st query, I just don't know where to place it. This query will be ran as an event on the MySQL server.

The access query is ran as two, the first one, which determines the transaction ID of the determining transaction. I have converted already to MySQL and works correctly is:

SELECT DISTINCT t.patient_id, MAX(t.id) AS MaxOfid
FROM transactions AS t
INNER JOIN disposition_transaction_type AS dt
    ON t.disposition_transaction_type_id = dt.id
INNER JOIN dispositions AS d
    ON dt.disposition_id = d.id
WHERE (d.member_status = "Unenrolled" AND (t.created_at BETWEEN '2019-05-01' AND '2019-05-31')) OR ((t.created_at BETWEEN '2019-05-01' AND '2019-05-31') AND (t.disposition_transaction_type_id = 24))
GROUP BY t.patient_id;

which producers the correct return

+------------+---------+
| patient_id | MaxOfid |
+------------+---------+
|         10 |       8 |
+------------+---------+
|        112 |    4321 |
+------------+---------+

The 2nd query, which determines the determining disposition and status for the patient:

SELECT qryAgreedToServiceOrUnenrolled.patient_id, dispositions.description, dispositions.member_status
FROM ((qryAgreedToServiceOrUnenrolled
INNER JOIN transactions ON qryAgreedToServiceOrUnenrolled.MaxOfid = transactions.id)
INNER JOIN disposition_transaction_type ON transactions.disposition_transaction_type_id = disposition_transaction_type.id)
INNER JOIN dispositions ON disposition_transaction_type.disposition_id = dispositions.id;

Body:
Assuming the first query to run is named qryAgreedToServiceOrUnenrolled. Try nesting the first SQL in the second's FROM clause. Can replace qryAgreedToServiceOrUnenrolled with some other alias everywhere it is referenced.

SELECT qryAgreedToServiceOrUnenrolled.patient_id, dispositions.description, dispositions.member_status
FROM ((

    (SELECT DISTINCT t.patient_id, MAX(t.id) AS MaxOfid
    FROM transactions AS t
    INNER JOIN disposition_transaction_type AS dt
        ON t.disposition_transaction_type_id = dt.id
    INNER JOIN dispositions AS d
        ON dt.disposition_id = d.id
    WHERE (d.member_status = "Unenrolled" AND (t.created_at BETWEEN '2019-05-01' AND '2019-05-31')) OR ((t.created_at BETWEEN '2019-05-01' AND '2019-05-31') AND (t.disposition_transaction_type_id = 24))
    GROUP BY t.patient_id) AS qryAgreedToServiceOrUnenrolled

INNER JOIN transactions ON qryAgreedToServiceOrUnenrolled.MaxOfid = transactions.id)
INNER JOIN disposition_transaction_type ON transactions.disposition_transaction_type_id = disposition_transaction_type.id)
INNER JOIN dispositions ON disposition_transaction_type.disposition_id = dispositions.id;

I agree that DISTINCT is probably not needed.


问:
Solving a recurrence relation for a recursive function
I need to create and solve a recurrence relation for the worst-case analysis for the following psuedocode. I am counting the number additions (not including the for loop counter) as my basic operation.
I am assuming n=2^k.

Here is the progress I have made...
Base Case:
T(n<=4) = 1

W(n)=W(2^k)=additions to calculate answer+additions in next recursion+addition in for loop
W(2^k) = 2 + W(2^(k-2)) + (2^k) - 2 = W(2^(k-2)) + (2^k)

I use back substitution and get the following recurrence relation...

for the jth recursive call
W(2^k) = W(2^(k-2j)) + (2^k) + sum(t=1,j,2^(k-2(t-1)))

I know that I can simplify this because I take W(2^(k-2j)) = W(4) and solve for j to see how many recursive steps the code takes.
In this case, j=(k/2) - 1. Reducing the recurrence gives me...

W(2^k) = 1 + (2^k) + sum(t=1,j,2^(k-2(t-1))).

Reducing the summation gives me...

W(2^k) = 1 + (2^k) + (2^k)*(2^2)*sum(t=1,j,2^(-2t)) or

W(n) = 1 + n + 4n*sum(t=1,j,2^(-2t))

What I cannot simplify is the summation. In lectures, we may have a summation of sum(i=1,n,2^i), which would be 2^(n+1)-1, but this one is different.

```<code>int function calc(int n) {
   int num,answer;
   if(n<=4) {return n+10;}
   else {
     num=calc(n/4);
     answer=(num+num+10);
     for(int i=2;i<=n-1;i++) {
         answer=answer+answer;
     }
     return answer;
  }
}
</code>```

Any help would be appreciated. This assignment is due tonight. Thanks

答: The time complexity of the problem is T(n) = T(n/4) + n. The term n could mean \Theta(n). Hence, T(n) = n + n/4 + n/4^2 + ... + n/(4^log_4(n)) = n(1 + 1/4 + ... + 1/n) = \Theta(n). Notice that lim_{n\to \infty} 1 + 1/4 + ... + 1/4^log_4(n) = 4/3 which is a constant number.

Body:
I need to create and solve a recurrence relation for the worst-case analysis for the following psuedocode. I am counting the number additions (not including the for loop counter) as my basic operation.
I am assuming n=2^k.

Here is the progress I have made...
Base Case:
T(n<=4) = 1

W(n)=W(2^k)=additions to calculate answer+additions in next recursion+addition in for loop
W(2^k) = 2 + W(2^(k-2)) + (2^k) - 2 = W(2^(k-2)) + (2^k)

I use back substitution and get the following recurrence relation...

for the jth recursive call
W(2^k) = W(2^(k-2j)) + (2^k) + sum(t=1,j,2^(k-2(t-1)))

I know that I can simplify this because I take W(2^(k-2j)) = W(4) and solve for j to see how many recursive steps the code takes.
In this case, j=(k/2) - 1. Reducing the recurrence gives me...

W(2^k) = 1 + (2^k) + sum(t=1,j,2^(k-2(t-1))).

Reducing the summation gives me...

W(2^k) = 1 + (2^k) + (2^k)*(2^2)*sum(t=1,j,2^(-2t)) or

W(n) = 1 + n + 4n*sum(t=1,j,2^(-2t))

What I cannot simplify is the summation. In lectures, we may have a summation of sum(i=1,n,2^i), which would be 2^(n+1)-1, but this one is different.

int function calc(int n) {
   int num,answer;
   if(n<=4) {return n+10;}
   else {
     num=calc(n/4);
     answer=(num+num+10);
     for(int i=2;i<=n-1;i++) {
         answer=answer+answer;
     }
     return answer;
  }
}

Any help would be appreciated. This assignment is due tonight. Thanks


问:
`' '.join(e)` isn't changing value of e
I'm creating a function to create all 26 combinations of words with a fixed suffix. The script works except for the JOIN in the second-to-last line.

```<code>def create_word(suffix):
    e=[]
    letters="abcefghijklmnopqrstuvwxyz"
    t=list(letters)
    for i in t:
        e.append(i)
        e.append(suffix)
    ' '.join(e)
    print e
</code>```

Currently, it is printing ['a', 'suffix', 'b', 'suffix, ...etc]. And I want it to print out as one long string: 'aSuffixbSuffixcSuffix...etc.' Why isn't the join working in this? How can I fix this?

In addition, how would I separate the characters once I have the string? For example to translate "take the last character of the suffix and add a space to it every time ('aSuffixbSuffixcSuffix' --> 'aSuffix bSuffix cSuffix')". Or, more generally, to replace the x-nth character, where x is any integer (e.g., to replace the 3rd, 6th, 9th, etc. character some something I choose).

答:
str.join returns the new value, not transform the existing one.  Here's one way to accomplish it.

```<code>result = ' '.join(e)
print result
</code>```

But if you're feeling clever, you can streamline a lot of the setup.

```<code>import string
def create_word(suffix):
   return ' '.join(i + suffix for i in string.ascii_lowercase)
</code>```

Title: `' '.join(e)` isn't changing value of e

Body:
I'm creating a function to create all 26 combinations of words with a fixed suffix. The script works except for the JOIN in the second-to-last line.

def create_word(suffix):
    e=[]
    letters="abcefghijklmnopqrstuvwxyz"
    t=list(letters)
    for i in t:
        e.append(i)
        e.append(suffix)
    ' '.join(e)
    print e

Currently, it is printing ['a', 'suffix', 'b', 'suffix, ...etc]. And I want it to print out as one long string: 'aSuffixbSuffixcSuffix...etc.' Why isn't the join working in this? How can I fix this?

In addition, how would I separate the characters once I have the string? For example to translate "take the last character of the suffix and add a space to it every time ('aSuffixbSuffixcSuffix' --> 'aSuffix bSuffix cSuffix')". Or, more generally, to replace the x-nth character, where x is any integer (e.g., to replace the 3rd, 6th, 9th, etc. character some something I choose).

Body:
str.join returns the new value, not transform the existing one.  Here's one way to accomplish it.

result = ' '.join(e)
print result

But if you're feeling clever, you can streamline a lot of the setup.

import string
def create_word(suffix):
   return ' '.join(i + suffix for i in string.ascii_lowercase)


问:
How to merge audio and video in Java
We have created an application that records web camera streams using Xuggler, but video and audio are separated.

We need to merge, not concatenate, these two files.

How can this be done in Java?

答:
As the other answers suggested already, ffmeg does seem to be the best solution here.

Here the code I ended up with:

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;
</code>```

```<code>public static File mergeAudioToVideo(
        File ffmpegExecutable,  // ffmpeg/bin/ffmpeg.exe
        File audioFile,
        File videoFile,
        File outputDir,
        String outFileName) throws IOException, InterruptedException {

    for (File f : Arrays.asList(ffmpegExecutable, audioFile, videoFile, outputDir)) {
        if (! f.exists()) {
            throw new FileNotFoundException(f.getAbsolutePath());
        }
    }

    File mergedFile = Paths.get(outputDir.getAbsolutePath(), outFileName).toFile();
    if (mergedFile.exists()) {
        mergedFile.delete();
    }

    ProcessBuilder pb = new ProcessBuilder(
            ffmpegExecutable.getAbsolutePath(),
            "-i",
            audioFile.getAbsolutePath(),
            "-i",
            videoFile.getAbsolutePath() ,
            "-acodec",
            "copy",
            "-vcodec",
            "copy",
            mergedFile.getAbsolutePath()
    );
    pb.redirectErrorStream(true);
    Process process = pb.start();
    process.waitFor();

    if (!mergedFile.exists()) {
        return null;
    }
    return mergedFile;
}
</code>```

Title: How to merge audio and video in Java

Body:
As the other answers suggested already, ffmeg does seem to be the best solution here.

Here the code I ended up with:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;

public static File mergeAudioToVideo(
        File ffmpegExecutable,  // ffmpeg/bin/ffmpeg.exe
        File audioFile,
        File videoFile,
        File outputDir,
        String outFileName) throws IOException, InterruptedException {

    for (File f : Arrays.asList(ffmpegExecutable, audioFile, videoFile, outputDir)) {
        if (! f.exists()) {
            throw new FileNotFoundException(f.getAbsolutePath());
        }
    }

    File mergedFile = Paths.get(outputDir.getAbsolutePath(), outFileName).toFile();
    if (mergedFile.exists()) {
        mergedFile.delete();
    }

    ProcessBuilder pb = new ProcessBuilder(
            ffmpegExecutable.getAbsolutePath(),
            "-i",
            audioFile.getAbsolutePath(),
            "-i",
            videoFile.getAbsolutePath() ,
            "-acodec",
            "copy",
            "-vcodec",
            "copy",
            mergedFile.getAbsolutePath()
    );
    pb.redirectErrorStream(true);
    Process process = pb.start();
    process.waitFor();

    if (!mergedFile.exists()) {
        return null;
    }
    return mergedFile;
}


问:
How do libraries/programming languages convert floats to strings
This is a mystery that I was trying to figure out when I was 15, but I failed. I still don't know the answer.

Here's a naive and flawed solution (like some other failed attempts I've seen here on Stack Overflow):

```<code>const numberToString = number => {
  let result = '';
  let multiplier = Math.floor(Math.log10(number));
  while (number > 0) {
    const currentDigit = Math.floor(number / 10 ** multiplier);
    if (multiplier === -1) result += '.';
    result += `${currentDigit}`;
    number -= 10 ** multiplier * currentDigit;
    multiplier -= 1;
  }

  if (multiplier >= 0) {
    result += Array(multiplier + 1)
      .fill('0')
      .join('');
  }
  return result;
};

numberToString(0.3) //.29999999999999998010382707025852380980776467160900842259699366886095386217478302201335914442574948883370288946713085380211028267974348864228883494754227105763273602317743416839701366257194448416238466245093684421946526875873398794558223163136792877759774069929483218021428696258138483228158055137040848084556063610493291767
</code>```

The language here is in Javascript, but the question is language agnostic. However, feel free to improve the existing code if it's possible.

If the way this works is language dependent, I would appreciate some insights how this might look in various programming languages, for example Javascript.

答:
(I don't have enough reputation to comment, so am resorting to using an answer...)

I notice that you ran the precision out to 300+ digits, well beyond the precision of the floating point numbers, hence the imprecise result.  If you're looking for a means to have high precision calculations, you can probably resort to BigInt, and scale up the numbers accordingly.  (I say "probably", because BigInt can be coerced into fixed precision calculations, not floating point, and thus depending on one's goal, BigInt might not meet the requirement.)

Eg, calculating 1000 / 17 to 100 significant digits can be handled via the following function, which essentially scales up 1000 and 17 to ensure 100 significant digits.  (Note that this is just a concept function for handling high precision division between two integers, but can be the basis for non-integers by scaling up the dividend and divisor until they're integers, and adjusting digits accordingly.  Plus you might need to fudge in some extra "hidden" digits of precision to handle rounding)...

```<code>function divideN(dividend, divisor, digits) {
  dividend = dividend * 10n ** (BigInt(digits) * 2n);
  divisor = divisor * 10n ** BigInt(digits);
  var s = (dividend/divisor).toString();
  if (s.length < digits) {
    s = "0".repeat(digits - s.length) + s;
  }
  s = s.slice(0, s.length - digits) + "." + s.slice(-digits);
  return s;
}
</code>```

BigInt requires numbers to end in "n", so the function needs to be called as follows...

```<code>divideN(1000n,17n,100)
</code>```

...which in this case returns...

```<code>"58.8235294117647058823529411764705882352941176470588235294117647058823529411764705882352941176470588235"
</code>```

Note in this case, 102 digits of precision are returned rather than 100 because of the relative size of the dividend (1000) to the divisor (17).

Body:
This is a mystery that I was trying to figure out when I was 15, but I failed. I still don't know the answer.

Here's a naive and flawed solution (like some other failed attempts I've seen here on Stack Overflow):

const numberToString = number => {
  let result = '';
  let multiplier = Math.floor(Math.log10(number));
  while (number > 0) {
    const currentDigit = Math.floor(number / 10 ** multiplier);
    if (multiplier === -1) result += '.';
    result += `${currentDigit}`;
    number -= 10 ** multiplier * currentDigit;
    multiplier -= 1;
  }

  if (multiplier >= 0) {
    result += Array(multiplier + 1)
      .fill('0')
      .join('');
  }
  return result;
};

numberToString(0.3) //.29999999999999998010382707025852380980776467160900842259699366886095386217478302201335914442574948883370288946713085380211028267974348864228883494754227105763273602317743416839701366257194448416238466245093684421946526875873398794558223163136792877759774069929483218021428696258138483228158055137040848084556063610493291767

The language here is in Javascript, but the question is language agnostic. However, feel free to improve the existing code if it's possible.

If the way this works is language dependent, I would appreciate some insights how this might look in various programming languages, for example Javascript.

Body:
(I don't have enough reputation to comment, so am resorting to using an answer...)

I notice that you ran the precision out to 300+ digits, well beyond the precision of the floating point numbers, hence the imprecise result.  If you're looking for a means to have high precision calculations, you can probably resort to BigInt, and scale up the numbers accordingly.  (I say "probably", because BigInt can be coerced into fixed precision calculations, not floating point, and thus depending on one's goal, BigInt might not meet the requirement.)

Eg, calculating 1000 / 17 to 100 significant digits can be handled via the following function, which essentially scales up 1000 and 17 to ensure 100 significant digits.  (Note that this is just a concept function for handling high precision division between two integers, but can be the basis for non-integers by scaling up the dividend and divisor until they're integers, and adjusting digits accordingly.  Plus you might need to fudge in some extra "hidden" digits of precision to handle rounding)...

function divideN(dividend, divisor, digits) {
  dividend = dividend * 10n ** (BigInt(digits) * 2n);
  divisor = divisor * 10n ** BigInt(digits);
  var s = (dividend/divisor).toString();
  if (s.length < digits) {
    s = "0".repeat(digits - s.length) + s;
  }
  s = s.slice(0, s.length - digits) + "." + s.slice(-digits);
  return s;
}

BigInt requires numbers to end in "n", so the function needs to be called as follows...

divideN(1000n,17n,100)

...which in this case returns...

"58.8235294117647058823529411764705882352941176470588235294117647058823529411764705882352941176470588235"

Note in this case, 102 digits of precision are returned rather than 100 because of the relative size of the dividend (1000) to the divisor (17).


问:
How to parse huge JSON file as stream in Json.NET?
I have a very, very large JSON file (1000+ MB) of identical JSON objects. For example:

```<code>[
    {
        "id": 1,
        "value": "hello",
        "another_value": "world",
        "value_obj": {
            "name": "obj1"
        },
        "value_list": [
            1,
            2,
            3
        ]
    },
    {
        "id": 2,
        "value": "foo",
        "another_value": "bar",
        "value_obj": {
            "name": "obj2"
        },
        "value_list": [
            4,
            5,
            6
        ]
    },
    {
        "id": 3,
        "value": "a",
        "another_value": "b",
        "value_obj": {
            "name": "obj3"
        },
        "value_list": [
            7,
            8,
            9
        ]

    },
    ...
]
</code>```

Every single item in the root JSON list follows the same structure and thus would be individually deserializable. I already have the C# classes written to receive this data, and deserializing a JSON file containing a single object without the list works as expected.

At first, I tried to just directly deserialize my objects in a loop:

```<code>JsonSerializer serializer = new JsonSerializer();
MyObject o;
using (FileStream s = File.Open("bigfile.json", FileMode.Open))
using (StreamReader sr = new StreamReader(s))
using (JsonReader reader = new JsonTextReader(sr))
{
    while (!sr.EndOfStream)
    {
        o = serializer.Deserialize<MyObject>(reader);
    }
}
</code>```

This didn't work, threw an exception clearly stating that an object is expected, not a list. My understanding is that this command would just read a single object contained at the root level of the JSON file, but since we have a list of objects, this is an invalid request.

My next idea was to deserialize as a C# List of objects:

```<code>JsonSerializer serializer = new JsonSerializer();
List<MyObject> o;
using (FileStream s = File.Open("bigfile.json", FileMode.Open))
using (StreamReader sr = new StreamReader(s))
using (JsonReader reader = new JsonTextReader(sr))
{
    while (!sr.EndOfStream)
    {
        o = serializer.Deserialize<List<MyObject>>(reader);
    }
}
</code>```

This does succeed. However, it only somewhat reduces the issue of high RAM usage. In this case it does look like the application is deserializing items one at a time, and so is not reading the entire JSON file into RAM, but we still end up with a lot of RAM usage because the C# List object now contains all of the data from the JSON file in RAM. This has only displaced the problem.

I then decided to simply try taking a single character off the beginning of the stream (to eliminate the [) by doing sr.Read() before going into the loop. The first object then does read successfully, but subsequent ones do not, with an exception of "unexpected token". My guess is this is the comma and space between the objects throwing the reader off.

Simply removing square brackets won't work since the objects do contain a primitive list of their own, as you can see in the sample. Even trying to use }, as a separator won't work since, as you can see, there are sub-objects within the objects.

What my goal is, is to be able to read the objects from the stream one at a time. Read an object, do something with it, then discard it from RAM, and read the next object, and so on. This would eliminate the need to load either the entire JSON string or the entire contents of the data into RAM as C# objects.

What am I missing?

答:
I think we can do better than the accepted answer, using more features of JsonReader to make a more generalized solution.

As a JsonReader consumes tokens from a JSON, the path is recorded in the JsonReader.Path property.

We can use this to precisely select deeply nested data from a JSON file, using regex to ensure that we're on the right path.

So, using the following extension method:

```<code>public static class JsonReaderExtensions
{
    public static IEnumerable<T> SelectTokensWithRegex<T>(
        this JsonReader jsonReader, Regex regex)
    {
        JsonSerializer serializer = new JsonSerializer();
        while (jsonReader.Read())
        {
            if (regex.IsMatch(jsonReader.Path)
                && jsonReader.TokenType != JsonToken.PropertyName)
            {
                yield return serializer.Deserialize<T>(jsonReader);
            }
        }
    }
}
</code>```

The data you are concerned with lies on paths:

```<code>[0]
[1]
[2]
... etc
</code>```

We can construct the following regex to precisely match this path:

```<code>var regex = new Regex(@"^\[\d+\]$");
</code>```

it now becomes possible to stream objects out of your data (without fully loading or parsing the entire JSON) as follows

```<code>IEnumerable<MyObject> objects = jsonReader.SelectTokensWithRegex<MyObject>(regex);
</code>```

Or if we want to dig even deeper into the structure, we can be even more precise with our regex

```<code>var regex = new Regex(@"^\[\d+\]\.value$");
IEnumerable<string> objects = jsonReader.SelectTokensWithRegex<string>(regex);
</code>```

to only extract value properties from the items in the array.

I've found this technique extremely useful for extracting specific data from huge (100 GiB) JSON dumps, directly from HTTP using a network stream (with low memory requirements and no intermediate storage required).

Body:
I have a very, very large JSON file (1000+ MB) of identical JSON objects. For example:

[
    {
        "id": 1,
        "value": "hello",
        "another_value": "world",
        "value_obj": {
            "name": "obj1"
        },
        "value_list": [
            1,
            2,
            3
        ]
    },
    {
        "id": 2,
        "value": "foo",
        "another_value": "bar",
        "value_obj": {
            "name": "obj2"
        },
        "value_list": [
            4,
            5,
            6
        ]
    },
    {
        "id": 3,
        "value": "a",
        "another_value": "b",
        "value_obj": {
            "name": "obj3"
        },
        "value_list": [
            7,
            8,
            9
        ]

    },
    ...
]

Every single item in the root JSON list follows the same structure and thus would be individually deserializable. I already have the C# classes written to receive this data, and deserializing a JSON file containing a single object without the list works as expected.

At first, I tried to just directly deserialize my objects in a loop:

JsonSerializer serializer = new JsonSerializer();
MyObject o;
using (FileStream s = File.Open("bigfile.json", FileMode.Open))
using (StreamReader sr = new StreamReader(s))
using (JsonReader reader = new JsonTextReader(sr))
{
    while (!sr.EndOfStream)
    {
        o = serializer.Deserialize<MyObject>(reader);
    }
}

This didn't work, threw an exception clearly stating that an object is expected, not a list. My understanding is that this command would just read a single object contained at the root level of the JSON file, but since we have a list of objects, this is an invalid request.

My next idea was to deserialize as a C# List of objects:

JsonSerializer serializer = new JsonSerializer();
List<MyObject> o;
using (FileStream s = File.Open("bigfile.json", FileMode.Open))
using (StreamReader sr = new StreamReader(s))
using (JsonReader reader = new JsonTextReader(sr))
{
    while (!sr.EndOfStream)
    {
        o = serializer.Deserialize<List<MyObject>>(reader);
    }
}

This does succeed. However, it only somewhat reduces the issue of high RAM usage. In this case it does look like the application is deserializing items one at a time, and so is not reading the entire JSON file into RAM, but we still end up with a lot of RAM usage because the C# List object now contains all of the data from the JSON file in RAM. This has only displaced the problem.

I then decided to simply try taking a single character off the beginning of the stream (to eliminate the [) by doing sr.Read() before going into the loop. The first object then does read successfully, but subsequent ones do not, with an exception of "unexpected token". My guess is this is the comma and space between the objects throwing the reader off.

Simply removing square brackets won't work since the objects do contain a primitive list of their own, as you can see in the sample. Even trying to use }, as a separator won't work since, as you can see, there are sub-objects within the objects.

What my goal is, is to be able to read the objects from the stream one at a time. Read an object, do something with it, then discard it from RAM, and read the next object, and so on. This would eliminate the need to load either the entire JSON string or the entire contents of the data into RAM as C# objects.

What am I missing?

Body:
I think we can do better than the accepted answer, using more features of JsonReader to make a more generalized solution.

As a JsonReader consumes tokens from a JSON, the path is recorded in the JsonReader.Path property.

We can use this to precisely select deeply nested data from a JSON file, using regex to ensure that we're on the right path.

So, using the following extension method:

public static class JsonReaderExtensions
{
    public static IEnumerable<T> SelectTokensWithRegex<T>(
        this JsonReader jsonReader, Regex regex)
    {
        JsonSerializer serializer = new JsonSerializer();
        while (jsonReader.Read())
        {
            if (regex.IsMatch(jsonReader.Path)
                && jsonReader.TokenType != JsonToken.PropertyName)
            {
                yield return serializer.Deserialize<T>(jsonReader);
            }
        }
    }
}

The data you are concerned with lies on paths:

[0]
[1]
[2]
... etc

We can construct the following regex to precisely match this path:

var regex = new Regex(@"^\[\d+\]$");

it now becomes possible to stream objects out of your data (without fully loading or parsing the entire JSON) as follows

IEnumerable<MyObject> objects = jsonReader.SelectTokensWithRegex<MyObject>(regex);

Or if we want to dig even deeper into the structure, we can be even more precise with our regex

var regex = new Regex(@"^\[\d+\]\.value$");
IEnumerable<string> objects = jsonReader.SelectTokensWithRegex<string>(regex);

to only extract value properties from the items in the array.

I've found this technique extremely useful for extracting specific data from huge (100 GiB) JSON dumps, directly from HTTP using a network stream (with low memory requirements and no intermediate storage required).