问:
Get class name using jQuery
I want to get the class name using jQuery

And if it has an id

```<code><div class="myclass"></div>
</code>```

答:
If we have a code:

```<code><div id="myDiv" class="myClass myClass2"></div>
</code>```

to take class name by using jQuery we could define and use a simple plugin method:

```<code>$.fn.class = function(){
  return Array.prototype.slice.call( $(this)[0].classList );
}
</code>```

or

```<code> $.fn.class = function(){
   return $(this).prop('class');
 }
</code>```

The use of the method will be:

```<code>$('#myDiv').class();
</code>```

We have to notice that it will return a list of classes unlike of native method element.className which returns only first class of the attached classes. Because often the element has more than one class attached to it, I recommend you not to use this native method but element.classlist or the method described above.

The first variant of it will return a list of classes as an array, the second as a string - class names separated by spaces:

```<code>// [myClass, myClass2]
// "myClass myClass2"
</code>```

Another important notice is that both methods as well as jQuery method

```<code>$('div').prop('class');
</code>```

return only class list of the first element caught by the jQuery object if we use a more common selector which points many other elements. In such a case we have to mark the element, we want to get his classes, by using some index, e.g.

```<code>$('div:eq(2)').prop('class');
</code>```

It depends also what you need to do with these classes. If you want just to check for a class into the class list of the element with this id you should just use method "hasClass":

```<code>if($('#myDiv').hasClass('myClass')){
   // do something
}
</code>```

as mentioned in the comments above. But if you could need to take all classes as a selector, then use this code:

```<code>$.fn.classes = function(){
   var o = $(this);
   return o.prop('class')? [''].concat( o.prop('class').split(' ') ).join('.') : '';
 }

 var mySelector = $('#myDiv').classes();
</code>```

The result will be:

```<code>// .myClass.myClass2
</code>```

and you could get it to create dynamically a specific rewriting css rule for example.

Regards

Title: Get class name using jQuery

Body:
If we have a code:

<div id="myDiv" class="myClass myClass2"></div>

to take class name by using jQuery we could define and use a simple plugin method:

$.fn.class = function(){
  return Array.prototype.slice.call( $(this)[0].classList );
}

or

 $.fn.class = function(){
   return $(this).prop('class');
 }

The use of the method will be:

$('#myDiv').class();

We have to notice that it will return a list of classes unlike of native method element.className which returns only first class of the attached classes. Because often the element has more than one class attached to it, I recommend you not to use this native method but element.classlist or the method described above.

The first variant of it will return a list of classes as an array, the second as a string - class names separated by spaces:

// [myClass, myClass2]
// "myClass myClass2"

Another important notice is that both methods as well as jQuery method

$('div').prop('class');

return only class list of the first element caught by the jQuery object if we use a more common selector which points many other elements. In such a case we have to mark the element, we want to get his classes, by using some index, e.g.

$('div:eq(2)').prop('class');

It depends also what you need to do with these classes. If you want just to check for a class into the class list of the element with this id you should just use method "hasClass":

if($('#myDiv').hasClass('myClass')){
   // do something
}

as mentioned in the comments above. But if you could need to take all classes as a selector, then use this code:

$.fn.classes = function(){
   var o = $(this);
   return o.prop('class')? [''].concat( o.prop('class').split(' ') ).join('.') : '';
 }

 var mySelector = $('#myDiv').classes();

The result will be:

// .myClass.myClass2

and you could get it to create dynamically a specific rewriting css rule for example.

Regards


来源: stackexchange

问:
How to get key pressed as char in DrawingPanel
I'm putting together a simple game as part of a project in Java. I'm using a DrawingPanel window, and need to be able to get the current keyboard key pressed as a char. Specifically, I have the DrawingPanel class and a class for the game, and need to get the char variable from within the public static void main of the game class.

I noticed that DrawingPanel contains KeyListener methods, specifically onKeyDown, but I have no idea how to use this. It is a void method, so I don't know how I would get the key pressed as an output, nor do I know what the DPKeyEventHandler input is for.

答:
I think with some reading about KeyListeners in java, you will be able to do what you want.

To give you something to start, look at this code, and how it behaves:

```<code>import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class KeyEventClass extends JFrame implements KeyListener {

public KeyEventClass(){
    this.setLayout(new BorderLayout());
    JTextField field = new JTextField();
    field.addKeyListener(this);
    this.add(field, BorderLayout.CENTER);
    this.pack();
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);
    this.setVisible(true);
}

public void keyTyped(KeyEvent e) {
    System.out.println("KeyTyped: ");
    if(e.getKeyChar() == KeyEvent.CHAR_UNDEFINED){
        System.out.println("No Unicode-Character typed!");
    }else{
        System.out.println(e.getKeyChar() + " typed!");
    }
    System.out.println("---");
}
public void keyPressed(KeyEvent e) {
    System.out.println("Key: " + e.getKeyChar() + ", Code: " + e.getKeyCode());
    System.out.println("Key-Location: " + e.getKeyLocation());
    System.out.println("---");
}

public void keyReleased(KeyEvent e) {
    System.out.println("KeyReleased: ");
    if(e.getKeyCode() == KeyEvent.VK_SPACE){
        System.out.println("ABORT!");
        System.exit(0);
    }
    System.out.println("Key: " + e.getKeyChar() + ", Code: " + e.getKeyCode());
    System.out.println("---");
}

public static void main(String[] args) {
    new KeyEventClass();
}
}
</code>```

Some more information about it:

https://examples.javacodegeeks.com/desktop-java/awt/event/a-complete-keylistener-example/

ContentLicense: CC BY-SA 4.0

Body:
I think with some reading about KeyListeners in java, you will be able to do what you want.

To give you something to start, look at this code, and how it behaves:

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class KeyEventClass extends JFrame implements KeyListener {

public KeyEventClass(){
    this.setLayout(new BorderLayout());
    JTextField field = new JTextField();
    field.addKeyListener(this);
    this.add(field, BorderLayout.CENTER);
    this.pack();
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);
    this.setVisible(true);
}

public void keyTyped(KeyEvent e) {
    System.out.println("KeyTyped: ");
    if(e.getKeyChar() == KeyEvent.CHAR_UNDEFINED){
        System.out.println("No Unicode-Character typed!");
    }else{
        System.out.println(e.getKeyChar() + " typed!");
    }
    System.out.println("---");
}
public void keyPressed(KeyEvent e) {
    System.out.println("Key: " + e.getKeyChar() + ", Code: " + e.getKeyCode());
    System.out.println("Key-Location: " + e.getKeyLocation());
    System.out.println("---");
}

public void keyReleased(KeyEvent e) {
    System.out.println("KeyReleased: ");
    if(e.getKeyCode() == KeyEvent.VK_SPACE){
        System.out.println("ABORT!");
        System.exit(0);
    }
    System.out.println("Key: " + e.getKeyChar() + ", Code: " + e.getKeyCode());
    System.out.println("---");
}

public static void main(String[] args) {
    new KeyEventClass();
}
}

Some more information about it:

https://examples.javacodegeeks.com/desktop-java/awt/event/a-complete-keylistener-example/


问:
SQL Server Management Studio 2017 Database Diagram Folder Missing
I have SSMS 2017 installed and I want to use it to create an ERD for some of my databases. The documentation online says you just need to right click on the "Database Diagrams" folder under your database in the navigation panel. However, that folder is simply not there for any of my databases. I cannot find any fix or work around. Does anyone have any ideas on how to fix this?</p>

答:
The SQL 2017 documentation has a page explaining how to use database diagrams which conflicts with the release notes that @squillman posted. I've opened an issue with Microsoft docs about it.

EDIT: Do to feedback, Microsoft is returning this feature in release 18.1.


问:
PHP 5 second countdown (CLI, not JavaScript)
I am writing a PHP CLI (command line) script that will do some irreversible damage if it is run by accident. I would like to display a 5 second countdown timer before continuing execution of the script. How can I do this with PHP?</p>

答:
This is what I ended up doing:

```<code># from Wiseguy's answer

echo 'Continue? (Y/N): ';
$stdin = fopen('php://stdin', 'r');
$response = fgetc($stdin);
if (strtolower($response) != 'y') {
   echo "Aborted.\n";
   exit;
}
</code>```

However, for a pretty countdown, this is what I came up with:

```<code>/**
 * Displays a countdown.
 * @param int $seconds
 */
function countdown($seconds) {
    for ($i=$seconds; $i>0; $i--) {
        echo "\r"; //start at the beginning of the line
        echo "$i "; //added space moves cursor further to the right
        sleep(1);
    }
    echo "\r\n"; //clear last number (overwrite it with spaces)
}
</code>```

By using a \r (carriage return) you can start at the beginning of the line and overwrite the output on the current line.

ContentLicense: CC BY-SA 3.0

Body:
This is what I ended up doing:

# from Wiseguy's answer

echo 'Continue? (Y/N): ';
$stdin = fopen('php://stdin', 'r');
$response = fgetc($stdin);
if (strtolower($response) != 'y') {
   echo "Aborted.\n";
   exit;
}

However, for a pretty countdown, this is what I came up with:

/**
 * Displays a countdown.
 * @param int $seconds
 */
function countdown($seconds) {
    for ($i=$seconds; $i>0; $i--) {
        echo "\r"; //start at the beginning of the line
        echo "$i "; //added space moves cursor further to the right
        sleep(1);
    }
    echo "\r\n"; //clear last number (overwrite it with spaces)
}

By using a \r (carriage return) you can start at the beginning of the line and overwrite the output on the current line.


问:
React: How to add onChange functionality inside of Function component using React Hooks? Need onClick event from a checkbox to influence input state
I have a function component with a checkbox and an input. I'm trying to create an onChange function for the checkbox that clears the input and disables it whenever a user clicks it by implementing the useState React Hook. Does anyone have any experience with Hooks who's done something like this before? I'm trying to look at code samples to better wrap my head around this as I'm still new to React Hooks

```<code>import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import {
  Col, Row, Icon, Input, Tooltip
} from 'antd'
import Checkbox from '../elements/Checkbox'

const CustomerDetails = ({ customer }) => {
  if (customer === null) {
    return (
      <Container>
        <Row>
          <Col span={24}>
            <ErrorContainer>
              <Icon type="exclamation-circle" />
            </ErrorContainer>
          </Col>
        </Row>
      </Container>
    )
  }

  return (
    <Container>
      <h2>{customer.contact.name}</h2>
      <Row>
        <Col span={8}>
          <H3>
            <strong>Primary Contact:</strong>
          </H3>
          <P>{customer.contact.name}</P>
          <P>{customer.contact.phone}</P>
        </Col>
        <Col span={8}>
          <H3>
            <strong>Service Address:</strong>
          </H3>
          <P>{customer.site.address1}</P>
          <P>{customer.site.address2}</P>
          <P>
            {customer.site.city}, {customer.site.state}
            {customer.site.postalCode}
          </P>
        </Col>
        <Col span={8}>
          <H3>
            <strong>Billing Address:</strong>
          </H3>
          <P>{customer.account.billingStreet}</P>
          <P>
            {customer.account.billingCity}, {customer.account.billingState}

            {customer.account.billingPostalCode}
          </P>
        </Col>
      </Row>
      <br />
      <Row>
        <Col span={10}>
          <h4>
            PRIMARY CONTACT EMAIL
            <Tooltip
              placement="topRight"
              title={primaryContact}
            >
              <StyledTooltipIcon
                type="question-circle"
                theme="filled"
              />
            </Tooltip>
          </h4>
        </Col>
      </Row>
      <Row>
        <Col span={8}>
          <StyledInput value={customer.contact.email} />
        </Col>
        <Col span={2} />
        <Col span={8}>
          <StyledCheckbox /> EMAIL OPT OUT{' '}
          <Tooltip
            placement="topRight"
            title={emailText}
          >
            <StyledTooltipIcon
              type="question-circle"
              theme="filled"
            />
          </Tooltip>
        </Col>
      </Row>
    </Container>
  )
}

CustomerDetails.propTypes = {
  customer: PropTypes.object
}

CustomerDetails.defaultProps = {
  customer: {}
}

const Container = styled.div`
  text-align: left;
`
const StyledCheckbox = styled(Checkbox)`
  input + span {
    border-radius: 0px;
    width: 35px;
    height: 35px;
    border: 2px solid ${({ theme }) => theme.colors.black};
    background-color: transparent;
    color: ${({ theme }) => theme.colors.black};
    border-color: ${({ theme }) => theme.colors.black};
    transition: none;
  }

  input:checked + span {
    border: 2px solid ${({ theme }) => theme.colors.black};
    width: 30px;
    height: 30px;
  }

  input + span:after {
    border-color: ${({ theme }) => theme.colors.black};
    left: 20%;
    transition: none;
    width: 12.5px;
    height: 20px;
  }

  input:disabled + span:after {
    border-color: ${({ theme }) => theme.colors.gray};
  }

  input:not(:checked):hover + span:after {
    border-color: ${({ theme }) => theme.colors.gray};
    opacity: 1;
    transform: rotate(45deg) scale(1) translate(-50%, -50%);
  }

  input:focus + span {
    border-color: ${({ theme }) => theme.colors.primary};
  }
`

const StyledInput = styled(Input)`
  max-width: 100%;

  &&& {
    border: 2px solid ${({ theme }) => theme.colors.black};
    border-radius: 0px;
    height: 35px;
  }
`

const ErrorContainer = styled.div`
  /* margin-left: 25%; */
`

const StyledTooltipIcon = styled(Icon)`
  color: #1571da;
`

const H3 = styled.h3`
  white-space: nowrap;
  margin-top: 0;
  margin-bottom: 0;
  line-height: 1.5;
}
`

const H4 = styled.h4`
  text-decoration: underline;
  color: #1590ff;
`

const P = styled.p`
  margin-top: 0;
  margin-bottom: 0;
  font-size: 1rem;
`

export default CustomerDetails

</code>```

答:
You can use the useState hook to create a state variable that tracks whether the user has clicked the checkbox to disable the other input. The useState hook is a function that takes an initial value and returns a state variable and a function used to update the value of that state variable (which works pretty much the same as setState but only for a single state variable).

For example:

const [x, setX] = React.useState(1); // `x` is initially 1, but that will change on later renders

setX(prevX => prevX + 1); // increments `x` for the next render;
```

<p>You'll also need to create an event handler function to respond to the clicking of this checkbox.</p>

<p>Here is a full example:</p>

<pre class="lang-js prettyprint-override"><code>import React from "react";

const MyComponent = props => {
    const [disableInputIsChecked, setDisableInputIsChecked] = React.useState(false);
    const [inputValue, setInputValue] = React.useState("");

    function clearInput() {
        setInputValue("");
    }

    function handleInputChange(event) {
        setInputValue(event.target.value);
    }

    function handleCheckboxClick(event) {
        if (!disableInputIsChecked) { // this click was to check the box
            clearInput();
        }
        setDisableInputIsChecked(prevValue => !prevValue); // invert value
    }

    return (
        <form>
            <input type="checkbox" value={ disableInputIsChecked } onChange={ handleCheckboxClick }/>
            <input type="text" value={ inputValue } onChange={ handleInputChange } disabled={ disableInputIsChecked }/>
        </form>
    )
}
</code>```

Here's a working example.

Probably you'll want to come up with better names for these values, but hopefully you get the point here.

Body:
I have a function component with a checkbox and an input. I'm trying to create an onChange function for the checkbox that clears the input and disables it whenever a user clicks it by implementing the useState React Hook. Does anyone have any experience with Hooks who's done something like this before? I'm trying to look at code samples to better wrap my head around this as I'm still new to React Hooks

import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import {
  Col, Row, Icon, Input, Tooltip
} from 'antd'
import Checkbox from '../elements/Checkbox'

const CustomerDetails = ({ customer }) => {
  if (customer === null) {
    return (
      <Container>
        <Row>
          <Col span={24}>
            <ErrorContainer>
              <Icon type="exclamation-circle" />
            </ErrorContainer>
          </Col>
        </Row>
      </Container>
    )
  }

  return (
    <Container>

{customer.contact.name}

      <Row>
        <Col span={8}>

            Primary Contact:

{customer.contact.name}

{customer.contact.phone}

        </Col>
        <Col span={8}>

            Service Address:

{customer.site.address1}

{customer.site.address2}

            {customer.site.city}, {customer.site.state}
            {customer.site.postalCode}

        </Col>
        <Col span={8}>

            Billing Address:

{customer.account.billingStreet}

            {customer.account.billingCity}, {customer.account.billingState}

            {customer.account.billingPostalCode}

        </Col>
      </Row>

      <Row>
        <Col span={10}>

            PRIMARY CONTACT EMAIL
            <Tooltip
              placement="topRight"
              title={primaryContact}
            >

Body:
You can use the useState hook to create a state variable that tracks whether the user has clicked the checkbox to disable the other input. The useState hook is a function that takes an initial value and returns a state variable and a function used to update the value of that state variable (which works pretty much the same as setState but only for a single state variable).

For example:

const [x, setX] = React.useState(1); // `x` is initially 1, but that will change on later renders

setX(prevX => prevX + 1); // increments `x` for the next render;

You'll also need to create an event handler function to respond to the clicking of this checkbox.

Here is a full example:

import React from "react";

const MyComponent = props => {
    const [disableInputIsChecked, setDisableInputIsChecked] = React.useState(false);
    const [inputValue, setInputValue] = React.useState("");

    function clearInput() {
        setInputValue("");
    }

    function handleInputChange(event) {
        setInputValue(event.target.value);
    }

    function handleCheckboxClick(event) {
        if (!disableInputIsChecked) { // this click was to check the box
            clearInput();
        }
        setDisableInputIsChecked(prevValue => !prevValue); // invert value
    }

    return (
        <form>
            <input type="checkbox" value={ disableInputIsChecked } onChange={ handleCheckboxClick }/>
            <input type="text" value={ inputValue } onChange={ handleInputChange } disabled={ disableInputIsChecked }/>
        </form>
    )
}

Here's a working example.

Probably you'll want to come up with better names for these values, but hopefully you get the point here.


问:
flask-mail : ConnectionRefusedError when trying to send an email from flask server
I am doing a web application where the only users are adminstrators who may received mail from server once a week. Currently, I'm just trying to send mail from click command to test the module but I always get a 'ConnectionRefusedError [WinError 10061]...

I looked at different posts where the problem was barely the same but none of them resolved mine.

Here's my flask configuration

```<code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail ,Message
from flask_login import LoginManager
from apscheduler.schedulers.background import BackgroundScheduler
import os.path

def mkpath(p):
    return os.path.normpath(
        os.path.join(
            os.path.dirname(__file__),
            p
        )
    )

app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = "847b5600-f639-4d07-803e-de716f4e89b7"
app.config['SQLALCHEMY_DATABASE_URI'] = (
    'sqlite:///'+mkpath('./app.db')
)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

UPLOAD_FOLDER_CSV = "static/tmp/"
ALLOWED_EXTENSION = set(['csv', 'xls'])
UPLOAD_FOLDER_FLUX = "static/flux/"

MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT = 465
MAIL_USE_TLS = False
MAIL_USE_SSL = True
MAIL_USERNAME = 'mymail@gmail.com'
MAIL_PASSWORD = 'mygmailpassword'

db = SQLAlchemy(app)
login_manager = LoginManager(app)
scheduler = BackgroundScheduler()
mail = Mail(app)

if __name__ == '__main__':
    app.run(debug=True)
</code>```

and here's the command I am calling to test it :

```<code>def sendmail():
    msg = Message(
                  recipients=["anothermail@gmail.com"])

    msg.body = "testing"
    mail.connect()
    mail.send(msg)
</code>```

Thanks :)

答:
You should update configuration before you initialize Mail:

```<code>app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'mymail@gmail.com'
app.config['MAIL_PASSWORD'] = 'mygmailpassword'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True

mail = Mail(app)
</code>```

Then, you should allow access from less secure apps via this link.

Body:
I am doing a web application where the only users are adminstrators who may received mail from server once a week. Currently, I'm just trying to send mail from click command to test the module but I always get a 'ConnectionRefusedError [WinError 10061]...

I looked at different posts where the problem was barely the same but none of them resolved mine.

Here's my flask configuration

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail ,Message
from flask_login import LoginManager
from apscheduler.schedulers.background import BackgroundScheduler
import os.path

def mkpath(p):
    return os.path.normpath(
        os.path.join(
            os.path.dirname(__file__),
            p
        )
    )

app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = "847b5600-f639-4d07-803e-de716f4e89b7"
app.config['SQLALCHEMY_DATABASE_URI'] = (
    'sqlite:///'+mkpath('./app.db')
)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

UPLOAD_FOLDER_CSV = "static/tmp/"
ALLOWED_EXTENSION = set(['csv', 'xls'])
UPLOAD_FOLDER_FLUX = "static/flux/"

MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT = 465
MAIL_USE_TLS = False
MAIL_USE_SSL = True
MAIL_USERNAME = 'mymail@gmail.com'
MAIL_PASSWORD = 'mygmailpassword'

db = SQLAlchemy(app)
login_manager = LoginManager(app)
scheduler = BackgroundScheduler()
mail = Mail(app)

if __name__ == '__main__':
    app.run(debug=True)

and here's the command I am calling to test it :

def sendmail():
    msg = Message(
                  recipients=["anothermail@gmail.com"])

    msg.body = "testing"
    mail.connect()
    mail.send(msg)

Thanks :)

Body:
You should update configuration before you initialize Mail:

app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'mymail@gmail.com'
app.config['MAIL_PASSWORD'] = 'mygmailpassword'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True

mail = Mail(app)

Then, you should allow access from less secure apps via this link.


问:
Beginner Python Code Issues
5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter the numbers from the book for problem 5.1 and Match the desired output as shown.

Here is my Code:

```<code>largest = None
smallest = None
while True:
    inp = raw_input("Enter a number: ")
    if inp == "done" : break
    try:
        num = float(inp)
    except:
        print "Invalid input"
    if smallest is None:
        smallest = num
    elif num < smallest:
        smallest = num
    elif num > largest:
        largest = num

    continue

print "Maximum is", largest
print "Minimum is", smallest
</code>```

******Please let me know the Logic errors in this CODE*****

答:
```<code>#by Aless
largest  = None
smallest = None
while True:
    num = input("Enter a number: ")
    if num == "done" : break

    try:
        intNum = int(num)
    except ValueError:
        #print('Error: Invalid input', num)
        print('Invalid input')
        continue
    else:
        if (largest  < intNum): largest = intNum
        if (smallest > intNum) or (smallest is None): smallest = intNum

print("Maximum", largest)
print("Minimum", smallest)
</code>```

Title: Beginner Python Code Issues

Body:
5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter the numbers from the book for problem 5.1 and Match the desired output as shown.

Here is my Code:

largest = None
smallest = None
while True:
    inp = raw_input("Enter a number: ")
    if inp == "done" : break
    try:
        num = float(inp)
    except:
        print "Invalid input"
    if smallest is None:
        smallest = num
    elif num < smallest:
        smallest = num
    elif num > largest:
        largest = num

    continue

print "Maximum is", largest
print "Minimum is", smallest

******Please let me know the Logic errors in this CODE*****


问:
MYSWL database. Trying to display a table. res.length is undefind
I am working on displaying a mysql data table and creating a function which displays my data. When I run this function I receive the following error.

```<code>     for (var i = 0; i < res.length; i++) {
                              ^

TypeError: Cannot read property 'length' of undefined
</code>```

```<code>function viewProducts(){
    var query = 'SELECT id, product_name, department, price, stock_quantity  FROM products Where stock_quantity > 0';

    connection.query(query, function(err, res){
        console.log('Items for Sale');
        console.log('Id \t Name \t Department \t Price \t Quantity\n');

            for (var i = 0; i < res.length; i++) {
                console.log(
                    res[i].id + '\t' + res[i].product_name + '\t' + res[i].department + '\t' +
                    res[i].price + '\t' + res[i].quantity + '\n');
            };
         runSearch();
    });

}
</code>```

答:
You are probably getting an error, and you're not checking for it.

Add something like

```<code>if (err) throw new Error(err);
</code>```

to the callback function to see what's going wrong.

Body:
I am working on displaying a mysql data table and creating a function which displays my data. When I run this function I receive the following error.

     for (var i = 0; i < res.length; i++) {
                              ^

TypeError: Cannot read property 'length' of undefined

function viewProducts(){
    var query = 'SELECT id, product_name, department, price, stock_quantity  FROM products Where stock_quantity > 0';

    connection.query(query, function(err, res){
        console.log('Items for Sale');
        console.log('Id \t Name \t Department \t Price \t Quantity\n');

            for (var i = 0; i < res.length; i++) {
                console.log(
                    res[i].id + '\t' + res[i].product_name + '\t' + res[i].department + '\t' +
                    res[i].price + '\t' + res[i].quantity + '\n');
            };
         runSearch();
    });

}

Body:
You are probably getting an error, and you're not checking for it.

Add something like

if (err) throw new Error(err);

to the callback function to see what's going wrong.


问:
Calculator layout not staying stable with varying width
When i shrink the web page to check for responsive behavior, the layout is all jumbled.

Converted the padding from pixels to rem
Converted font size from pixels to VW

.main-class{
}
.calculator-begin{
  align-items: center;
  margin-top: 3.125rem;
  margin-bottom: 3.125rem;
}

.row{
  width: 50%;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}

.screen{
  font: monospace;
  font-size: 2.778vw;
  flex-basis: 100%;
  padding: 3.125rem;
   text-align: right;
   color: white;
   background-color: black;
}

.cancel{
  background-color: #bababa;
  font-size: 2.778vw;
  flex-basis: 50%;
  padding: 3.125rem;
   text-align: center;
   border: 1.5px solid black;
}
.cancel:active{
  background: #a0a0a0;
}
.numbers{
  padding: 3.125rem;
  font-size: 2.778vw;
  flex-basis: 25%;
  text-align: center;
  background-color:  #bababa;
  border: 1.5px solid black;
}
.numbers:active{
  background: #a0a0a0;
}
.operations{
  padding: 3.125rem;
  font-size: 2.778vw;
  flex-basis: 25%;
  text-align: center;
  background-color:  #ffa642;
  border: 1.5px solid black;
}
.operations:active{
  background-color: #ff8905;
}
.zero{
  padding: 3.125rem;
  flex-basis: 75%;
  font-size: 2.778vw;
  text-align: center;
  background-color:   #bababa;
  border: 1.5px solid black;
}
.zero:active{
  background: #a0a0a0;
}

.remove-left-border{
  border-left: 0px;
}

.remove-right-border{
  border-right: 0px;
}

.remote-bot-border{
  border-bottom: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="calculatorStyle.css">
    <title>Calculator using JS</title>
  </head>
  <body>
    <div class="main-class">
      <center>
      <div class="calculator-begin">
        <div class="row">
         <div class="screen">
           <section>
             XXXXX
           </section>
         </div>
        </div>
        <div class="row">
          <button class="cancel remove-left-border">C</button>
          <button class="numbers">←</button>
          <button class="operations remove-right-border">÷</button>
        </div>
        <div class="row">
          <button class="numbers remove-left-border">7</button>
          <button class="numbers">8</button>
          <button class="numbers">9</button>
          <button class="operations remove-right-border">X</button>
        </div>
        <div class="row">
          <button class="numbers remove-left-border">4</button>
          <button class="numbers">5</button>
          <button class="numbers">6</button>
          <button class="operations remove-right-border">-</button>
        </div>
        <div class="row">
          <button class="numbers remove-left-border">1</button>
          <button class="numbers">2</button>
          <button class="numbers">3</button>
          <button class="operations remove-right-border">+</button>
        </div>
        <div class="row">
          <button class="zero remove-left-border remove-bottom-border">0</button>
          <button class="operations remove-right-border remove-bottom-border">=</button>
        </div>
      </div>
      </center>
    </div>
  </body>
</html></code>```

I want the layout to be rigid and to scale along with the browser size, that is , the relative positions of these elements should remain the same.

答: The padding you have set on the buttons is making it impossible for the browser to make the elements small enough to fit in the rows. Remove that line and it should work much better. You don't need the padding because your layout is controlled with flex.

Body:
When i shrink the web page to check for responsive behavior, the layout is all jumbled.

Converted the padding from pixels to rem
Converted font size from pixels to VW

.main-class{
}
.calculator-begin{
  align-items: center;
  margin-top: 3.125rem;
  margin-bottom: 3.125rem;
}

.row{
  width: 50%;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}

.screen{
  font: monospace;
  font-size: 2.778vw;
  flex-basis: 100%;
  padding: 3.125rem;
   text-align: right;
   color: white;
   background-color: black;
}

.cancel{
  background-color: #bababa;
  font-size: 2.778vw;
  flex-basis: 50%;
  padding: 3.125rem;
   text-align: center;
   border: 1.5px solid black;
}
.cancel:active{
  background: #a0a0a0;
}
.numbers{
  padding: 3.125rem;
  font-size: 2.778vw;
  flex-basis: 25%;
  text-align: center;
  background-color:  #bababa;
  border: 1.5px solid black;
}
.numbers:active{
  background: #a0a0a0;
}
.operations{
  padding: 3.125rem;
  font-size: 2.778vw;
  flex-basis: 25%;
  text-align: center;
  background-color:  #ffa642;
  border: 1.5px solid black;
}
.operations:active{
  background-color: #ff8905;
}
.zero{
  padding: 3.125rem;
  flex-basis: 75%;
  font-size: 2.778vw;
  text-align: center;
  background-color:   #bababa;
  border: 1.5px solid black;
}
.zero:active{
  background: #a0a0a0;
}

.remove-left-border{
  border-left: 0px;
}

.remove-right-border{
  border-right: 0px;
}

.remote-bot-border{
  border-bottom: 0px;
}

<!DOCTYPE html>

    <meta charset="utf-8">
    <link rel="stylesheet" href="calculatorStyle.css">
    <title>Calculator using JS</title>

             XXXXX

          <button class="cancel remove-left-border">C</button>
          <button class="numbers">←</button>
          <button class="operations remove-right-border">÷</button>

          <button class="numbers remove-left-border">7</button>
          <button class="numbers">8</button>
          <button class="numbers">9</button>
          <button class="operations remove-right-border">X</button>

          <button class="numbers remove-left-border">4</button>
          <button class="numbers">5</button>
          <button class="numbers">6</button>
          <button class="operations remove-right-border">-</button>

          <button class="numbers remove-left-border">1</button>
          <button class="numbers">2</button>
          <button class="numbers">3</button>
          <button class="operations remove-right-border">+</button>

          <button class="zero remove-left-border remove-bottom-border">0</button>
          <button class="operations remove-right-border remove-bottom-border">=</button>

I want the layout to be rigid and to scale along with the browser size, that is , the relative positions of these elements should remain the same.


问:
REQUEST_URI not matching explicit path and filename
Really stumped, because form and syntax seem fine.

RewriteCond for REQUEST_URI is not matching the explicit path and filename.  When isolated, RewriteCond for REQUEST_FILENAME matches just fine.  I have verified using phpinfo() that REQUEST_URI contains the leading slash, and have tested without the leading slash, also.

The goal here is to know that the request is for this file and, if it doesn't exist, then throw a 410.

```<code>RewriteCond %{REQUEST_URI} ^/dir1/dir2/dir3/v_9991_0726dd5b5e8dd67a214c0c243436d131_all\.css$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ - [R=410,L]
</code>```

I don't want to omit the first Cond, because I only want to do this for a handful of files similar to this one.

UPDATE I

trying to get a definitive test.  Test set-up:

testmee.txt does not exist

request is for testmee.txt in the root

verified the request_uri is matching, by redirecting to google

cannot get 410 when using only first Cond

(when using only first Cond, server serves 404, not 410)

(using both Conds, server serves 404, not 410)

CAN get 410 when using only second Cond

```<code>RewriteCond %{REQUEST_URI} ^/testmee\.txt$
#RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ - [R=410,L]
</code>```

versus

```<code>#RewriteCond %{REQUEST_URI} ^/testmee\.txt$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ - [R=410,L]
</code>```

UPDATE II

Response for MrWhite:

ughh, same symptom.  Might have to live with googlebot hitting 404s instead of a desired 410 for outdated css/js.  No biggie in the long run, probably.

Thank you for that request_uri test redirect.  Everything is working normally in those tests.  Page names, etc. are returned as expected, in the var= rewrite URL.

At this point, I think it must be some internal handling of 404s related to the file type extensions.  See clue below.  I have Prestashop shopping cart software, and it must be forcing 404s on file types.

This will redirect to google (to affirm pattern match):

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^testmee\.txt$ http://www.google.com/ [L]
(L flag is needed or else other Rules further down will interfere.)
</code>```

This will continue to return 404 instead of 410:

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^testmee\.txt$ - [NC,R=410]
</code>```

And as a control test, this will return a 410:

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ - [NC,R=410]
</code>```

If file type is css in the above failed test, then my custom 404 controller does not get invoked.  I just get a plain 404 Response, w/o the custom 404 that is wrapped with all my site templating.

For example:

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^testmee\.css$ - [NC,R=410]
</code>```

I'm afraid I've wasted some of your time.  My apologies.  I never imagined that Prestashop's code would be forcing 404 based on file type, but I can't see any other explanation.  I could dig into it and maybe find the spot in the Controllers that is doing it.  Gotta take a break, though.

答:
I was unable to determine why server configuration or site code was forcing '410 Gone' response directive in htaccess to be overridden with a 404 response, so had to do something like this to tell googlebot to stop hunting for CSS/JS files that get purged periodically (and renamed when regenerated).

in .htaccess:

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule v_(.*)_(.*)$ /410response.php [L]
</code>```

in 410response.php placed in root:

<?php header($_SERVER['SERVER_PROTOCOL'].' 410 Gone');

UPDATE I

The 404 response when attempting to use htaccess for the 410 directive was being forced by the server, because of server apparently having a custom 410 document, that apparently routed to 404.  Adding a directive to prevent that then properly allowed use of htaccess to return 410 for pattern matches in RewriteRule.  (I thought that I had already checked yesterday to see if this would work, since @MrWhite said in his answer above to control for server possibly having a custom 410; today when making this check, it did work and indicate that server 410-to-404 redirection was overridding my 410 directive.)

```<code>ErrorDocument 410 default
RewriteRule test\.txt$ - [NC,R=410]
</code>```

MrWhite!  I located this solution in one of your posts on Stack Exchange.

Body:
Really stumped, because form and syntax seem fine.

RewriteCond for REQUEST_URI is not matching the explicit path and filename.  When isolated, RewriteCond for REQUEST_FILENAME matches just fine.  I have verified using phpinfo() that REQUEST_URI contains the leading slash, and have tested without the leading slash, also.

The goal here is to know that the request is for this file and, if it doesn't exist, then throw a 410.

RewriteCond %{REQUEST_URI} ^/dir1/dir2/dir3/v_9991_0726dd5b5e8dd67a214c0c243436d131_all\.css$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ - [R=410,L]

I don't want to omit the first Cond, because I only want to do this for a handful of files similar to this one.

UPDATE I

trying to get a definitive test.  Test set-up:

testmee.txt does not exist

request is for testmee.txt in the root

verified the request_uri is matching, by redirecting to google

cannot get 410 when using only first Cond

(when using only first Cond, server serves 404, not 410)

(using both Conds, server serves 404, not 410)

CAN get 410 when using only second Cond

RewriteCond %{REQUEST_URI} ^/testmee\.txt$
#RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ - [R=410,L]

versus

#RewriteCond %{REQUEST_URI} ^/testmee\.txt$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ - [R=410,L]

UPDATE II

Response for MrWhite:

ughh, same symptom.  Might have to live with googlebot hitting 404s instead of a desired 410 for outdated css/js.  No biggie in the long run, probably.

Thank you for that request_uri test redirect.  Everything is working normally in those tests.  Page names, etc. are returned as expected, in the var= rewrite URL.

At this point, I think it must be some internal handling of 404s related to the file type extensions.  See clue below.  I have Prestashop shopping cart software, and it must be forcing 404s on file types.

This will redirect to google (to affirm pattern match):

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^testmee\.txt$ http://www.google.com/ [L]
(L flag is needed or else other Rules further down will interfere.)

This will continue to return 404 instead of 410:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^testmee\.txt$ - [NC,R=410]

And as a control test, this will return a 410:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ - [NC,R=410]

If file type is css in the above failed test, then my custom 404 controller does not get invoked.  I just get a plain 404 Response, w/o the custom 404 that is wrapped with all my site templating.

For example:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^testmee\.css$ - [NC,R=410]

I'm afraid I've wasted some of your time.  My apologies.  I never imagined that Prestashop's code would be forcing 404 based on file type, but I can't see any other explanation.  I could dig into it and maybe find the spot in the Controllers that is doing it.  Gotta take a break, though.

Body:
I was unable to determine why server configuration or site code was forcing '410 Gone' response directive in htaccess to be overridden with a 404 response, so had to do something like this to tell googlebot to stop hunting for CSS/JS files that get purged periodically (and renamed when regenerated).

in .htaccess:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule v_(.*)_(.*)$ /410response.php [L]

in 410response.php placed in root:

<?php header($_SERVER['SERVER_PROTOCOL'].' 410 Gone');

UPDATE I

The 404 response when attempting to use htaccess for the 410 directive was being forced by the server, because of server apparently having a custom 410 document, that apparently routed to 404.  Adding a directive to prevent that then properly allowed use of htaccess to return 410 for pattern matches in RewriteRule.  (I thought that I had already checked yesterday to see if this would work, since @MrWhite said in his answer above to control for server possibly having a custom 410; today when making this check, it did work and indicate that server 410-to-404 redirection was overridding my 410 directive.)

ErrorDocument 410 default
RewriteRule test\.txt$ - [NC,R=410]

MrWhite!  I located this solution in one of your posts on Stack Exchange.


问:
Rxjs conditional switchMap based on a condition
I have a situation like the following:

myObservable1.pipe(
  switchMap((result1: MyObservable1) => {
    if (condition) {
      return myObservable2;
    } else {
      return of(null);
    }
  })
).subscribe(myObservable1 | myObservable2) => {
```

So if condition is false I only have to perform one request, if the condition is true, I have to chain the first request to the following one, they are essentially two requests to the server api.

Is there a better solution without returning that null?

Is there any conditional operator in RxJs?

Thanks!

答:
No need to return of(null), you should use the RxJs filter operator</p>

```<code>myObservable1.pipe(
  filter((result1) => condition)
  switchMap((result1: MyObservable1) => {
    return myObservable2;
  })
).subscribe((result2) => { ... })
</code>```

Body:
I have a situation like the following:

myObservable1.pipe(
  switchMap((result1: MyObservable1) => {
    if (condition) {
      return myObservable2;
    } else {
      return of(null);
    }
  })
).subscribe(myObservable1 | myObservable2) => {

So if condition is false I only have to perform one request, if the condition is true, I have to chain the first request to the following one, they are essentially two requests to the server api.

Is there a better solution without returning that null?

Is there any conditional operator in RxJs?

Thanks!

Body:
No need to return of(null), you should use the RxJs filter operator

myObservable1.pipe(
  filter((result1) => condition)
  switchMap((result1: MyObservable1) => {
    return myObservable2;
  })
).subscribe((result2) => { ... })


问:
How do you update a CoreData entry that has already been saved in Swift?
I'm not sure what I'm doing wrong here, but when I save the first time into coredata, it works just fine. When I try to overwrite that, it doesn't.

```<code>func testStuff() {
    var token = loadLoginData()
    println("Token \(token)")
    saveLoginData("New Token")
    var newToken = loadLoginData()
    println("Token \(newToken)")
}

func saveLoginData(accessToken: String) {
    var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    var context: NSManagedObjectContext = appDel.managedObjectContext!
    // save data to core data
    var loginData = NSEntityDescription.insertNewObjectForEntityForName("LoginData", inManagedObjectContext: context) as NSManagedObject
    loginData.setValue(accessToken, forKey: "accessToken")
    context.save(nil)
    println("Done saving user")
}

/* Output
Token Optional("12345")
Done saving user
Token Optional("12345")
*/
</code>```

Load Login Data Func
the function that calls on saveLogin data

```<code>func loadLoginData() -> String? {
    var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    var context: NSManagedObjectContext = appDel.managedObjectContext!

    var request = NSFetchRequest(entityName: "LoginData")
    request.returnsObjectsAsFaults = false

    var results: NSArray = context.executeFetchRequest(request, error: nil)!
    if (results.count > 0) {
        var userData: NSManagedObject = results[0] as NSManagedObject
        var accessToken: String = userData.valueForKey("accessToken") as String

        return accessToken.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

    } else {
        println("0 results returned, potential error")
        return nil
    }
}
</code>```

答:
This worked for me. First i set filter by given attribute "taskName" with fetchRequest.predicate. Then i fetch data that already been saved and set value for "status" to update that object.</p>

```<code>func updateTaskStatus(status: Bool){

    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
    let managedContext = appDelegate.persistentContainer.viewContext
    let fetchRequest: NSFetchRequest<Task> = Task.fetchRequest()
    let predicate = NSPredicate(format: "(taskName = %@)", (task?.taskName)!)
    fetchRequest.predicate = predicate
    do {
        let result = try managedContext.fetch(fetchRequest)
        task = result[0] as NSManagedObject as? Task
        task?.setValue(status, forKey: "status")
        do {
            try managedContext.save()
        }catch  let error as NSError {
            print("\(error)")
        }
    }catch let error as NSError {
        print("\(error)")
    }
}
</code>```

Body:
I'm not sure what I'm doing wrong here, but when I save the first time into coredata, it works just fine. When I try to overwrite that, it doesn't.

func testStuff() {
    var token = loadLoginData()
    println("Token \(token)")
    saveLoginData("New Token")
    var newToken = loadLoginData()
    println("Token \(newToken)")
}

func saveLoginData(accessToken: String) {
    var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    var context: NSManagedObjectContext = appDel.managedObjectContext!
    // save data to core data
    var loginData = NSEntityDescription.insertNewObjectForEntityForName("LoginData", inManagedObjectContext: context) as NSManagedObject
    loginData.setValue(accessToken, forKey: "accessToken")
    context.save(nil)
    println("Done saving user")
}

/* Output
Token Optional("12345")
Done saving user
Token Optional("12345")
*/

Load Login Data Func
the function that calls on saveLogin data

func loadLoginData() -> String? {
    var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    var context: NSManagedObjectContext = appDel.managedObjectContext!

    var request = NSFetchRequest(entityName: "LoginData")
    request.returnsObjectsAsFaults = false

    var results: NSArray = context.executeFetchRequest(request, error: nil)!
    if (results.count > 0) {
        var userData: NSManagedObject = results[0] as NSManagedObject
        var accessToken: String = userData.valueForKey("accessToken") as String

        return accessToken.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

    } else {
        println("0 results returned, potential error")
        return nil
    }
}

Body:
This worked for me. First i set filter by given attribute "taskName" with fetchRequest.predicate. Then i fetch data that already been saved and set value for "status" to update that object.

func updateTaskStatus(status: Bool){

    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
    let managedContext = appDelegate.persistentContainer.viewContext
    let fetchRequest: NSFetchRequest<Task> = Task.fetchRequest()
    let predicate = NSPredicate(format: "(taskName = %@)", (task?.taskName)!)
    fetchRequest.predicate = predicate
    do {
        let result = try managedContext.fetch(fetchRequest)
        task = result[0] as NSManagedObject as? Task
        task?.setValue(status, forKey: "status")
        do {
            try managedContext.save()
        }catch  let error as NSError {
            print("\(error)")
        }
    }catch let error as NSError {
        print("\(error)")
    }
}


问:
WCF Service fails to send mail through MailDefinition
```<code>    // stuff......

    return SendCreationMail(Membership.GetUser((Guid)request.UserEntityId), request, new Control());
}

private const string TemplateRoot = "~/app_shared/templates/mail/";
private const string ServerRoot = TemplateRoot + "server/";

public static bool SendCreationMail(MembershipUser user, IServerAccountRequest request, Control owner)
{
    var definition = new MailDefinition { BodyFileName = string.Concat(ServerRoot, "creation.htm"), IsBodyHtml = true };
    var subject = "New {0} account created!".FormatWith(request.ServerApplicationContract.Id);

    var data = ExtendedData(DefaultData, subject, user);

    data.Add("<%ServerApplication%>", request.ServerApplicationContract.Id);
    data.Add("<%ServerApplicationName%>", request.ServerApplicationContract.ApplicationName);
    data.Add("<%AccountUsername%>", request.AccountUsername);

    data.Add("<%ServerInfo%>", "/server/{0}/info".FormatWith(request.ServerApplicationContract.Id.ToLower()));

    return definition.CreateMailMessage(user.Email, data, owner).Send(subject, ApplicationConfiguration.MailSenderDisplayName);
}
</code>```

I get:

Value cannot be null. Parameter name: basepath

at System.Web.Util.UrlPath.Combine(String appPath, String basepath,
  String relative)

  at
  System.Web.UI.WebControls.MailDefinition.CreateMailMessage(String
  recipients, IDictionary replacements, Control owner)

  at
  Damnation.Website.Main.Common.MailTemplating.Server.SendCreationMail(MembershipUser
  user, IServerAccountRequest request, Control owner)

  at Damnation.Website.Main.Common.MailTemplating.Server.SendCreationMail(IServerAccountRequest
  request)

  at Damnation.Website.Main.Business.Model.ServerAccountRequest.UpdateRequestsAfterServerProcessing(IEnumerable`1
  results)

Thing is I don't have an actual Control to pass to it, I'd like to know how to setup a control that avoids this senseless exception. I'm using a relative path... so this makes no sense.

The application that has the service is under ASP.NET WebForms .NET 4. The consumer application is a console application also under .NET 4

答: I had the same error but the problem for me was that I was using relative paths for my BodyFileName and EmbeddedObjects. Changing them to absolute paths fixed this error for me.</p>

Body:
    // stuff......

    return SendCreationMail(Membership.GetUser((Guid)request.UserEntityId), request, new Control());
}

private const string TemplateRoot = "~/app_shared/templates/mail/";
private const string ServerRoot = TemplateRoot + "server/";

public static bool SendCreationMail(MembershipUser user, IServerAccountRequest request, Control owner)
{
    var definition = new MailDefinition { BodyFileName = string.Concat(ServerRoot, "creation.htm"), IsBodyHtml = true };
    var subject = "New {0} account created!".FormatWith(request.ServerApplicationContract.Id);

    var data = ExtendedData(DefaultData, subject, user);

    data.Add("<%ServerApplication%>", request.ServerApplicationContract.Id);
    data.Add("<%ServerApplicationName%>", request.ServerApplicationContract.ApplicationName);
    data.Add("<%AccountUsername%>", request.AccountUsername);

    data.Add("<%ServerInfo%>", "/server/{0}/info".FormatWith(request.ServerApplicationContract.Id.ToLower()));

    return definition.CreateMailMessage(user.Email, data, owner).Send(subject, ApplicationConfiguration.MailSenderDisplayName);
}

I get:

Value cannot be null. Parameter name: basepath

at System.Web.Util.UrlPath.Combine(String appPath, String basepath,
  String relative)

  at
  System.Web.UI.WebControls.MailDefinition.CreateMailMessage(String
  recipients, IDictionary replacements, Control owner)

  at
  Damnation.Website.Main.Common.MailTemplating.Server.SendCreationMail(MembershipUser
  user, IServerAccountRequest request, Control owner)

  at Damnation.Website.Main.Common.MailTemplating.Server.SendCreationMail(IServerAccountRequest
  request)

  at Damnation.Website.Main.Business.Model.ServerAccountRequest.UpdateRequestsAfterServerProcessing(IEnumerable`1
  results)

Thing is I don't have an actual Control to pass to it, I'd like to know how to setup a control that avoids this senseless exception. I'm using a relative path... so this makes no sense.

The application that has the service is under ASP.NET WebForms .NET 4. The consumer application is a console application also under .NET 4


问:
Controlling async function in another file
I am calling another function in a file called feedFactory, the function has a asynchronous call,School.findOne, that returns a promise. So the following get postFields value is null since it doesn't wait. How can I control the asynchronous flow from the file that calls the function feedFactory.BuildPostBody?

```<code>const postFields = feedFactory.BuildPostBody(req, res, errorResponse);
</code>```

And the in the file
feedFactory
I have the following block of code that returns a promise after I do a query.

```<code>      exports = module.exports = {
  BuildPostBody: (req, res, errorResponse) => {
    //Determine what account type we are going to post as using field
    //postToFeedAs
    let postFields;

      case "School":
        {
          //Get industry partner name and company logo
          School.findOne({ _id: req.user.school }).then(school => {
              let avatar =
                "https://image.png";
              if (typeof school.profile.school_logo !== "undefined") {
                avatar = school.profile.school_logo.url;
              }

                  postFields = {
                    author: {
                      userType: req.body.postToFeedAs,
                      user: req.user.school,
                      name: school.name,
                      avatar: avatar
                    },
                    postType: "text",
                    postBody: req.body.postBody
                  };
                  console.log("returning post back from factory");
                  return postFields; <--Returns late

              ...
</code>```

答:
You can use Async/await to accomplish your goal:

Put this code into an async function and change to:

const postFields = await feedFactory.BuildPostBody(...)

then when using postFields do

postFields.then(...)

Body:
I am calling another function in a file called feedFactory, the function has a asynchronous call,School.findOne, that returns a promise. So the following get postFields value is null since it doesn't wait. How can I control the asynchronous flow from the file that calls the function feedFactory.BuildPostBody?

const postFields = feedFactory.BuildPostBody(req, res, errorResponse);

And the in the file
feedFactory
I have the following block of code that returns a promise after I do a query.

      exports = module.exports = {
  BuildPostBody: (req, res, errorResponse) => {
    //Determine what account type we are going to post as using field
    //postToFeedAs
    let postFields;

      case "School":
        {
          //Get industry partner name and company logo
          School.findOne({ _id: req.user.school }).then(school => {
              let avatar =
                "https://image.png";
              if (typeof school.profile.school_logo !== "undefined") {
                avatar = school.profile.school_logo.url;
              }

                  postFields = {
                    author: {
                      userType: req.body.postToFeedAs,
                      user: req.user.school,
                      name: school.name,
                      avatar: avatar
                    },
                    postType: "text",
                    postBody: req.body.postBody
                  };
                  console.log("returning post back from factory");
                  return postFields; <--Returns late

              ...


问:
equality test for atomic variables in C and gcc
I have a dummy question about atomic variables using gcc.
My machine supports __sync_add_and_fetch function; I use this call in thread A to set my_variable (int) .

I want Thread B reading that shared variable to test it against a value e.g. 20.
Is it correct to write the following

```<code>   if( __sync_bool_compare_and_swap( &my_variable, 20, 20 ) ){
          //..Ok! It is 20 so go ahead!
   }else{
          // wrong: it is not ok.
   }
</code>```

If  am not wrong in gcc the __sync_val_compare_and_swap might fail when there is a race in the shared variable, but I don't know what it does return; how does it work with __sync_bool_compare_and_swap?

Problem is what happens also when at the same time Thread A is changing the value using __sync_fetch_and_add? Is it always guaranteed that it will return the value of that sum event when __sync_bool_compare_and_swap is running concurrently?

Ideally speaking and for my purpose, I would really need a function doing exactly an atomic READ only, nor a Swap. Has C or gcc something like this?

Thanks A lot

AFG

答:
As far as atomic operations go, they are meant to complete without interruption. If you have multiple atomic operations you expect to run concurrently, there will be a race condition concerning their order, but each will be run to completion. For example, say __sync_fetch_and_add was first, it would perform both the fetch and the add before the __sync_bool_compare_and_swap would perform its compare and swap.

You might also consider looking at other methods of signaling. You may have a race condition between the value being updated in one thread and having the other thread check it for the exact value 20. In other words, it could be updated right passed 20 with the other thread never knowing it.

But if none of this is too important, you could just do all this without any __sync* functions since only one thread is writing and the other reading; no need to worry about corrupt data. Also no need to worry about the variable being up to date since you have a separate race condition involving that (value is updated faster than its checked).

Body:
I have a dummy question about atomic variables using gcc.
My machine supports __sync_add_and_fetch function; I use this call in thread A to set my_variable (int) .

I want Thread B reading that shared variable to test it against a value e.g. 20.
Is it correct to write the following

   if( __sync_bool_compare_and_swap( &my_variable, 20, 20 ) ){
          //..Ok! It is 20 so go ahead!
   }else{
          // wrong: it is not ok.
   }

If  am not wrong in gcc the __sync_val_compare_and_swap might fail when there is a race in the shared variable, but I don't know what it does return; how does it work with __sync_bool_compare_and_swap?

Problem is what happens also when at the same time Thread A is changing the value using __sync_fetch_and_add? Is it always guaranteed that it will return the value of that sum event when __sync_bool_compare_and_swap is running concurrently?

Ideally speaking and for my purpose, I would really need a function doing exactly an atomic READ only, nor a Swap. Has C or gcc something like this?

Thanks A lot

AFG


问:
Selecting all rows whose time spans cover a specific time
Table rows have a start time column and an end time column. I am searching for any rows whose times exist between 3pm and 4pm.  In other words the row should be included if either: (1) Its start and end were both between 3 and 4, (2) It started before 3 and ended after 4, (3) It started before 3 and ended after 3, (4) It started before 4 and ended after 4. I have tried adding the following where clause to cover those 4 options and it works, but it takes a very long time.  It seems like there must be better code for this.</p>

```<code>    Where
(
    (
    (TO_CHAR(vltecl.Patient_in_ROOM_DTTM, 'HH24:MI:SS')                  < '15:00:00')
    and (TO_CHAR(vltecl.patient_out_ROOM_DTTM, 'HH24:MI:SS')                 > '16:00:00')
    )
   or
   (  (TO_CHAR(vltecl.Patient_in_ROOM_DTTM, 'HH24:MI:SS')                  < '16:00:00')
    and (TO_CHAR(vltecl.patient_out_ROOM_DTTM, 'HH24:MI:SS')                 > '16:00:00')
    )
    or
    (
     (TO_CHAR(vltecl.Patient_in_ROOM_DTTM, 'HH24:MI:SS')                  < '15:00:00')
    and (TO_CHAR(vltecl.patient_out_ROOM_DTTM, 'HH24:MI:SS')                 > '15:00:00')
    )
    or
     ((TO_CHAR(vltecl.Patient_in_ROOM_DTTM, 'HH24:MI:SS')                  < '16:00:00')
    and (TO_CHAR(vltecl.patient_out_ROOM_DTTM, 'HH24:MI:SS')                 > '16:00:00')
    and (TO_CHAR(vltecl.Patient_in_ROOM_DTTM, 'HH24:MI:SS')                  > '15:00:00')
    )
    )
</code>```

答:
Dealing with generic times can be a bit fiddly in oracle (as opposed to a specific time on a specific day).
Approach is generally ok, but it can be simplified a little I think by turning it on it's head.
Basically you want every one which overlaps the hour 3-4, yes?
Well that is anything that didn't end before 3, or started after 4 (Assuming 'out' is always after 'in')

```<code>Where
NOT (TO_CHAR(vltecl.Patient_in_ROOM_DTTM, 'HH24:MI:SS')                  > '16:00:00'
    OR TO_CHAR(vltecl.Patient_OUT_ROOM_DTTM, 'HH24:MI:SS')                 < '15:00:00'
    )
</code>```

I think that works (Not got access to knock up a test right now)

This may still be slow if you are dealing with a lot of data here - even if the In/Out dates are indexed, it has to full scan the table.

Body:
Table rows have a start time column and an end time column. I am searching for any rows whose times exist between 3pm and 4pm.  In other words the row should be included if either: (1) Its start and end were both between 3 and 4, (2) It started before 3 and ended after 4, (3) It started before 3 and ended after 3, (4) It started before 4 and ended after 4. I have tried adding the following where clause to cover those 4 options and it works, but it takes a very long time.  It seems like there must be better code for this.

    Where
(
    (
    (TO_CHAR(vltecl.Patient_in_ROOM_DTTM, 'HH24:MI:SS')                  < '15:00:00')
    and (TO_CHAR(vltecl.patient_out_ROOM_DTTM, 'HH24:MI:SS')                 > '16:00:00')
    )
   or
   (  (TO_CHAR(vltecl.Patient_in_ROOM_DTTM, 'HH24:MI:SS')                  < '16:00:00')
    and (TO_CHAR(vltecl.patient_out_ROOM_DTTM, 'HH24:MI:SS')                 > '16:00:00')
    )
    or
    (
     (TO_CHAR(vltecl.Patient_in_ROOM_DTTM, 'HH24:MI:SS')                  < '15:00:00')
    and (TO_CHAR(vltecl.patient_out_ROOM_DTTM, 'HH24:MI:SS')                 > '15:00:00')
    )
    or
     ((TO_CHAR(vltecl.Patient_in_ROOM_DTTM, 'HH24:MI:SS')                  < '16:00:00')
    and (TO_CHAR(vltecl.patient_out_ROOM_DTTM, 'HH24:MI:SS')                 > '16:00:00')
    and (TO_CHAR(vltecl.Patient_in_ROOM_DTTM, 'HH24:MI:SS')                  > '15:00:00')
    )
    )

Body:
Dealing with generic times can be a bit fiddly in oracle (as opposed to a specific time on a specific day).
Approach is generally ok, but it can be simplified a little I think by turning it on it's head.
Basically you want every one which overlaps the hour 3-4, yes?
Well that is anything that didn't end before 3, or started after 4 (Assuming 'out' is always after 'in')

Where
NOT (TO_CHAR(vltecl.Patient_in_ROOM_DTTM, 'HH24:MI:SS')                  > '16:00:00'
    OR TO_CHAR(vltecl.Patient_OUT_ROOM_DTTM, 'HH24:MI:SS')                 < '15:00:00'
    )

I think that works (Not got access to knock up a test right now)

This may still be slow if you are dealing with a lot of data here - even if the In/Out dates are indexed, it has to full scan the table.


问:
Is it possible to use AWS Lambda to process an HTTP response without making the corresponding HTTP request?
I have to make an HTTP request that takes a long time to receive a response.  I don't want AWS Lambda to make this request as I will be charged for the time it is waiting for the response.  Is there any way to use AWS Lambda to handle the response without being charged while waiting?</p>

答:
Based on my comment, I would recommend hitting the long poll endpoint often as opposed to staying connected for long periods of time. You can use a CloudWatch Rule to trigger the lambda function every 5 minutes (or whatever interval you choose). You can give the Lambda a short timeout, say 5-10 seconds, which should prevent it from running for too long. I'm assuming the long poll endpoint will guarantee delivery at least once.

Here is some CloudFormation YAML to get you started on the setup. Far from complete, but should get you on the right track.

```<code>Description: Automatically hit long poll endpoint
Resources:

  #################################################
  # IAM Role for Lambda
  #################################################
  ROLELAMBDADEFAULT:
    Type: AWS::IAM::Role
    Properties:
      RoleName: your-lambda-default
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - edgelambda.amazonaws.com
            - lambda.amazonaws.com
          Action: sts:AssumeRole
      ManagedPolicyArns:
      - arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole
      - arn:aws:iam::aws:policy/service-role/AWSLambdaRole
      Policies: []

  #################################################
  # Lambda function
  #################################################
  LFUNC:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        S3Bucket: bucket-with-code
        S3Key: code.zip
      Description: Some function name
      FunctionName: my-function-name
      Handler: index.handler
      MemorySize: 256
      Role: !GetAtt ROLELAMBDADEFAULT.Arn
      #choose your runtime here
      Runtime: nodejs8.10
      Timeout: 6

  #################################################
  # Rule to trigger the lambda
  #################################################
  RULE1:
    Type: AWS::Events::Rule
    Properties:
      Name: custom-trigger
      Description: Trigger my lambda
      ScheduleExpression: rate(5 minutes)
      State: ENABLED
      Targets:
        - Arn: !GetAtt LFUNC.Arn
          Id: uniqueid1
</code>```

Body:
Based on my comment, I would recommend hitting the long poll endpoint often as opposed to staying connected for long periods of time. You can use a CloudWatch Rule to trigger the lambda function every 5 minutes (or whatever interval you choose). You can give the Lambda a short timeout, say 5-10 seconds, which should prevent it from running for too long. I'm assuming the long poll endpoint will guarantee delivery at least once.

Here is some CloudFormation YAML to get you started on the setup. Far from complete, but should get you on the right track.

Description: Automatically hit long poll endpoint
Resources:

  #################################################
  # IAM Role for Lambda
  #################################################
  ROLELAMBDADEFAULT:
    Type: AWS::IAM::Role
    Properties:
      RoleName: your-lambda-default
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - edgelambda.amazonaws.com
            - lambda.amazonaws.com
          Action: sts:AssumeRole
      ManagedPolicyArns:
      - arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole
      - arn:aws:iam::aws:policy/service-role/AWSLambdaRole
      Policies: []

  #################################################
  # Lambda function
  #################################################
  LFUNC:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        S3Bucket: bucket-with-code
        S3Key: code.zip
      Description: Some function name
      FunctionName: my-function-name
      Handler: index.handler
      MemorySize: 256
      Role: !GetAtt ROLELAMBDADEFAULT.Arn
      #choose your runtime here
      Runtime: nodejs8.10
      Timeout: 6

  #################################################
  # Rule to trigger the lambda
  #################################################
  RULE1:
    Type: AWS::Events::Rule
    Properties:
      Name: custom-trigger
      Description: Trigger my lambda
      ScheduleExpression: rate(5 minutes)
      State: ENABLED
      Targets:
        - Arn: !GetAtt LFUNC.Arn
          Id: uniqueid1


问:
make radio button selected based on an event
I have several divs of class OuterDiv that contain divs of class InnerDiv that contain radio buttons.

```<code><div class="OuterDiv">
  <div class="InnerDiv">
    <input type="radio" name="TheOptions" />option 1
  </div>
</div>

<div class="OuterDiv">
  <div class="InnerDiv">
    <input type="radio" name="TheOptions" />option 2
  </div>
</div>

<div class="OuterDiv">
  <div class="InnerDiv">
    <input type="radio" name="TheOptions" />option 3
  </div>
</div>
</code>```

I'm looking to catch the event "user clicked on div" to make the corresponding radio button selected.

This is what I have so far:

```<code>$('.OuterDiv .InnerDiv').click(function {

  $(this).find('radio')....

});
</code>```

I can get to the radio button but I'm stuck on making it selected and making any of the currently selected button unselected (unless selecting one automatically unselects all others).

Thanks for your suggestions.

答:
try this

```<code>$('.OuterDiv .InnerDiv').click(function() {

  $(this).find('input:radio').attr('checked','checked');

});
</code>```

working Demo

Body:
I have several divs of class OuterDiv that contain divs of class InnerDiv that contain radio buttons.

    <input type="radio" name="TheOptions" />option 1

    <input type="radio" name="TheOptions" />option 2

    <input type="radio" name="TheOptions" />option 3

I'm looking to catch the event "user clicked on div" to make the corresponding radio button selected.

This is what I have so far:

$('.OuterDiv .InnerDiv').click(function {

  $(this).find('radio')....

});

I can get to the radio button but I'm stuck on making it selected and making any of the currently selected button unselected (unless selecting one automatically unselects all others).

Thanks for your suggestions.

Body:
try this

$('.OuterDiv .InnerDiv').click(function() {

  $(this).find('input:radio').attr('checked','checked');

});

working Demo


问:
PowerShell conversion attempted with .NET class
I've read a few similar Q&As regarding PS and type conversions, but as far as I can see they're not the same situations.

I am attempting to use RMO classes in a Powershell script, but for some reason it thinks a conversion to the same type is necessary and fails to do so.

The code in question is basically:

```<code>$conn = New-Object "Microsoft.SqlServer.Management.Common.ServerConnection" @($server, $dbUsernm, $dbPasswd);

$publicationDb = New-Object "Microsoft.SqlServer.Replication.ReplicationDatabase"
$publicationDb.Name = $dbName;
$publicationDb.ConnectionContext = $conn;
</code>```

(A similar type error occurs if I try to use the two-argument constructor.)

The error is:

```<code>Exception setting "ConnectionContext": "Cannot convert the "(..snip..)" value of type
"Microsoft.SqlServer.Management.Common.ServerConnection" to type "Microsoft.SqlServer.Management.Common.ServerConnection"."
</code>```

So what's going on here? It's clearly trying to convert to the same data types. These aren't defined in PowerShell scripts so shouldn't it be able to track the type? I've also tried casting the variable to [Microsoft.SqlServer.Management.Common.ServerConnection] in its declaration and/or in the calls / member set, to no avail.

In case it is relevant, I'm loading the RMO classes this way (which appears to be the only working method, even though from what I understand LoadWithPartialName is deprecated):

```<code>[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.RMO")
</code>```

which says:

```<code>GAC    Version        Location
---    -------        --------
True   v4.0.30319     C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Microsoft.SqlServer.RMO\v4.0_14.0.0.0__89845dcd8080cc91\...
</code>```

Does that mean it's v4.x of that class, or that it's a .NET 4.x class? If it is a .NET 4.x class, is that relevant in any way i.e. is that a problem for Powershell?

答:
TLDR: Summary of troubleshooting: @Keilaron had executed an Import-Module SqlServer earlier on in the PowerShell session which caused the odd behavior.

Personally, I wasn't satisfied that a simple restart of the PowerShell session fixed the issue, as this kind of error shouldn't happen. When I did some further digging, I think I discovered the root cause, and discovered that this is a bigger issue that could be easily missed.

First, the code to replicate the discovered behavior:

```<code>Import-Module SqlServer

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.RMO")

$server = 'MyServer'
$dbuser = 'sa'
$dbPasswd = '1234'
$conn = New-Object "Microsoft.SqlServer.Management.Common.ServerConnection" @($server, $dbUser, $dbPasswd);
$publicationDb = New-Object "Microsoft.SqlServer.Replication.ReplicationDatabase"
$publicationDb.Name = 'RandomDatabase'
$publicationDb.ConnectionContext = $conn;
</code>```

Two key things happen:

The Import-Module SqlServer loads the SqlServer .dll's included with the module, and not the GAC installed modules. This is by design, as the the module is not dependent on SQL Server being installed.

The Microsoft.SqlServer.Rmo.dll is not a part of, or loaded with the SqlServer module, as there are no Replication commands in the SqlServer module. So to use the Replication commands, we have to manually load that .dll ourselves.

The two .dll's that we care about that the Import-Module SqlServer transparently imported were the two connection dependent .dll's from the SqlServer PowerShell module location:

```<code>[System.Reflection.Assembly]::LoadFile('C:\Windows\System32\WindowsPowerShell\v1.0\Modules\SqlServer\Microsoft.SqlServer.ConnectionInfo.dll')
[System.Reflection.Assembly]::LoadFile('C:\Windows\System32\WindowsPowerShell\v1.0\Modules\SqlServer\Microsoft.SqlServer.SqlClrProvider.dll')
</code>```

--> Note: These .dll's were imported as 64 bit .dll's.

The RMO .dll that we had to manually import, come from the GAC, but essentially come from:

```<code>"C:\Program Files (x86)\Microsoft SQL Server\140\SDK\Assemblies\Microsoft.SqlServer.Rmo.dll"
</code>```

Note: This is a 32 bit .dll. This is why we couldn't convert a "Microsoft.SqlServer.Management.Common.ServerConnection" to type "Microsoft.SqlServer.Management.Common.ServerConnection". Even though they are the same "type", as in name, their different bitness causes them to be incompatible.

Body:
I've read a few similar Q&As regarding PS and type conversions, but as far as I can see they're not the same situations.

I am attempting to use RMO classes in a Powershell script, but for some reason it thinks a conversion to the same type is necessary and fails to do so.

The code in question is basically:

$conn = New-Object "Microsoft.SqlServer.Management.Common.ServerConnection" @($server, $dbUsernm, $dbPasswd);

$publicationDb = New-Object "Microsoft.SqlServer.Replication.ReplicationDatabase"
$publicationDb.Name = $dbName;
$publicationDb.ConnectionContext = $conn;

(A similar type error occurs if I try to use the two-argument constructor.)

The error is:

Exception setting "ConnectionContext": "Cannot convert the "(..snip..)" value of type
"Microsoft.SqlServer.Management.Common.ServerConnection" to type "Microsoft.SqlServer.Management.Common.ServerConnection"."

So what's going on here? It's clearly trying to convert to the same data types. These aren't defined in PowerShell scripts so shouldn't it be able to track the type? I've also tried casting the variable to [Microsoft.SqlServer.Management.Common.ServerConnection] in its declaration and/or in the calls / member set, to no avail.

In case it is relevant, I'm loading the RMO classes this way (which appears to be the only working method, even though from what I understand LoadWithPartialName is deprecated):

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.RMO")

which says:

GAC    Version        Location
---    -------        --------
True   v4.0.30319     C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Microsoft.SqlServer.RMO\v4.0_14.0.0.0__89845dcd8080cc91\...

Does that mean it's v4.x of that class, or that it's a .NET 4.x class? If it is a .NET 4.x class, is that relevant in any way i.e. is that a problem for Powershell?

Body:
TLDR: Summary of troubleshooting: @Keilaron had executed an Import-Module SqlServer earlier on in the PowerShell session which caused the odd behavior.

Personally, I wasn't satisfied that a simple restart of the PowerShell session fixed the issue, as this kind of error shouldn't happen. When I did some further digging, I think I discovered the root cause, and discovered that this is a bigger issue that could be easily missed.

First, the code to replicate the discovered behavior:

Import-Module SqlServer

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.RMO")

$server = 'MyServer'
$dbuser = 'sa'
$dbPasswd = '1234'
$conn = New-Object "Microsoft.SqlServer.Management.Common.ServerConnection" @($server, $dbUser, $dbPasswd);
$publicationDb = New-Object "Microsoft.SqlServer.Replication.ReplicationDatabase"
$publicationDb.Name = 'RandomDatabase'
$publicationDb.ConnectionContext = $conn;

Two key things happen:

The Import-Module SqlServer loads the SqlServer .dll's included with the module, and not the GAC installed modules. This is by design, as the the module is not dependent on SQL Server being installed.

The Microsoft.SqlServer.Rmo.dll is not a part of, or loaded with the SqlServer module, as there are no Replication commands in the SqlServer module. So to use the Replication commands, we have to manually load that .dll ourselves.

The two .dll's that we care about that the Import-Module SqlServer transparently imported were the two connection dependent .dll's from the SqlServer PowerShell module location:

[System.Reflection.Assembly]::LoadFile('C:\Windows\System32\WindowsPowerShell\v1.0\Modules\SqlServer\Microsoft.SqlServer.ConnectionInfo.dll')
[System.Reflection.Assembly]::LoadFile('C:\Windows\System32\WindowsPowerShell\v1.0\Modules\SqlServer\Microsoft.SqlServer.SqlClrProvider.dll')

--> Note: These .dll's were imported as 64 bit .dll's.

The RMO .dll that we had to manually import, come from the GAC, but essentially come from:

"C:\Program Files (x86)\Microsoft SQL Server\140\SDK\Assemblies\Microsoft.SqlServer.Rmo.dll"

Note: This is a 32 bit .dll. This is why we couldn't convert a "Microsoft.SqlServer.Management.Common.ServerConnection" to type "Microsoft.SqlServer.Management.Common.ServerConnection". Even though they are the same "type", as in name, their different bitness causes them to be incompatible.


问:
Why does Visual Studio 2017 fail to generate REST API client for Swagger Petstore?
I'm playing around with using Swagger / OpenAPI docs/specs to generate REST API client code in C#, but I'm running into several problems.

Most notably - when trying to use the Swagger.io Petstore example as a starting point:

Using the VS 2017 Add > REST API client option in VS 2017, I don't get any code produced - instead an error is shown:

Generating client code and adding to project started

  Generate client code for REST API with following parameters:

  REST API Name: OpenApiClientClient, Base namespace: OpenApiClient, Metadata file path: C:\Users\Marc\AppData\Local\Temp\WebToolsAutoRest\OpenApiClientClient\201807162213351660\swagger.json

  [Info]AutoRest Core 0.16.0.0

  [Info]Initializing modeler.

  [Info]Initializing modeler.

  [Info]Parsing swagger json file.

  [Info]Generating client model from swagger model.

  [Fatal]Error generating client model: Collection format "multi" is not supported (in parameter 'status').

  Exception: There was an error during code generation when trying to add a client for the REST API

  Generating client code and adding to project failed

  Adding REST API client for failed

So if the Swagger sample app isn't compatible - how will others be?? (and I tried a few others, all with the same results, unfortunately).

What's wrong here? Am I missing something, do I need to add some extra tooling to VS 2017 to make this work?

UPDATE:

OK, so I now tried to install Autorest using npm directly:

```<code>npm install -g autorest
</code>```

This appears to work - no errors shown or anything.

But trying to run Autorest - with a set of command line parameters, or even just on its own - results in an error:

```<code>AutoRest -CodeGenerator CSharp -Modeler Swagger
         -Input https://petstore.swagger.io/v2/swagger.json
         -Namespace Services.UserServiceClient -OutputDirectory d:\projects
         -AddCrendentials true
</code>```

or just

```<code>AutoRest <kbd>Enter</kbd>
</code>```

results in:

AutoRest code generation utility [version: 2.0.4280; node: v9.9.0]

  (C) 2018 Microsoft Corporation.

  https://aka.ms/autorest

  Failure:

  Error: Unable to start AutoRest Core from C:\Users\Marc.autorest\@microsoft.azure_autorest-core@2.0.4280\node_modules\@microsoft.azure\autorest-core

  Error: Unable to start AutoRest Core from C:\Users\Marc.autorest\@microsoft.azure_autorest-core@2.0.4280\node_modules\@microsoft.azure\autorest-core

  at main (C:\Users\Marc\AppData\Roaming\npm\node_modules\autorest  \dist\app.js:232:19)
  at

Any further ideas?

答:
I also had this problem so I built a tool for it called REST API Client Code Generator. I worked in teams where we used tools like AutoRest, NSwag, and Swagger Codegen to generate our REST API Clients and it always annoyed me that the "Add New - REST API Client..." tooling in Visual Studio didn't always work and was very troublesome when it was time to re-generate the client

This would add the OpenAPI specification file (Swagger.json) to the project and set a custom tool so that every time changes are made to it the REST API Client code is re-generated. You can also right click on the Swagger.json file and switch code generators

I built the tool mainly for personal use and for use within my teams but if you find it useful and think it lacks something you really need then please reach out

Body:
I'm playing around with using Swagger / OpenAPI docs/specs to generate REST API client code in C#, but I'm running into several problems.

Most notably - when trying to use the Swagger.io Petstore example as a starting point:

Using the VS 2017 Add > REST API client option in VS 2017, I don't get any code produced - instead an error is shown:

Generating client code and adding to project started

  Generate client code for REST API with following parameters:

  REST API Name: OpenApiClientClient, Base namespace: OpenApiClient, Metadata file path: C:\Users\Marc\AppData\Local\Temp\WebToolsAutoRest\OpenApiClientClient\201807162213351660\swagger.json

  [Info]AutoRest Core 0.16.0.0

  [Info]Initializing modeler.

  [Info]Initializing modeler.

  [Info]Parsing swagger json file.

  [Info]Generating client model from swagger model.

  [Fatal]Error generating client model: Collection format "multi" is not supported (in parameter 'status').

  Exception: There was an error during code generation when trying to add a client for the REST API

  Generating client code and adding to project failed

  Adding REST API client for failed

So if the Swagger sample app isn't compatible - how will others be?? (and I tried a few others, all with the same results, unfortunately).

What's wrong here? Am I missing something, do I need to add some extra tooling to VS 2017 to make this work?

UPDATE:

OK, so I now tried to install Autorest using npm directly:

npm install -g autorest

This appears to work - no errors shown or anything.

But trying to run Autorest - with a set of command line parameters, or even just on its own - results in an error:

AutoRest -CodeGenerator CSharp -Modeler Swagger
         -Input https://petstore.swagger.io/v2/swagger.json
         -Namespace Services.UserServiceClient -OutputDirectory d:\projects
         -AddCrendentials true

or just

AutoRest Enter

results in:

AutoRest code generation utility [version: 2.0.4280; node: v9.9.0]

  (C) 2018 Microsoft Corporation.

  https://aka.ms/autorest

  Failure:

  Error: Unable to start AutoRest Core from C:\Users\Marc.autorest\@microsoft.azure_autorest-core@2.0.4280\node_modules\@microsoft.azure\autorest-core

  Error: Unable to start AutoRest Core from C:\Users\Marc.autorest\@microsoft.azure_autorest-core@2.0.4280\node_modules\@microsoft.azure\autorest-core

  at main (C:\Users\Marc\AppData\Roaming\npm\node_modules\autorest  \dist\app.js:232:19)
  at

Any further ideas?


问:
Extracting 'href' under 'a' tag
I'm trying to extract a link under "a href="link"..."

As there are multiple rows I iterate over every one of them. The first link per row is the one I need so I use find_all('tr') and find('a').
I know find('a') returns a Nonetype but do not know how to work around this

I had a piece of code that worked but is inefficient (in comments).

```<code>sauce = urllib.request.urlopen('https://morocco.observation.org/soortenlijst_wg_v3.php')
soup = bs.BeautifulSoup(sauce, 'lxml')

tabel = soup.find('table', {'class': 'tablesorter'})
for i in tabel.find_all('tr'):
#     if 'view' in i.get('href'):
#         link_list.append(i.get('href'))

    link = i.find('a')
#<a class="z1" href="/soort/view/164?from=1987-12-05&to=2019-05-31">Common Reed Bunting - <em>Emberiza schoeniclus</em></a>
</code>```

How do I retrieve the link under href and work around the Nonetype getting only /soort/view/164?from=1987-12-05&to=2019-05-31?

Thanks in advance

答:
```<code>link = i.find('a')
_href = link['href']
print(_href)
</code>```

O/P:

```<code>"/soort/view/164?from=1987-12-05&to=2019-05-31?"
</code>```

This is not proper url link, you should concate with domain name

```<code>new_url = "https://morocco.observation.org"+_href
print(new_url)
</code>```

O/p:

https://morocco.observation.org/soort/view/164?from=1987-12-05&to=2019-05-31?

Update:

```<code>from bs4 import BeautifulSoup
from bs4.element import Tag
import requests

resp = requests.get("https://morocco.observation.org/soortenlijst_wg_v3.php")
soup = BeautifulSoup(resp.text, 'lxml')
tabel = soup.find('table', {'class': 'tablesorter'})
base_url = "https://morocco.observation.org"

for i in tabel.find_all('tr'):
    link = i.find('a',href=True)
    if link is None or not isinstance(link,Tag):
        continue

    url = base_url + link['href']
    print(url)
</code>```

O/P:

```<code>https://morocco.observation.org/soort/view/248?from=1975-05-05&to=2019-06-01
https://morocco.observation.org/soort/view/174?from=1989-12-15&to=2019-06-01
https://morocco.observation.org/soort/view/57?from=1975-05-05&to=2019-06-01
https://morocco.observation.org/soort/view/19278?from=1975-05-13&to=2019-06-01
https://morocco.observation.org/soort/view/56?from=1993-03-25&to=2019-06-01
https://morocco.observation.org/soort/view/1504?from=1979-05-25&to=2019-06-01
https://morocco.observation.org/soort/view/78394?from=1975-05-09&to=2019-06-01
https://morocco.observation.org/soort/view/164?from=1987-12-05&to=2019-06-01
</code>```

Title: Extracting 'href' under 'a' tag

Body:
I'm trying to extract a link under "a href="link"..."

As there are multiple rows I iterate over every one of them. The first link per row is the one I need so I use find_all('tr') and find('a').
I know find('a') returns a Nonetype but do not know how to work around this

I had a piece of code that worked but is inefficient (in comments).

sauce = urllib.request.urlopen('https://morocco.observation.org/soortenlijst_wg_v3.php')
soup = bs.BeautifulSoup(sauce, 'lxml')

tabel = soup.find('table', {'class': 'tablesorter'})
for i in tabel.find_all('tr'):
#     if 'view' in i.get('href'):
#         link_list.append(i.get('href'))

    link = i.find('a')
#Common Reed Bunting - Emberiza schoeniclus

How do I retrieve the link under href and work around the Nonetype getting only /soort/view/164?from=1987-12-05&to=2019-05-31?

Thanks in advance

Body:
link = i.find('a')
_href = link['href']
print(_href)

O/P:

"/soort/view/164?from=1987-12-05&to=2019-05-31?"

This is not proper url link, you should concate with domain name

new_url = "https://morocco.observation.org"+_href
print(new_url)

O/p:

https://morocco.observation.org/soort/view/164?from=1987-12-05&to=2019-05-31?

Update:

from bs4 import BeautifulSoup
from bs4.element import Tag
import requests

resp = requests.get("https://morocco.observation.org/soortenlijst_wg_v3.php")
soup = BeautifulSoup(resp.text, 'lxml')
tabel = soup.find('table', {'class': 'tablesorter'})
base_url = "https://morocco.observation.org"

for i in tabel.find_all('tr'):
    link = i.find('a',href=True)
    if link is None or not isinstance(link,Tag):
        continue

    url = base_url + link['href']
    print(url)

O/P:

https://morocco.observation.org/soort/view/248?from=1975-05-05&to=2019-06-01
https://morocco.observation.org/soort/view/174?from=1989-12-15&to=2019-06-01
https://morocco.observation.org/soort/view/57?from=1975-05-05&to=2019-06-01
https://morocco.observation.org/soort/view/19278?from=1975-05-13&to=2019-06-01
https://morocco.observation.org/soort/view/56?from=1993-03-25&to=2019-06-01
https://morocco.observation.org/soort/view/1504?from=1979-05-25&to=2019-06-01
https://morocco.observation.org/soort/view/78394?from=1975-05-09&to=2019-06-01
https://morocco.observation.org/soort/view/164?from=1987-12-05&to=2019-06-01


问:
Why can Serde not derive Deserialize for a struct containing only a &Path?
I tried to derive serde::Deserialize for a struct containing a reference to a Path. This yielded an error message which doesn't occur if you replace &'a Path with &'a str. What causes the different behaviours of #[derive(Deserialize)]?

Playground

#!/bin/cargo script
//! ```cargo
//! [dependencies]
//! serde_derive="1.0"
//! serde="1.0"
//! ```

extern crate serde_derive;

use serde_derive::*;

#[derive(Deserialize)]
struct A<'a> {
    a: &'a std::path::Path,
    //a: &'a str,
}

fn main() {}
```

<pre class="lang-none prettyprint-override"><code>error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'de` due to conflicting requirements
 --> src/main.rs:7:5
  |
7 |     a: &'a std::path::Path,
  |     ^
  |
note: first, the lifetime cannot outlive the lifetime 'de as defined on the impl at 5:10...
 --> src/main.rs:5:10
  |
5 | #[derive(Deserialize)]
  |          ^^^^^^^^^^^
  = note: ...so that the types are compatible:
          expected _IMPL_DESERIALIZE_FOR_A::_serde::de::SeqAccess<'_>
             found _IMPL_DESERIALIZE_FOR_A::_serde::de::SeqAccess<'de>
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 6:10...
 --> src/main.rs:6:10
  |
6 | struct A<'a> {
  |          ^^
  = note: ...so that the types are compatible:
          expected _IMPL_DESERIALIZE_FOR_A::_serde::Deserialize<'_>
             found _IMPL_DESERIALIZE_FOR_A::_serde::Deserialize<'_>

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'de` due to conflicting requirements
 --> src/main.rs:7:5
  |
7 |     a: &'a std::path::Path,
  |     ^
  |
note: first, the lifetime cannot outlive the lifetime 'de as defined on the impl at 5:10...
 --> src/main.rs:5:10
  |
5 | #[derive(Deserialize)]
  |          ^^^^^^^^^^^
  = note: ...so that the types are compatible:
          expected _IMPL_DESERIALIZE_FOR_A::_serde::de::MapAccess<'_>
             found _IMPL_DESERIALIZE_FOR_A::_serde::de::MapAccess<'de>
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 6:10...
 --> src/main.rs:6:10
  |
6 | struct A<'a> {
  |          ^^
  = note: ...so that the types are compatible:
          expected _IMPL_DESERIALIZE_FOR_A::_serde::Deserialize<'_>
             found _IMPL_DESERIALIZE_FOR_A::_serde::Deserialize<'_>
</code>```

Strangely enough, the code compiles if the struct contains both fields _a: &'a Path and _b: &'a str... At this point I think this is a bug.

答:
Add an attribute to the field: #[serde(borrow)]. That will indicate to serde that it should be borrowing the value. You must provide this attribute for every borrow except for &str and &[u8].

Source: https://serde.rs/lifetimes.html#borrowing-data-in-a-derived-impl

Body:
I tried to derive serde::Deserialize for a struct containing a reference to a Path. This yielded an error message which doesn't occur if you replace &'a Path with &'a str. What causes the different behaviours of #[derive(Deserialize)]?

Playground

#!/bin/cargo script
//! ```cargo
//! [dependencies]
//! serde_derive="1.0"
//! serde="1.0"
//! ```

extern crate serde_derive;

use serde_derive::*;

#[derive(Deserialize)]
struct A<'a> {
    a: &'a std::path::Path,
    //a: &'a str,
}

fn main() {}

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'de` due to conflicting requirements
 --> src/main.rs:7:5
  |
7 |     a: &'a std::path::Path,
  |     ^
  |
note: first, the lifetime cannot outlive the lifetime 'de as defined on the impl at 5:10...
 --> src/main.rs:5:10
  |
5 | #[derive(Deserialize)]
  |          ^^^^^^^^^^^
  = note: ...so that the types are compatible:
          expected _IMPL_DESERIALIZE_FOR_A::_serde::de::SeqAccess<'_>
             found _IMPL_DESERIALIZE_FOR_A::_serde::de::SeqAccess<'de>
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 6:10...
 --> src/main.rs:6:10
  |
6 | struct A<'a> {
  |          ^^
  = note: ...so that the types are compatible:
          expected _IMPL_DESERIALIZE_FOR_A::_serde::Deserialize<'_>
             found _IMPL_DESERIALIZE_FOR_A::_serde::Deserialize<'_>

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'de` due to conflicting requirements
 --> src/main.rs:7:5
  |
7 |     a: &'a std::path::Path,
  |     ^
  |
note: first, the lifetime cannot outlive the lifetime 'de as defined on the impl at 5:10...
 --> src/main.rs:5:10
  |
5 | #[derive(Deserialize)]
  |          ^^^^^^^^^^^
  = note: ...so that the types are compatible:
          expected _IMPL_DESERIALIZE_FOR_A::_serde::de::MapAccess<'_>
             found _IMPL_DESERIALIZE_FOR_A::_serde::de::MapAccess<'de>
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 6:10...
 --> src/main.rs:6:10
  |
6 | struct A<'a> {
  |          ^^
  = note: ...so that the types are compatible:
          expected _IMPL_DESERIALIZE_FOR_A::_serde::Deserialize<'_>
             found _IMPL_DESERIALIZE_FOR_A::_serde::Deserialize<'_>

Strangely enough, the code compiles if the struct contains both fields _a: &'a Path and _b: &'a str... At this point I think this is a bug.