问:
How to change text color of TextFormField according to theme
I want to change inputted text color as per the current theme, as text color is not a part of InputDecorationTheme.

As of now the only possible way to change inputted text color is to give style to TextFormField but that also not work when theme gets changed + in that way I need to repeat the similar code for each of my text field available in the app.

答:
you can do by using property subhead inside the TextTheme

```<code> theme: ThemeData(
    brightness: Brightness.dark,
    primaryColor: Colors.orange,
    accentColor: Colors.green,
    textTheme: TextTheme(
      subhead: TextStyle(color: Colors.blue),
    ),
  ),
</code>```

Or by using this :

```<code> theme: ThemeData(
      brightness: Brightness.dark,
      primaryColor: Colors.orange,
      accentColor: Colors.green,
      textTheme: Theme.of(context)
          .textTheme
          .apply(bodyColor: Colors.red)`enter code here`

  ),
</code>```

A blog on Text Styling in Flutter https://medium.com/flutter-
 community/beginners-guide-to-text-styling-in-flutter-3939085d6607

NOTE: The Material Design typography scheme was significantly changed in the
current (2018) version of the specification
more info https://material.io/design/typography.

The 2018 spec has thirteen text styles:

```<code> NAME         SIZE  WEIGHT  SPACING
 headline1    96.0  light   -1.5
 headline2    60.0  light   -0.5
 headline3    48.0  regular  0.0
 headline4    34.0  regular  0.25
 headline5    24.0  regular  0.0
 headline6    20.0  medium   0.15
 subtitle1    16.0  regular  0.15
 subtitle2    14.0  medium   0.1
 body1        16.0  regular  0.5   (bodyText1)
 body2        14.0  regular  0.25  (bodyText2)
 button       14.0  medium   1.25
 caption      12.0  regular  0.4
 overline     10.0  regular  1.5
</code>```

where "light" is FontWeight.w300, "regular" is FontWeight.w400 and
"medium" is FontWeight.w500.

The [TextTheme] API was originally based on the original material (2014)
design spec, which used different text style names. For backwards
compatibility's sake, this API continues to expose the old names. The table
below should help with understanding the mapping of the API's old names and
the new names (those in terms of the 2018 material specification).

Each of the [TextTheme] text styles corresponds to one of the
  styles from 2018 spec. By default, the font sizes, font weights
  and letter spacings have not changed from their original,
  2014, values.

```<code> NAME       SIZE   WEIGHT   SPACING  2018 NAME
 display4   112.0  thin     0.0      headline1
 display3   56.0   normal   0.0      headline2
 display2   45.0   normal   0.0      headline3
 display1   34.0   normal   0.0      headline4
 headline   24.0   normal   0.0      headline5
 title      20.0   medium   0.0      headline6
 subhead    16.0   normal   0.0      subtitle1
 body2      14.0   medium   0.0      body1 (bodyText1)
 body1      14.0   normal   0.0      body2 (bodyText2)
 caption    12.0   normal   0.0      caption
 button     14.0   medium   0.0      button
 subtitle   14.0   medium   0.0      subtitle2
 overline   10.0   normal   0.0      overline
</code>```

Body:
you can do by using property subhead inside the TextTheme

 theme: ThemeData(
    brightness: Brightness.dark,
    primaryColor: Colors.orange,
    accentColor: Colors.green,
    textTheme: TextTheme(
      subhead: TextStyle(color: Colors.blue),
    ),
  ),

Or by using this :

 theme: ThemeData(
      brightness: Brightness.dark,
      primaryColor: Colors.orange,
      accentColor: Colors.green,
      textTheme: Theme.of(context)
          .textTheme
          .apply(bodyColor: Colors.red)`enter code here`

  ),

A blog on Text Styling in Flutter https://medium.com/flutter-
 community/beginners-guide-to-text-styling-in-flutter-3939085d6607

NOTE: The Material Design typography scheme was significantly changed in the
current (2018) version of the specification
more info https://material.io/design/typography.

The 2018 spec has thirteen text styles:

 NAME         SIZE  WEIGHT  SPACING
 headline1    96.0  light   -1.5
 headline2    60.0  light   -0.5
 headline3    48.0  regular  0.0
 headline4    34.0  regular  0.25
 headline5    24.0  regular  0.0
 headline6    20.0  medium   0.15
 subtitle1    16.0  regular  0.15
 subtitle2    14.0  medium   0.1
 body1        16.0  regular  0.5   (bodyText1)
 body2        14.0  regular  0.25  (bodyText2)
 button       14.0  medium   1.25
 caption      12.0  regular  0.4
 overline     10.0  regular  1.5

where "light" is FontWeight.w300, "regular" is FontWeight.w400 and
"medium" is FontWeight.w500.

The [TextTheme] API was originally based on the original material (2014)
design spec, which used different text style names. For backwards
compatibility's sake, this API continues to expose the old names. The table
below should help with understanding the mapping of the API's old names and
the new names (those in terms of the 2018 material specification).

Each of the [TextTheme] text styles corresponds to one of the
  styles from 2018 spec. By default, the font sizes, font weights
  and letter spacings have not changed from their original,
  2014, values.

 NAME       SIZE   WEIGHT   SPACING  2018 NAME
 display4   112.0  thin     0.0      headline1
 display3   56.0   normal   0.0      headline2
 display2   45.0   normal   0.0      headline3
 display1   34.0   normal   0.0      headline4
 headline   24.0   normal   0.0      headline5
 title      20.0   medium   0.0      headline6
 subhead    16.0   normal   0.0      subtitle1
 body2      14.0   medium   0.0      body1 (bodyText1)
 body1      14.0   normal   0.0      body2 (bodyText2)
 caption    12.0   normal   0.0      caption
 button     14.0   medium   0.0      button
 subtitle   14.0   medium   0.0      subtitle2
 overline   10.0   normal   0.0      overline


来源: stackexchange

问:
Any tips from a book on traffic analysis?
I'm studying to pentest, so I basically start with networking, programming, and pentest methods, but in a book called The Basics of Hacking and Penetration Testing on Port Scanning, she says that "she tries to log on to any remote access that were discovered on your doorstep scan", but the problem starts here, I began to be in doubt about the relationship between ports and their services, and how to deeply understand things like:

80 / tcp open http openresty

443 / tcp open ssl / https

8080 / tcp open http-proxy?

So i was searching google about ssl, openresty, in the case https and http i study from some about networks but still i was only touching on deeper knowledge and dispersed on the internet, so i would like one or more books that deal specifically with the part practice a network traffic analysis and recommend other books to better understand processes for answering questions like "oh cool, but which port is associated with remote access?".

I've researched remote access and found that port 3389 is commonly used at first, but I feel that's not what that quoted part of the book meant.

Thanks and sorry for my bad english!

答:
First off, I have not read the book, so I cannot comment on it.

However, I can give some direction on what the nmap scan means and what your next steps would likely be.

The line

80 / tcp open http openresty

means that TCP port 80 is open, the protocol name is "http" and the server is running "openresty".

For port 80, your next step would be to run some sort of fingerprinting on that server. For example, an "nmap -sV -p 80" scan or run some tool like Sparta or Nikto.

This should be done to identify the version of openresty on the server. The next step would be to see if there are any login pages exposed on the server. If you do find login pages, you could try brute-forcing the login to get access.

Or, using the version of openresty, you could search for exploits for that version of openresty (usually via Google search, or some exploit database like "exploit-db.com"). Then use those exploits to gain access to the server, or do a DoS for example.

However, when you do any of this, make sure you get permission from your target to do this, or be aware that there can be consequences. If you are just starting to learn about this stuff, it would be better to create your own VM with DVWA deployed on it. That would be your target for practice.

Hope that helps.

ContentLicense: CC BY-SA 4.0


问:
ReactJS error getting object assigned from axios call to api
I have the following code:

```<code>import React, { Component } from 'react';
import axios from 'axios';

class Dashboard extends Component {
     state = {
         name : 'randomname',
         apiData: {}
};

componentDidMount() {
  axios.get('https://api_url/getdata)
    .then(res => {
        const apiData = res.data
        this.setState({apiData});
    });
}

render() {
  const { name, apiData} = this.state;

  //THIS WORKS
  var objTest = [{game_id: 2}]; //This is returned from apical
  console.log(objTest[0].game_id);

  console.log(apiData); //logs the following: [{game_id: 2}]
  console.log(apiData[0]); //logs the following: {game_id: 2}
  console.log(apiData[0].game_id); //Error occurs See error below

  return (
    <div className="wrap">
         TESTING
    </div>
  );
}
}

export default Dashboard;
</code>```

While testing and trying to get game_id using: console.log(apiData[0].game_id); I get the following error:

TypeError: undefined is not an object (evaluating
  'apiData[0].game_id')

I would like to know why this works when I declare a variable and assign it the same values as the api call returns. But it does not work then I'm assigning the api call to apiData. It can only access apiData[0] which returns {game_id:2} , but cannot access apiData[0].game_id.

Thanks for all the help!

答:
Simply defined one flag in the state and check whether your data is available or not once you get data change that flag and and load your component element accordingly.

see below solution for your problem statement.

import React, { Component } from 'react';
import axios from 'axios';

class Dashboard extends Component {
     state = {
         loading:true,
         name : 'randomname',
         apiData: {}
};

componentDidMount() {
  axios.get('https://api_url/getdata').then(res => {
        this.setState({apiData:res.data, loading:false});
    });
}

render() {
  const { name, apiData, loading} = this.state;

  //THIS WORKS
  var objTest = [{game_id: 2}]; //This is returned from apical
  console.log(objTest[0].game_id);

  console.log(apiData); //logs the following: [{game_id: 2}]
  console.log(apiData[0]); //logs the following: {game_id: 2}
  console.log(apiData[0].game_id); //Error occurs See error below

  return (

         {loading ?
Loading ...
 :
TESTING
}

  );
}
}

export default Dashboard;```

Body:
I have the following code:

import React, { Component } from 'react';
import axios from 'axios';

class Dashboard extends Component {
     state = {
         name : 'randomname',
         apiData: {}
};

componentDidMount() {
  axios.get('https://api_url/getdata)
    .then(res => {
        const apiData = res.data
        this.setState({apiData});
    });
}

render() {
  const { name, apiData} = this.state;

  //THIS WORKS
  var objTest = [{game_id: 2}]; //This is returned from apical
  console.log(objTest[0].game_id);

  console.log(apiData); //logs the following: [{game_id: 2}]
  console.log(apiData[0]); //logs the following: {game_id: 2}
  console.log(apiData[0].game_id); //Error occurs See error below

  return (

         TESTING

  );
}
}

export default Dashboard;

While testing and trying to get game_id using: console.log(apiData[0].game_id); I get the following error:

TypeError: undefined is not an object (evaluating
  'apiData[0].game_id')

I would like to know why this works when I declare a variable and assign it the same values as the api call returns. But it does not work then I'm assigning the api call to apiData. It can only access apiData[0] which returns {game_id:2} , but cannot access apiData[0].game_id.

Thanks for all the help!

Body:
Simply defined one flag in the state and check whether your data is available or not once you get data change that flag and and load your component element accordingly.

see below solution for your problem statement.

import React, { Component } from 'react';
import axios from 'axios';

class Dashboard extends Component {
     state = {
         loading:true,
         name : 'randomname',
         apiData: {}
};

componentDidMount() {
  axios.get('https://api_url/getdata').then(res => {
        this.setState({apiData:res.data, loading:false});
    });
}

render() {
  const { name, apiData, loading} = this.state;

  //THIS WORKS
  var objTest = [{game_id: 2}]; //This is returned from apical
  console.log(objTest[0].game_id);

  console.log(apiData); //logs the following: [{game_id: 2}]
  console.log(apiData[0]); //logs the following: {game_id: 2}
  console.log(apiData[0].game_id); //Error occurs See error below

  return (
    <div className="wrap">
         {loading ? <div>Loading ...</div> : <div className="wrap">TESTING</div>}
    </div>
  );
}
}

export default Dashboard;


问:
How to avoid N + 1 queries in Firestore?
Is there something similar to the "populate" method in Mongodb and includes in rails where Document Id's that are associated with other documents can be populated instead of me having to iterate through each document and make a separate query.

For instance let's say that I have a group document that has a collection called members. And each document in that collection corresponds to the ID of a User document. Is there any way to populate each one of those documents, without me actually making a separate query to pull the user document for each of those IDs.

答: If you want to update the contents of documents in a collection, you will have to query for each one, iterate them, and update the contents individually.  There is no "update where" function in Firestore like SQL that lets you update multiple documents in a single operation.</p>


问:
Adjacent CSS Collapsible Widgets
I used this tutorial (https://alligator.io/css/collapsible/) to create 2 collapsible widgets. I need the header labels to be adjacent to each other on the same line with the collapsible part takeing up the length of both headers like whats shown in the image. How can this be done?

I've tried using position: absolute; but then one header remains unselectable and the containing border it's surrounded by remains unaffected by its expansion which is a problem.

Also, how would I make it so that if one collapsible widget is open the other is automatically closed?

答:
You need to change several things:

Change your HTML structure.

Check the first radio by default to show the first tab content by default.

In the wrapper element, change display: grid by display: flex and wrap the content

I made a lot of necessary modifications to the CSS so check that out.

body {
  font-family: consolas;
}

*,
*::before,
*::after {
  box-sizing: border-box;
}

input.collapse[type="radio"] {
  display: none;
}

.lbl-toggle {
  cursor: pointer;
  border: solid 1px #FAE042;
  transition: all 0.25s ease-out;
  order: 1;
  display: block;
  padding: .3rem 1rem;
  width: 50%;
  background-color: rgba(250, 224, 66, .2);
  font-weight: bold;
}

.lbl-toggle:hover {
  color: #000;
}

.lbl-toggle:first-of-type {
  border-top-left-radius: 7px;
}

.lbl-toggle:last-of-type {
  border-top-right-radius: 7px;
}

.collapsible-content {
  overflow: hidden;
  width: 100%;
  max-height: 0;
  order: 2;
  padding: 0 1rem;
  background-color: #FAE042;
  border-bottom: 1px solid rgba(250, 224, 66, .45);
  border-bottom-left-radius: 7px;
  border-bottom-right-radius: 7px;
  display: inline-block;
}

.toggle:checked+.lbl-toggle {
  background-color: #FAE042;
}

.toggle:checked+.lbl-toggle+.collapsible-content {
  max-height: 100%;
}

.collapsible-content th.head {
  padding: 6px 4px;
  font-size: small;
}

.collapsible-content td.data {
  padding: 6px 4px;
}

.lbl-toggle::after {
  content: " ";
  display: inline-block;
  border-top: 5px solid transparent;
  border-bottom: 5px solid transparent;
  border-left: 5px solid currentColor;
  vertical-align: middle;
  margin-left: 0.7rem;
  transition: transform 0.2s ease-out;
}

.toggle:checked+.lbl-toggle::after {
  transform: rotate(90deg);
}

.toggle:checked+.lbl-toggle {
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}

.wrapper {
  display: flex;
  flex-wrap: wrap;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <input class="collapse toggle" id="#collapsible1" type="radio" name="collapsibleItem" checked/>
  <label for="#collapsible1" class="lbl-toggle">
        Header 1
        </label>
  <div class="collapsible-content">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed fermentum, sapien et consectetur finibus, elit ex sodales purus, vel pretium libero lectus feugiat erat.</p>
  </div>

  <input class="collapse toggle" id="#collapsible2" type="radio" name="collapsibleItem" />
  <label for="#collapsible2" class="lbl-toggle">
          Header 2
        </label>
  <div class="collapsible-content">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed fermentum, sapien et consectetur finibus, elit ex sodales purus, vel pretium libero lectus feugiat erat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed fermentum, sapien et
      consectetur finibus, elit ex sodales purus, vel pretium libero lectus feugiat erat. </p>
  </div>
</div></code>```

For the second question, you can use radio buttons instead of checkboxes.

```<code><input id="collapsible1" name="collapsibleItem" class="toggle" type="radio">
<input id="collapsible2" name="collapsibleItem" class="toggle" type="radio">
<input id="collapsible3" name="collapsibleItem" class="toggle" type="radio">

input[type='radio'] {
  display: none;
}
</code>```

Notice that all radios have the same name attribute; that's necessary to unmark the current marked radio when you check a new one.

Title: Adjacent CSS Collapsible Widgets

Body:
You need to change several things:

Change your HTML structure.

Check the first radio by default to show the first tab content by default.

In the wrapper element, change display: grid by display: flex and wrap the content

I made a lot of necessary modifications to the CSS so check that out.

body {
  font-family: consolas;
}

*,
*::before,
*::after {
  box-sizing: border-box;
}

input.collapse[type="radio"] {
  display: none;
}

.lbl-toggle {
  cursor: pointer;
  border: solid 1px #FAE042;
  transition: all 0.25s ease-out;
  order: 1;
  display: block;
  padding: .3rem 1rem;
  width: 50%;
  background-color: rgba(250, 224, 66, .2);
  font-weight: bold;
}

.lbl-toggle:hover {
  color: #000;
}

.lbl-toggle:first-of-type {
  border-top-left-radius: 7px;
}

.lbl-toggle:last-of-type {
  border-top-right-radius: 7px;
}

.collapsible-content {
  overflow: hidden;
  width: 100%;
  max-height: 0;
  order: 2;
  padding: 0 1rem;
  background-color: #FAE042;
  border-bottom: 1px solid rgba(250, 224, 66, .45);
  border-bottom-left-radius: 7px;
  border-bottom-right-radius: 7px;
  display: inline-block;
}

.toggle:checked+.lbl-toggle {
  background-color: #FAE042;
}

.toggle:checked+.lbl-toggle+.collapsible-content {
  max-height: 100%;
}

.collapsible-content th.head {
  padding: 6px 4px;
  font-size: small;
}

.collapsible-content td.data {
  padding: 6px 4px;
}

.lbl-toggle::after {
  content: " ";
  display: inline-block;
  border-top: 5px solid transparent;
  border-bottom: 5px solid transparent;
  border-left: 5px solid currentColor;
  vertical-align: middle;
  margin-left: 0.7rem;
  transition: transform 0.2s ease-out;
}

.toggle:checked+.lbl-toggle::after {
  transform: rotate(90deg);
}

.toggle:checked+.lbl-toggle {
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}

.wrapper {
  display: flex;
  flex-wrap: wrap;
}

<div class="wrapper">
  <input class="collapse toggle" id="#collapsible1" type="radio" name="collapsibleItem" checked/>
  <label for="#collapsible1" class="lbl-toggle">
        Header 1
        </label>
  <div class="collapsible-content">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed fermentum, sapien et consectetur finibus, elit ex sodales purus, vel pretium libero lectus feugiat erat.</p>
  </div>

  <input class="collapse toggle" id="#collapsible2" type="radio" name="collapsibleItem" />
  <label for="#collapsible2" class="lbl-toggle">
          Header 2
        </label>
  <div class="collapsible-content">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed fermentum, sapien et consectetur finibus, elit ex sodales purus, vel pretium libero lectus feugiat erat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed fermentum, sapien et
      consectetur finibus, elit ex sodales purus, vel pretium libero lectus feugiat erat. </p>
  </div>
</div>

For the second question, you can use radio buttons instead of checkboxes.

<input id="collapsible1" name="collapsibleItem" class="toggle" type="radio">
<input id="collapsible2" name="collapsibleItem" class="toggle" type="radio">
<input id="collapsible3" name="collapsibleItem" class="toggle" type="radio">

input[type='radio'] {
  display: none;
}

Notice that all radios have the same name attribute; that's necessary to unmark the current marked radio when you check a new one.


问:
Getting Invalid Hook Procedure error after injected dll in windows hook
I am trying to hook into windows globally by injecting a dll.
My code works with python2.7, but sadly fails, when using Python3.7 with the already mentioned error.
Here is an example code:

```<code>user32.SetWindowsHookExA.errcheck = errcheck_bool
user32.SetWindowsHookExA.restype = HHOOK
user32.SetWindowsHookExA.argtypes = (c_int,     # _In_ idHook
                                     HOOKPROC,  # _In_ lpfn
                                     HINSTANCE, # _In_ hMod
                                     DWORD)     # _In_ dwThreadId

user32.CallNextHookEx.restype = LRESULT
user32.CallNextHookEx.argtypes = (HHOOK,  # _In_opt_ hhk
                                  c_int,  # _In_     nCode
                                  WPARAM, # _In_     wParam
                                  LPARAM) # _In_     lParam

user32.GetMessageW.argtypes = (LPMSG, # _Out_    lpMsg
                               HWND,  # _In_opt_ hWnd
                               UINT,  # _In_     wMsgFilterMin
                               UINT)  # _In_     wMsgFilterMax

user32.TranslateMessage.argtypes = (LPMSG,)
user32.DispatchMessageW.argtypes = (LPMSG,)

GetModuleHandle = ctypes.windll.kernel32.GetModuleHandleA
GetModuleHandle.restype = POINTER(c_void_p)

LoadLibrary = ctypes.windll.kernel32.LoadLibraryA
LoadLibrary.restype = HINSTANCE

GetProcAddress = ctypes.windll.kernel32.GetProcAddress
GetProcAddress.restype = HOOKPROC

user32.GetWindowThreadProcessId.restype = DWORD

def pointer_msg_loop():
    lib = LoadLibrary(r'C:\Users\Braun\Documents\BA_Thesis\ba-oliver-braun-logging-tool-code\MessagesDll\x64\Release\Dll.dll')
    handle = GetModuleHandle(r'C:\Users\Braun\Documents\BA_Thesis\ba-oliver-braun-logging-tool-code\MessagesDll\x64\Release\Dll.dll')
    print(lib)
    print(handle)
    procedure = GetProcAddress(handle, "meconnect".encode())
    print(procedure)
    print('correct value procedure')
    tHook = user32.SetWindowsHookExA(WH_GETMESSAGE, procedure, lib, 0)
    time.sleep(30)
    user32.UnhookWindowsHookEx(tHook)
    print(tHook)
    msg = MSG()
    while True:
        bRet = user32.GetMessageW(byref(msg), None, 0, 0)
        if not bRet:
            break
        if bRet == -1:
            raise WinError(get_last_error())
        user32.TranslateMessage(byref(msg))
        user32.DispatchMessageW(byref(msg))

if __name__ == '__main__':
    import time
    import datetime
    import threading
    control_key_pressed = False
    startTime = datetime.datetime.now()
    tmouse = threading.Thread(target=mouse_msg_loop)
    tkeyboard = threading.Thread(target=keyboard_msg_loop)
    ttouch = threading.Thread(target=pointer_msg_loop)
    tmouse.start()
    tkeyboard.start()
    ttouch.start()
    while True:
        try:
            time.sleep(1)
        except KeyboardInterrupt:
            user32.PostThreadMessageW(tmouse.ident, WM_QUIT, 0, 0)
            break
</code>```

DLL:

```<code>// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#pragma data_seg("Shared")
#pragma data_seg()
#pragma comment(linker,"/section:Shared,rws")

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

HHOOK tHook;

extern "C" __declspec(dllexport) LRESULT meconnect(int code, WPARAM wParam, LPARAM lParam) {
    BOOL EnableMouseInPointer = TRUE;
    if (code == HC_ACTION) {
        LPMSG data = (LPMSG)lParam;
        if (data->message == WM_POINTERDOWN) {
            MessageBoxA(NULL, "eee", NULL, 0);
        }
    }
    return(CallNextHookEx(tHook, code, wParam, lParam));
}
</code>```

Some interesting observations: When changing LoadLibraryA to LoadLibraryW even python2.7 fails.
This seems really obvious and i suspect its because of maybe the different string types that both versions enforce? But yeah what can i change to make it work in Python3.7

答:
In Python 3.7, the result of sys.getdefaultencoding() is 'utf-8'. This answer from @jfs metioned that

sys.getdefaultencoding() always runs 'ascii' on all systems of
  Python 2, unless you rewrite it.

This may be why you got it wrong.

use b'' instead of r'', or just use Wide-byte function.

GetProcAddress has no Wide-byte version. Just use GetProcAddress(handle, b'meconnect') as well.

tHook in DLL is not defined, and it will cause undefined behavior in next hook.

You'd better put the message loop before UnhookWindowsHookEx and instead of the sleep method.

You can call SetWindowsHookEx in the DLL. Here is the sample.
DLL:

```<code>// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#include <windows.h>
#include <stdio.h>
#include <string.h>
HHOOK tHook;
HMODULE hinstDLL;
LRESULT CALLBACK meconnect(int code, WPARAM wParam, LPARAM lParam) {
    BOOL EnableMouseInPointer = TRUE;
    if (code == HC_ACTION) {
        LPMSG data = (LPMSG)lParam;
        if (data->message == WM_POINTERDOWN) {
            MessageBoxA(NULL, "eee", NULL, 0);
        }
    }
    return(CallNextHookEx(tHook, code, wParam, lParam));
}
extern "C" __declspec(dllexport) BOOL SetHook()
{
    tHook = SetWindowsHookEx(WH_GETMESSAGE, meconnect, hinstDLL, 0);

    if (tHook == NULL)
        return FALSE;
    else
        return TRUE;
}
extern "C" __declspec(dllexport) BOOL UnHook()
{
    return UnhookWindowsHookEx(tHook);
}

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        hinstDLL = hModule;
        break;
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}
</code>```

python:

```<code>import threading
import ctypes
from ctypes import wintypes
from ctypes import *
import win32api
import win32gui
def pointer_msg_loop():
    lib = cdll.LoadLibrary(r'PATH\DLL.dll')
    print(lib)
    res = lib.SetHook()
    print(res)
    win32gui.PumpMessages()
    res = lib.UnHook()

if __name__ == '__main__':
    ttouch = threading.Thread(target=pointer_msg_loop)
    ttouch.start()
    ttouch.join()
</code>```

Body:
I am trying to hook into windows globally by injecting a dll.
My code works with python2.7, but sadly fails, when using Python3.7 with the already mentioned error.
Here is an example code:

user32.SetWindowsHookExA.errcheck = errcheck_bool
user32.SetWindowsHookExA.restype = HHOOK
user32.SetWindowsHookExA.argtypes = (c_int,     # _In_ idHook
                                     HOOKPROC,  # _In_ lpfn
                                     HINSTANCE, # _In_ hMod
                                     DWORD)     # _In_ dwThreadId

user32.CallNextHookEx.restype = LRESULT
user32.CallNextHookEx.argtypes = (HHOOK,  # _In_opt_ hhk
                                  c_int,  # _In_     nCode
                                  WPARAM, # _In_     wParam
                                  LPARAM) # _In_     lParam

user32.GetMessageW.argtypes = (LPMSG, # _Out_    lpMsg
                               HWND,  # _In_opt_ hWnd
                               UINT,  # _In_     wMsgFilterMin
                               UINT)  # _In_     wMsgFilterMax

user32.TranslateMessage.argtypes = (LPMSG,)
user32.DispatchMessageW.argtypes = (LPMSG,)

GetModuleHandle = ctypes.windll.kernel32.GetModuleHandleA
GetModuleHandle.restype = POINTER(c_void_p)

LoadLibrary = ctypes.windll.kernel32.LoadLibraryA
LoadLibrary.restype = HINSTANCE

GetProcAddress = ctypes.windll.kernel32.GetProcAddress
GetProcAddress.restype = HOOKPROC

user32.GetWindowThreadProcessId.restype = DWORD

def pointer_msg_loop():
    lib = LoadLibrary(r'C:\Users\Braun\Documents\BA_Thesis\ba-oliver-braun-logging-tool-code\MessagesDll\x64\Release\Dll.dll')
    handle = GetModuleHandle(r'C:\Users\Braun\Documents\BA_Thesis\ba-oliver-braun-logging-tool-code\MessagesDll\x64\Release\Dll.dll')
    print(lib)
    print(handle)
    procedure = GetProcAddress(handle, "meconnect".encode())
    print(procedure)
    print('correct value procedure')
    tHook = user32.SetWindowsHookExA(WH_GETMESSAGE, procedure, lib, 0)
    time.sleep(30)
    user32.UnhookWindowsHookEx(tHook)
    print(tHook)
    msg = MSG()
    while True:
        bRet = user32.GetMessageW(byref(msg), None, 0, 0)
        if not bRet:
            break
        if bRet == -1:
            raise WinError(get_last_error())
        user32.TranslateMessage(byref(msg))
        user32.DispatchMessageW(byref(msg))

if __name__ == '__main__':
    import time
    import datetime
    import threading
    control_key_pressed = False
    startTime = datetime.datetime.now()
    tmouse = threading.Thread(target=mouse_msg_loop)
    tkeyboard = threading.Thread(target=keyboard_msg_loop)
    ttouch = threading.Thread(target=pointer_msg_loop)
    tmouse.start()
    tkeyboard.start()
    ttouch.start()
    while True:
        try:
            time.sleep(1)
        except KeyboardInterrupt:
            user32.PostThreadMessageW(tmouse.ident, WM_QUIT, 0, 0)
            break

DLL:

// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#pragma data_seg("Shared")
#pragma data_seg()
#pragma comment(linker,"/section:Shared,rws")

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

HHOOK tHook;

extern "C" __declspec(dllexport) LRESULT meconnect(int code, WPARAM wParam, LPARAM lParam) {
    BOOL EnableMouseInPointer = TRUE;
    if (code == HC_ACTION) {
        LPMSG data = (LPMSG)lParam;
        if (data->message == WM_POINTERDOWN) {
            MessageBoxA(NULL, "eee", NULL, 0);
        }
    }
    return(CallNextHookEx(tHook, code, wParam, lParam));
}

Some interesting observations: When changing LoadLibraryA to LoadLibraryW even python2.7 fails.
This seems really obvious and i suspect its because of maybe the different string types that both versions enforce? But yeah what can i change to make it work in Python3.7

Body:
In Python 3.7, the result of sys.getdefaultencoding() is 'utf-8'. This answer from @jfs metioned that

sys.getdefaultencoding() always runs 'ascii' on all systems of
  Python 2, unless you rewrite it.

This may be why you got it wrong.

use b'' instead of r'', or just use Wide-byte function.

GetProcAddress has no Wide-byte version. Just use GetProcAddress(handle, b'meconnect') as well.

tHook in DLL is not defined, and it will cause undefined behavior in next hook.

You'd better put the message loop before UnhookWindowsHookEx and instead of the sleep method.

You can call SetWindowsHookEx in the DLL. Here is the sample.
DLL:

// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#include <windows.h>
#include <stdio.h>
#include <string.h>
HHOOK tHook;
HMODULE hinstDLL;
LRESULT CALLBACK meconnect(int code, WPARAM wParam, LPARAM lParam) {
    BOOL EnableMouseInPointer = TRUE;
    if (code == HC_ACTION) {
        LPMSG data = (LPMSG)lParam;
        if (data->message == WM_POINTERDOWN) {
            MessageBoxA(NULL, "eee", NULL, 0);
        }
    }
    return(CallNextHookEx(tHook, code, wParam, lParam));
}
extern "C" __declspec(dllexport) BOOL SetHook()
{
    tHook = SetWindowsHookEx(WH_GETMESSAGE, meconnect, hinstDLL, 0);

    if (tHook == NULL)
        return FALSE;
    else
        return TRUE;
}
extern "C" __declspec(dllexport) BOOL UnHook()
{
    return UnhookWindowsHookEx(tHook);
}

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        hinstDLL = hModule;
        break;
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

python:

import threading
import ctypes
from ctypes import wintypes
from ctypes import *
import win32api
import win32gui
def pointer_msg_loop():
    lib = cdll.LoadLibrary(r'PATH\DLL.dll')
    print(lib)
    res = lib.SetHook()
    print(res)
    win32gui.PumpMessages()
    res = lib.UnHook()

if __name__ == '__main__':
    ttouch = threading.Thread(target=pointer_msg_loop)
    ttouch.start()
    ttouch.join()


问:
How can I correctly mock my controllercontext to test ViewResult.ExecuteResult()?
I am attempting to create integration tests to make sure my views do not have any runtime errors in them.   Thus I need to create a test that checks if ViewResult.ExecuteResult() works correctly but it seems I have hit a snag.

I found this site which gave me a starting point, and I have the following code:

```<code>    [TestMethod]
    public void RegisterResultExecutes()
    {
        //arrange
        RequestContext requestContext = new RequestContext(new MockHttpContext(), new RouteData());
        AccountController controller = new AccountController
        {
            FormsService = new MockFormsAuthenticationService(),
            MembershipService = new MockMembershipService(),
            Url = new UrlHelper(requestContext)
        };

        var result = controller.Register();
        var sb = new StringBuilder();
        Mock<HttpResponseBase> response = new Mock<HttpResponseBase>();
        response.Setup(x => x.Write(It.IsAny<string>())).Callback<string>(y =>
        {
            sb.Append(y);
        });
        Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();
        controllerContext.Setup(x => x.HttpContext.Response).Returns(response.Object);

        //act
        result.ExecuteResult(controllerContext.Object);
    }
</code>```

The problem is that when result.ExecuteResult() is called I get the following exception

```<code>System.NullReferenceException: Object reference not set to an instance of an object.

System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
MyApp.Tests.Controllers.AccountControllerTest.RegisterResultExecutes() in C:\Users\KallDrexx\Documents\Projects\MyApp\MyApp.Tests\Controllers\AccountControllerTests.cs: line 297
</code>```

Unfortunately, that stack trace isn't very useful as I'm not sure what it's trying to access that is null.  Does anyone have any suggestions on how I can create a test for ExecuteResult()?

答:
Based on the stack trace, it is something in the ViewResultBase.ExecuteResult method that throws the exception. Using reflector, here is the definition of that method:

```<code>public override void ExecuteResult(ControllerContext context)
{
    if (context == null)
    {
        throw new ArgumentNullException("context");
    }
    if (string.IsNullOrEmpty(this.ViewName))
    {
        this.ViewName = context.RouteData.GetRequiredString("action");
    }
    ViewEngineResult result = null;
    if (this.View == null)
    {
        result = this.FindView(context);
        this.View = result.View;
    }
    TextWriter output = context.HttpContext.Response.Output;
    ViewContext viewContext = new ViewContext(context, this.View, this.ViewData, this.TempData, output);
    this.View.Render(viewContext, output);
    if (result != null)
    {
        result.ViewEngine.ReleaseView(context, this.View);
    }
}
</code>```

Based on that code, an object reference exception could be thrown when the code tries to access the RouteData property from the context (if the name of the view wasn't explicitly given to the return type).

The exception could be thrown by accessing the HttpContext property. I haven't used Moq well enough to know if it can handle the fact that you haven't told it how to mock the HttpContext property, but you have told it how to mock the Response property from the HttpContext property's type, so that's another area that is suspect to me.

All other uses of context in the method are passing it into other methods, which if those were the problem, then the stack trace would have revealed that.

The easiest way to see which of the two I mentioned are the problem, I would write a quick test to pull those properties from your mocks and see which one causes the exception.

ContentLicense: CC BY-SA 3.0

Body:
I am attempting to create integration tests to make sure my views do not have any runtime errors in them.   Thus I need to create a test that checks if ViewResult.ExecuteResult() works correctly but it seems I have hit a snag.

I found this site which gave me a starting point, and I have the following code:

    [TestMethod]
    public void RegisterResultExecutes()
    {
        //arrange
        RequestContext requestContext = new RequestContext(new MockHttpContext(), new RouteData());
        AccountController controller = new AccountController
        {
            FormsService = new MockFormsAuthenticationService(),
            MembershipService = new MockMembershipService(),
            Url = new UrlHelper(requestContext)
        };

        var result = controller.Register();
        var sb = new StringBuilder();
        Mock<HttpResponseBase> response = new Mock<HttpResponseBase>();
        response.Setup(x => x.Write(It.IsAny<string>())).Callback<string>(y =>
        {
            sb.Append(y);
        });
        Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();
        controllerContext.Setup(x => x.HttpContext.Response).Returns(response.Object);

        //act
        result.ExecuteResult(controllerContext.Object);
    }

The problem is that when result.ExecuteResult() is called I get the following exception

System.NullReferenceException: Object reference not set to an instance of an object.

System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
MyApp.Tests.Controllers.AccountControllerTest.RegisterResultExecutes() in C:\Users\KallDrexx\Documents\Projects\MyApp\MyApp.Tests\Controllers\AccountControllerTests.cs: line 297

Unfortunately, that stack trace isn't very useful as I'm not sure what it's trying to access that is null.  Does anyone have any suggestions on how I can create a test for ExecuteResult()?

Body:
Based on the stack trace, it is something in the ViewResultBase.ExecuteResult method that throws the exception. Using reflector, here is the definition of that method:

public override void ExecuteResult(ControllerContext context)
{
    if (context == null)
    {
        throw new ArgumentNullException("context");
    }
    if (string.IsNullOrEmpty(this.ViewName))
    {
        this.ViewName = context.RouteData.GetRequiredString("action");
    }
    ViewEngineResult result = null;
    if (this.View == null)
    {
        result = this.FindView(context);
        this.View = result.View;
    }
    TextWriter output = context.HttpContext.Response.Output;
    ViewContext viewContext = new ViewContext(context, this.View, this.ViewData, this.TempData, output);
    this.View.Render(viewContext, output);
    if (result != null)
    {
        result.ViewEngine.ReleaseView(context, this.View);
    }
}

Based on that code, an object reference exception could be thrown when the code tries to access the RouteData property from the context (if the name of the view wasn't explicitly given to the return type).

The exception could be thrown by accessing the HttpContext property. I haven't used Moq well enough to know if it can handle the fact that you haven't told it how to mock the HttpContext property, but you have told it how to mock the Response property from the HttpContext property's type, so that's another area that is suspect to me.

All other uses of context in the method are passing it into other methods, which if those were the problem, then the stack trace would have revealed that.

The easiest way to see which of the two I mentioned are the problem, I would write a quick test to pull those properties from your mocks and see which one causes the exception.


问:
Unable to swap multiple elements in a list in python
I'm new to python and am trying to make a function that swaps multiple values in a list at once.

```<code>def swap(deck: List[int], start1: int, end1: int, start2: int, end2: int) -> None:

    start1 = start1 % len(deck)
    start2 = start2 % len(deck)

    end1 = end1 % len(deck)
    end2 = end2 % len(deck)

    if start1 < start2:
        deck[start1: end1], deck[start2: end2] = deck[start2: end2], deck[start1: end1]
    else:
        deck[start2: end2], deck[start1: end1] = deck[start1: end1], deck[start2: end2]
</code>```

when deck = [0,1,2,3,4,5,6,7,8,9,10]
swap(deck, -3, 11, 0, 2) should mutate the deck to be [8,9,2,3,4,5,6,7,0,1,10], but I get this instead [2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 10]

I have also tried it with the temp variable method

```<code>    temp = deck[start1: start1]

    deck[start1: start1] = deck[start2: end2]

    deck[start2: end2] = temp
</code>```

but I get the same result... An explanation of why this is happening and how I can fix it is greatly appreciated.

答:
Basically, what you want to do is:

```<code>deck = deck[s2:e2] + deck[e1:s2] + deck[s1:e1]
</code>```

Don't try to use two variables before and after the equal sign =.

Body:
I'm new to python and am trying to make a function that swaps multiple values in a list at once.

def swap(deck: List[int], start1: int, end1: int, start2: int, end2: int) -> None:

    start1 = start1 % len(deck)
    start2 = start2 % len(deck)

    end1 = end1 % len(deck)
    end2 = end2 % len(deck)

    if start1 < start2:
        deck[start1: end1], deck[start2: end2] = deck[start2: end2], deck[start1: end1]
    else:
        deck[start2: end2], deck[start1: end1] = deck[start1: end1], deck[start2: end2]

when deck = [0,1,2,3,4,5,6,7,8,9,10]
swap(deck, -3, 11, 0, 2) should mutate the deck to be [8,9,2,3,4,5,6,7,0,1,10], but I get this instead [2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 10]

I have also tried it with the temp variable method

    temp = deck[start1: start1]

    deck[start1: start1] = deck[start2: end2]

    deck[start2: end2] = temp

but I get the same result... An explanation of why this is happening and how I can fix it is greatly appreciated.

Body:
Basically, what you want to do is:

deck = deck[s2:e2] + deck[e1:s2] + deck[s1:e1]

Don't try to use two variables before and after the equal sign =.


问:
How to open .pdf URL in Safari browser in swift
Here i trying to open URL with .pdf extension in Safari Browser. But code is not working I'm getting nil in URL. But when i tried URL like "www.google.com" it's working fine

Code

```<code>   let cerificateURl = "https://file-examples.com/wp-content/uploads/2017/10/file-sample_150kB.pdf"

    guard let url = URL(string: cerificateURl) else {
      return
    }

   if #available(iOS 10.0, *) {
       UIApplication.shared.open(url, options: [:], completionHandler: nil)
   } else {
      UIApplication.shared.openURL(url)
   }
</code>```

Thanks in Advance

答:
Try This one.</p>

```<code>let cerificateURl = "https://file-examples.com/wp-content/uploads/2017/10/file-sample_150kB.pdf"

if let myURL = URL(string: url) {
    if let data = try? Data(contentsOf: myURL) {
        webView.load(data, mimeType: "application/pdf", characterEncodingName: "", baseURL: myURL
    }
}
</code>```

Body:
Here i trying to open URL with .pdf extension in Safari Browser. But code is not working I'm getting nil in URL. But when i tried URL like "www.google.com" it's working fine

Code

   let cerificateURl = "https://file-examples.com/wp-content/uploads/2017/10/file-sample_150kB.pdf"

    guard let url = URL(string: cerificateURl) else {
      return
    }

   if #available(iOS 10.0, *) {
       UIApplication.shared.open(url, options: [:], completionHandler: nil)
   } else {
      UIApplication.shared.openURL(url)
   }

Thanks in Advance

Body:
Try This one.

let cerificateURl = "https://file-examples.com/wp-content/uploads/2017/10/file-sample_150kB.pdf"

if let myURL = URL(string: url) {
    if let data = try? Data(contentsOf: myURL) {
        webView.load(data, mimeType: "application/pdf", characterEncodingName: "", baseURL: myURL
    }
}


问:
How to convert Unicode string to Cyrillic format
I have this kind of string "%D0%91%D0%B5%D0%B7%D1%8B%D0%BC%D1%8F%D0%BD%D0%BD%D1%8B%D0%B9_67haV9G.jpg" . I need to convert it to "Безымянный_67haV9G.jpg" . Could you please help me with that?  </p>

答:
You can use below to convert Unicode string to Cyrillic:

```<code>decodeURIComponent("YourstringToCyrillic")
</code>```

Body:
You can use below to convert Unicode string to Cyrillic:

decodeURIComponent("YourstringToCyrillic")


问:
Get an input's "checked" state
I have this basic HTML structure:

```<code><fieldset>
    <input/>
    <label></label>
    <div class="toggle_box">
        <div class="switch"></div>
    </div>
</fieldset>
</code>```

I would like this to happen when my input is checked:

```<code><fieldset>
    <input checked="checked" />
    <label></label>
    <div class="toggle_box">
        <div class="switch" state="on"></div>
    </div>
</fieldset>
</code>```

Add state="on" to the switch div. Is there any selector in jquery I can use to get the checked state of that particular input? (there are multiple on a page).

Thanks for your brainstorming!

答:
This works; you'll need to add type="checkbox" to your inputs to make them checkboxes.  (Observe the effect by inspecting the switch divs with Chrome's Dev Tools or Firebug.)

```<code>$('fieldset input[type=checkbox]').change(function() {
    var el=$(this).parent().find('.switch');
    if ($(this).is(':checked')) el.attr('state','on');
    else el.removeAttr('state');
});
</code>```

Title: Get an input's "checked" state

Body:
I have this basic HTML structure:

<fieldset>
    <input/>

</fieldset>

I would like this to happen when my input is checked:

<fieldset>
    <input checked="checked" />

</fieldset>

Add state="on" to the switch div. Is there any selector in jquery I can use to get the checked state of that particular input? (there are multiple on a page).

Thanks for your brainstorming!

Body:
This works; you'll need to add type="checkbox" to your inputs to make them checkboxes.  (Observe the effect by inspecting the switch divs with Chrome's Dev Tools or Firebug.)

$('fieldset input[type=checkbox]').change(function() {
    var el=$(this).parent().find('.switch');
    if ($(this).is(':checked')) el.attr('state','on');
    else el.removeAttr('state');
});


问:
go template - nested templated
I have several go templates. The below examples are oversimplified, but it states my idea correctly. For example, I have

```<code>{{ define "div-block" }}
   <div style="display:block">
         .....
   </div>
{{ end }}
</code>```

Now I want to transfer any other template inside div-block when using it, so that I could put anything inside div. E.g:

```<code>{{ template "div-block" . }}
    {{ template "header" }}
{{ end }}

{{ template "div-block" . }}
    <ul>
       <li>1</li>
    </ul>
{{ end }}
</code>```

Where "header" is some other template.

Which is the the right way to do this with go template? Is it possible to do it with custom function? Is it possible to make custom actions in go template? (actions can have end  statement and therefore the body, while functions are not)

答: define another template outside, and use it inside div-block template </p>

Title: go template - nested templated

Body:
I have several go templates. The below examples are oversimplified, but it states my idea correctly. For example, I have

{{ define "div-block" }}

         .....

{{ end }}

Now I want to transfer any other template inside div-block when using it, so that I could put anything inside div. E.g:

{{ template "div-block" . }}
    {{ template "header" }}
{{ end }}

{{ template "div-block" . }}

1

{{ end }}

Where "header" is some other template.

Which is the the right way to do this with go template? Is it possible to do it with custom function? Is it possible to make custom actions in go template? (actions can have end  statement and therefore the body, while functions are not)


问:
i cannot start docker in windows 10pro 64
Starting "default"...
(default) Check network to re-create if needed...
(default) Windows might ask for the permission to configure a dhcp server. Sometimes, such confirmation window is minimized in the taskbar.
Unable to start the VM: C:\Program Files\Oracle\VirtualBox\VBoxManage.exe startvm default --type headless failed:
VBoxManage.exe: error: Raw-mode is unavailable courtesy of Hyper-V. (VERR_SUPDRV_NO_RAW_MODE_HYPER_V_ROOT)
VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole

Details: 00:00:08.284942 Power up failed (vrc=VERR_SUPDRV_NO_RAW_MODE_HYPER_V_ROOT, rc=E_FAIL (0X80004005))
Looks like something went wrong in step ?Checking status on default?... Press any key to continue...

答:
It is very simple as you think.

1. Copy the command which one you will execute

2. go task manager

3. go more details

4. go file in top left of the window in task manager

5.run new task

6. paste your command in the open box

7. click on dialog box
8.ok
your command will execute and it will ask for restart, restart it.


问:
How to show the variable name on the exception message when the assertion fails using FluentAssertions?
I am trying to create some Assertion classes using the FluentAssertions library. This is the Assertion code:

public AndConstraint<MyTaskAssertions> Work(string because = "", params object[] becauseArgs)
{
    Execute.Assertion
        .BecauseOf(because, becauseArgs)
        .WithExpectation("Expected {context:mytask} to work{reason}, ")
        .Given(() => Subject)
        .ForCondition(x => x.Works)
        .FailWith("but it doesn't");

    return new AndConstraint<MyTaskAssertions>(this);
}
```

<p>And this is my test:</p>

<pre class="lang-cs prettyprint-override"><code>var t = new MyTask {Works=false};
t.Should().Work();
</code>```

Everything works fine, except for the fact that instead of the variable name t, "mytask" is displayed on the exception message:

Expected mytask to work, but it doesn't

I've read the Extensibility page on the Documentation, and I also checked the source code for the built-in assertions, but I am still not sure what exactly I am missing for the exception message to show the actual variable name instead of what is after the "context:" placeholder.

答: You need to mark your method with [CustomAssertion]. See also https://fluentassertions.com/introduction#subject-identification

Body:
I am trying to create some Assertion classes using the FluentAssertions library. This is the Assertion code:

public AndConstraint<MyTaskAssertions> Work(string because = "", params object[] becauseArgs)
{
    Execute.Assertion
        .BecauseOf(because, becauseArgs)
        .WithExpectation("Expected {context:mytask} to work{reason}, ")
        .Given(() => Subject)
        .ForCondition(x => x.Works)
        .FailWith("but it doesn't");

    return new AndConstraint<MyTaskAssertions>(this);
}

And this is my test:

var t = new MyTask {Works=false};
t.Should().Work();

Everything works fine, except for the fact that instead of the variable name t, "mytask" is displayed on the exception message:

Expected mytask to work, but it doesn't

I've read the Extensibility page on the Documentation, and I also checked the source code for the built-in assertions, but I am still not sure what exactly I am missing for the exception message to show the actual variable name instead of what is after the "context:" placeholder.


问:
Prevent form from submitting if form is empty
In my HTML form, I would like to use a button for submitting a form instead of input type submit.
I have got a javascript code to give an error if the email if empty, also to prevent the form from submitting.
However, the code does not seem to work and I get this error: Cannot GET /submit
The weird thing is that the code works here in stackoverflow when you run it!

const email = document.getElementById('email');
const form = document.getElementById('form');
const emailMessage = document.getElementById('email-message');

form.addEventListener('submit', e => {
  if (email.value === '' || email.value === null) {
    emailMessage.innerHTML = 'where is the email';
    e.preventDefault();
  } else {
    return true;
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <form id="form" action="submit">
            <input id="email" type="email" />
            <button type="submit">Go</button>
            <p id="email-message"></p>
          </form></code>```

答:
Why not just use the required attribute? No JS necessary

```<code><input id="email" type="email" required>
</code>```

This will check if the email field is not empty and additionally entered string is a valid email format.

Note that HTML "required" does not work in safari browser whose version less than Safari 10.1 (May 2017)

Edit:
To display a custom message, subscribe to the invalid event

```<code>const email = document.getElementById('email');
email.addEventListener('invalid', function(e){
   if (email.value == '')
     email.setCustomValidity('Where is the email?');
   else if (email.validity.typeMismatch)
     email.setCustomValidity('Email address be invalid!');
});
</code>```

You can learn more about Form Validation at Mozilla

Body:
In my HTML form, I would like to use a button for submitting a form instead of input type submit.
I have got a javascript code to give an error if the email if empty, also to prevent the form from submitting.
However, the code does not seem to work and I get this error: Cannot GET /submit
The weird thing is that the code works here in stackoverflow when you run it!

const email = document.getElementById('email');
const form = document.getElementById('form');
const emailMessage = document.getElementById('email-message');

form.addEventListener('submit', e => {
  if (email.value === '' || email.value === null) {
    emailMessage.innerHTML = 'where is the email';
    e.preventDefault();
  } else {
    return true;
  }
});

  <form id="form" action="submit">
            <input id="email" type="email" />
            <button type="submit">Go</button>

          </form>

Body:
Why not just use the required attribute? No JS necessary

<input id="email" type="email" required>

This will check if the email field is not empty and additionally entered string is a valid email format.

Note that HTML "required" does not work in safari browser whose version less than Safari 10.1 (May 2017)

Edit:
To display a custom message, subscribe to the invalid event

const email = document.getElementById('email');
email.addEventListener('invalid', function(e){
   if (email.value == '')
     email.setCustomValidity('Where is the email?');
   else if (email.validity.typeMismatch)
     email.setCustomValidity('Email address be invalid!');
});

You can learn more about Form Validation at Mozilla


问:
How to implement shadow in Android?
My UX designer has provided me with an elegant design and exported it as an Xd file. For shadows of some elements, Xd gives me below information:

```<code>Shadow color: #101F400D
X: 0dp
Y: 3dp
Blur: 10dp
</code>```

How can I create this layout in android with the above information?

Note: elevation is not what I want!

答:
You have to use a nine patch image to achieve this. Create a nine patch image using any tool like this - https://inloop.github.io/shadow4android/

Then, set this image as background to your view.

Title: How to implement shadow in Android?

Body:
My UX designer has provided me with an elegant design and exported it as an Xd file. For shadows of some elements, Xd gives me below information:

Shadow color: #101F400D
X: 0dp
Y: 3dp
Blur: 10dp

How can I create this layout in android with the above information?

Note: elevation is not what I want!


问:
How do I log from my Python Spark script
I have a Python Spark program which I run with spark-submit. I want to put logging statements in it.

```<code>logging.info("This is an informative message.")
logging.debug("This is a debug message.")
</code>```

I want to use the same logger that Spark is using so that the log messages come out in the same format and the level is controlled by the same configuration files. How do I do this?

I've tried putting the logging statements in the code and starting out with a logging.getLogger(). In both cases I see Spark's log messages but not mine. I've been looking at the Python logging documentation, but haven't been able to figure it out from there.

Not sure if this is something specific to scripts submitted to Spark or just me not understanding how logging works.

答:
```<code>import logging

# Logger

logging.basicConfig(format='%(asctime)s %(filename)s %(funcName)s %(lineno)d %(message)s')
logger = logging.getLogger('driver_logger')
logger.setLevel(logging.DEBUG)
</code>```

Simplest way to log from pyspark !

Body:
I have a Python Spark program which I run with spark-submit. I want to put logging statements in it.

logging.info("This is an informative message.")
logging.debug("This is a debug message.")

I want to use the same logger that Spark is using so that the log messages come out in the same format and the level is controlled by the same configuration files. How do I do this?

I've tried putting the logging statements in the code and starting out with a logging.getLogger(). In both cases I see Spark's log messages but not mine. I've been looking at the Python logging documentation, but haven't been able to figure it out from there.

Not sure if this is something specific to scripts submitted to Spark or just me not understanding how logging works.

Body:
import logging

# Logger

logging.basicConfig(format='%(asctime)s %(filename)s %(funcName)s %(lineno)d %(message)s')
logger = logging.getLogger('driver_logger')
logger.setLevel(logging.DEBUG)

Simplest way to log from pyspark !


问:
How to combine 2 list into pairs of nested list?
So, I have 2 lists:

```<code>list1 = [1,2,3,4,5]
list2= [6,7,8,9,10]
</code>```

The desired output:

```<code>newlist = [[1,6],[2,7],[3,8],[4,9],[5,10]]
</code>```

How to do that in Python?

答:
Use zip, but output is list of tuples, so added map by list:

```<code>a = list(map(list, zip(list1, list2)))
print (a)
[[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]
</code>```

Or use list comprehension:

```<code>a = [list(x) for x in zip(list1, list2)]
</code>```

Body:
So, I have 2 lists:

list1 = [1,2,3,4,5]
list2= [6,7,8,9,10]

The desired output:

newlist = [[1,6],[2,7],[3,8],[4,9],[5,10]]

How to do that in Python?

Body:
Use zip, but output is list of tuples, so added map by list:

a = list(map(list, zip(list1, list2)))
print (a)
[[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]

Or use list comprehension:

a = [list(x) for x in zip(list1, list2)]


问:
Spring boot Rest API Request Body (POST)
Request Body has one parameter such as int data. Where as if i pass extra parameter which is not there in the class it does not throw an error.
Why its able to consume the data which is not part of request body.</p>

答:
Having used RESTful APIs from numerous vendors over the years, let me give you a "users" perspective.

A lot of times documentation is simply bad or out of date. Maybe a parameter name changed, maybe you enforce exact casing on the property names, maybe you have used the wrong font in your documentation .

So by default , REST API doesn't check for the extra attributes not presents in request body; otherwise checks whether the supplied attributes is present or not.
if you want not to deserialise the property which is not present; you can add validations as follows :

```<code>import java.io.Serializable;
import javax.validation.constraints.NotBlank;
public class DemoDto implements Serializable{

    private static final long serialVersionUID = 1L;

    private int id;

    @NotBlank(message = "name can't be empty.")
    private String name;

    //getters & setters
}
</code>```

Controller :

```<code>import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @PostMapping("/test")
    public ResponseEntity<DemoDto> test(@RequestBody  @Valid DemoDto demoDto){
        return ResponseEntity.ok(demoDto);
    }
}
</code>```

Body:
Having used RESTful APIs from numerous vendors over the years, let me give you a "users" perspective.

A lot of times documentation is simply bad or out of date. Maybe a parameter name changed, maybe you enforce exact casing on the property names, maybe you have used the wrong font in your documentation .

So by default , REST API doesn't check for the extra attributes not presents in request body; otherwise checks whether the supplied attributes is present or not.
if you want not to deserialise the property which is not present; you can add validations as follows :

import java.io.Serializable;
import javax.validation.constraints.NotBlank;
public class DemoDto implements Serializable{

    private static final long serialVersionUID = 1L;

    private int id;

    @NotBlank(message = "name can't be empty.")
    private String name;

    //getters & setters
}

Controller :

import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @PostMapping("/test")
    public ResponseEntity<DemoDto> test(@RequestBody  @Valid DemoDto demoDto){
        return ResponseEntity.ok(demoDto);
    }
}


问:
How to store the result of a multiplication table inside a list in python?
I tried the below code but it's not working, please help</p>

```<code>def table(n):
for i in range(1,11):
    print(n*i)
n = int(input("Enter the Number\n"))
a = []
a.append(table(n))
print(a)
</code>```

答:
table(n) doesn't return anything. To return you can use return or yield.

Using return.

```<code>def table(n,lst=[]):
    for i in range(1,11):
        lst=lst+[n*i]
    return lst
n = int(input("Enter the Number\n"))
a=table(n)
</code>```

Using yield.

```<code>def table(n):
    for i in range(1,11):
        yield n*i
n=int(input())
a=list(table(table(n))
</code>```

Body:
I tried the below code but it's not working, please help

def table(n):
for i in range(1,11):
    print(n*i)
n = int(input("Enter the Number\n"))
a = []
a.append(table(n))
print(a)

Body:
table(n) doesn't return anything. To return you can use return or yield.

Using return.

def table(n,lst=[]):
    for i in range(1,11):
        lst=lst+[n*i]
    return lst
n = int(input("Enter the Number\n"))
a=table(n)

Using yield.

def table(n):
    for i in range(1,11):
        yield n*i
n=int(input())
a=list(table(table(n))


问:
get variables substituted when I cat a file
Is it possible, in a clean way to get the variable values when I cat a file, instead of the variable names, as written in the file. It's hard to explain, but here goes a simple example:

```<code>$ cat <<EOF
$HOME
EOF
/home/myself
</code>```

cat returns /home/myself because it is already expanded by the shell.

```<code>$ echo \$HOME >/tmp/home
$ cat /tmp/home
$HOME
</code>```

cat simply reads the file, I want $HOME to be expanded here somehow by cat, because the file will contain variable names (not like HOME=/home/myself)

My question is if this is possible somehow, otherwise I will have to write some dirty code.

EDIT: they are big xml files containing

```<code><checkbox active="$value">
</code>```

true or false

答:
cat copies its inputs unchanged to its outputs - at least in its original (1st Edition UNIX) form.  It didn't have any options to start with.  Then BSD added a bunch, and the original UNIX team objected: 'cat came back from Berkeley waving flags' (see: 1 - passim).  It should not be used to edit files - that is not its purpose. (I found a reference to the article in the BSD (Mac OS X) man page for cat:  Rob Pike, "UNIX Style, or cat -v Considered Harmful", USENIX Summer Conference Proceedings, 1983.  See also http://quotes.cat-v.org/programming/)

So, you need something other than cat to do the job.  I'd recommend Perl or Python; either can do it pretty easily.  Alternatively, consider sed, or perhaps awk.

```<code>#!/usr/bin/env perl
use strict;
use warnings;
while (<>)
{
    foreach my $key (keys %ENV)
    {
        s/\$$key\b/$ENV{$key}/g;  # $envvar
        s/\${$key}/$ENV{$key}/g;  # ${envvar}
    }
    print;
}
</code>```

This loops through the input line, looking for each environment variable in turn.  The alternative mechanism is to look for possible variables and do the relevant substitution.  This turns out to be a little tricky, but doable:

```<code>#!/usr/bin/env perl
use strict;
use warnings;
while (<>)
{
    while (m/\$((\w+))/ || m/\$({(\w+)})/)
    {
        my $key = $2;
        my $var = $1;
        s/\$$var/$ENV{$key}/g if defined $ENV{$key};
    }
    print;
}
</code>```

When I included the literal $ in the captures, the substitute operation did not work correctly.

Body:
Is it possible, in a clean way to get the variable values when I cat a file, instead of the variable names, as written in the file. It's hard to explain, but here goes a simple example:

$ cat <<EOF
$HOME
EOF
/home/myself

cat returns /home/myself because it is already expanded by the shell.

$ echo \$HOME >/tmp/home
$ cat /tmp/home
$HOME

cat simply reads the file, I want $HOME to be expanded here somehow by cat, because the file will contain variable names (not like HOME=/home/myself)

My question is if this is possible somehow, otherwise I will have to write some dirty code.

EDIT: they are big xml files containing

<checkbox active="$value">

true or false

Body:
cat copies its inputs unchanged to its outputs - at least in its original (1st Edition UNIX) form.  It didn't have any options to start with.  Then BSD added a bunch, and the original UNIX team objected: 'cat came back from Berkeley waving flags' (see: 1 - passim).  It should not be used to edit files - that is not its purpose. (I found a reference to the article in the BSD (Mac OS X) man page for cat:  Rob Pike, "UNIX Style, or cat -v Considered Harmful", USENIX Summer Conference Proceedings, 1983.  See also http://quotes.cat-v.org/programming/)

So, you need something other than cat to do the job.  I'd recommend Perl or Python; either can do it pretty easily.  Alternatively, consider sed, or perhaps awk.

#!/usr/bin/env perl
use strict;
use warnings;
while (<>)
{
    foreach my $key (keys %ENV)
    {
        s/\$$key\b/$ENV{$key}/g;  # $envvar
        s/\${$key}/$ENV{$key}/g;  # ${envvar}
    }
    print;
}

This loops through the input line, looking for each environment variable in turn.  The alternative mechanism is to look for possible variables and do the relevant substitution.  This turns out to be a little tricky, but doable:

#!/usr/bin/env perl
use strict;
use warnings;
while (<>)
{
    while (m/\$((\w+))/ || m/\$({(\w+)})/)
    {
        my $key = $2;
        my $var = $1;
        s/\$$var/$ENV{$key}/g if defined $ENV{$key};
    }
    print;
}

When I included the literal $ in the captures, the substitute operation did not work correctly.


问:
How to adapt to a kubernetes path change in Python Flask routes
I have a Python Flask app I've deployed on IBM Kubernetes Service. My deployment YAML specifies path: /, which is handled in my code with @app.route('/'). That works fine. I then attempted to move the app by changing path: / to path: /foo in my deployment YAML. I was expecting the request coming into my app to still come in as /, but it's coming in as /foo. Ultimately what I'm trying to do is to be flexible in the deployment of the app without having the change source code. I don't see a way in either Kubernetes or Flask to create this level of indirection. Am I missing something?

Original YAML:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: my-ingress
spec:
  tls:
  - hosts:
      - my....us-east.containers.appdomain.cloud
    secretName: my...
  rules:
  - host: my....us-east.containers.appdomain.cloud
    http:
      paths:
       - path: /
         backend:
           serviceName: my-service
           servicePort: 5000
</code>```

答:
Need to check the content of your ingress yaml definition.

Here's an example yaml definition with rewrites

```<code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
  name: rewrite
  namespace: default
spec:
  rules:
  - host: rewrite.bar.com
    http:
      paths:
      - backend:
          serviceName: http-svc
          servicePort: 80
        path: /something(/|$)(.*)
</code>```

For example, the ingress definition above will result in the following rewrites:

```<code>rewrite.bar.com/something rewrites to rewrite.bar.com/
rewrite.bar.com/something/ rewrites to rewrite.bar.com/
rewrite.bar.com/something/new rewrites to rewrite.bar.com/new
</code>```

You can check Nginx Ingress controller Rewrite annotations here. You can also customize Ingress routing with annotations on IBM Cloud following the documentation here

Body:
I have a Python Flask app I've deployed on IBM Kubernetes Service. My deployment YAML specifies path: /, which is handled in my code with @app.route('/'). That works fine. I then attempted to move the app by changing path: / to path: /foo in my deployment YAML. I was expecting the request coming into my app to still come in as /, but it's coming in as /foo. Ultimately what I'm trying to do is to be flexible in the deployment of the app without having the change source code. I don't see a way in either Kubernetes or Flask to create this level of indirection. Am I missing something?

Original YAML:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: my-ingress
spec:
  tls:
  - hosts:
      - my....us-east.containers.appdomain.cloud
    secretName: my...
  rules:
  - host: my....us-east.containers.appdomain.cloud
    http:
      paths:
       - path: /
         backend:
           serviceName: my-service
           servicePort: 5000

Body:
Need to check the content of your ingress yaml definition.

Here's an example yaml definition with rewrites

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
  name: rewrite
  namespace: default
spec:
  rules:
  - host: rewrite.bar.com
    http:
      paths:
      - backend:
          serviceName: http-svc
          servicePort: 80
        path: /something(/|$)(.*)

For example, the ingress definition above will result in the following rewrites:

rewrite.bar.com/something rewrites to rewrite.bar.com/
rewrite.bar.com/something/ rewrites to rewrite.bar.com/
rewrite.bar.com/something/new rewrites to rewrite.bar.com/new

You can check Nginx Ingress controller Rewrite annotations here. You can also customize Ingress routing with annotations on IBM Cloud following the documentation here


问:
How to merge two arrays of objects in Laravel controller?
I have these function to call to sets of data which is using DB query for Data A and CURL for Data B.

Right now I managed to display the output but somehow Data A cannot merge into Data B. My code as below.

Namespace :

```<code>use \stdClass;
</code>```

Code :

```<code>public function find($user = null) {
    if($user)
    {
        // Data A
        $sql            = "SELECT * FROM TABLE WHERE ID = '".$user."' ";
        $arr            = DB::connection('mysql')->select($sql);
        $resultData     = new \stdClass();

        foreach ($arr as $key => $value)
        {
            $resultData->$key = $value; // Extract Data A table
        }

        // Data B
        $url    = "http://localhost/data/curl.php?value=".$user;
        $ch     = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL,$url);
        $result = curl_exec($ch);
        curl_close($ch);
        $row    = json_decode($result, true);

        foreach ($row as $key => $value)
        {
            $resultData->$key = $value; // Extract Data B
        }

        dd($resultData);
        return true;
    }
    return false;
}
</code>```

My goal is to merge these two sets of data (A & B) into one.

What I get right now is like this in my browser if I display output separately. When I combined it, it only show Data B :

Data A

```<code>{#310
  +"0": {#213
    +"id": "1"
    +"name": "MIKE"
    +"acc_no": "AAA001"
    +"email": "mike@col.com"
  }
}
</code>```

Data B

```<code>{#310
  +"0": "CLERK"
  +"TITLE": "CLERK"
  +"1": "Clerk, IT Department"
  +"POSITION": "Clerk, IT Department"
  +"2": "Rozaimi Bin Zamahri"
  +"SECTION": "Office"
}
</code>```

Appreciate if someone can help me. Thanks.

答:
Try this:-

```<code>    $data1=(object)['a','b'];
    $data2=(object)['c','d'];
    $result = (object) array_merge(
        (array) $data1, (array) $data2);

    print_r($result);
</code>```

Body:
I have these function to call to sets of data which is using DB query for Data A and CURL for Data B.

Right now I managed to display the output but somehow Data A cannot merge into Data B. My code as below.

Namespace :

use \stdClass;

Code :

public function find($user = null) {
    if($user)
    {
        // Data A
        $sql            = "SELECT * FROM TABLE WHERE ID = '".$user."' ";
        $arr            = DB::connection('mysql')->select($sql);
        $resultData     = new \stdClass();

        foreach ($arr as $key => $value)
        {
            $resultData->$key = $value; // Extract Data A table
        }

        // Data B
        $url    = "http://localhost/data/curl.php?value=".$user;
        $ch     = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL,$url);
        $result = curl_exec($ch);
        curl_close($ch);
        $row    = json_decode($result, true);

        foreach ($row as $key => $value)
        {
            $resultData->$key = $value; // Extract Data B
        }

        dd($resultData);
        return true;
    }
    return false;
}

My goal is to merge these two sets of data (A & B) into one.

What I get right now is like this in my browser if I display output separately. When I combined it, it only show Data B :

Data A

{#310
  +"0": {#213
    +"id": "1"
    +"name": "MIKE"
    +"acc_no": "AAA001"
    +"email": "mike@col.com"
  }
}

Data B

{#310
  +"0": "CLERK"
  +"TITLE": "CLERK"
  +"1": "Clerk, IT Department"
  +"POSITION": "Clerk, IT Department"
  +"2": "Rozaimi Bin Zamahri"
  +"SECTION": "Office"
}

Appreciate if someone can help me. Thanks.

Body:
Try this:-

    $data1=(object)['a','b'];
    $data2=(object)['c','d'];
    $result = (object) array_merge(
        (array) $data1, (array) $data2);

    print_r($result);


问:
Node js Rest API not working - Shared Hosting Server - Plesk
Node js Rest API not working in the prod server. it is locally working fine.

server.js

```<code>var app = require('./app');
var http = require('http');
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
function normalizePort(val) {
    var port = parseInt(val, 10);
    if (isNaN(port)) {
        return val;
    }
    if (port >= 0) {
        return port;
    }
    return false;
}
function onError(error) {
    if (error.syscall !== 'listen') {
        throw error;
    }
    var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;
    switch (error.code) {
        case 'EACCES':
            console.error(bind + ' requires elevated privileges');
            process.exit(1);
            break;
        case 'EADDRINUSE':
            console.error(bind + ' is already in use');
            process.exit(1);
            break;
        default:
            throw error;
    }
}
function onListening() {
    var addr = server.address();
    var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
    console.log('Listening on ' + bind);
}
</code>```

app.js

```<code>var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json())
var cors = require('cors');
app.use(cors());
const db = require('./app/config/db.config.js');
const Role = db.role;

const auth = require('./app/router/auth.routes');
app.get('/', (req, res) => { res.send('Hey app.js!') });
app.use('/api/auth',auth);

module.exports = app;
</code>```

auth.routes.js

```<code>const router = require("express").Router();
const verifySignUp = require('./verifySignUp');
const authJwt = require('./verifyJwtToken');
const controller = require('../controller/auth.controller');

router.get('/', (req, res) => { res.send('Hey this auth.routes.js!') });
router.post('/signup', [verifySignUp.checkDuplicateUserNameOrEmail], controller.signup);
router.post('/signin', controller.signin);

module.exports = router;
</code>```

auth.controller.js

```<code>const db = require('../config/db.config.js');
const config = require('../config/config.js');
const User = db.user;
const Role = db.role;

const Op = db.Sequelize.Op;

var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');

exports.signup = (req, res) => {
    // Save User to Database
    console.log("Processing func -> SignUp");

    User.create({
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        userName: req.body.userName,
        email: req.body.email,
        passWord: bcrypt.hashSync(req.body.passWord, 8),
        phone: req.body.phone
    }).then(user => {
        Role.findAll({
            where: {
                name: {
                    [Op.or]: req.body.roles
                }
            }
        }).then(roles => {
            user.setRoles(roles).then(() => {
                res.send({ data: "User registered successfully!" });
            });
        }).catch(err => {
            res.status(500).send("Error -> " + err);
        });
    }).catch(err => {
        res.status(500).send("Fail! Error -> " + err);
    })
}

exports.signin = (req, res) => {
    console.log("Sign-In");

    User.findOne({
        where: {
            userName: req.body.userName
        }
    }).then(user => {
        if (!user) {
            return res.status(404).send('User Not Found.');
        }

        var passwordIsValid = bcrypt.compareSync(req.body.passWord, user.passWord);
        if (!passwordIsValid) {
            return res.status(401).send({ auth: false, accessToken: null, reason: "Invalid Password!" });
        }

        var token = jwt.sign({ id: user.id }, config.secret, {
            expiresIn: 86400 // expires in 24 hours
        });
        var authoritie = [];
        user.getRoles().then(roles => {
            for (let i = 0; i < roles.length; i++) {
                authoritie.push(roles[i].name.toUpperCase())
            }
            res.status(200).send({
                auth: true,
                accessToken: token,
                userId: user.id,
                userName: user.userName,
                authorities: authoritie
            });
        }
        )

    }).catch(err => {
        res.status(500).send('Error -> ' + err);
    });
}
</code>```

Get: http://api.**********.xyz/ is working in local and prod server

get: http://api.*******.xyz/api/auth/ is working in local and prod server

Post: http://api.*******.xyz/api/auth/signin is working in local and not working in prod server (Plesk server). All post and put methods not working in prod server but locally working fine

答:
In your signup post request, you are using middleware as array, Please remove the third parenthesis and try again.

Your signup route should be,

```<code>router.post('/signup', verifySignUp.checkDuplicateUserNameOrEmail, controller.signup);
</code>```

Body:
Node js Rest API not working in the prod server. it is locally working fine.

server.js

var app = require('./app');
var http = require('http');
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
function normalizePort(val) {
    var port = parseInt(val, 10);
    if (isNaN(port)) {
        return val;
    }
    if (port >= 0) {
        return port;
    }
    return false;
}
function onError(error) {
    if (error.syscall !== 'listen') {
        throw error;
    }
    var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;
    switch (error.code) {
        case 'EACCES':
            console.error(bind + ' requires elevated privileges');
            process.exit(1);
            break;
        case 'EADDRINUSE':
            console.error(bind + ' is already in use');
            process.exit(1);
            break;
        default:
            throw error;
    }
}
function onListening() {
    var addr = server.address();
    var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
    console.log('Listening on ' + bind);
}

app.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json())
var cors = require('cors');
app.use(cors());
const db = require('./app/config/db.config.js');
const Role = db.role;

const auth = require('./app/router/auth.routes');
app.get('/', (req, res) => { res.send('Hey app.js!') });
app.use('/api/auth',auth);

module.exports = app;

auth.routes.js

const router = require("express").Router();
const verifySignUp = require('./verifySignUp');
const authJwt = require('./verifyJwtToken');
const controller = require('../controller/auth.controller');

router.get('/', (req, res) => { res.send('Hey this auth.routes.js!') });
router.post('/signup', [verifySignUp.checkDuplicateUserNameOrEmail], controller.signup);
router.post('/signin', controller.signin);

module.exports = router;

auth.controller.js

const db = require('../config/db.config.js');
const config = require('../config/config.js');
const User = db.user;
const Role = db.role;

const Op = db.Sequelize.Op;

var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');

exports.signup = (req, res) => {
    // Save User to Database
    console.log("Processing func -> SignUp");

    User.create({
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        userName: req.body.userName,
        email: req.body.email,
        passWord: bcrypt.hashSync(req.body.passWord, 8),
        phone: req.body.phone
    }).then(user => {
        Role.findAll({
            where: {
                name: {
                    [Op.or]: req.body.roles
                }
            }
        }).then(roles => {
            user.setRoles(roles).then(() => {
                res.send({ data: "User registered successfully!" });
            });
        }).catch(err => {
            res.status(500).send("Error -> " + err);
        });
    }).catch(err => {
        res.status(500).send("Fail! Error -> " + err);
    })
}

exports.signin = (req, res) => {
    console.log("Sign-In");

    User.findOne({
        where: {
            userName: req.body.userName
        }
    }).then(user => {
        if (!user) {
            return res.status(404).send('User Not Found.');
        }

        var passwordIsValid = bcrypt.compareSync(req.body.passWord, user.passWord);
        if (!passwordIsValid) {
            return res.status(401).send({ auth: false, accessToken: null, reason: "Invalid Password!" });
        }

        var token = jwt.sign({ id: user.id }, config.secret, {
            expiresIn: 86400 // expires in 24 hours
        });
        var authoritie = [];
        user.getRoles().then(roles => {
            for (let i = 0; i < roles.length; i++) {
                authoritie.push(roles[i].name.toUpperCase())
            }
            res.status(200).send({
                auth: true,
                accessToken: token,
                userId: user.id,
                userName: user.userName,
                authorities: authoritie
            });
        }
        )

    }).catch(err => {
        res.status(500).send('Error -> ' + err);
    });
}

Get: http://api.**********.xyz/ is working in local and prod server

get: http://api.*******.xyz/api/auth/ is working in local and prod server

Post: http://api.*******.xyz/api/auth/signin is working in local and not working in prod server (Plesk server). All post and put methods not working in prod server but locally working fine

Body:
In your signup post request, you are using middleware as array, Please remove the third parenthesis and try again.

Your signup route should be,

router.post('/signup', verifySignUp.checkDuplicateUserNameOrEmail, controller.signup);


问:
How can I use dowloaded weight and cfg files with cvlib?
How can I use pre-downloaded .weight and .cfg files instead of downloading them again every time I run an object detection code, using cvlib?</p>

答:
The pretrained weights and config files will be downloaded only once when you run the script for the first time. Next time it won't download again if the files already exist in the path.

```<code>if not os.path.exists(config_file_abs_path):
    download_file(url=cfg_url, file_name=config_file_name, dest_dir=dest_dir)

if not os.path.exists(weights_file_abs_path):
    download_file(url=weights_url, file_name=weights_file_name, dest_dir=dest_dir)
</code>```

Checkout the complete implementation here.

Body:
The pretrained weights and config files will be downloaded only once when you run the script for the first time. Next time it won't download again if the files already exist in the path.

if not os.path.exists(config_file_abs_path):
    download_file(url=cfg_url, file_name=config_file_name, dest_dir=dest_dir)

if not os.path.exists(weights_file_abs_path):
    download_file(url=weights_url, file_name=weights_file_name, dest_dir=dest_dir)

Checkout the complete implementation here.


问:
How to display radio buttons as

I want to display my radio buttons as  so that i can give style sheet and make div clickable.

here are my radio buttons.

and I want to show them like this.

div as radio

This is what I have tried but did not work.

HTML

```<code><div class="radio-toolbar">
    <table>
        <tr>
            <td><input type="radio" id="radioone" name="product" value="first">
                <label for="radioone">50</label></td>

            <td><input type="radio" id="radiotwo" name="product" value="second">
                <label for="radiotwo">100</label></td>

            <td><input type="radio" id="radiothree" name="product" value="third">
                <label for="radiothree">500</label></td>
</div>
</code>```

CSS

```<code>.radio-toolbar input[type='radio']:focus + label {
  border: 2px thin blue;
}
.radio-toolbar input[type='radio']:checked + label {
  background-color: #86b1f7;
  border-color: #4c4;
  color: white;
}
</code>```

So how can I achive this
Small help will be appreciated.
Thanks in advance :)

答:
I had do this before.and I have the code preperd.I hope It will be useful for you.

.switch-field {
    display: flex;
    overflow: hidden;
    direction: ltr;
    float: right;
    text-align:right;
}

.switch-field input {
    position: absolute !important;
    clip: rect(0, 0, 0, 0);
    height: 1px;
    width: 1px;
    border: 0;
    overflow: hidden;
}

.switch-field label {
    /*width: 33.33%;*/
    background-color: transparent;
    color: #666666;
    font-size: 14px;
    line-height: 1;
    text-align: center;
    padding: 10px 12px;
    margin-left: 0px;
    /*margin-right: -1px;*/
    border: 1px solid #ddd;
    transition: all 0.1s ease-in-out;
}

.switch-field label:hover {
    cursor: pointer;
}

.switch-field input:checked + label {
    background-color: #F4F5F9;
    box-shadow: none;
    border-color: #3E7DE7;
    color: #3E7DE7;
}

.switch-field label:first-of-type {
    border-radius: 2px 0px 0px 2px;

}

.switch-field label:last-of-type {
    border-radius: 0px 2px 2px 0px;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="switch-field">
  <input class="uk-radio" id="radio-six" type="radio" value="admin" name="user_type" checked>
  <label for="radio-six">admin</label>
   <input class="uk-radio" id="radio-seven" type="radio" value="user" name="user_type" >
   <label for="radio-seven">user</label>
</div></code>```

Title: How to display radio buttons as <div>

Body:
I want to display my radio buttons as  so that i can give style sheet and make div clickable.

here are my radio buttons.

and I want to show them like this.

div as radio

This is what I have tried but did not work.

HTML

            <input type="radio" id="radioone" name="product" value="first">
                50

            <input type="radio" id="radiotwo" name="product" value="second">
                100

            <input type="radio" id="radiothree" name="product" value="third">
                500

CSS

.radio-toolbar input[type='radio']:focus + label {
  border: 2px thin blue;
}
.radio-toolbar input[type='radio']:checked + label {
  background-color: #86b1f7;
  border-color: #4c4;
  color: white;
}

So how can I achive this
Small help will be appreciated.
Thanks in advance :)

Body:
I had do this before.and I have the code preperd.I hope It will be useful for you.

.switch-field {
    display: flex;
    overflow: hidden;
    direction: ltr;
    float: right;
    text-align:right;
}

.switch-field input {
    position: absolute !important;
    clip: rect(0, 0, 0, 0);
    height: 1px;
    width: 1px;
    border: 0;
    overflow: hidden;
}

.switch-field label {
    /*width: 33.33%;*/
    background-color: transparent;
    color: #666666;
    font-size: 14px;
    line-height: 1;
    text-align: center;
    padding: 10px 12px;
    margin-left: 0px;
    /*margin-right: -1px;*/
    border: 1px solid #ddd;
    transition: all 0.1s ease-in-out;
}

.switch-field label:hover {
    cursor: pointer;
}

.switch-field input:checked + label {
    background-color: #F4F5F9;
    box-shadow: none;
    border-color: #3E7DE7;
    color: #3E7DE7;
}

.switch-field label:first-of-type {
    border-radius: 2px 0px 0px 2px;

}

.switch-field label:last-of-type {
    border-radius: 0px 2px 2px 0px;

}

<div class="switch-field">
  <input class="uk-radio" id="radio-six" type="radio" value="admin" name="user_type" checked>
  <label for="radio-six">admin</label>
   <input class="uk-radio" id="radio-seven" type="radio" value="user" name="user_type" >
   <label for="radio-seven">user</label>
</div>


问:
Can we assign a variable for looping to a value inside the loop in Java?
I would like to assign a certain value to an iteration variable inside a for loop in Java.

```<code>List<Integer> values = Arrays.asList(1,2,4,16,32,64,128);
for (Integer value: values) {
   value = value / 2;  // local value
}
</code>```

Is this assignment working in java?

答:
No you can't and also its not recommended however in your case

```<code>List<Integer> values = Arrays.asList(1,2,4,16,32,64,128);
    for (Integer value: values) {
       value = value / 2;  // local value even its modify it will not affect in collection so you will not get an error.
    }
</code>```

Java is having value type and reference type. so if you are modifying anything inside a foreach loop and its value type it will work and its local value so it will not modify a collection, but if its reference type you will get an error.

In for-each loop, we can’t modify collection, it will throw a ConcurrentModificationException
Modifying a collection simply means removing an element or changing content of an item stored in the collection.

If you want to modify a collection use iterator

if you just need traversing use foreach

for more please visit here

Body:
I would like to assign a certain value to an iteration variable inside a for loop in Java.

List<Integer> values = Arrays.asList(1,2,4,16,32,64,128);
for (Integer value: values) {
   value = value / 2;  // local value
}

Is this assignment working in java?

Body:
No you can't and also its not recommended however in your case

List<Integer> values = Arrays.asList(1,2,4,16,32,64,128);
    for (Integer value: values) {
       value = value / 2;  // local value even its modify it will not affect in collection so you will not get an error.
    }

Java is having value type and reference type. so if you are modifying anything inside a foreach loop and its value type it will work and its local value so it will not modify a collection, but if its reference type you will get an error.

In for-each loop, we can’t modify collection, it will throw a ConcurrentModificationException
Modifying a collection simply means removing an element or changing content of an item stored in the collection.

If you want to modify a collection use iterator

if you just need traversing use foreach

for more please visit here


问:
How do you handle checks to see if a user changed something in a dialog
Talking .NET WinForms here:

If you have an application where someone can change items using some properties dialog for example, how do you determine if a user has changed something when he clicks on cancel (to decide whether to display a cancel confirmation message box, or not).

I can think of 2 methods:

Defining a dirty bit and handling all "changed" events to set this bit to true.

Clone the original object and write some comparison code to determine if the modified object really was modified compared with the original

Is there any more elegant and/or more generic way to do that?

答:
If you wish to know if anything changed (uspecific to what exactly changed) then on loading of the form, GetHashCode on your object(s) then on close, call GetHashCode again, and see if the results are different.

you will need to override the GetHashcode function in your objects however:

```<code>Public Class Person

    Private _firstName as string = string.empty
    Private _lastName as string = string.empty
    Private _dob as Datetime = Date.MinVal
    private _weight as single = 0.0

    ...

    Public Overrides GetHashCode as Integer

        Dim sb as new System.Text.StringBuilder

        sb.append(_firstName)
        sb.append(_lastName)
        sb.append(_dob)
        ...
        sb.append(_weight)

        Return sb.ToString.GetHashCode

    End Function

End Class
</code>```

this works well for our objects and DAL :)

HTH

OwnerDisplayName: Stefan Koell

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Drew Noakes

Body:
If you wish to know if anything changed (uspecific to what exactly changed) then on loading of the form, GetHashCode on your object(s) then on close, call GetHashCode again, and see if the results are different.

you will need to override the GetHashcode function in your objects however:

Public Class Person

    Private _firstName as string = string.empty
    Private _lastName as string = string.empty
    Private _dob as Datetime = Date.MinVal
    private _weight as single = 0.0

    ...

    Public Overrides GetHashCode as Integer

        Dim sb as new System.Text.StringBuilder

        sb.append(_firstName)
        sb.append(_lastName)
        sb.append(_dob)
        ...
        sb.append(_weight)

        Return sb.ToString.GetHashCode

    End Function

End Class

this works well for our objects and DAL :)

HTH

OwnerDisplayName: Andy

LastEditorDisplayName: Andy


问:
Magento Option Question
This seems simple enough in theory but I haven't found anything on it. I need it for a client. Please see this page as an example: http://www.customsportsteamuniforms.com/index.php/test-shirt.html

On that page, you will find the first option that says "What kind of Screen Printing do you want?" If you select 1 color and you also happen to want more than 1 quantity (let's say 5), you will end up with this formula for the product cost:

$5 (cost) x $25 (option) x 5 quantity = total.

I DO NOT want it to do that. The option should be a one time fee in this case. The formula should read:

$5 (cost) x 5 quantity = sub-total + $25 (option) = total

How do I do this?

答: Magento's additional fees are all calculated on a per-product basis. If you want to add a fee to the entire order, you'll need to add some custom code to add this as a sort of handling fee for the order. The semantics for this are up to you (for instance, what about 2 different shirts both with 1-color screen printing options). </p>

Title: Magento Option Question