问:
Unable to contact Active Directory through pyad
I'm not able to connect to pyad module to create Active Directory objects. I'm getting an exception as shown below:</p>

```<code>Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Users\sparava\PycharmProjects\imds_ad_pycliient\venv\lib\site-packages\pyad\adobject.py", line 135, in from_cn
    return cls(adsearch.by_cn(cn, search_base, options), None, options)
  File "C:\Users\sparava\PycharmProjects\imds_ad_pycliient\venv\lib\site-packages\pyad\adsearch.py", line 17, in by_cn
    type="GC")
  File "C:\Users\sparava\PycharmProjects\imds_ad_pycliient\venv\lib\site-packages\pyad\adquery.py", line 78, in execute_query
    self.__rs, self.__rc = command.Execute()
  File "<COMObject ADODB.Command>", line 3, in Execute
  File "C:\Users\sparava\PycharmProjects\imds_ad_pycliient\venv\lib\site-packages\win32com\client\dynamic.py", line 287, in _ApplyTypes_
    result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Active Directory', 'The server is not operational.\r\n', None, 0, -2147217865), None)
</code>```

答:
"The server is not operational" means that it cannot contact the server.

I assume type="GC" means that it is trying to contact the Global Catalog, which is on port 3268 by default, unless you specifically specified a different port.

So all this means that it cannot open a connection to your AD server on port 3268.

Maybe it's a network issue, or maybe it's a configuration issue in your application. If you update your question with your code, I might be able to spot something that looks off, or maybe not

Body:
I'm not able to connect to pyad module to create Active Directory objects. I'm getting an exception as shown below:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Users\sparava\PycharmProjects\imds_ad_pycliient\venv\lib\site-packages\pyad\adobject.py", line 135, in from_cn
    return cls(adsearch.by_cn(cn, search_base, options), None, options)
  File "C:\Users\sparava\PycharmProjects\imds_ad_pycliient\venv\lib\site-packages\pyad\adsearch.py", line 17, in by_cn
    type="GC")
  File "C:\Users\sparava\PycharmProjects\imds_ad_pycliient\venv\lib\site-packages\pyad\adquery.py", line 78, in execute_query
    self.__rs, self.__rc = command.Execute()
  File "<COMObject ADODB.Command>", line 3, in Execute
  File "C:\Users\sparava\PycharmProjects\imds_ad_pycliient\venv\lib\site-packages\win32com\client\dynamic.py", line 287, in _ApplyTypes_
    result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Active Directory', 'The server is not operational.\r\n', None, 0, -2147217865), None)


来源: stackexchange

问:
Is it faster to store window.location.href in a const to do several comparisons or check it directly?
Is it faster to store the window.location.href in a const to check if contains several strings,

```<code>   const fullUrl = window.location.href;

 function checkUrlContains() {
   return fullUrl.indexOf("string1") > 1 || fullUrl.indexOf("string2") > 1  || fullUrl.indexOf("string3") > 1 || fullUrl.indexOf("string4") > 1
 }
</code>```

or to check directly the window.location.href?

```<code>     function checkUrlContains() {
   return window.location.href.indexOf("string1") > 1 || window.location.href.indexOf("string2") > 1  || window.location.href.indexOf("string3") > 1 ...
 }
</code>```

Thank you

答:
Sometimes the "thin" books are the best ones.  Such as, The Elements of Programming Style.  In which you will read:

```<code>"Don't 'diddle' code to make it faster -- find a better algorithm."
</code>```

But also:  "don't assume that an algorithm is 'too slow' unless you can prove by actual profiling measures that it is too slow and where it is.  In your case, that source-code change probably won't make any measurable difference in performance, but it just might make your code harder to "instantly understand" by the next programmer who follows in your footsteps.  The only time (these days) when you should seriously be concerned about such things is when profiling results prove that this-or-that is a true "hot spot."  Otherwise, just write code as clearly and obviously as you can, and of course be very certain that it works!

ContentLicense: CC BY-SA 4.0

Body:
Is it faster to store the window.location.href in a const to check if contains several strings,

   const fullUrl = window.location.href;

 function checkUrlContains() {
   return fullUrl.indexOf("string1") > 1 || fullUrl.indexOf("string2") > 1  || fullUrl.indexOf("string3") > 1 || fullUrl.indexOf("string4") > 1
 }

or to check directly the window.location.href?

     function checkUrlContains() {
   return window.location.href.indexOf("string1") > 1 || window.location.href.indexOf("string2") > 1  || window.location.href.indexOf("string3") > 1 ...
 }

Thank you

Body:
Sometimes the "thin" books are the best ones.  Such as, The Elements of Programming Style.  In which you will read:

"Don't 'diddle' code to make it faster -- find a better algorithm."

But also:  "don't assume that an algorithm is 'too slow' unless you can prove by actual profiling measures that it is too slow and where it is.  In your case, that source-code change probably won't make any measurable difference in performance, but it just might make your code harder to "instantly understand" by the next programmer who follows in your footsteps.  The only time (these days) when you should seriously be concerned about such things is when profiling results prove that this-or-that is a true "hot spot."  Otherwise, just write code as clearly and obviously as you can, and of course be very certain that it works!


问:
load a php image using src
Is it possible to load a image using:

```<code><img src="image.php?image_id=1">
</code>```

?

for image.php:

```<code>$image_id = $_GET['image_id'];
echo "image".$image_id.".png";
</code>```

答: No, this is not possible that way. You would have to write the contents of the image file to the output stream instead.</p>

ContentLicense: CC BY-SA 3.0

Title: load a php image using src

Body:
Is it possible to load a image using:

?

for image.php:

$image_id = $_GET['image_id'];
echo "image".$image_id.".png";


问:
Redis script for memory flush
Is it possible to create a script for Redis that flush its memory when it is above a certain value?
In my specific case, I want a flush when the memory is above 90%.
What is the best way, via bash script or Lua script?</p>

答:
I would use a Lua script as it will perform faster, atomically, and it would be easy to use both from redis-cli and any application code.

Here a Lua script to get memory used and maxmemory, the percent, and an action placeholder. It uses both MEMORY STATS and INFO memory to illustrate.

MEMORY STATS brings structured information, but doesn't include maxmemory or total_system_memory, as INFO memory does. CONFIG GET is not allowed from Lua scripts.

```<code>local stats = redis.call('MEMORY', 'STATS')
local memused = 0
for i = 1,table.getn(stats),2 do
    if stats[i] == 'total.allocated' then
        memused = stats[i+1]
        break
    end
end
local meminfo = redis.call('INFO', 'memory')
local maxmemory = 0
for s in meminfo:gmatch('[^\\r\\n]+') do
    if string.sub(s,1,10) == 'maxmemory:' then
        maxmemory = tonumber(string.sub(s,11))
    end
end
local mempercent = memused/maxmemory
local action = 'No action'
if mempercent > tonumber(ARGV[1]) then
    action = 'Flush here'
end
return {memused, maxmemory, tostring(mempercent), action}
</code>```

Use as:

```<code>> EVAL "local stats = redis.call('MEMORY', 'STATS') \n local memused = 0 \n for i = 1,table.getn(stats),2 do \n     if stats[i] == 'total.allocated' then \n     memused = stats[i+1] \n break \n end \n end \n local meminfo = redis.call('INFO', 'memory') \n local maxmemory = 0 \n for s in meminfo:gmatch('[^\\r\\n]+') do \n     if string.sub(s,1,10) == 'maxmemory:' then \n     maxmemory = tonumber(string.sub(s,11)) \n end \n end \n local mempercent = memused/maxmemory \n local action = 'No action' \n if mempercent > tonumber(ARGV[1]) then \n     action = 'Flush here' \n end \n return {memused, maxmemory, tostring(mempercent), action}" 0 0.9
1) (integer) 860264
2) (integer) 100000000
3) "0.00860264"
4) "No action"
</code>```

Title: Redis script for memory flush

Body:
I would use a Lua script as it will perform faster, atomically, and it would be easy to use both from redis-cli and any application code.

Here a Lua script to get memory used and maxmemory, the percent, and an action placeholder. It uses both MEMORY STATS and INFO memory to illustrate.

MEMORY STATS brings structured information, but doesn't include maxmemory or total_system_memory, as INFO memory does. CONFIG GET is not allowed from Lua scripts.

local stats = redis.call('MEMORY', 'STATS')
local memused = 0
for i = 1,table.getn(stats),2 do
    if stats[i] == 'total.allocated' then
        memused = stats[i+1]
        break
    end
end
local meminfo = redis.call('INFO', 'memory')
local maxmemory = 0
for s in meminfo:gmatch('[^\\r\\n]+') do
    if string.sub(s,1,10) == 'maxmemory:' then
        maxmemory = tonumber(string.sub(s,11))
    end
end
local mempercent = memused/maxmemory
local action = 'No action'
if mempercent > tonumber(ARGV[1]) then
    action = 'Flush here'
end
return {memused, maxmemory, tostring(mempercent), action}

Use as:

> EVAL "local stats = redis.call('MEMORY', 'STATS') \n local memused = 0 \n for i = 1,table.getn(stats),2 do \n     if stats[i] == 'total.allocated' then \n     memused = stats[i+1] \n break \n end \n end \n local meminfo = redis.call('INFO', 'memory') \n local maxmemory = 0 \n for s in meminfo:gmatch('[^\\r\\n]+') do \n     if string.sub(s,1,10) == 'maxmemory:' then \n     maxmemory = tonumber(string.sub(s,11)) \n end \n end \n local mempercent = memused/maxmemory \n local action = 'No action' \n if mempercent > tonumber(ARGV[1]) then \n     action = 'Flush here' \n end \n return {memused, maxmemory, tostring(mempercent), action}" 0 0.9
1) (integer) 860264
2) (integer) 100000000
3) "0.00860264"
4) "No action"


问:
Flutter DataStream not closing and re-building properly. [Bad state: Stream has already been listened to.]
Okay, so I'm aware that a stream can be manufactured to listen to a stream more than once, using a broadcast system, but that's specifically NOT what I'm trying to do here.

I'm also editing this as the one answer I have received isn't currently able to resolve my issue, so any assistance would be greatly appreciated.

Effectively for some reason the code I have is not deleting the stream in it's entirety, and if re-used, it is trying to re-listen to the same stream that has already been listened-to and closed, none of which works (Obviously).  Instead of trying to listen to that same stream again, I'm trying to create a NEW stream to listen to.  (Deleting and cleaning away all information from the original first stream).

Original post continues below:

I'm using a DataStream template for streaming data to and/or from various parts of my program, and I'm not entirely certain how to rectify this.  I'm certain it's a silly newb error, but I haven't used DataStreams enough to understand why this is happening.

Now don't get me wrong, going through a single cycle of my program works perfectly fine, no issues at all.  However, once I've completed a single cycle through the program, if I try to go through a second time, I get the error:

Bad state: Stream has already been listened to.

So from this I know my program is not creating a new stream, and instead trying to re-use the original stream, and I'm not 100% certain how to stop this functionality, (Or even if I should).  (Honestly the number of times I would expect multiple cycles to be completed are slim to null, but I want to resolve these kinds of errors before they become problems.)

Edit:  Minimal Reproducible Example to Follow

File 1 (main.dart)

```<code>import 'package:flutter/cupertino.dart';
import 'dart:async';
import './page2.dart';
import './stream.dart';

void main() => runApp(MyApp());

DataStream stream = DataStream();

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return CupertinoApp(
      title: 'Splash Test',
      theme: CupertinoThemeData(
        primaryColor: Color.fromARGB(255, 0, 0, 255),
      ),
      home: MyHomePage(title: 'Splash Test Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool textBool = false;
  int counter = 0;

  void changeTest(context) async {
    int counter = 0;
    Timer.periodic(Duration (seconds: 2), (Timer t) {
      counter++;
      stream.dataSink.add(true);
      if (counter >= 3) {
        t.cancel();
        stream.dispose();
        Navigator.pop(context);
      }
    },);
    Navigator.push(context, CupertinoPageRoute(builder: (context) => Page2(stream: stream)));
  }

  @override
  Widget build(BuildContext context) {

    return CupertinoPageScaffold(
      child: Center(
        child: CupertinoButton(
          child: Text('To Splash'),
          onPressed: () => changeTest(context),
        ),
      ),
    );
  }
}
</code>```

File 2 (stream.dart)

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

class DataStream {
  StreamController _streamController;

    StreamSink<bool> get dataSink =>
      _streamController.sink;

  Stream<bool> get dataStream =>
      _streamController.stream;

  DataStream() {
    _streamController = StreamController<bool>();
  }

  dispose() {
    _streamController?.close();
  }

}
</code>```

File 3 (page2.dart)

```<code>import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';

import './main.dart';
import './stream.dart';

class Page2 extends StatefulWidget {

  DataStream stream;
  Page2({this.stream});

  @override
  State<StatefulWidget> createState() => new PageState();
}

class PageState extends State<Page2> {

bool textChanger = false;
bool firstText = true;

Text myText() {
  if (textChanger) {
    Text text1 = new Text('Text One',
      style: TextStyle(color: Color.fromARGB(255, 0, 0, 0)));
    return text1;
  } else {
    Text text1 = new Text('Text Two',
      style: TextStyle(color: Color.fromARGB(255, 0, 0, 0)));
    return text1;
  }
}

void changeText() {
  if (!firstText) {
    if (textChanger) {
      print('Change One');
      setState(() {
        textChanger = false;
      });
    } else {
      print('Change Two');
      setState(() {
        textChanger = true;
      });
    }
  } else {
    firstText = false;
  }
}

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Container(
        child: Center(
          child: myText()
        )
      ),);
  }

@override
  void initState() {
    super.initState();
    widget.stream.dataStream.listen((onData) {
      changeText();
    });
  }

}
</code>```

Effectively, in this example, you can click on the text, and goto the second page, which will correctly change text when told, and return to the original page once completed.  That would be a single "Cycle" of my program.

And you can see that this program then immediately disposes of the stream.

The issue is that if I click the text a second time, it is still trying to listen to the original stream, rather than creating a brand new stream and starting fresh.

Why?  And how do I fix this?

答:
What I would do is to move stream to StatefulWidget and recreate it on "to Splash" tap

In real case scenario put it in to stateful widget in widget tree where all widgets that needs access will be able to find it (in your case even higher than navigator).

```<code>import 'package:flutter/cupertino.dart';
import 'dart:async';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return CupertinoApp(
      title: 'Splash Test',
      theme: CupertinoThemeData(
        primaryColor: Color.fromARGB(255, 0, 0, 255),
      ),
      home: MyHomePage(title: 'Splash Test Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool textBool = false;
  int counter = 0;

  DataStream stream = DataStream();

  void changeTest(context) async {
    setState(() {
      stream = DataStream();
    });
    int counter = 0;
    Timer.periodic(Duration (seconds: 2), (Timer t) {
      counter++;
      stream.dataSink.add(true);
      if (counter >= 3) {
        t.cancel();
        stream.dispose();
        Navigator.pop(context);
      }
    },);
    Navigator.push(context, CupertinoPageRoute(builder: (context) => Page2(stream: stream)));
  }

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      child: Center(
        child: CupertinoButton(
          child: Text('To Splash'),
          onPressed: () => changeTest(context),
        ),
      ),
    );
  }
}

class DataStream {
  StreamController _streamController;

  StreamSink<bool> get dataSink =>
      _streamController.sink;

  Stream<bool> get dataStream =>
      _streamController.stream;

  DataStream() {
    _streamController = StreamController<bool>();
  }

  dispose() {
    _streamController?.close();
  }

}

class Page2 extends StatefulWidget {

  DataStream stream;
  Page2({this.stream});

  @override
  State<StatefulWidget> createState() => new PageState();
}

class PageState extends State<Page2> {

  bool textChanger = false;
  bool firstText = true;

  Text myText() {
    if (textChanger) {
      Text text1 = new Text('Text One',
          style: TextStyle(color: Color.fromARGB(255, 0, 0, 0)));
      return text1;
    } else {
      Text text1 = new Text('Text Two',
          style: TextStyle(color: Color.fromARGB(255, 0, 0, 0)));
      return text1;
    }
  }

  void changeText() {
    if (!firstText) {
      if (textChanger) {
        print('Change One');
        setState(() {
          textChanger = false;
        });
      } else {
        print('Change Two');
        setState(() {
          textChanger = true;
        });
      }
    } else {
      firstText = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Container(
          child: Center(
              child: myText()
          )
      ),);
  }

  @override
  void initState() {
    super.initState();
    widget.stream.dataStream.listen((onData) {
      changeText();
    });
  }

}
</code>```

Body:
Okay, so I'm aware that a stream can be manufactured to listen to a stream more than once, using a broadcast system, but that's specifically NOT what I'm trying to do here.

I'm also editing this as the one answer I have received isn't currently able to resolve my issue, so any assistance would be greatly appreciated.

Effectively for some reason the code I have is not deleting the stream in it's entirety, and if re-used, it is trying to re-listen to the same stream that has already been listened-to and closed, none of which works (Obviously).  Instead of trying to listen to that same stream again, I'm trying to create a NEW stream to listen to.  (Deleting and cleaning away all information from the original first stream).

Original post continues below:

I'm using a DataStream template for streaming data to and/or from various parts of my program, and I'm not entirely certain how to rectify this.  I'm certain it's a silly newb error, but I haven't used DataStreams enough to understand why this is happening.

Now don't get me wrong, going through a single cycle of my program works perfectly fine, no issues at all.  However, once I've completed a single cycle through the program, if I try to go through a second time, I get the error:

Bad state: Stream has already been listened to.

So from this I know my program is not creating a new stream, and instead trying to re-use the original stream, and I'm not 100% certain how to stop this functionality, (Or even if I should).  (Honestly the number of times I would expect multiple cycles to be completed are slim to null, but I want to resolve these kinds of errors before they become problems.)

Edit:  Minimal Reproducible Example to Follow

File 1 (main.dart)

import 'package:flutter/cupertino.dart';
import 'dart:async';
import './page2.dart';
import './stream.dart';

void main() => runApp(MyApp());

DataStream stream = DataStream();

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return CupertinoApp(
      title: 'Splash Test',
      theme: CupertinoThemeData(
        primaryColor: Color.fromARGB(255, 0, 0, 255),
      ),
      home: MyHomePage(title: 'Splash Test Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool textBool = false;
  int counter = 0;

  void changeTest(context) async {
    int counter = 0;
    Timer.periodic(Duration (seconds: 2), (Timer t) {
      counter++;
      stream.dataSink.add(true);
      if (counter >= 3) {
        t.cancel();
        stream.dispose();
        Navigator.pop(context);
      }
    },);
    Navigator.push(context, CupertinoPageRoute(builder: (context) => Page2(stream: stream)));
  }

  @override
  Widget build(BuildContext context) {

    return CupertinoPageScaffold(
      child: Center(
        child: CupertinoButton(
          child: Text('To Splash'),
          onPressed: () => changeTest(context),
        ),
      ),
    );
  }
}

File 2 (stream.dart)

import 'dart:async';

class DataStream {
  StreamController _streamController;

    StreamSink<bool> get dataSink =>
      _streamController.sink;

  Stream<bool> get dataStream =>
      _streamController.stream;

  DataStream() {
    _streamController = StreamController<bool>();
  }

  dispose() {
    _streamController?.close();
  }

}

File 3 (page2.dart)

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

import './main.dart';
import './stream.dart';

class Page2 extends StatefulWidget {

  DataStream stream;
  Page2({this.stream});

  @override
  State<StatefulWidget> createState() => new PageState();
}

class PageState extends State<Page2> {

bool textChanger = false;
bool firstText = true;

Text myText() {
  if (textChanger) {
    Text text1 = new Text('Text One',
      style: TextStyle(color: Color.fromARGB(255, 0, 0, 0)));
    return text1;
  } else {
    Text text1 = new Text('Text Two',
      style: TextStyle(color: Color.fromARGB(255, 0, 0, 0)));
    return text1;
  }
}

void changeText() {
  if (!firstText) {
    if (textChanger) {
      print('Change One');
      setState(() {
        textChanger = false;
      });
    } else {
      print('Change Two');
      setState(() {
        textChanger = true;
      });
    }
  } else {
    firstText = false;
  }
}

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Container(
        child: Center(
          child: myText()
        )
      ),);
  }

@override
  void initState() {
    super.initState();
    widget.stream.dataStream.listen((onData) {
      changeText();
    });
  }

}

Effectively, in this example, you can click on the text, and goto the second page, which will correctly change text when told, and return to the original page once completed.  That would be a single "Cycle" of my program.

And you can see that this program then immediately disposes of the stream.

The issue is that if I click the text a second time, it is still trying to listen to the original stream, rather than creating a brand new stream and starting fresh.

Why?  And how do I fix this?

Body:
What I would do is to move stream to StatefulWidget and recreate it on "to Splash" tap

In real case scenario put it in to stateful widget in widget tree where all widgets that needs access will be able to find it (in your case even higher than navigator).

import 'package:flutter/cupertino.dart';
import 'dart:async';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return CupertinoApp(
      title: 'Splash Test',
      theme: CupertinoThemeData(
        primaryColor: Color.fromARGB(255, 0, 0, 255),
      ),
      home: MyHomePage(title: 'Splash Test Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool textBool = false;
  int counter = 0;

  DataStream stream = DataStream();

  void changeTest(context) async {
    setState(() {
      stream = DataStream();
    });
    int counter = 0;
    Timer.periodic(Duration (seconds: 2), (Timer t) {
      counter++;
      stream.dataSink.add(true);
      if (counter >= 3) {
        t.cancel();
        stream.dispose();
        Navigator.pop(context);
      }
    },);
    Navigator.push(context, CupertinoPageRoute(builder: (context) => Page2(stream: stream)));
  }

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      child: Center(
        child: CupertinoButton(
          child: Text('To Splash'),
          onPressed: () => changeTest(context),
        ),
      ),
    );
  }
}

class DataStream {
  StreamController _streamController;

  StreamSink<bool> get dataSink =>
      _streamController.sink;

  Stream<bool> get dataStream =>
      _streamController.stream;

  DataStream() {
    _streamController = StreamController<bool>();
  }

  dispose() {
    _streamController?.close();
  }

}

class Page2 extends StatefulWidget {

  DataStream stream;
  Page2({this.stream});

  @override
  State<StatefulWidget> createState() => new PageState();
}

class PageState extends State<Page2> {

  bool textChanger = false;
  bool firstText = true;

  Text myText() {
    if (textChanger) {
      Text text1 = new Text('Text One',
          style: TextStyle(color: Color.fromARGB(255, 0, 0, 0)));
      return text1;
    } else {
      Text text1 = new Text('Text Two',
          style: TextStyle(color: Color.fromARGB(255, 0, 0, 0)));
      return text1;
    }
  }

  void changeText() {
    if (!firstText) {
      if (textChanger) {
        print('Change One');
        setState(() {
          textChanger = false;
        });
      } else {
        print('Change Two');
        setState(() {
          textChanger = true;
        });
      }
    } else {
      firstText = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Container(
          child: Center(
              child: myText()
          )
      ),);
  }

  @override
  void initState() {
    super.initState();
    widget.stream.dataStream.listen((onData) {
      changeText();
    });
  }

}


问:
Python-Tkinter-askopenfilename: Use filepath of the opened file for reading values
I want to store the filepath to an opened file (via askopenfilename in tkinter) into a variable and later on use it for other purposes such as reading the file through the variable and use its values. How do I do that?

Also I am an absolute beginner so please explain the procedure too. Thanks in advance.

答:
Here is a code to start you off </p>

```<code>from tkinter import filedialog as fd

filename = fd.askopenfilename(title = "Attach file", initialdir = 'c:/')

f = open(filename, "r")
print(f.read())
f.close()
</code>```

Body:
Here is a code to start you off

from tkinter import filedialog as fd

filename = fd.askopenfilename(title = "Attach file", initialdir = 'c:/')

f = open(filename, "r")
print(f.read())
f.close()


问:
Python true global variables (python 3.7.0)
I know you can use the global keyword. But that's not...global. It's just a way to reference another variable outside of this function. If you have one variable that you want to reference it's no big deal I guess (although still troublesome). But what if you have lots of variables that you want to move around functions? Do I have to declare those 2 or 3 or 10 variables each and every time in each function that  are of global scope? Isn't there a way to declare[1] a variable (someplace or somehow) so as to be truly global?

Ideally I would like to have one file main.py with my main code and one file common.py with all my global variables (declared/initialized[1]) and with a from common import * I would be able to use every variable declared in common.py.

I apologize if it's a duplicate. I did search around but I can't seem to find something. Maybe you could do it with classes(?), but I'm trying to avoid using them for this particular program (but if there's no other way I'll take it)

EDIT: Adding code to show the example of two files not working:

file main.py

```<code>from common import *

def func1():
    x=2
    print('func1', x)

def func2():
    print('fuc2',x)

print('a',x)
func1()
func2()
</code>```

file common.py

```<code>x=3
</code>```

this prints:

```<code>a 3
func1 2
fuc2 3
</code>```

but it should print:

```<code>a 3
func1 2
fuc2 2
</code>```

because func2 even though it's called after func1 (where x is assigned a value) sees x as 3. Meaning that fuc1 didn't actually use the "global" variable x but a local variable x different from the "global" one. Correct me If I'm wrong

[1] I know that in python you don't really declare variables, you just initialize them but you get my point

答:
Technically, every module-level variable is global, and you can mess with them from anywhere. A simple example you might not have realized is sys:

```<code>import sys

myfile = open('path/to/file.txt', 'w')
sys.stdout = myfile
</code>```

sys.stdout is a global variable. Many things in various parts of the program - including parts you don't have direct access to - use it, and you'll notice that changing it here will change the behavior of the entire program. If anything, anywhere, uses print(), it will output to your file instead of standard output.

You can co-opt this behavior by simply making a common sourcefile that's accessible to your entire project:

common.py

```<code>var1 = 3
var2 = "Hello, World!"
</code>```

sourcefile1.py

```<code>from . import common

print(common.var2)
# "Hello, World!"

common.newVar = [3, 6, 8]
</code>```

fldr/sourcefile2.py

```<code>from .. import common

print(common.var2)
# "Hello, World!"
print(common.newVar)
# [3, 6, 8]
</code>```

As you can see, you can even assign new properties that weren't there in the first place (common.newVar).

It might be better practice, however, to simply place a dict in common and store your various global values in that - pushing a new key to a dict is an easier-to-maintain operation than adding a new attribute to a module.

If you use this method, you're going to want to be wary of doing from .common import *. This locks you out of ever changing your global variables, because of namespaces - when you assign a new value, you're modifying only your local namespace.

In general, you shouldn't be doing import * for this reason, but this is particular symptom of that.

Body:
I know you can use the global keyword. But that's not...global. It's just a way to reference another variable outside of this function. If you have one variable that you want to reference it's no big deal I guess (although still troublesome). But what if you have lots of variables that you want to move around functions? Do I have to declare those 2 or 3 or 10 variables each and every time in each function that  are of global scope? Isn't there a way to declare[1] a variable (someplace or somehow) so as to be truly global?

Ideally I would like to have one file main.py with my main code and one file common.py with all my global variables (declared/initialized[1]) and with a from common import * I would be able to use every variable declared in common.py.

I apologize if it's a duplicate. I did search around but I can't seem to find something. Maybe you could do it with classes(?), but I'm trying to avoid using them for this particular program (but if there's no other way I'll take it)

EDIT: Adding code to show the example of two files not working:

file main.py

from common import *

def func1():
    x=2
    print('func1', x)

def func2():
    print('fuc2',x)

print('a',x)
func1()
func2()

file common.py

x=3

this prints:

a 3
func1 2
fuc2 3

but it should print:

a 3
func1 2
fuc2 2

because func2 even though it's called after func1 (where x is assigned a value) sees x as 3. Meaning that fuc1 didn't actually use the "global" variable x but a local variable x different from the "global" one. Correct me If I'm wrong

[1] I know that in python you don't really declare variables, you just initialize them but you get my point

Body:
Technically, every module-level variable is global, and you can mess with them from anywhere. A simple example you might not have realized is sys:

import sys

myfile = open('path/to/file.txt', 'w')
sys.stdout = myfile

sys.stdout is a global variable. Many things in various parts of the program - including parts you don't have direct access to - use it, and you'll notice that changing it here will change the behavior of the entire program. If anything, anywhere, uses print(), it will output to your file instead of standard output.

You can co-opt this behavior by simply making a common sourcefile that's accessible to your entire project:

common.py

var1 = 3
var2 = "Hello, World!"

sourcefile1.py

from . import common

print(common.var2)
# "Hello, World!"

common.newVar = [3, 6, 8]

fldr/sourcefile2.py

from .. import common

print(common.var2)
# "Hello, World!"
print(common.newVar)
# [3, 6, 8]

As you can see, you can even assign new properties that weren't there in the first place (common.newVar).

It might be better practice, however, to simply place a dict in common and store your various global values in that - pushing a new key to a dict is an easier-to-maintain operation than adding a new attribute to a module.

If you use this method, you're going to want to be wary of doing from .common import *. This locks you out of ever changing your global variables, because of namespaces - when you assign a new value, you're modifying only your local namespace.

In general, you shouldn't be doing import * for this reason, but this is particular symptom of that.


问:
Which Linux distribution should I use as a Xen host?
I ordered a server for the home office and I would like to partition it with Xen. I think this will keep things clean and easier to maintain. I will be running things like MySQL, PostgreSQL, Tomcat, and my own code.

What freely available Linux distribution has the best Xen hosting facilities?

答: Debian is very good choice. You may also use xen live cd to test everything and if everything is ok, install it on HDD.</p>

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Roger Pate

OwnerDisplayName: Waltharius


问:
How to compile tflite with GPU support?
I try to compile tflite for Android with GPU support

```<code>bazel build --cxxopt='--std=c++11' -c opt --fat_apk_cpu=arm64-v8a //tensorflow/lite/java:tensorflowlite_gpu
</code>```

but I get several error messages like:

```<code>./tensorflow/lite/delegates/gpu/gl/gl_call.h:60:29: error: no viable conversion from returned value of type 'tflite::gpu::Status' to function return type 'int'
    if (status.ok()) return OkStatus();
</code>```

Do I need to pass any other command line params to bazel?

答: You need the -DMESA_EGL_NO_X11_HEADERS flag. See https://github.com/tensorflow/tensorflow/issues/27320

Title: How to compile tflite with GPU support?

Body:
I try to compile tflite for Android with GPU support

bazel build --cxxopt='--std=c++11' -c opt --fat_apk_cpu=arm64-v8a //tensorflow/lite/java:tensorflowlite_gpu

but I get several error messages like:

./tensorflow/lite/delegates/gpu/gl/gl_call.h:60:29: error: no viable conversion from returned value of type 'tflite::gpu::Status' to function return type 'int'
    if (status.ok()) return OkStatus();

Do I need to pass any other command line params to bazel?


问:
Can I insert backing fields for properties with a specific implementation?
I'm trying to create an attribute with PostSharp to implement specific backing fields of properties. However I did not find any helpful answers in the documentation, official examples or here on SO.

Here's an example of what I'm trying to do:

```<code>[WrappedProperty]
public int MyProperty { get; set; }
</code>```

will compile to

```<code>private WrapperClass<int> _generatedBackingField_myProperty;

public int MyProperty
{
    get => _generatedBackingField_myProperty.Value;
    set => _generatedBackingField_myProperty.Value = value;
}
</code>```

Is there any way to achieve this with PostSharp?

答:
I found the answer, you can use LocationInterceptionAspect to intercept properties.
So the code would look like this:

```<code>[PSerializable]
public class WrappedProperty : LocationInterceptionAspect
{
    private WrapperClass<object> _backingField;

    public override void OnGetValue(LocationInterceptionArgs args)
    {
        InitBackingField();

        args.Value = _backingField.Value;
    }

    public override void OnSetValue(LocationInterceptionArgs args)
    {
        InitBackingField();

        _backingField.Value = args.Value;
    }
}
</code>```

Body:
I'm trying to create an attribute with PostSharp to implement specific backing fields of properties. However I did not find any helpful answers in the documentation, official examples or here on SO.

Here's an example of what I'm trying to do:

[WrappedProperty]
public int MyProperty { get; set; }

will compile to

private WrapperClass<int> _generatedBackingField_myProperty;

public int MyProperty
{
    get => _generatedBackingField_myProperty.Value;
    set => _generatedBackingField_myProperty.Value = value;
}

Is there any way to achieve this with PostSharp?

Body:
I found the answer, you can use LocationInterceptionAspect to intercept properties.
So the code would look like this:

[PSerializable]
public class WrappedProperty : LocationInterceptionAspect
{
    private WrapperClass<object> _backingField;

    public override void OnGetValue(LocationInterceptionArgs args)
    {
        InitBackingField();

        args.Value = _backingField.Value;
    }

    public override void OnSetValue(LocationInterceptionArgs args)
    {
        InitBackingField();

        _backingField.Value = args.Value;
    }
}


问:
VueJs Watch per key of a model
I have an object (model), as an input field,for a search method, and I want that the watcher to detect changes per key, and not for all.

Right now ,if an input is changed, the watcher is called 10 times  (the number of inputs that I have).

```<code><b-form-input
        v-model="search[field.column]"
        type="search"
        id="filterInput"
        placeholder="search.."
></b-form-input>

watch:{
search: {
    handler(){
        // do somenthing
    },
    deep: true
}
}
</code>```

答:
You can explicitly watch the required key only.

new Vue({
  el: '#app',

  data: {
    search: {
      name: { placeholder: 'search name', value: '' },
      age: { placeholder: 'search age', value: '' },
      country: { placeholder: 'search country', value: '' }
    }
  },

  watch:{
    'search.name.value': { // Explicitly watch the required key.
        handler(){
            console.log('name changed...')
        }
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">

   <form>
    <input
      v-for="(value, key, i) in search"
      :key="i"
      v-model="search[key].value"
      type="search"
      id="filterInput"
      :placeholder="value.placeholder"
    />
   </form>

 </div></code>```

So, here watch's handler is called only when the name is searched & does not get called when age or country is searched.

Title: VueJs Watch per key of a model

Body:
I have an object (model), as an input field,for a search method, and I want that the watcher to detect changes per key, and not for all.

Right now ,if an input is changed, the watcher is called 10 times  (the number of inputs that I have).

watch:{
search: {
    handler(){
        // do somenthing
    },
    deep: true
}
}

Body:
You can explicitly watch the required key only.

new Vue({
  el: '#app',

  data: {
    search: {
      name: { placeholder: 'search name', value: '' },
      age: { placeholder: 'search age', value: '' },
      country: { placeholder: 'search country', value: '' }
    }
  },

  watch:{
    'search.name.value': { // Explicitly watch the required key.
        handler(){
            console.log('name changed...')
        }
    }
  }
})

 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">

   <form>
    <input
      v-for="(value, key, i) in search"
      :key="i"
      v-model="search[key].value"
      type="search"
      id="filterInput"
      :placeholder="value.placeholder"
    />
   </form>

 </div>

So, here watch's handler is called only when the name is searched & does not get called when age or country is searched.


问:
Can we created @CollectionTable inside @Entity class which class is used as CollectionTable in some other @Entity class
I have @Entity class as

```<code>@Entity
@Table(name = "EMPLOYEE")
public class Emplyee
{
  @Id
  @Column(name = "ID", length = 50)
  private String id;

  @Column(name = "ID", length = 50)
  private String name;

  @CollectionTable(name = "Address", joinColumns = @JoinColumn(name = "ID"),
      indexes = @Index(name = "Address_FK_IDX", columnList = "ID"),
      foreignKey = @ForeignKey(name = "EMPLOYEE_Address_FK"))
  @Column(name = "EXPORT_FORMAT", length = 50)
  private List<Address> address;

}
</code>```

I want to create Address entity which will hold below attributes

```<code>String addressLine;
String city;
String pinCode;
List<String> phoneNo;
</code>```

In this entity class I want to store list of phoneNo inside another collection table.
Can we do this using @CollectionTable or is there any other way to do this?

答:
You can do this as below. CollectionTableis normally used for collections of embeddable items rather than entities. You'd need to read up on the difference. While there is a good case for making Address an embeddable here rather than an entity, that would cause issues with the phone numbers so we make Address an Entity mapped to Employee using @OneToManyand use ElementCollection within Address for phone numbers.

```<code>@Entity
@Table(name = "EMPLOYEE")
public class Employee
{
  @Id//<-need to specify a generator here
  @Column(name = "ID", length = 50)
  private String id;

  @Column(name = "ID", length = 50)
  private String name;

  @OneToMany(cascade = CascadeType.ALL)
  //define FK column in Address table
  @JoinColumn(joinColumns = @JoinColumn(name = "EMPLOYEE_ID"),
      foreignKey = @ForeignKey(name = "EMPLOYEE_Address_FK"))
  private List<Address> address;
}
</code>```

Address:

```<code>@Entity
@Table("Address")
public class Address {
    @Id //<-need to specify a generator here
    private Long id;
    String addressLine;
    String city;
    String pinCode;

    @ElementCollection
    @CollectionTable(name = "Phone", joinColumns = @JoinColumn(name = "ADDRESS_ID"), foreignKey = @ForeignKey(name = "PHONE_Address_FK"))
    List<String> phoneNo;
}
</code>```

As noted above, @CollectionTable is normally used with collections of embeddables and while there is a case for making Address an @Embeddable rather than an @Entity that would cause issues as the JPA spec (2.6) notes:

An embeddable class (including an embeddable class within another
  embeddable class) that is contained within an element collection must
  not contain an element collection, nor may it contain a relationship
  to an entity other than a many-to-one or one-to-one relationship. The
  embeddable class must be on the owning side of such a relationship and
  the relationship must be mapped by a foreign key mapping. (See Section
  2.9.)

Body:
I have @Entity class as

@Entity
@Table(name = "EMPLOYEE")
public class Emplyee
{
  @Id
  @Column(name = "ID", length = 50)
  private String id;

  @Column(name = "ID", length = 50)
  private String name;

  @CollectionTable(name = "Address", joinColumns = @JoinColumn(name = "ID"),
      indexes = @Index(name = "Address_FK_IDX", columnList = "ID"),
      foreignKey = @ForeignKey(name = "EMPLOYEE_Address_FK"))
  @Column(name = "EXPORT_FORMAT", length = 50)
  private List<Address> address;

}

I want to create Address entity which will hold below attributes

String addressLine;
String city;
String pinCode;
List<String> phoneNo;

In this entity class I want to store list of phoneNo inside another collection table.
Can we do this using @CollectionTable or is there any other way to do this?

Body:
You can do this as below. CollectionTableis normally used for collections of embeddable items rather than entities. You'd need to read up on the difference. While there is a good case for making Address an embeddable here rather than an entity, that would cause issues with the phone numbers so we make Address an Entity mapped to Employee using @OneToManyand use ElementCollection within Address for phone numbers.

@Entity
@Table(name = "EMPLOYEE")
public class Employee
{
  @Id//<-need to specify a generator here
  @Column(name = "ID", length = 50)
  private String id;

  @Column(name = "ID", length = 50)
  private String name;

  @OneToMany(cascade = CascadeType.ALL)
  //define FK column in Address table
  @JoinColumn(joinColumns = @JoinColumn(name = "EMPLOYEE_ID"),
      foreignKey = @ForeignKey(name = "EMPLOYEE_Address_FK"))
  private List<Address> address;
}

Address:

@Entity
@Table("Address")
public class Address {
    @Id //<-need to specify a generator here
    private Long id;
    String addressLine;
    String city;
    String pinCode;

    @ElementCollection
    @CollectionTable(name = "Phone", joinColumns = @JoinColumn(name = "ADDRESS_ID"), foreignKey = @ForeignKey(name = "PHONE_Address_FK"))
    List<String> phoneNo;
}

As noted above, @CollectionTable is normally used with collections of embeddables and while there is a case for making Address an @Embeddable rather than an @Entity that would cause issues as the JPA spec (2.6) notes:

An embeddable class (including an embeddable class within another
  embeddable class) that is contained within an element collection must
  not contain an element collection, nor may it contain a relationship
  to an entity other than a many-to-one or one-to-one relationship. The
  embeddable class must be on the owning side of such a relationship and
  the relationship must be mapped by a foreign key mapping. (See Section
  2.9.)


问:
React TS - How to map through FontAwesome icons and display them
I'm trying to create a reusable component that allows me to pass in the href, target, rel attributes along with the type of FontAwesome Icon I would like to use. I'd like to be able to pass as many icons as I would like into this list and it would map through them, using the Social component as a template.

I would like the map to happen within the Social.tsx file, then I can simply just add the component anywhere in my project and then pass the props to it.

Something like this:

```<code><Social
  icons={[
    { icon: "facebook", href: "", target: "", rel: "" },
    { icon: "twitter", href: "", target: "", rel: "" },
    { icon: "discord", href: "", target: "", rel: "" }
  ]}
/>
</code>```

I currently have my component:

Social.tsx

```<code>import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as React from "react";

interface ISocial {
  href?: string
  target?: string
  rel?: string
}

const Social: React.FC<ISocial> = (props) => {
  return (
    <div>
      <a href={props.href} target={props.target} rel={props.rel}>
        {/* I don't want to hardcode the icon, but dynamically pass it as a prop */}
        <FontAwesomeIcon icon={["fab", "discord"]} />
      </a>
    </div>
  );
};

export default Social;
</code>```

App.tsx

```<code>import * as React from "react";
import "./styles.css";
import Social from "./components/Social";

export default function App() {
  // I'd like to be able to pass in a list of different icons
  // followed by the href, target, rel, etc for each item.
  // The Social component would be able to map through them
  // and display them.
  return <Social />;
</code>```

How can I adapt this to do what I described above?

Here's a CodeSandBox

Thanks for any help in advance!

答:
//App.tsx

import * as React from "react";
import "./styles.css";
import Social from "./components/Social";

export default function App() {
  // I'd like to be able to pass in a list of different icons
  // followed by the href, target, rel, etc for each one.
  // The Social component would be able to map through them
  // and display them.

  const iconList = [
    {
      name: "twitter",
      href: "https://www.google.com",
      target: "_blank"
    },
    {
      name: "discord",
      href: "https://www.google.com",
      target: "_blank"
    }
  ];
  return (

      {iconList.map(ico => {
        return <Social icon={ico.name} href={ico.href} />;
      })}

  );
}

//Social.tsx

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as React from "react";

interface ISocial {
  href?: string;
  target?: string;
  rel?: string;
  icon: String;
}

const Social: React.FC<ISocial> = props => {
  return (

        <FontAwesomeIcon icon={["fab", props.icon]} />

  );
};

export default Social;```

Body:
I'm trying to create a reusable component that allows me to pass in the href, target, rel attributes along with the type of FontAwesome Icon I would like to use. I'd like to be able to pass as many icons as I would like into this list and it would map through them, using the Social component as a template.

I would like the map to happen within the Social.tsx file, then I can simply just add the component anywhere in my project and then pass the props to it.

Something like this:

<Social
  icons={[
    { icon: "facebook", href: "", target: "", rel: "" },
    { icon: "twitter", href: "", target: "", rel: "" },
    { icon: "discord", href: "", target: "", rel: "" }
  ]}
/>

I currently have my component:

Social.tsx

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as React from "react";

interface ISocial {
  href?: string
  target?: string
  rel?: string
}

const Social: React.FC<ISocial> = (props) => {
  return (

        {/* I don't want to hardcode the icon, but dynamically pass it as a prop */}
        <FontAwesomeIcon icon={["fab", "discord"]} />

  );
};

export default Social;

App.tsx

import * as React from "react";
import "./styles.css";
import Social from "./components/Social";

export default function App() {
  // I'd like to be able to pass in a list of different icons
  // followed by the href, target, rel, etc for each item.
  // The Social component would be able to map through them
  // and display them.
  return <Social />;

How can I adapt this to do what I described above?

Here's a CodeSandBox

Thanks for any help in advance!

Body:
//App.tsx

import * as React from "react";
import "./styles.css";
import Social from "./components/Social";

export default function App() {
  // I'd like to be able to pass in a list of different icons
  // followed by the href, target, rel, etc for each one.
  // The Social component would be able to map through them
  // and display them.

  const iconList = [
    {
      name: "twitter",
      href: "https://www.google.com",
      target: "_blank"
    },
    {
      name: "discord",
      href: "https://www.google.com",
      target: "_blank"
    }
  ];
  return (
    <div>
      {iconList.map(ico => {
        return <Social icon={ico.name} href={ico.href} />;
      })}
    </div>
  );
}

//Social.tsx

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as React from "react";

interface ISocial {
  href?: string;
  target?: string;
  rel?: string;
  icon: String;
}

const Social: React.FC<ISocial> = props => {
  return (
    <div>
      <a href={props.href} target={props.target} rel={props.rel}>
        <FontAwesomeIcon icon={["fab", props.icon]} />
      </a>
    </div>
  );
};

export default Social;


问:
How to transform categorical column using one hot encoder in sklearn
I have a dataframe with a categorical column and am trying to one hot encode it using sklearn using the below snippit

```<code>oneEncoder= OneHotEncoder()
features['COL2'] = features['COL2'].apply(lambda col :  oneEncoder.fit_transform(col))
</code>```

but it keep throwing
ValueError: Expected 2D array, got scalar array instead:
array=1771. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

I also tried

```<code>oneEncoder= OneHotEncoder() #initializing an object of class LabelEncoder
oneEncoder.fit_transform( features['COL2'])
</code>```

but it throws
ValueError: Expected 2D array, got 1D array instead:

答:
Try:

```<code>oneEncoder.fit_transform(df[["Col2"]]).todense()
</code>```

Suppose we have:

```<code>features = pd.DataFrame({"Col2":["a","b","c"]})
</code>```

Then:

```<code>oneEncoder= OneHotEncoder()
oneEncoder.fit_transform(features[["Col2"]]).todense()
matrix([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])
</code>```

If you're dealing with a Series object, you may wish to reshape it:

```<code>oneEncoder.fit_transform(features.Col2.values.reshape(-1,1)).todense()
matrix([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])
</code>```

Dropping todense() method will leave your transformation in a sparse matrix.

And finally, you may alway decode what the columns of your matrix mean by:

```<code>oneEncoder.categories_
[array(['a', 'b', 'c'], dtype=object)]
</code>```

Not surpisingly, they are your unique inputs ordered alphabetically.

Body:
I have a dataframe with a categorical column and am trying to one hot encode it using sklearn using the below snippit

oneEncoder= OneHotEncoder()
features['COL2'] = features['COL2'].apply(lambda col :  oneEncoder.fit_transform(col))

but it keep throwing
ValueError: Expected 2D array, got scalar array instead:
array=1771. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

I also tried

oneEncoder= OneHotEncoder() #initializing an object of class LabelEncoder
oneEncoder.fit_transform( features['COL2'])

but it throws
ValueError: Expected 2D array, got 1D array instead:

Body:
Try:

oneEncoder.fit_transform(df[["Col2"]]).todense()

Suppose we have:

features = pd.DataFrame({"Col2":["a","b","c"]})

Then:

oneEncoder= OneHotEncoder()
oneEncoder.fit_transform(features[["Col2"]]).todense()
matrix([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])

If you're dealing with a Series object, you may wish to reshape it:

oneEncoder.fit_transform(features.Col2.values.reshape(-1,1)).todense()
matrix([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])

Dropping todense() method will leave your transformation in a sparse matrix.

And finally, you may alway decode what the columns of your matrix mean by:

oneEncoder.categories_
[array(['a', 'b', 'c'], dtype=object)]

Not surpisingly, they are your unique inputs ordered alphabetically.


问:
Building a library consisting of C and C++ files
I have a .so library where all code was written in plain ANSI C, so compiling it is straightforward. Now, I need to add C++ code in it. What would be the compilation process now?

Do I have to compile C++ files with g++ and the rest with gcc, but what about linking into .so file, do I do this with g++?

Thanks!

答:
Yes,

Compile .c with gcc

Compile .cpp with g++

Link with g++

Note:

If a C++ function needs to be invokable from C code, wrap it in extern "C" { ... }.


问:
What is the flow of execution in the following functions?
I dont undertand after of call y(k), in the function "y"  what execute first? the parameters or the body
the function. How the number 5 arrive at the function k

```<code>def k(x:Int) = x*x

def y(h:Int => Int) = h(5)

y(k)
</code>```

OUTPUT:

```<code>25
</code>```

答:
So the beauty of Functional Programming is that we can reason about or programs as expressions.

Given:

```<code>def k(x: Int) = x * x // 1.
def y(h: Int => Int) = h(5) // 2.
</code>```

Then:

```<code>y(k) = k(5)  // By definition of y (2).
y(k) = 5 * 5 // By definition of k (1).
y(k) = 25    // By definition of multiplication.
</code>```

Here I made some simplifications. like I didn't do type checking, but that should be pretty straight forward.

Body:
I dont undertand after of call y(k), in the function "y"  what execute first? the parameters or the body
the function. How the number 5 arrive at the function k

def k(x:Int) = x*x

def y(h:Int => Int) = h(5)

y(k)

OUTPUT:

25

Body:
So the beauty of Functional Programming is that we can reason about or programs as expressions.

Given:

def k(x: Int) = x * x // 1.
def y(h: Int => Int) = h(5) // 2.

Then:

y(k) = k(5)  // By definition of y (2).
y(k) = 5 * 5 // By definition of k (1).
y(k) = 25    // By definition of multiplication.

Here I made some simplifications. like I didn't do type checking, but that should be pretty straight forward.


问:
What can I do to fix this do-while?
```<code>#include <stdlib.h>
#include <stdio.h>

main()
{
    float n1, n2, n3, m;
    int op;
    do{
    printf("Digite a primeira nota: ");
    scanf("%f", &n1);
    printf("Digite a segunda nota: ");
    scanf("%f", &n2);
    m = ((n1 + n2) / 2);
    printf("%.2f", m);
    printf("\nDeseja calcular novamente?\n 1 - SIM\n 2 - NAO\n"); scanf("%d", op);
    } while (op == 1);
}
</code>```

This is my code and I expected it to rerun when the user inputs "1" in the last scanf
What did I do wrong?

答:
This:

```<code>scanf("%d", op);
</code>```

is instant undefined behavior; you need to pass the address like with the other calls (i.e. &op). You need to look for compiler warnings, they usually spot these things even though it's not possible from the pure prototype of scanf() but takes heuristics.

That said, this kind of field-at-a-time input using scanf() on stdio is brittle; it's better to read full lines using fgets() and then parse the strings. Please note that scanf() can fail, and you don't check for that. If someone enters duck for the final prompt, op will never be assigned a value and reading it in the do{}while is also undefined behavior.

Title: What can I do to fix this do-while?

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

main()
{
    float n1, n2, n3, m;
    int op;
    do{
    printf("Digite a primeira nota: ");
    scanf("%f", &n1);
    printf("Digite a segunda nota: ");
    scanf("%f", &n2);
    m = ((n1 + n2) / 2);
    printf("%.2f", m);
    printf("\nDeseja calcular novamente?\n 1 - SIM\n 2 - NAO\n"); scanf("%d", op);
    } while (op == 1);
}

This is my code and I expected it to rerun when the user inputs "1" in the last scanf
What did I do wrong?

Body:
This:

scanf("%d", op);

is instant undefined behavior; you need to pass the address like with the other calls (i.e. &op). You need to look for compiler warnings, they usually spot these things even though it's not possible from the pure prototype of scanf() but takes heuristics.

That said, this kind of field-at-a-time input using scanf() on stdio is brittle; it's better to read full lines using fgets() and then parse the strings. Please note that scanf() can fail, and you don't check for that. If someone enters duck for the final prompt, op will never be assigned a value and reading it in the do{}while is also undefined behavior.


答:
Maybe you can try something like this :</p>

```<code>SELECT
    *
FROM foo
WHERE day BETWEEN 2020-01-01 AND 2020-01-04
    AND total > 150
</code>```

Title: With Oracle SQL how can I find 3 days where total sum >= 150

Body:
I have a report that needs to list activity where total is >= 150 over 3 consecutive days.

Let's say I've created a temp table foo, to summarize daily totals.

| ID | Day        | Total |
| -- | ---------- | ----- |
| 01 | 2020-01-01 |   10  |
| 01 | 2020-01-02 |   50  |
| 01 | 2020-01-03 |   50  |
| 01 | 2020-01-04 |   50  |
| 01 | 2020-01-05 |   20  |
| 02 | 2020-01-01 |   10  |
| 02 | 2020-01-02 |   10  |
| 02 | 2020-01-03 |   10  |
| 02 | 2020-01-04 |   10  |
| 02 | 2020-01-05 |   10  |

How Would I write SQL to return ID 01, but not 02?

Example Result:

| ID |
| -- |
| 01 |

Body:
Maybe you can try something like this :

SELECT
    *
FROM foo
WHERE day BETWEEN 2020-01-01 AND 2020-01-04
    AND total > 150


问:
Angular Proxy Configuration
I have a basic question but I cannot sort this out.
I want to connect to git hub api from my angular app but always received 400 (Bad Request).

What I did:

package.json - I added/edited "start": "ng serve --proxy-config proxy.config.json"

I created new file proxy.config.json

Inside this file I added below /api configuration

{
    "/api": {
      "target": "https://api.github.com/",
      "secure": false
    }
}

In my someComponent.ts component I added:

import { HttpClient } from '@angular/common/http';

constructor(private http:HttpClient){}

and below func:

somefunc(){
        return this.http.get("/api/users?per_page=10")
                .subscribe(data =>{
                    this.datas = data
                    console.log(this.datas)
                })
}

But when I tried to execute this get method in console I received:

GET http://localhost:4200/api/users?per_page=10 400 (Bad Request)

and

ERROR HttpErrorResponse {headers: HttpHeaders, status: 400,
  statusText: "Bad Request", url:
  "http://localhost:4200/api/users?per_page=10", ok: false, …}

Can someone help me what I did wrong, please?

答:
For those who will have similar issue.
If your api is not hosted on localhost (external api as on my example) you need to add below lines in proxy.config.json

Code to add:

"pathRewrite": {
      "^/api": ""
    },

Title: Angular Proxy Configuration


问:
ResourcePurchaseValidationFailed error while creating Azure pipeline
I am getting below error while spinning up vm through Azure devops CD

Failure sending request: StatusCode=400 -- Original Error: Code="ResourcePurchaseValidationFailed" Message="User failed validation to purchase resources. Error message: 'Legal terms have not been accepted for this item on this subscription

答:
You are trying to deploy a resource which require additional legal and purchasing terms acceptance. You need identify the resource (normally it could be something non-Microsoft, like Oracle database or any network appliance) and use Set-AzureRmMarketplaceTerms before deployment (one time for any new non-standard Azure product).

AzureRm:

Get-AzureRmMarketplaceTerms -Publisher "microsoft-ads" -Product "windows-data-science-vm" -Name "windows2016" | Set-AzureRmMarketplaceTerms -Accept
```

<p>Doc: https://learn.microsoft.com/en-us/powershell/module/azurerm.marketplaceordering/set-azurermmarketplaceterms?view=azurermps-6.13.0</p>

<p>Az:</p>

<pre class="lang-bsh prettyprint-override"><code>Get-AzMarketplaceTerms -Publisher "microsoft-ads" -Product "windows-data-science-vm" -Name "windows2016" | Set-AzMarketplaceTerms -Accept
</code>```

Doc: https://learn.microsoft.com/en-us/powershell/module/az.marketplaceordering/set-azmarketplaceterms?view=azps-3.4.0

Body:
You are trying to deploy a resource which require additional legal and purchasing terms acceptance. You need identify the resource (normally it could be something non-Microsoft, like Oracle database or any network appliance) and use Set-AzureRmMarketplaceTerms before deployment (one time for any new non-standard Azure product).

AzureRm:

Get-AzureRmMarketplaceTerms -Publisher "microsoft-ads" -Product "windows-data-science-vm" -Name "windows2016" | Set-AzureRmMarketplaceTerms -Accept

Doc: https://learn.microsoft.com/en-us/powershell/module/azurerm.marketplaceordering/set-azurermmarketplaceterms?view=azurermps-6.13.0

Az:

Get-AzMarketplaceTerms -Publisher "microsoft-ads" -Product "windows-data-science-vm" -Name "windows2016" | Set-AzMarketplaceTerms -Accept

Doc: https://learn.microsoft.com/en-us/powershell/module/az.marketplaceordering/set-azmarketplaceterms?view=azps-3.4.0


问:
load a php image using src
Is it possible to load a image using:

```<code><img src="image.php?image_id=1">
</code>```

?

for image.php:

```<code>$image_id = $_GET['image_id'];
echo "image".$image_id.".png";
</code>```

答:
Is it possible to load a image use:

Yes. URLs are URLs. It is content-type that determines content, not any characters in the URL itself.

$image_id = $_GET['image_id'];
  echo "image".$image_id.".png";

Not like that. You either have to read the image file in and then output it with a suitable content-type, or redirect (with a location header) to a static image.

Title: load a php image using src

Body:
Is it possible to load a image using:

?

for image.php:

$image_id = $_GET['image_id'];
echo "image".$image_id.".png";

Body:
Is it possible to load a image use:
  <img src="image.php?image_id=1">

Yes. URLs are URLs. It is content-type that determines content, not any characters in the URL itself.

$image_id = $_GET['image_id'];
  echo "image".$image_id.".png";

Not like that. You either have to read the image file in and then output it with a suitable content-type, or redirect (with a location header) to a static image.


问:
Change your password on the Woocommerce Checkout-page
I'm working on a development and I need that users already registered on my site, change their password obligatorily on the woocommerce checkout-page.

I tried the classic solution:

```<code>add_filter('woocommerce_checkout_fields', 'custom_override_checkout_fields');

function custom_override_checkout_fields($fields)
{
    $fields['account']['account_password'] = array(
      'type' => 'password',
      'required'  => true,
      'label' => __('Pass', 'woocommerce'),
      'placeholder' => _x('Pass', 'placeholder', 'woocommerce'),
      'class' => array('form-row-wide')
  );

    return $fields;
}
</code>```

This mode only works for me when the user is registering, but not for changing their password.

Do you think I should make a wp_set_password( $password, $user_id ); ? If so, where would you place the code?

I need a way to do an UPDATE and change user_pass from wp_users table.

答:
I tried with a mix between @Raihan code and Googling´s code but I can't change user_pass. With this code it dont show "Internal server error" by Woocommerce.

```<code>add_action( 'woocommerce_checkout_process', 'user_fields_woocommerce_checkout_process' );

function user_fields_woocommerce_checkout_process(){
    if( is_user_logged_in() ){
        add_action('woocommerce_checkout_update_user_meta',
        'my_custom_checkout_field_update_user_meta' );
    }
}

function my_custom_checkout_field_update_user_meta( $user_id ) {
    if ( $data['account_password'] ) {
        update_user_meta( $user_id, 'account_password', $data['account_password'] );
    }
}
</code>```

Body:
I'm working on a development and I need that users already registered on my site, change their password obligatorily on the woocommerce checkout-page.

I tried the classic solution:

add_filter('woocommerce_checkout_fields', 'custom_override_checkout_fields');

function custom_override_checkout_fields($fields)
{
    $fields['account']['account_password'] = array(
      'type' => 'password',
      'required'  => true,
      'label' => __('Pass', 'woocommerce'),
      'placeholder' => _x('Pass', 'placeholder', 'woocommerce'),
      'class' => array('form-row-wide')
  );

    return $fields;
}

This mode only works for me when the user is registering, but not for changing their password.

Do you think I should make a wp_set_password( $password, $user_id ); ? If so, where would you place the code?

I need a way to do an UPDATE and change user_pass from wp_users table.

Body:
I tried with a mix between @Raihan code and Googling´s code but I can't change user_pass. With this code it dont show "Internal server error" by Woocommerce.

add_action( 'woocommerce_checkout_process', 'user_fields_woocommerce_checkout_process' );

function user_fields_woocommerce_checkout_process(){
    if( is_user_logged_in() ){
        add_action('woocommerce_checkout_update_user_meta',
        'my_custom_checkout_field_update_user_meta' );
    }
}

function my_custom_checkout_field_update_user_meta( $user_id ) {
    if ( $data['account_password'] ) {
        update_user_meta( $user_id, 'account_password', $data['account_password'] );
    }
}


问:
OpenStreetMap API - find & visualize gravel roads
Does the API allow you to retrieve all roads/trails of a given type (eg gravel/unpaved)?
If so, could you point me to some good tutorial that explain it's usage, if better than its own documentation?

I'd like to make a map where gravel/unpaved roads are highlighted, or live on its own layer.

Thanks in advance, and be merciful of the general question - I don't expect an in-depth answer, just a primer for my own research :)

答:
First, open street map api, server public has limit request, and recomendation is that you only install server type reverse "name of place or road name to coordenates" or "coordenates to name of place or road name" this server is called "nominatim" , all depend in that country, you need data, because some countries has many data in roads,load all world data to server and display it's too late,
so you can only install a single country if you wish , the response in this server is type json, and roads have a list of coordenates, and description, if you need display this in a map, you need other server that render map, maplink is the main tool to make it.</p>


问:
Access subform does not show data from linked table correctly
I have a linked table "SELECTSYSTEM2" on MS SQL Server that is created with autoincrement ID as primary key and 4 more columns [SYS, MANDT, SYS_TYPE, LIC_SYS].
Then I run this procedure to link the table and it works perfectly, as the table shows in the linked table list and it is editable.

```<code>Set db = CurrentDb()
ODBCTableName = "dbo.SELECTSYSTEM"
AccessTableName = "SELECTSYSTEM"
db.TableDefs.Refresh
For Each tdf In db.TableDefs
    If tdf.Name = AccessTableName Then
        db.TableDefs.Delete tdf.Name
        Exit For
    End If
Next tdf
Set tdf = db.CreateTableDef(AccessTableName)

tdf.SourceTableName = ODBCTableName
tdf.Connect = strConn
db.TableDefs.Append tdf
</code>```

The problem is when I try to link it directly to the subform "selectsyssub" in the form "CheckLicence" as in the snippet below.

```<code>Forms!CheckLicence!selectsyssub.SourceObject = "Table.SELECTSYSTEM2"
</code>```

The other tables that are not assigned primary key (I know, bad practice) and the tables that are assigned primary key from unique string values (no row-numbering or auto-incrementing) are all showing correctly in subforms.

I tried to change the LinkMasterFields and LinkChildFields, as on the snippet below, but it gives me Run-time error 2335: You must specify the same number of fields when you set the LinkChildFields and LinkMasterFields properties.

```<code>Forms!CheckLicence!selectsyssub.LinkMasterFields = "ID, SYS, MANDT, SYS_TYPE, SEL_SYS"
Forms!CheckLicence!selectsyssub.LinkChildFields = "ID, SYS, MANDT, SYS_TYPE, SEL_SYS"
</code>```

Any ideas how to show correctly the properly linked table from MS SQL server directly into the subform?

答: Everything got resolved when I renamed the ID field to SYSID.

Body:
I have a linked table "SELECTSYSTEM2" on MS SQL Server that is created with autoincrement ID as primary key and 4 more columns [SYS, MANDT, SYS_TYPE, LIC_SYS].
Then I run this procedure to link the table and it works perfectly, as the table shows in the linked table list and it is editable.

Set db = CurrentDb()
ODBCTableName = "dbo.SELECTSYSTEM"
AccessTableName = "SELECTSYSTEM"
db.TableDefs.Refresh
For Each tdf In db.TableDefs
    If tdf.Name = AccessTableName Then
        db.TableDefs.Delete tdf.Name
        Exit For
    End If
Next tdf
Set tdf = db.CreateTableDef(AccessTableName)

tdf.SourceTableName = ODBCTableName
tdf.Connect = strConn
db.TableDefs.Append tdf

The problem is when I try to link it directly to the subform "selectsyssub" in the form "CheckLicence" as in the snippet below.

Forms!CheckLicence!selectsyssub.SourceObject = "Table.SELECTSYSTEM2"

The other tables that are not assigned primary key (I know, bad practice) and the tables that are assigned primary key from unique string values (no row-numbering or auto-incrementing) are all showing correctly in subforms.

I tried to change the LinkMasterFields and LinkChildFields, as on the snippet below, but it gives me Run-time error 2335: You must specify the same number of fields when you set the LinkChildFields and LinkMasterFields properties.

Forms!CheckLicence!selectsyssub.LinkMasterFields = "ID, SYS, MANDT, SYS_TYPE, SEL_SYS"
Forms!CheckLicence!selectsyssub.LinkChildFields = "ID, SYS, MANDT, SYS_TYPE, SEL_SYS"

Any ideas how to show correctly the properly linked table from MS SQL server directly into the subform?


问:
AWS Lambda Flask file upload issue
Im looking at a super strange issue when uploading files, using boto3 and Flask.
If I upload a standard txt file, all is fine and dandy, but if any other file type, like zip, exe or pdf, the files is changed. IE. the file size, type and hash is different the the original file.

Here as an example I've uploaded Putty.exe.
Output :

```<code>{
"file": "putty.exe",
"message": "success",
"path": "/tmp/putty.exe",
"s3": "",
"sha1": "9b36616702410e029857bc2dd3b7f2f0d7db187a",
"sha256": "5e3dfdce6cefb28f3cafe506a657a5ff44e199c3c821cbd587906f5aea435d10",
"size": "1.7 MB",
"type": "MS-DOS executable"
}
</code>```

The correct SHA-1 of putty is 73016558c8353509b15cd757063816369e9abfa7

And when testing by flask app locally the file size and info is correct.

output from local test.

```<code>{
"file": "putty.exe",
"message": "success",
"path": "/tmp/putty.exe",
"s3": "",
"sha1": "73016558c8353509b15cd757063816369e9abfa7",
"sha256": "736330aaa3a4683d3cc866153510763351a60062a236d22b12f4fe0f10853582",
"size": "1.0 MB",
"type": "PE32 executable (GUI) Intel 80386, for MS Windows"
}
</code>```

Here is my current testing code.

```<code>import os
import boto3
import yara
import tempfile
import hashlib
import pefile
import uuid
import magic
from flask import Flask, request, redirect, send_file, url_for, jsonify
from werkzeug.utils import secure_filename

app = Flask(__name__)
bucket_name = "<Bucket name>"

# File size
def convert_bytes(num):
    """
    this function will convert bytes to MB.... GB... etc
    """
    for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
        if num < 1024.0:
            return "%3.1f %s" % (num, x)
        num /= 1024.0

def file_size(file_path):
    """
    this function will return the file size
    """
    if os.path.isfile(file_path):
        file_info = os.stat(file_path)
        return convert_bytes(file_info.st_size)

def get_hash(filename):
    fh = open(filename, 'rb')
    m = hashlib.md5()
    s = hashlib.sha1()
    s256 = hashlib.sha256()
    s512 = hashlib.sha512()
    while True:
        data = fh.read(8192)
        if not data:
                break

        m.update(data)
        s.update(data)
        s256.update(data)
        s512.update(data)

    md5  = m.hexdigest()
    sha1 = s.hexdigest()
    sha256 = s256.hexdigest()
    sha512 = s512.hexdigest()

    return md5,sha1,sha256,sha512

def process_file(file):
    s3_resource = boto3.resource('s3')
    file_path = os.path.join(tempfile.gettempdir(),file)
    s3_resource.Bucket(bucket_name).download_file(file,file_path)
    return True

@app.route("/")
def main():
    return  '{"messasge" : "Hello world"}'

@app.route("/realtimescan", methods=['POST'])
def realtimescan():
    filetype = ""
    tempdirectory = tempfile.gettempdir()
    file = request.files['file']
    content_type = request.mimetype
    if file:
        filename = secure_filename(file.filename)
        s3_resource = boto3.resource('s3')
        my_bucket = s3_resource.Bucket(bucket_name)
        my_bucket.Object(filename).put(Body=file.file)
        #boto3.client('s3').put_object(Bucket=bucket_name, Key=filename, Body=file)
        tmp_path = os.path.join(tempdirectory, filename)

        if process_file(filename):
            md5, sha1, sha256, sha512 = get_hash(tmp_path)
            try:
                filetype = str(magic.from_file(tmp_path, mime=False))
            except:
                filetype = "na"

            ret = ({"message" : "success",
                "file" : filename,
                "path" : tmp_path,
                "size" : file_size(tmp_path),
                "type" : filetype,
                "sha256" : sha256,
                "sha1" : sha1,
                "s3" : ""
            })
        else:
            ret = ({"message" : "error"})
        return ret

if __name__ == "__main__":
    app.run()
</code>```

I have zero clue what the issue is.
Also, if there are a better way to process the file in memory rather then saving to /tmp, tips & tricks are more than welcome.

Thanks

答: Ok turned out that one needs to set Binary Media Types under API Gateway settings to */* to accept binary file types.

Title: AWS Lambda Flask file upload issue

Body:
Im looking at a super strange issue when uploading files, using boto3 and Flask.
If I upload a standard txt file, all is fine and dandy, but if any other file type, like zip, exe or pdf, the files is changed. IE. the file size, type and hash is different the the original file.

Here as an example I've uploaded Putty.exe.
Output :

{
"file": "putty.exe",
"message": "success",
"path": "/tmp/putty.exe",
"s3": "",
"sha1": "9b36616702410e029857bc2dd3b7f2f0d7db187a",
"sha256": "5e3dfdce6cefb28f3cafe506a657a5ff44e199c3c821cbd587906f5aea435d10",
"size": "1.7 MB",
"type": "MS-DOS executable"
}

The correct SHA-1 of putty is 73016558c8353509b15cd757063816369e9abfa7

And when testing by flask app locally the file size and info is correct.

output from local test.

{
"file": "putty.exe",
"message": "success",
"path": "/tmp/putty.exe",
"s3": "",
"sha1": "73016558c8353509b15cd757063816369e9abfa7",
"sha256": "736330aaa3a4683d3cc866153510763351a60062a236d22b12f4fe0f10853582",
"size": "1.0 MB",
"type": "PE32 executable (GUI) Intel 80386, for MS Windows"
}

Here is my current testing code.

import os
import boto3
import yara
import tempfile
import hashlib
import pefile
import uuid
import magic
from flask import Flask, request, redirect, send_file, url_for, jsonify
from werkzeug.utils import secure_filename

app = Flask(__name__)
bucket_name = "<Bucket name>"

# File size
def convert_bytes(num):
    """
    this function will convert bytes to MB.... GB... etc
    """
    for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
        if num < 1024.0:
            return "%3.1f %s" % (num, x)
        num /= 1024.0

def file_size(file_path):
    """
    this function will return the file size
    """
    if os.path.isfile(file_path):
        file_info = os.stat(file_path)
        return convert_bytes(file_info.st_size)

def get_hash(filename):
    fh = open(filename, 'rb')
    m = hashlib.md5()
    s = hashlib.sha1()
    s256 = hashlib.sha256()
    s512 = hashlib.sha512()
    while True:
        data = fh.read(8192)
        if not data:
                break

        m.update(data)
        s.update(data)
        s256.update(data)
        s512.update(data)

    md5  = m.hexdigest()
    sha1 = s.hexdigest()
    sha256 = s256.hexdigest()
    sha512 = s512.hexdigest()

    return md5,sha1,sha256,sha512

def process_file(file):
    s3_resource = boto3.resource('s3')
    file_path = os.path.join(tempfile.gettempdir(),file)
    s3_resource.Bucket(bucket_name).download_file(file,file_path)
    return True

@app.route("/")
def main():
    return  '{"messasge" : "Hello world"}'

@app.route("/realtimescan", methods=['POST'])
def realtimescan():
    filetype = ""
    tempdirectory = tempfile.gettempdir()
    file = request.files['file']
    content_type = request.mimetype
    if file:
        filename = secure_filename(file.filename)
        s3_resource = boto3.resource('s3')
        my_bucket = s3_resource.Bucket(bucket_name)
        my_bucket.Object(filename).put(Body=file.file)
        #boto3.client('s3').put_object(Bucket=bucket_name, Key=filename, Body=file)
        tmp_path = os.path.join(tempdirectory, filename)

        if process_file(filename):
            md5, sha1, sha256, sha512 = get_hash(tmp_path)
            try:
                filetype = str(magic.from_file(tmp_path, mime=False))
            except:
                filetype = "na"

            ret = ({"message" : "success",
                "file" : filename,
                "path" : tmp_path,
                "size" : file_size(tmp_path),
                "type" : filetype,
                "sha256" : sha256,
                "sha1" : sha1,
                "s3" : ""
            })
        else:
            ret = ({"message" : "error"})
        return ret

if __name__ == "__main__":
    app.run()

I have zero clue what the issue is.
Also, if there are a better way to process the file in memory rather then saving to /tmp, tips & tricks are more than welcome.

Thanks


问:
On Silverstripe, how do I retrieve a DataList of grandchild objects including their extrafields?
I have a setup similar to that outlined below.

```<code>class A extends DataObject{
    private static $many_many = array(
        'Bs' => 'B'
    );

    public function Grandchildren(){
        // return grandchildren, including their many_many_extraFields data (ExtraData)
    }
}

class B extends DataObject{
    private static $many_many = array(
        'Cs' => 'C'
    );

    private static $belongs_many_many = array(
        'As' => 'A'
    );

    private static $many_many_extraFields = array(
        'As' => array(
            'ExtraData' => 'Int'
        )
    );
}

class C extends DataObject{
    private static $db = array(
        'Name' => Varchar(255)
    );

    private static $belongs_many_many = array(
        'Bs' => 'B'
    );
}
</code>```

I wish to retrieve all the C objects of all the B objects from a function on A (here called Grandchildren()).

Two potential solutions that I can't get to work:

1 -

```<code>public function Grandchildren(){
    $grandchildren = DataList::create();
    foreach($this->Bs() as $b){
        $Cs = $b->Cs();
        // How would I then merge these into one single DataList ($grandchildren)?
    }
    return $grandchildren;
}
</code>```

2 -

```<code>public function Grandchildren(){
    return C::get()->leftJoin('B_Cs', 'B_Cs.CID = C.ID')->where('B_Cs.AID = ' . $this->ID);
    // This works but doesn't contain the needed ExtraData.
}
</code>```

Many thanks in advance for any help.

答:
Ah sorry. The answer was much simpler than I realised. Just took going through every method on the docs for DataList again.

```<code>public function Grandchildren(){
    return $this->Bs()->relation('Cs');
}
</code>```

Leaving question and answer here to help any of those stuck in the same situation as me (as I've been stuck with this problem many times before).

Body:
I have a setup similar to that outlined below.

class A extends DataObject{
    private static $many_many = array(
        'Bs' => 'B'
    );

    public function Grandchildren(){
        // return grandchildren, including their many_many_extraFields data (ExtraData)
    }
}

class B extends DataObject{
    private static $many_many = array(
        'Cs' => 'C'
    );

    private static $belongs_many_many = array(
        'As' => 'A'
    );

    private static $many_many_extraFields = array(
        'As' => array(
            'ExtraData' => 'Int'
        )
    );
}

class C extends DataObject{
    private static $db = array(
        'Name' => Varchar(255)
    );

    private static $belongs_many_many = array(
        'Bs' => 'B'
    );
}

I wish to retrieve all the C objects of all the B objects from a function on A (here called Grandchildren()).

Two potential solutions that I can't get to work:

1 -

public function Grandchildren(){
    $grandchildren = DataList::create();
    foreach($this->Bs() as $b){
        $Cs = $b->Cs();
        // How would I then merge these into one single DataList ($grandchildren)?
    }
    return $grandchildren;
}

2 -

public function Grandchildren(){
    return C::get()->leftJoin('B_Cs', 'B_Cs.CID = C.ID')->where('B_Cs.AID = ' . $this->ID);
    // This works but doesn't contain the needed ExtraData.
}

Many thanks in advance for any help.

Body:
Ah sorry. The answer was much simpler than I realised. Just took going through every method on the docs for DataList again.

public function Grandchildren(){
    return $this->Bs()->relation('Cs');
}

Leaving question and answer here to help any of those stuck in the same situation as me (as I've been stuck with this problem many times before).


问:
What are non-scriptable objects in Django?
I have the following model:

```<code>class Performance(Event):
    date_created = models.DateTimeField(_('date created'), default=timezone.now)
    date_modified = models.DateTimeField(_('date_modified'), auto_now=True)

class PerformanceWork(models.Model):
    perf = models.ForeignKey(Performance, related_name='perf_work', blank=True, null=True, on_delete=models.CASCADE)
    work =  models.ForeignKey(WorkMusic, related_name='work', blank=True, null=True, on_delete=models.CASCADE)

class WorkMusic(MPTTModel, Work):
    ...
</code>```

In my view.py:

```<code>class PerformanceView(TemplateView):
    template_name = 'performances/performance.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            'perf': Performance.objects.get(pk=self.kwargs['pk'])
        })
        return context
</code>```

In my template, I am trying to render a recursive tree with this in my template:

```<code>  {% for work in perf.perf_work.all %}
    {% recursetree work.work %}
    <li>
      {% if node.is_leaf_node %}
        {{ node.name_original }}
      {% endif %}
      {% if not node.is_leaf_node %}
        <ul class="children">
          {{ children }}
        </ul>
      {% endif %}
    </li>
    {% endrecursetree %}
{% endfor %}
</code>```

When run my app, I get the following error.

```<code>Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/performance/2/

Django Version: 3.0
Python Version: 3.7.5
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'opus',
 'generic',
 'art_perf',
 'art_visual',
 'debug_toolbar',
 'mptt',
 'import_export',
 'googlemaps']
Installed Middleware:
('whitenoise.middleware.WhiteNoiseMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware')

Template error:
In template /Users/howiec/Desktop/Opus/templates/performances/base.html, error at line 0
   'WorkMusic' object is not subscriptable
   1 : {% load static i18n %}
   2 :
   3 : <!DOCTYPE html>
   4 : <html lang="en" class="{% block html_class %}{% endblock %}">
   5 : <head>
   6 :     <meta charset="UTF-8">
   7 :     <meta name="viewport" content="width=device-width, initial-scale=1.0">
   8 :     <meta http-equiv="X-UA-Compatible" content="ie=edge">
   9 :
   10 :     <link rel="stylesheet" type="text/css" href="{% static 'css/performance.css' %}">

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 145, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 143, in _get_response
    response = response.render()
  File "/usr/local/lib/python3.7/site-packages/django/template/response.py", line 105, in render
    self.content = self.rendered_content
  File "/usr/local/lib/python3.7/site-packages/django/template/response.py", line 83, in rendered_content
    return template.render(context, self._request)
  File "/usr/local/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 171, in render
    return self._render(context)
  File "/usr/local/lib/python3.7/site-packages/django/test/utils.py", line 95, in instrumented_test_render
    return self.nodelist.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 936, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "/usr/local/lib/python3.7/site-packages/django/test/utils.py", line 95, in instrumented_test_render
    return self.nodelist.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 936, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 936, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/defaulttags.py", line 209, in render
    nodelist.append(node.render_annotated(context))
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.7/site-packages/mptt/templatetags/mptt_tags.py", line 257, in render
    roots = cache_tree_children(queryset)
  File "/usr/local/lib/python3.7/site-packages/mptt/templatetags/mptt_tags.py", line 236, in cache_tree_children
    return get_cached_trees(queryset)
  File "/usr/local/lib/python3.7/site-packages/mptt/utils.py", line 232, in get_cached_trees
    parent_attr = queryset[0]._mptt_meta.parent_attr

Exception Type: TypeError at /performance/2/
Exception Value: 'WorkMusic' object is not subscriptable
</code>```

Work.work is a queryset with a WorkMusic object:

I know this is graphable when I just graph a WorkMusic object directly. I'm not sure why this break when I access the object through another model?

答:
The problem is that recursetree expects a collection and you're passing it an instance.

```<code>{% recursetree work.work %}
</code>```

When you get this error it effectively means that you're trying to do a collection based operation on a Django model instance. Or at least that's what I've seen in my experience.

Body:
I have the following model:

class Performance(Event):
    date_created = models.DateTimeField(_('date created'), default=timezone.now)
    date_modified = models.DateTimeField(_('date_modified'), auto_now=True)

class PerformanceWork(models.Model):
    perf = models.ForeignKey(Performance, related_name='perf_work', blank=True, null=True, on_delete=models.CASCADE)
    work =  models.ForeignKey(WorkMusic, related_name='work', blank=True, null=True, on_delete=models.CASCADE)

class WorkMusic(MPTTModel, Work):
    ...

In my view.py:

class PerformanceView(TemplateView):
    template_name = 'performances/performance.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            'perf': Performance.objects.get(pk=self.kwargs['pk'])
        })
        return context

In my template, I am trying to render a recursive tree with this in my template:

  {% for work in perf.perf_work.all %}
    {% recursetree work.work %}

      {% if node.is_leaf_node %}
        {{ node.name_original }}
      {% endif %}
      {% if not node.is_leaf_node %}

          {{ children }}

      {% endif %}

    {% endrecursetree %}
{% endfor %}

When run my app, I get the following error.

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/performance/2/

Django Version: 3.0
Python Version: 3.7.5
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'opus',
 'generic',
 'art_perf',
 'art_visual',
 'debug_toolbar',
 'mptt',
 'import_export',
 'googlemaps']
Installed Middleware:
('whitenoise.middleware.WhiteNoiseMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware')

Template error:
In template /Users/howiec/Desktop/Opus/templates/performances/base.html, error at line 0
   'WorkMusic' object is not subscriptable
   1 : {% load static i18n %}
   2 :
   3 : <!DOCTYPE html>
   4 :
   5 :
   6 :     <meta charset="UTF-8">
   7 :     <meta name="viewport" content="width=device-width, initial-scale=1.0">
   8 :     <meta http-equiv="X-UA-Compatible" content="ie=edge">
   9 :
   10 :     <link rel="stylesheet" type="text/css" href="{% static 'css/performance.css' %}">

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 145, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 143, in _get_response
    response = response.render()
  File "/usr/local/lib/python3.7/site-packages/django/template/response.py", line 105, in render
    self.content = self.rendered_content
  File "/usr/local/lib/python3.7/site-packages/django/template/response.py", line 83, in rendered_content
    return template.render(context, self._request)
  File "/usr/local/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 171, in render
    return self._render(context)
  File "/usr/local/lib/python3.7/site-packages/django/test/utils.py", line 95, in instrumented_test_render
    return self.nodelist.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 936, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "/usr/local/lib/python3.7/site-packages/django/test/utils.py", line 95, in instrumented_test_render
    return self.nodelist.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 936, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 936, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.7/site-packages/django/template/defaulttags.py", line 209, in render
    nodelist.append(node.render_annotated(context))
  File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python3.7/site-packages/mptt/templatetags/mptt_tags.py", line 257, in render
    roots = cache_tree_children(queryset)
  File "/usr/local/lib/python3.7/site-packages/mptt/templatetags/mptt_tags.py", line 236, in cache_tree_children
    return get_cached_trees(queryset)
  File "/usr/local/lib/python3.7/site-packages/mptt/utils.py", line 232, in get_cached_trees
    parent_attr = queryset[0]._mptt_meta.parent_attr

Exception Type: TypeError at /performance/2/
Exception Value: 'WorkMusic' object is not subscriptable

Work.work is a queryset with a WorkMusic object:

I know this is graphable when I just graph a WorkMusic object directly. I'm not sure why this break when I access the object through another model?

Body:
The problem is that recursetree expects a collection and you're passing it an instance.

{% recursetree work.work %}

When you get this error it effectively means that you're trying to do a collection based operation on a Django model instance. Or at least that's what I've seen in my experience.