问:
If else not working in cypress it only going into if condition
this is only going to if condition not else if()
how to do this with cypress???

if(cy.get('div > div > span.fa.fa-exclamation-triangle.ns-icon').should('be.visible') ){

```<code>        cy.log("This user is already Exist")

    }

    else if( cy.get('.login-message')
    .should('have.text', 'An email has been sent to you to verify the email address you provided with
     a link to activate your account.'))
    {

        cy.log('New user has been signed up successfully')
        cy.wait(5000)

        //Assertion
        //cy.get('.login-message')
            //.should('have.text', 'An email has been sent to you to verify the email address you provided with a link to activate your account.')

        cy.wait(5000)
        cy.get('.icon').click();
        cy.url().should('include', '/Public/Login')

        cy.wait(10000)

    }
</code>```

答:
cy.get('selector').should('clause') is not meant to return a boolean value so it should never be used for condition check.

In the below snippet, $el is a jquery (cypress automatically includes jquery) instance which is used to any required value.

```<code>cy.get('div > div > span.fa.fa-exclamation-triangle.ns-icon').then(($el) => {
    if ($el.is(':visible')) {
        cy.log("This user is already Exist");
    }
});

cy.get('.login-message').then(($el) => {
    const message = 'An email has been sent to you to verify the email address you provided with a link to activate your account.'
    if ($el.text() !== message) {
        return;
    }

    cy.log('New user has been signed up successfully')
    cy.wait(5000)

    //Assertion
    //cy.get('.login-message')
        //.should('have.text', message);

    cy.wait(5000)
    cy.get('.icon').click();
    cy.url().should('include', '/Public/Login')

    cy.wait(10000)
});
</code>```

Body:
this is only going to if condition not else if()
how to do this with cypress???

if(cy.get('div > div > span.fa.fa-exclamation-triangle.ns-icon').should('be.visible') ){

        cy.log("This user is already Exist")

    }

    else if( cy.get('.login-message')
    .should('have.text', 'An email has been sent to you to verify the email address you provided with
     a link to activate your account.'))
    {

        cy.log('New user has been signed up successfully')
        cy.wait(5000)

        //Assertion
        //cy.get('.login-message')
            //.should('have.text', 'An email has been sent to you to verify the email address you provided with a link to activate your account.')

        cy.wait(5000)
        cy.get('.icon').click();
        cy.url().should('include', '/Public/Login')

        cy.wait(10000)

    }

Body:
cy.get('selector').should('clause') is not meant to return a boolean value so it should never be used for condition check.

In the below snippet, $el is a jquery (cypress automatically includes jquery) instance which is used to any required value.

cy.get('div > div > span.fa.fa-exclamation-triangle.ns-icon').then(($el) => {
    if ($el.is(':visible')) {
        cy.log("This user is already Exist");
    }
});

cy.get('.login-message').then(($el) => {
    const message = 'An email has been sent to you to verify the email address you provided with a link to activate your account.'
    if ($el.text() !== message) {
        return;
    }

    cy.log('New user has been signed up successfully')
    cy.wait(5000)

    //Assertion
    //cy.get('.login-message')
        //.should('have.text', message);

    cy.wait(5000)
    cy.get('.icon').click();
    cy.url().should('include', '/Public/Login')

    cy.wait(10000)
});


来源: stackexchange

问:
What pattern of datetimeformat is needed for DateTimeFormatter to parse JAN01/2020?
I'm being passed a date in ths format - "JAN01/2020" but I can't seem to find the DateTimeFormatter pattern for it. I tried these (as well as several others) but they're resulting in DateTimeParseException -

```<code> DateTimeFormatter.ofPattern("MMMd/YYYY").parse("JAN01/2020")
 DateTimeFormatter.ofPattern("MMMdd/YYYY").parse("JAN01/2020")
</code>```

I also considered this post's solution and the three lines below also result in DateTimeParseException. It does not appear to be a case-sensitivity issue
Java 8 DateTimeFormatter for month in all CAPS not working

```<code>DateTimeFormatter formatter= DateTimeFormatter.ofPattern("MMMdd/yyyy");
LocalDateTime dateTime = LocalDateTime.parse("JAN14/2020", formatter);
System.out.println(dateTime.getYear());
</code>```

I appreciate any suggestions!

答:
As the question you are linking to says, you need to use a DateTimeFormatterBuilder for case insensitive parsing of your month abbreviation in upper case.

Beware of the case of format pattern letters. yyyy and YYYY are different. See for example this question: Can't parse String to LocalDate (Java 8).

Supply a locale for your formatter. If JAN is English, then supply an English-speaking locale. For example:

```<code>    new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("MMMdd/yyyy")
            .toFormatter(Locale.ENGLISH)
</code>```

As azro said, since you haven’t got a time of day, parse into a LocalDate, not a LocalDateTime (or specify a default hour of day on the builder to be able to parse into a LocalDateTime, but I don’t see the advantage).

ContentLicense: CC BY-SA 4.0

Body:
I'm being passed a date in ths format - "JAN01/2020" but I can't seem to find the DateTimeFormatter pattern for it. I tried these (as well as several others) but they're resulting in DateTimeParseException -

 DateTimeFormatter.ofPattern("MMMd/YYYY").parse("JAN01/2020")
 DateTimeFormatter.ofPattern("MMMdd/YYYY").parse("JAN01/2020")

I also considered this post's solution and the three lines below also result in DateTimeParseException. It does not appear to be a case-sensitivity issue
Java 8 DateTimeFormatter for month in all CAPS not working

DateTimeFormatter formatter= DateTimeFormatter.ofPattern("MMMdd/yyyy");
LocalDateTime dateTime = LocalDateTime.parse("JAN14/2020", formatter);
System.out.println(dateTime.getYear());

I appreciate any suggestions!

Body:
As the question you are linking to says, you need to use a DateTimeFormatterBuilder for case insensitive parsing of your month abbreviation in upper case.

Beware of the case of format pattern letters. yyyy and YYYY are different. See for example this question: Can't parse String to LocalDate (Java 8).

Supply a locale for your formatter. If JAN is English, then supply an English-speaking locale. For example:

    new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("MMMdd/yyyy")
            .toFormatter(Locale.ENGLISH)

As azro said, since you haven’t got a time of day, parse into a LocalDate, not a LocalDateTime (or specify a default hour of day on the builder to be able to parse into a LocalDateTime, but I don’t see the advantage).


问:
Handle text overflow in flutter
How to manage input to Text widget below, when i am having a hardcoded value like "data" it works fine but when i pass variable which has input value i get overflow issue. I am able to understand why its giving error but not sure how to fix that.</p>

```<code> return Container(
      width: sizew,
      height: sizeh,
      decoration: boxDecoration,

      child: FlatButton(
        padding: EdgeInsets.all(10),
        onPressed: onTap,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.elliptical(10,10),)
        ),
        child: SingleChildScrollView(
            child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              child  ?? Container(),
              Text("data"),
            ],
          ),
        ),

      ),
    );
</code>```

答:
You can give property of overflow to the Text widgets as follows:

```<code>Text("data", overflow: TextOverflow.ellipsis)
</code>```

There are plenty of others which you can try, have a look at these and chose which suits your requirements.

Title: Handle text overflow in flutter

Body:
How to manage input to Text widget below, when i am having a hardcoded value like "data" it works fine but when i pass variable which has input value i get overflow issue. I am able to understand why its giving error but not sure how to fix that.

 return Container(
      width: sizew,
      height: sizeh,
      decoration: boxDecoration,

      child: FlatButton(
        padding: EdgeInsets.all(10),
        onPressed: onTap,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.elliptical(10,10),)
        ),
        child: SingleChildScrollView(
            child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              child  ?? Container(),
              Text("data"),
            ],
          ),
        ),

      ),
    );

Body:
You can give property of overflow to the Text widgets as follows:

Text("data", overflow: TextOverflow.ellipsis)

There are plenty of others which you can try, have a look at these and chose which suits your requirements.


问:
(FLASK) I can't figure out why my html file doesn't update/render
I already tried clearing my browser cache and history, but that did not seem to help. The old html file I used (Jinja) doesn't seem to update.

Basically, I rendered a file before this and jinja seems to be rendering that old file (not sample or index) instead of either sample or index .html.

I'm a beginner at Flask, so if this is a simple fix I apologize I don't know much...

Here is my code:

sample.py

```<code>from flask import Flask, render_template, redirect, url_for

app = Flask(" APP ")

@app.route("/home")
def home():
    return render_template("sample.html")

if __name__ == "__main__":
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    app.run(debug = True)
</code>```

index.html (inherits from sample.html)

```<code>{% extends "sample.html" %}
{% block title %}Home Page {% endblock %}
{% block content %}
<h1> Welcome to the Index Page!</h1>
{% endblock %}
</code>```

sample.html

```<code><!doctype html>
<html>
<head>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
       <span class="navbar-toggler-icon"></span>
   </button>
         <div class="collapse navbar-collapse" id="navbarNav">
             <ul class="navbar-nav">
           <li class="nav-item active">
                     <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#">Pricing</a>
    </li>
    <li class="nav-item">
        <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
    </li>
      </ul>
        </div>
    </nav>
    {% block content %}
    {% endblock %}
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
</code>```

答:
Make sure html file is in templates folder.
We use the render_template() method to render the index.html template which we'll be creating in the templates folder of our project and then you should render index.html.

```<code>return render_template("index.html")
</code>```

Body:
I already tried clearing my browser cache and history, but that did not seem to help. The old html file I used (Jinja) doesn't seem to update.

Basically, I rendered a file before this and jinja seems to be rendering that old file (not sample or index) instead of either sample or index .html.

I'm a beginner at Flask, so if this is a simple fix I apologize I don't know much...

Here is my code:

sample.py

from flask import Flask, render_template, redirect, url_for

app = Flask(" APP ")

@app.route("/home")
def home():
    return render_template("sample.html")

if __name__ == "__main__":
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    app.run(debug = True)

index.html (inherits from sample.html)

{% extends "sample.html" %}
{% block title %}Home Page {% endblock %}
{% block content %}

 Welcome to the Index Page!

{% endblock %}

sample.html

<!doctype html>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>{% block title %}{% endblock %}</title>

        Navbar
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

   </button>

                     Home (current)

        Features

        Pricing

        Disabled

    {% block content %}
    {% endblock %}

Body:
Make sure html file is in templates folder.
We use the render_template() method to render the index.html template which we'll be creating in the templates folder of our project and then you should render index.html.

return render_template("index.html")


问:
React Native createStackNavigator and createBottomTabNavigator
So I was looking at React Native Tab Navigation v5 (https://reactnavigation.org/docs/tab-based-navigation)
and I can't seem to figure out how I can have a tab navigator and a stack navigator at the same time.

```<code>//react-native-gesture-handler at top according to reactnavigation.org/docs/
import 'react-native-gesture-handler';
import * as React from 'react';
import { View, Text } from 'react-native';

//npm packages
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

//pages
import login from './pages/login';
import main from './pages/main';
import page1 from './pages/page1';
import page2 from './pages/page2';
import page3 from './pages/page3';
import page4 from './pages/page4';
import page5 from './pages/page5';

const Stack = createStackNavigator();
const Tab = createBottomTabNavigator();

const TabStack = () => {
  return (
      <Tab.Navigator>
        <Tab.Screen name="Page1" component={page1} />
        <Tab.Screen name="Page2" component={page2} />
      </Tab.Navigator>
  );
}

const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Login" headerMode="none">
        <Stack.Screen name="Login" component={login} />
        <Stack.Screen name="Main" component={main} />
        <Stack.Screen name="page1" component={page1} />
        <Stack.Screen name="page2" component={page2} />
        <Stack.Screen name="page3" component={page3} />
        <Stack.Screen name="page4" component={page4} />
        <Stack.Screen name="page5" component={page5} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;
</code>```

The idea is that I want to be able to navigate between all screens but I want to include a bottomTabNavigator only on some. Anyone can give me a hint on how can this be achieved in React Native?

答:
From the documentation of React navigation 5

The easiest way to achieve this is to nest the tab navigator inside the first screen of the stack instead of nesting stack inside tab navigator

This is an example from the documentation:

```<code>function HomeTabs() {
  return (
    <Tab.Navigator>
      <Tab.Screen name="Home" component={Home} />
      <Tab.Screen name="Feed" component={Feed} />
      <Tab.Screen name="Notifications" component={Notifications} />
    </Tab.Navigator>
  );
}

function App() {
  return (
    <Stack.Navigator>
      <Stack.Screen name="Home" component={HomeTabs} />
      <Stack.Screen name="Profile" component={Profile} />
      <Stack.Screen name="Settings" component={Settings} />
    </Stack.Navigator>
  );
}
</code>```

Which in your case would translate into put all the screen where you want to show the tab bar into a TabStack:

```<code>const TabStack = () => {
  return (
      <Tab.Navigator>
        <Tab.Screen name="Page1" component={page1} />
        <Tab.Screen name="Page2" component={page2} />
      </Tab.Navigator>
  );
}
</code>```

and all the other screens and the tab navigator in the stack navigator

```<code>const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Login" headerMode="none">
        <Stack.Screen name="Page1" component={TabStack}
        <Stack.Screen name="Login" component={login} />
        <Stack.Screen name="Main" component={main} />
        <Stack.Screen name="page3" component={page3} />
        <Stack.Screen name="page4" component={page4} />
        <Stack.Screen name="page5" component={page5} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}
</code>```

Body:
So I was looking at React Native Tab Navigation v5 (https://reactnavigation.org/docs/tab-based-navigation)
and I can't seem to figure out how I can have a tab navigator and a stack navigator at the same time.

//react-native-gesture-handler at top according to reactnavigation.org/docs/
import 'react-native-gesture-handler';
import * as React from 'react';
import { View, Text } from 'react-native';

//npm packages
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

//pages
import login from './pages/login';
import main from './pages/main';
import page1 from './pages/page1';
import page2 from './pages/page2';
import page3 from './pages/page3';
import page4 from './pages/page4';
import page5 from './pages/page5';

const Stack = createStackNavigator();
const Tab = createBottomTabNavigator();

const TabStack = () => {
  return (
      <Tab.Navigator>
        <Tab.Screen name="Page1" component={page1} />
        <Tab.Screen name="Page2" component={page2} />
      </Tab.Navigator>
  );
}

const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Login" headerMode="none">
        <Stack.Screen name="Login" component={login} />
        <Stack.Screen name="Main" component={main} />
        <Stack.Screen name="page1" component={page1} />
        <Stack.Screen name="page2" component={page2} />
        <Stack.Screen name="page3" component={page3} />
        <Stack.Screen name="page4" component={page4} />
        <Stack.Screen name="page5" component={page5} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

The idea is that I want to be able to navigate between all screens but I want to include a bottomTabNavigator only on some. Anyone can give me a hint on how can this be achieved in React Native?

Body:
From the documentation of React navigation 5

The easiest way to achieve this is to nest the tab navigator inside the first screen of the stack instead of nesting stack inside tab navigator

This is an example from the documentation:

function HomeTabs() {
  return (
    <Tab.Navigator>
      <Tab.Screen name="Home" component={Home} />
      <Tab.Screen name="Feed" component={Feed} />
      <Tab.Screen name="Notifications" component={Notifications} />
    </Tab.Navigator>
  );
}

function App() {
  return (
    <Stack.Navigator>
      <Stack.Screen name="Home" component={HomeTabs} />
      <Stack.Screen name="Profile" component={Profile} />
      <Stack.Screen name="Settings" component={Settings} />
    </Stack.Navigator>
  );
}

Which in your case would translate into put all the screen where you want to show the tab bar into a TabStack:

const TabStack = () => {
  return (
      <Tab.Navigator>
        <Tab.Screen name="Page1" component={page1} />
        <Tab.Screen name="Page2" component={page2} />
      </Tab.Navigator>
  );
}

and all the other screens and the tab navigator in the stack navigator

const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Login" headerMode="none">
        <Stack.Screen name="Page1" component={TabStack}
        <Stack.Screen name="Login" component={login} />
        <Stack.Screen name="Main" component={main} />
        <Stack.Screen name="page3" component={page3} />
        <Stack.Screen name="page4" component={page4} />
        <Stack.Screen name="page5" component={page5} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}


问:
how to send typing alert and message to users in a particular room using nodejs socket.io
The code below works fine by broadcasting typing notification and chat messages to all connected users.

Here is what I want: How do I send typing notification and chat messages only to users connected to a particular room
say Room1, Room2 etc.

here is the code

index.html

```<code>var socket = io();
var user = 'nancy';
function submitfunction(){
  var from = 'nancy';
  var message = 'hello Nancy';
  socket.emit('chatMessage', from, message);
}

function notifyTyping() {
  var user = 'nancy'
  socket.emit('notifyUser', user);
}

socket.on('chatMessage', function(from, msg){
  //sent message goes here
});

socket.on('notifyUser', function(user){
    $('#notifyUser').text(nancy is typing ...');
  setTimeout(function(){ $('#notifyUser').text(''); }, 10000);
});
</code>```

server.js

```<code>var io = require('socket.io')(http);
io.on('connection', function(socket){
  socket.on('chatMessage', function(from, msg){
    io.emit('chatMessage', from, msg);
  });

  socket.on('notifyUser', function(user){
    io.emit('notifyUser', user);
  });
});
</code>```

am using npm installed socket.io ^2.3.0

答:
To send the message to a specific room, you will have to create and join a room with roomId. Below is a basic code snippet

```<code>//client side
const socket = io.connect();
socket.emit('create', 'room1');

// server side code
  socket.on('create', function(room1) {
    socket.join(room1);
  });

To emit data to a specific room

// sending to all clients in 'room1'except sender
  socket.to('room1').emit('event',data);

// sending to all clients in 'room1' room, including sender
 io.in('room1').emit('event', 'data');
</code>```

You can follow this question for details on how to create a room?

Creating Rooms in Socket.io

This emit cheat sheet might also be useful:
https://github.com/socketio/socket.io/blob/master/docs/emit.md

Body:
The code below works fine by broadcasting typing notification and chat messages to all connected users.

Here is what I want: How do I send typing notification and chat messages only to users connected to a particular room
say Room1, Room2 etc.

here is the code

index.html

var socket = io();
var user = 'nancy';
function submitfunction(){
  var from = 'nancy';
  var message = 'hello Nancy';
  socket.emit('chatMessage', from, message);
}

function notifyTyping() {
  var user = 'nancy'
  socket.emit('notifyUser', user);
}

socket.on('chatMessage', function(from, msg){
  //sent message goes here
});

socket.on('notifyUser', function(user){
    $('#notifyUser').text(nancy is typing ...');
  setTimeout(function(){ $('#notifyUser').text(''); }, 10000);
});

server.js

var io = require('socket.io')(http);
io.on('connection', function(socket){
  socket.on('chatMessage', function(from, msg){
    io.emit('chatMessage', from, msg);
  });

  socket.on('notifyUser', function(user){
    io.emit('notifyUser', user);
  });
});

am using npm installed socket.io ^2.3.0

Body:
To send the message to a specific room, you will have to create and join a room with roomId. Below is a basic code snippet

//client side
const socket = io.connect();
socket.emit('create', 'room1');

// server side code
  socket.on('create', function(room1) {
    socket.join(room1);
  });

To emit data to a specific room

// sending to all clients in 'room1'except sender
  socket.to('room1').emit('event',data);

// sending to all clients in 'room1' room, including sender
 io.in('room1').emit('event', 'data');

You can follow this question for details on how to create a room?

Creating Rooms in Socket.io

This emit cheat sheet might also be useful:
https://github.com/socketio/socket.io/blob/master/docs/emit.md


问:
Html To Pdf with bootstrap
I am making a payment gateway for a client using authorize.net which I have succesfully managed to do so. Now the client wants to have a receipt for the user to download on the success page. I have all the necessary data in php variables stored for printing. But the invoice that my client wants has a specific design , there are a lot of alignments, lines. I have tried jspdf. but doesnt go with the styling of my html. and I dont know how to align things in it myself. Can anyone give me a go-ahead what should I do to print pdf anyway I like.
Thanks</p>

答:
In case you are still looking for a solution, or someone else comes across this question, see this answer https://stackoverflow.com/a/61484708/3761687

While that question was about React, the solution works with any framework.

Title: Html To Pdf with bootstrap


问:
How can I outline the whole container when search bar is pressed?
How can I outline the whole container(search button and search bar) when search bar is pressed?

.container {
  display: flex;
  flex-direction: row;
  border: 1px solid gray;
  width: 22%;
  height: 42px;
}

.container:focus {
  outline-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <form>
    <center>
        <input type="text" class="sea" placeholder="Search supplies...">
        <button class="toc"></button>
    </center>
    </form>
</div></code>```

答:
If you want to use JavaScript for this, something like this should do the trick. Is this something you are looking for?

(function() {
  const inputForm = document.querySelector('.js-formInputX');
  const classFocus = "is-focused";

  inputForm.addEventListener("focusin", (event)=> {
    let currentInput = event.currentTarget;
    // Get parent, traverse 2 up, not the most elegant way
    let getParent = currentInput.parentNode.parentNode

    // Add class
    getParent.classList.add(`${classFocus}`);
  });

  inputForm.addEventListener("focusout", (event)=> {
    let currentInput = event.currentTarget;
    // Get parent, traverse 2 up, not the most elegant way
    let getParent = currentInput.parentNode.parentNode

    // Remove class
    getParent.classList.remove(`${classFocus}`);
  });
})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  display: flex;
  flex-direction: row;
  border: 1px solid gray;
  width: 22%;
  height: 42px;
}

/* Add custom styling here */
.container.is-focused {
  border: 2px solid black;
}

.container:focus {
  outline-color: green;
}</code>```

    <form>
        <input type="text" class="sea js-formInputX" placeholder="Search supplies...">
        <button class="toc"></button>
    </form>

```

Body:
How can I outline the whole container(search button and search bar) when search bar is pressed?

.container {
  display: flex;
  flex-direction: row;
  border: 1px solid gray;
  width: 22%;
  height: 42px;
}

.container:focus {
  outline-color: green;
}

    <form>

        <input type="text" class="sea" placeholder="Search supplies...">
        <button class="toc"></button>

    </form>

Body:
If you want to use JavaScript for this, something like this should do the trick. Is this something you are looking for?

(function() {
  const inputForm = document.querySelector('.js-formInputX');
  const classFocus = "is-focused";

  inputForm.addEventListener("focusin", (event)=> {
    let currentInput = event.currentTarget;
    // Get parent, traverse 2 up, not the most elegant way
    let getParent = currentInput.parentNode.parentNode

    // Add class
    getParent.classList.add(`${classFocus}`);
  });

  inputForm.addEventListener("focusout", (event)=> {
    let currentInput = event.currentTarget;
    // Get parent, traverse 2 up, not the most elegant way
    let getParent = currentInput.parentNode.parentNode

    // Remove class
    getParent.classList.remove(`${classFocus}`);
  });
})();

.container {
  display: flex;
  flex-direction: row;
  border: 1px solid gray;
  width: 22%;
  height: 42px;
}

/* Add custom styling here */
.container.is-focused {
  border: 2px solid black;
}

.container:focus {
  outline-color: green;
}

<div class="container">
    <form>
        <input type="text" class="sea js-formInputX" placeholder="Search supplies...">
        <button class="toc"></button>
    </form>
</div>


问:
no matching function for call to 'std::vector<std.. '
The question I am solving states: I have to take T test cases. For each test case I have to take string as an input, then I need to arrange the input string as: string at even position {double space} string at odd position (example: input - StackOverflow, output - Sakvrlw tcOefo). I've written the following code where I am taking input for all test cases and storing it in a vector. Then I am assigning the elements of vector to another declared string s.

```<code>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
     int T,i;
     cout << "Enter no. of test cases: ";
     cin >> T;

     vector<string> v;
     vector<string> odd;
     vector<string> even;
     string str;

     for(int i=0; i<T; i++){
        cin >> str;
        v.push_back(str);
     }

     string s;

     for(i=0; i<v.size(); i++){
        s = v.at(i);

        for(i=0; i<s.size(); i++){
            if(i==0){
                even.push_back(s[i]);  //*This is where I am getting error*.
            }else if(i==1){
                odd.push_back(s[i]);
            }else{
                if(i%2==0){
                    even.push_back(s[i]);
                }else{
                    odd.push_back(s[i]);
                }
            }
        }

        for(i=0; i<even.size(); i++){
            cout << even.at(i);
        }

        cout << "  ";

        for(i=0; i<odd.size(); i++){
            cout << odd.at(i);
        }

        cout << endl;

        even.clear();
        odd.clear();
        s.clear();
     }

     return 0;
}

</code>```

While compiling the above code I'm getting "no matching error for call std::vector...".
What exactly am I doing wrong?

答:
Welcome to Stack Overflow @Manish Jha,

So s[i] is a char

s is a std::string or an array of chars

The method must be push_back(std::string&) not push_back(std::char&)

The class template method std::vector::push_back(T&) is kind of "specialized" when you initialized your even/odd vector so, either append a std::string to std::vector<std::string> or a char to std::vector<char>

Otherwise, there is no maching for call the method std::vector<T>::push_back(T&)

Hope i answered correctly to your waitings, if there are any errors, please notify me.

Body:
The question I am solving states: I have to take T test cases. For each test case I have to take string as an input, then I need to arrange the input string as: string at even position {double space} string at odd position (example: input - StackOverflow, output - Sakvrlw tcOefo). I've written the following code where I am taking input for all test cases and storing it in a vector. Then I am assigning the elements of vector to another declared string s.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
     int T,i;
     cout << "Enter no. of test cases: ";
     cin >> T;

     vector<string> v;
     vector<string> odd;
     vector<string> even;
     string str;

     for(int i=0; i<T; i++){
        cin >> str;
        v.push_back(str);
     }

     string s;

     for(i=0; i<v.size(); i++){
        s = v.at(i);

        for(i=0; i<s.size(); i++){
            if(i==0){
                even.push_back(s[i]);  //*This is where I am getting error*.
            }else if(i==1){
                odd.push_back(s[i]);
            }else{
                if(i%2==0){
                    even.push_back(s[i]);
                }else{
                    odd.push_back(s[i]);
                }
            }
        }

        for(i=0; i<even.size(); i++){
            cout << even.at(i);
        }

        cout << "  ";

        for(i=0; i<odd.size(); i++){
            cout << odd.at(i);
        }

        cout << endl;

        even.clear();
        odd.clear();
        s.clear();
     }

     return 0;
}

While compiling the above code I'm getting "no matching error for call std::vector...".
What exactly am I doing wrong?


问:
checking if two dataframes have the same values at the same row and column in R
I have these two dataframes

```<code>x = c(2,4,2,4,4,6)
y = c("hi", "xyz" ,"xyz" ,"xyz" ,"xyz" ,"xyz")
z = c(2,4,5,5,5,5)
dfa = data.frame(X = x, Y = y, Z = z)
dfa

   X  Y      Z
1  2  "hi"   2
2  4  "xyz"  4
3  2  "xyz"  5
4  4  "xyz"  5
5  4  "xyz"  5
6  6  "xyz"  5
</code>```

And another one with same rows and columns

```<code>x = c(2,7,8,2,4,6)
y = c("hi", "234" ,"xyz" ,"25" ,"xyz" ,"dfs")
z = c(20,4,5,3,1,5)
dfb = data.frame(X = x, Y = y, Z = z)
dfb

   X  Y      Z
1  2  "hi"   20
2  7  "234"  4
3  8  "xyz"  5
4  2  "25"   3
5  4  "xyz"  1
6  6  "dfs"  5
</code>```

I want to get the number of times for each column that the value in dfa is the same as dfb

So for this example the output would be

```<code>    X   Y   Z
1   2   3   3
</code>```

Kindly let me know how to proceed with this.
Thank you very much

答:
We can use Map from base R

```<code>Map(function(x, y) sum(x == y, na.rm = TRUE), dfa, dfb)
</code>```

Body:
I have these two dataframes

x = c(2,4,2,4,4,6)
y = c("hi", "xyz" ,"xyz" ,"xyz" ,"xyz" ,"xyz")
z = c(2,4,5,5,5,5)
dfa = data.frame(X = x, Y = y, Z = z)
dfa

   X  Y      Z
1  2  "hi"   2
2  4  "xyz"  4
3  2  "xyz"  5
4  4  "xyz"  5
5  4  "xyz"  5
6  6  "xyz"  5

And another one with same rows and columns

x = c(2,7,8,2,4,6)
y = c("hi", "234" ,"xyz" ,"25" ,"xyz" ,"dfs")
z = c(20,4,5,3,1,5)
dfb = data.frame(X = x, Y = y, Z = z)
dfb

   X  Y      Z
1  2  "hi"   20
2  7  "234"  4
3  8  "xyz"  5
4  2  "25"   3
5  4  "xyz"  1
6  6  "dfs"  5

I want to get the number of times for each column that the value in dfa is the same as dfb

So for this example the output would be

    X   Y   Z
1   2   3   3

Kindly let me know how to proceed with this.
Thank you very much

Body:
We can use Map from base R

Map(function(x, y) sum(x == y, na.rm = TRUE), dfa, dfb)


问:
checking if the graph is bipartite.why is my function returning none?
```<code>import collections
class Solution(object):
    def possibleBipartition(self, N, dislikes):
        graph = collections.defaultdict(list)
        for u, v in dislikes:
            graph[u].append(v)
            graph[v].append(u)

        color = {}
        def dfs(node, c = 0):
            if node in color:
                return color[node] == c
            color[node] = c
            for nei in graph[node]:
                dfs(nei,c^1)

        for node in range(1, N+1):
            if node not in color:
                dfs(node)
g=Solution()
N=3
dislikes=[[1,2],[2,3]]
print(g.possibleBipartition(N, dislikes))
</code>```

Numerous solution is available online.But I am new to recursion. I want to understand why is my function returning none as the knowledge is going to help me later :)
Thanks in advance.

答:
Seems it's returning None since you don't have a return ... anywhere in your code. I'd make sure that you're explicitly returning where you need to be. For example, two spots that you might want to add a return statement:

return dfs(nei,c^1)
```

<p>in your <code>dfs()</code> function as well as:</p>

<pre class="lang-py prettyprint-override"><code>return dfs(node)
</code>```

in your possibleBipartition() function.

Note that you need to explicitly specify the return in Python if there is one unlike in languages like Racket and Haskell.

Body:
import collections
class Solution(object):
    def possibleBipartition(self, N, dislikes):
        graph = collections.defaultdict(list)
        for u, v in dislikes:
            graph[u].append(v)
            graph[v].append(u)

        color = {}
        def dfs(node, c = 0):
            if node in color:
                return color[node] == c
            color[node] = c
            for nei in graph[node]:
                dfs(nei,c^1)

        for node in range(1, N+1):
            if node not in color:
                dfs(node)
g=Solution()
N=3
dislikes=[[1,2],[2,3]]
print(g.possibleBipartition(N, dislikes))

Numerous solution is available online.But I am new to recursion. I want to understand why is my function returning none as the knowledge is going to help me later :)
Thanks in advance.

Body:
Seems it's returning None since you don't have a return ... anywhere in your code. I'd make sure that you're explicitly returning where you need to be. For example, two spots that you might want to add a return statement:

return dfs(nei,c^1)

in your dfs() function as well as:

return dfs(node)

in your possibleBipartition() function.

Note that you need to explicitly specify the return in Python if there is one unlike in languages like Racket and Haskell.


问:
Runnable Handler not executing inside fragment. Could not start a runnable
I have a runnable inside a fragment. The runnable is meant to update the textviews as well as receive input using buttons. But the program does not enter even once inside the runnable.

Please help. What am I doing wrong.
Thanks.
The code is as follows. I have buttons and textviews inside the runnable.

```<code>public class TodayFragment extends Fragment {
//initialisations

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

//UI initialisations

Handler mHandler = new Handler();
Runnable mTicker = new Runnable() {
            @Override
            public void run() {

//user interface interactions and updates on screen

    mHandler.postDelayed(mTicker, 1000);

   mTicker.run();

 }
</code>```

答:
It's work for me.</p>

```<code>public class TodayFragment extends Fragment {
//initialisations
Runnable mTicker;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    final Handler mHandler = new Handler();
    mTicker = new Runnable() {
        @Override
        public void run() {

            // user interface interactions and updates on screen

            mHandler.postDelayed(mTicker, 1000);

            }
        };

    mHandler.postDelayed(mTicker, 1000);

    return inflater.inflate(R.layout.fragment_today, container, false);;

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a runnable inside a fragment. The runnable is meant to update the textviews as well as receive input using buttons. But the program does not enter even once inside the runnable.

Please help. What am I doing wrong.
Thanks.
The code is as follows. I have buttons and textviews inside the runnable.

public class TodayFragment extends Fragment {
//initialisations

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

//UI initialisations

Handler mHandler = new Handler();
Runnable mTicker = new Runnable() {
            @Override
            public void run() {

//user interface interactions and updates on screen

    mHandler.postDelayed(mTicker, 1000);

   mTicker.run();

 }

Body:
It's work for me.

public class TodayFragment extends Fragment {
//initialisations
Runnable mTicker;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    final Handler mHandler = new Handler();
    mTicker = new Runnable() {
        @Override
        public void run() {

            // user interface interactions and updates on screen

            mHandler.postDelayed(mTicker, 1000);

            }
        };

    mHandler.postDelayed(mTicker, 1000);

    return inflater.inflate(R.layout.fragment_today, container, false);;

}


答:
On the surface, the function returns None because you have no return statement. So the function possibleBipartition doesn't return anything (i.e. None). This is just a syntax thing that python allows you to do without any error, which can be confusing to new people. You're going to need to return something from your function in order for your print statement to not just print None. A good idea might be to return True if and only if the possibleBipartition is valid.

One adjustment you could play with is checking the color dict you build in the function to see if the "possibleBipartition" is valid or not. This can be achieved knowing the following fact: A graph has a valid biparitition iff each vertex is only belongs to one color (0 or 1 in your case).

Title: checking if the graph is bipartite.why is my function returning none?


问:
How to Add Java Method Timer for Redirect in ZK
Hello fellow developer,i've getting problem to set the Timer method on ZK,default the method in my .zul page is:

```<code><timer id="timer" delay="1000" repeats="false"
onTimer="response.sendRedirect('./Login.zul')" />
</code>```

but the code is error(i think beacuse ('./Login.zul'),if i try (\"./Login.zul\"),still show error),i try to build in my controller page like this:

```<code>     private Timer timer=new Timer( 1000 );

    public OTPController() {

        timer.setRepeats( true );
        timer.setAttribute( "onTimer","response.sendRedirect(\"./Login.zul\")", Timer.COMPONENT_SCOPE );

        timer.start();
}
</code>```

but nothing happen..:(

anybody can help me?

maybe i have to create java script method or something like that?
iam still trying to find the answer,ive read the ZK Docs but nothing can help..

Thanks for your attention and sorry for my bad english :D

答:
onTimer

is an event not an attribute[1]. You should use addEventListener() [2] on your Timer component to add a method that does the actual sendRedirect. For eg. in your OTPController you can do

```<code><!-- language: lang-js -->
timer.addEventListener(Events.ON_TIMER, new EventListener() {
        public void onEvent(Event evt) {
           Executions.sendRedirect("./Login.zul"); //refer [3]
    }
});
</code>```

[1] http://books.zkoss.org/wiki/ZK_Component_Reference/Essential_Components/Timer#Supported_Events
[2] http://books.zkoss.org/wiki/ZK_Developer's_Reference/Event_Handling/Event_Listening#Event_Listener
[3] http://books.zkoss.org/wiki/ZK_Developer's_Reference/UI_Patterns/Forward_and_Redirect#Redirect_to_Another_URL

Body:
Hello fellow developer,i've getting problem to set the Timer method on ZK,default the method in my .zul page is:

<timer id="timer" delay="1000" repeats="false"
onTimer="response.sendRedirect('./Login.zul')" />

but the code is error(i think beacuse ('./Login.zul'),if i try (\"./Login.zul\"),still show error),i try to build in my controller page like this:

     private Timer timer=new Timer( 1000 );

    public OTPController() {

        timer.setRepeats( true );
        timer.setAttribute( "onTimer","response.sendRedirect(\"./Login.zul\")", Timer.COMPONENT_SCOPE );

        timer.start();
}

but nothing happen..:(

anybody can help me?

maybe i have to create java script method or something like that?
iam still trying to find the answer,ive read the ZK Docs but nothing can help..

Thanks for your attention and sorry for my bad english :D

Body:
onTimer

is an event not an attribute[1]. You should use addEventListener() [2] on your Timer component to add a method that does the actual sendRedirect. For eg. in your OTPController you can do

<!-- language: lang-js -->
timer.addEventListener(Events.ON_TIMER, new EventListener() {
        public void onEvent(Event evt) {
           Executions.sendRedirect("./Login.zul"); //refer [3]
    }
});

[1] http://books.zkoss.org/wiki/ZK_Component_Reference/Essential_Components/Timer#Supported_Events
[2] http://books.zkoss.org/wiki/ZK_Developer's_Reference/Event_Handling/Event_Listening#Event_Listener
[3] http://books.zkoss.org/wiki/ZK_Developer's_Reference/UI_Patterns/Forward_and_Redirect#Redirect_to_Another_URL


问:
Why is my Log4j logging not displaying to the console?
I have a web app built in Eclipse/STS with Spring MVC and Maven.

I want to add logging, so I added SLF4 and Log4J to the pom.xml like this ..

```<code>     <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.30</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.30</version>
        <scope>test</scope>
    </dependency>

     <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.30</version>
        <scope>test</scope>
    </dependency>
</code>```

I have a simple log4j.properties file in the project/src/main/resources folder, like this ...

```<code># Root logger option
log4j.rootLogger=DEBUG, stdout, file

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
</code>```

I created a Logger class in my main WebController, like this ...

```<code>private static Logger logger = LoggerFactory.getLogger(WebController.class);
</code>```

And in my "showMain" method I'm doing some logging stuff, like this ...

```<code>@RequestMapping(value={"", "/", "showhome"}, method={RequestMethod.POST,RequestMethod.GET})
public ModelAndView showHome(Model model) {

    logger.info("########### TEST LOG INFO");
    logger.error("########### TEST LOG ERROR");
    logger.warn("########### TEST LOG WARN");
    logger.debug("########### TEST LOG DEBUG");

    /* ... */
}
</code>```

But when I run the application, I don't see any logging output in the console.

I also don't see anything in the console output to indicate that it is even using the logging framework.  And there's no "can't find log4j.properties" message or anything.

I tried putting the log4j.properties in different places in the project, but nothing.

I must be missing something simple?  What have I missed?

答:
In your pom.xml is missing the logging engine, you could use log4j2.
Please Consider to use the latest version of log4j2 instead of log4j (1.2.x) because you could take advance of:

Lazy log: log4j(1.2.x) build a string also if a level is not activated

lambda in order to avoid evaluation of expensive methods

A lot of appenders for modern platform

More easy way to configure a lot of parameters (reload configuration, appenders, ...)

pom.xml

```<code><dependencies>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.13.3</version>
  </dependency>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.13.3</version>
  </dependency>
</dependencies>
</code>```

Body:
I have a web app built in Eclipse/STS with Spring MVC and Maven.

I want to add logging, so I added SLF4 and Log4J to the pom.xml like this ..

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.30</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.30</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.30</version>
        <scope>test</scope>
    </dependency>

I have a simple log4j.properties file in the project/src/main/resources folder, like this ...

# Root logger option
log4j.rootLogger=DEBUG, stdout, file

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

I created a Logger class in my main WebController, like this ...

private static Logger logger = LoggerFactory.getLogger(WebController.class);

And in my "showMain" method I'm doing some logging stuff, like this ...

@RequestMapping(value={"", "/", "showhome"}, method={RequestMethod.POST,RequestMethod.GET})
public ModelAndView showHome(Model model) {

    logger.info("########### TEST LOG INFO");
    logger.error("########### TEST LOG ERROR");
    logger.warn("########### TEST LOG WARN");
    logger.debug("########### TEST LOG DEBUG");

    /* ... */
}

But when I run the application, I don't see any logging output in the console.

I also don't see anything in the console output to indicate that it is even using the logging framework.  And there's no "can't find log4j.properties" message or anything.

I tried putting the log4j.properties in different places in the project, but nothing.

I must be missing something simple?  What have I missed?

Body:
In your pom.xml is missing the logging engine, you could use log4j2.
Please Consider to use the latest version of log4j2 instead of log4j (1.2.x) because you could take advance of:

Lazy log: log4j(1.2.x) build a string also if a level is not activated

lambda in order to avoid evaluation of expensive methods

A lot of appenders for modern platform

More easy way to configure a lot of parameters (reload configuration, appenders, ...)

pom.xml

<dependencies>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.13.3</version>
  </dependency>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.13.3</version>
  </dependency>
</dependencies>


问:
How to change the position of HTML elements with JavaScript
I have a site in WordPress and a widget generates this login, but I want to change the position of these two elements, it is a pity that I cannot edit the html code and I can only make the change with JavaScript

I'm trying to get the red down and the green up

I deal with CSS, but not responsive, now I am dealing with JavaScript but I am not very skilled with it

these are the two elements of the HTML

```<code><div class='mo-openid-app-icons'>
<p style='color:#000000; width: fit-content;'> Conectar con Google</p>Login with Google</span></a>
</div> <br><br/>
<a class="lost-pass-link" href="" title="Contraseña perdida">¿Perdiste tu contraseña?</a>
<p class="forgetmenot login-remember">
    <label for="popupRememberme"><input name="rememberme" type="checkbox" value="forever" id="popupRememberme"/>
        Recuérdame
    </label>
</p>
<p class="submit login-submit">
    <input type="submit" name="wp-submit"
    class="button button-primary button-large"
    value="Iniciar sesión"/>

    <input type="hidden" name="redirect_to"
    value="https://bloque10.unimagdalena.edu.co/ovateca/"/>
    <input type="hidden" name="testcookie" value="1"/>
    <input type="hidden" name="nonce" value="77ba00d276"/>
    <input type="hidden" name="eduma_login_user">
</p>
</code>```

I really appreciate any help

答:
You may insert a temporary element before the blue element, then swap the positions of blue and red elements using their common parent's Node.insertBefore method.

const redDiv = document.querySelector('.red');

const placeholder = document.createElement('span')
const blueP = document.querySelector('.blue');

const parent = redDiv.parentElement;
parent.insertBefore(placeholder, blueP);
parent.insertBefore(blueP, redDiv);
parent.insertBefore(redDiv, placeholder);
parent.removeChild(placeholder);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.red {
  border: 1px dashed red;
}
.blue {
  border: 1px dashed blue;
}</code>```

<form>

red

blue

</form>```

Body:
I have a site in WordPress and a widget generates this login, but I want to change the position of these two elements, it is a pity that I cannot edit the html code and I can only make the change with JavaScript

I'm trying to get the red down and the green up

I deal with CSS, but not responsive, now I am dealing with JavaScript but I am not very skilled with it

these are the two elements of the HTML

 Conectar con Google
Login with Google

¿Perdiste tu contraseña?

    <input name="rememberme" type="checkbox" value="forever" id="popupRememberme"/>
        Recuérdame

    <input type="submit" name="wp-submit"
    class="button button-primary button-large"
    value="Iniciar sesión"/>

    <input type="hidden" name="redirect_to"
    value="https://bloque10.unimagdalena.edu.co/ovateca/"/>
    <input type="hidden" name="testcookie" value="1"/>
    <input type="hidden" name="nonce" value="77ba00d276"/>
    <input type="hidden" name="eduma_login_user">

I really appreciate any help

Body:
You may insert a temporary element before the blue element, then swap the positions of blue and red elements using their common parent's Node.insertBefore method.

const redDiv = document.querySelector('.red');

const placeholder = document.createElement('span')
const blueP = document.querySelector('.blue');

const parent = redDiv.parentElement;
parent.insertBefore(placeholder, blueP);
parent.insertBefore(blueP, redDiv);
parent.insertBefore(redDiv, placeholder);
parent.removeChild(placeholder);

.red {
  border: 1px dashed red;
}
.blue {
  border: 1px dashed blue;
}

<form>
 <div class="red">red</div>
  <br>
  <br>
  <p class="blue">blue</p>
</form>


问:
Illustrator Scripting how to get the angle of an object
How to get angle of GroupItem or Layer ?

I tried this, but it not works for me:

```<code>var doc = app.activeDocument;
var sel = doc.selection[0];
if(sel.tags.length > 0 && sel.tags[0].name == "BBAccumRotation"){
    alert(sel.tags[0].value);
}
</code>```

答:
It's working, but it's giving you Radians -- you'll have to convert to degrees:

var doc = app.activeDocument;
var sel = doc.selection[0];

function rad2Deg(n) {
  return n * (180 / Math.PI);
}
if (sel.tags.length > 0 && sel.tags[0].name === "BBAccumRotation") {
  alert(rad2Deg(sel.tags[0].value));
}```

Body:
How to get angle of GroupItem or Layer ?

I tried this, but it not works for me:

var doc = app.activeDocument;
var sel = doc.selection[0];
if(sel.tags.length > 0 && sel.tags[0].name == "BBAccumRotation"){
    alert(sel.tags[0].value);
}


问:
Non-monotonous DTS after 26:30:02.81 recording time
I record an hls stream and after 26:30:02.81 there come the message:

```<code>[http @ 0x558330f5ba80] Opening 'http://de-origin-live-be-01.3qsdn.com:8081/3279/996191_PwxkbnqRThCDGXVr/l_94_95438333_16449.ts?nimblesessionid=2106' for reading
frame=2289669 fps= 24 q=-1.0 size=25056768kB time=26:30:02.81 bitrate=2151.6kbits/s speed=   1x
[mpegts @ 0x558330f07280] Invalid timestamps stream=0, pts=10378, dts=8589926250, size=11200
[mpegts @ 0x558330f07280] Invalid timestamps stream=0, pts=2908, dts=8589929940, size=3407
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:0; previous: 8586744840, current: -3185972; changing to 8586744841. This may result in incorrect timestamps in the output file.
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:1; previous: 4579598864, current: -1698561; changing to 4579598865. This may result in incorrect timestamps in the output file.
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:1; previous: 4579598865, current: -1697537; changing to 4579598866. This may result in incorrect timestamps in the output file.
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:1; previous: 4579598866, current: -1696513; changing to 4579598867. This may result in incorrect timestamps in the output file.
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:0; previous: 8586744841, current: -3182282; changing to 8586744842. This may result in incorrect timestamps in the output file.
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:1; previous: 4579598867, current: -1695489; changing to 4579598868. This may result in incorrect timestamps in the output file.
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:1; previous: 4579598868, current: -1694465; changing to 4579598869. This may result in incorrect timestamps in the output file.
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:1; previous: 4579598869, current: -1693441; changing to 4579598870. This may result in incorrect timestamps in the output file.
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:0; previous: 8586744842, current: -3178502; changing to 8586744843. This may result in incorrect timestamps in the output file.
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:0; previous: 8586744843, current: -3174722; changing to 8586744844. This may result in incorrect timestamps in the output file.
</code>```

There is no more video written to the file at this time but ffmpeg is not stopping. If i stop it manual after 30 hours the file is only 26 hours 30 minutes long.

How to reproduce:

```<code>ffmpeg -progress recorder.progress -reconnect 1 -user_agent 'sdn/1.0' -i http://source/playlist.m3u8 -codec copy -bsf:a aac_adtstoasc record.mp4

ffmpeg version 4.2.2 Copyright (c) 2000-2019 the FFmpeg developers
  built with gcc 7 (Ubuntu 7.4.0-1ubuntu1~18.04.1)
  configuration: --disable-debug --disable-doc --disable-ffplay --enable-shared --enable-avresample --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-gpl --enable-libass --enable-libfreetype --enable-libvidstab --enable-libmp3lame --enable-libopenjpeg --enable-libopus --enable-libtheora --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libxcb --enable-libx265 --enable-libxvid --enable-libx264 --enable-nonfree --enable-openssl --enable-libfdk_aac --enable-libkvazaar --enable-libaom --extra-libs=-lpthread --enable-postproc --enable-small --enable-version3 --enable-libbluray --enable-demuxer=dash --enable-decoder=hevc --enable-libxml2 --extra-cflags=-I/opt/ffmpeg/include --extra-ldflags=-L/opt/ffmpeg/lib --extra-libs=-ldl --prefix=/opt/ffmpeg
  libavutil      56. 31.100 / 56. 31.100
  libavcodec     58. 54.100 / 58. 54.100
  libavformat    58. 29.100 / 58. 29.100
  libavdevice    58.  8.100 / 58.  8.100
  libavfilter     7. 57.100 /  7. 57.100
  libavresample   4.  0.  0 /  4.  0.  0
  libswscale      5.  5.100 /  5.  5.100
  libswresample   3.  5.100 /  3.  5.100
  libpostproc    55.  5.100 / 55.  5.100
</code>```

答:
Transport streams use a time base of 1/90000, and a 33 bit timestamp

2^33/90000 seconds = 26 hours 30minutes 43.718 seconds

When that 33 bit number is exhausted, it overflows back to zero.

If ffmpeg is not handling the timestamp overflow, it is a bug. Report it to ffmpeg.

Body:
I record an hls stream and after 26:30:02.81 there come the message:

[http @ 0x558330f5ba80] Opening 'http://de-origin-live-be-01.3qsdn.com:8081/3279/996191_PwxkbnqRThCDGXVr/l_94_95438333_16449.ts?nimblesessionid=2106' for reading
frame=2289669 fps= 24 q=-1.0 size=25056768kB time=26:30:02.81 bitrate=2151.6kbits/s speed=   1x
[mpegts @ 0x558330f07280] Invalid timestamps stream=0, pts=10378, dts=8589926250, size=11200
[mpegts @ 0x558330f07280] Invalid timestamps stream=0, pts=2908, dts=8589929940, size=3407
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:0; previous: 8586744840, current: -3185972; changing to 8586744841. This may result in incorrect timestamps in the output file.
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:1; previous: 4579598864, current: -1698561; changing to 4579598865. This may result in incorrect timestamps in the output file.
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:1; previous: 4579598865, current: -1697537; changing to 4579598866. This may result in incorrect timestamps in the output file.
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:1; previous: 4579598866, current: -1696513; changing to 4579598867. This may result in incorrect timestamps in the output file.
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:0; previous: 8586744841, current: -3182282; changing to 8586744842. This may result in incorrect timestamps in the output file.
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:1; previous: 4579598867, current: -1695489; changing to 4579598868. This may result in incorrect timestamps in the output file.
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:1; previous: 4579598868, current: -1694465; changing to 4579598869. This may result in incorrect timestamps in the output file.
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:1; previous: 4579598869, current: -1693441; changing to 4579598870. This may result in incorrect timestamps in the output file.
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:0; previous: 8586744842, current: -3178502; changing to 8586744843. This may result in incorrect timestamps in the output file.
[mp4 @ 0x558330f20bc0] Non-monotonous DTS in output stream 0:0; previous: 8586744843, current: -3174722; changing to 8586744844. This may result in incorrect timestamps in the output file.

There is no more video written to the file at this time but ffmpeg is not stopping. If i stop it manual after 30 hours the file is only 26 hours 30 minutes long.

How to reproduce:

ffmpeg -progress recorder.progress -reconnect 1 -user_agent 'sdn/1.0' -i http://source/playlist.m3u8 -codec copy -bsf:a aac_adtstoasc record.mp4

ffmpeg version 4.2.2 Copyright (c) 2000-2019 the FFmpeg developers
  built with gcc 7 (Ubuntu 7.4.0-1ubuntu1~18.04.1)
  configuration: --disable-debug --disable-doc --disable-ffplay --enable-shared --enable-avresample --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-gpl --enable-libass --enable-libfreetype --enable-libvidstab --enable-libmp3lame --enable-libopenjpeg --enable-libopus --enable-libtheora --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libxcb --enable-libx265 --enable-libxvid --enable-libx264 --enable-nonfree --enable-openssl --enable-libfdk_aac --enable-libkvazaar --enable-libaom --extra-libs=-lpthread --enable-postproc --enable-small --enable-version3 --enable-libbluray --enable-demuxer=dash --enable-decoder=hevc --enable-libxml2 --extra-cflags=-I/opt/ffmpeg/include --extra-ldflags=-L/opt/ffmpeg/lib --extra-libs=-ldl --prefix=/opt/ffmpeg
  libavutil      56. 31.100 / 56. 31.100
  libavcodec     58. 54.100 / 58. 54.100
  libavformat    58. 29.100 / 58. 29.100
  libavdevice    58.  8.100 / 58.  8.100
  libavfilter     7. 57.100 /  7. 57.100
  libavresample   4.  0.  0 /  4.  0.  0
  libswscale      5.  5.100 /  5.  5.100
  libswresample   3.  5.100 /  3.  5.100
  libpostproc    55.  5.100 / 55.  5.100


问:
jQuery $(".class").click(); - multiple elements, click event once
I have multiple classes on a page of the same name. I then have a .click() event in my JS. What I want to happen is the click event only happen once, regardless of multiple classes on my page.

The scenario is that I am using AJAX to add to cart. Sometimes on the home page there might be a featured product and a top offer which means that the same class .add .#productid# is there and when clicked the add to cart AJAX is fired twice.

I thought about making 'click areas' so I would have .container-name .add .#pid# therefore giving unique clicks.

Is this the only solution?

```<code><div class="addproduct 151">product info</div>
<div class="addproduct 151">product info</div>
<div class="addproduct 151">product info</div>
<div class="addproduct 151">product info</div>
<div class="addproduct 151">product info</div>

$(".addproduct").click(function(){//do something fired 5 times});
</code>```

答:
$(document).ready(function(){

    $(".addproduct").each(function(){
          $(this).unbind().click(function(){
               console.log('div is clicked, my content => ' + $(this).html());
           });
     });
});
 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="addproduct 151">product info 1</div>
<div class="addproduct 151">product info 2</div>
<div class="addproduct 151">product info 3</div>
<div class="addproduct 151">product info 4</div>
<div class="addproduct 151">product info 5</div></code>```

ContentLicense: CC BY-SA 2.5

Body:
I have multiple classes on a page of the same name. I then have a .click() event in my JS. What I want to happen is the click event only happen once, regardless of multiple classes on my page.

The scenario is that I am using AJAX to add to cart. Sometimes on the home page there might be a featured product and a top offer which means that the same class .add .#productid# is there and when clicked the add to cart AJAX is fired twice.

I thought about making 'click areas' so I would have .container-name .add .#pid# therefore giving unique clicks.

Is this the only solution?

product info

product info

product info

product info

product info

$(".addproduct").click(function(){//do something fired 5 times});

Body:
$(document).ready(function(){

    $(".addproduct").each(function(){
          $(this).unbind().click(function(){
               console.log('div is clicked, my content => ' + $(this).html());
           });
     });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="addproduct 151">product info 1</div>
<div class="addproduct 151">product info 2</div>
<div class="addproduct 151">product info 3</div>
<div class="addproduct 151">product info 4</div>
<div class="addproduct 151">product info 5</div>


问:
MS Access multiple filter in the same field satisfying all of them
I am fairly new to access. I have a table similar to the following
enter image description here
I am trying to create a query that shows suppliers that are capable of BOTH Grinding and Milling.
This the outcome I am Hopping to get

```<code>A    Grinding
A    Milling
B    Grinding
B    Milling
</code>```

and Ignore the rest. Any help?

答:
You can use exists:

```<code>select t.*
from table1 t
where
    t.capatibilty in ('Grinding', 'Milling')
    and exists (
        select 1
        from table1 t1
        where
            t1.supplier = t.supplier
            and t1.capatibilty in ('Grinding', 'Milling')
            and t1.capability <> t.capability
    )
</code>```

If Grinding and Milling are the only two possible values, this can be simplified a little:

```<code>select t.*
from table1 t
where
    exists (
        select 1
        from table1 t1
        where
            t1.supplier = t.supplier
            and t1.capability <> t.capability
    )
</code>```

Body:
I am fairly new to access. I have a table similar to the following
enter image description here
I am trying to create a query that shows suppliers that are capable of BOTH Grinding and Milling.
This the outcome I am Hopping to get

A    Grinding
A    Milling
B    Grinding
B    Milling

and Ignore the rest. Any help?

Body:
You can use exists:

select t.*
from table1 t
where
    t.capatibilty in ('Grinding', 'Milling')
    and exists (
        select 1
        from table1 t1
        where
            t1.supplier = t.supplier
            and t1.capatibilty in ('Grinding', 'Milling')
            and t1.capability <> t.capability
    )

If Grinding and Milling are the only two possible values, this can be simplified a little:

select t.*
from table1 t
where
    exists (
        select 1
        from table1 t1
        where
            t1.supplier = t.supplier
            and t1.capability <> t.capability
    )


问:
Backbone.js How to use with PHP
I have been looking into backbone.js and I can't seem to figure out how to get it communicate with php in order to save the models data. It sends a request but how do I capture that request whether it be "Create", "Update", "Read", "Delete" etc.

Thanks

答: $GLOBALS['HTTP_RAW_POST_DATA'] works fine for me, i don't know for what reason print_r($_POST) doesn't print anithing!!</p>

Title: Backbone.js How to use with PHP


问:
How to convert number (string format from scraping) to number in a cell with Xlsxwriter
Purpose: to read the securities data from a sqlite database, extracting (scraping) quotations from the internet and inserting them in an excel sheet with xlswriter

```<code>import os
import sqlite3
import xlsxwriter
from xlsxwriter.utility import xl_rowcol_to_cell
from urllib.request import urlopen
from bs4 import BeautifulSoup

def GetPrice(myurl):
    html = urlopen(myurl)
    soup = BeautifulSoup(html,'lxml')
    return soup.select_one('.h-price').text

db_filename = 'getdata.db'
db_is_new = not os.path.exists(db_filename)
conn = sqlite3.connect(db_filename)
workbook = xlsxwriter.Workbook("isin.xlsx")
worksheet = workbook.add_worksheet()

if db_is_new:
    print('Need db schema')
else:
    cur = conn.cursor()
    curr_row=0

    worksheet.write_string(0,0,'Isin')
    worksheet.write_string(0,1,'Description')
    worksheet.write_string(0,2,'Url')
    worksheet.write_string(0,3,'Price')
    money = workbook.add_format({'num_format': '$#,##0'})

    for row in cur.execute('SELECT * FROM tbIsin'):
        curr_row += 1
        worksheet.write_string(curr_row,0,row[1])
        worksheet.write_string(curr_row,1,row[3])
        worksheet.write_url(curr_row,2,row[2], string='LINK')
        oldval = GetPrice(row[2])
        newval=oldval.replace('.', '')
        worksheet.write(curr_row,3,newval)
        cella = xl_rowcol_to_cell(curr_row, 3)
        formula = '=VAL(%s)' % cella
        worksheet.write(curr_row,4,formula)

conn.close()
workbook.close()
</code>```

My problem: the price is in text format (example 9963.71 with decimal Italian format), I can't convert it to number format. Formula I enter in the cell is correct but it gives the result #NAME?.

The best solution would be to enter the number directly into the cell

Today I solved it with a double replacement:

```<code>oldval = GetPrice (row [2])
newval = oldval.replace ('.', '')
curval = float (newval.replace (',', '.'))
</code>```

答:
If the input contains numbers as strings like this '9963.71' then you can use the XlsxWriter
strings_to_numbers constructor option to have write() convert them automatically to numbers:

workbook = xlsxwriter.Workbook('isin.xlsx', {'strings_to_numbers': True})
```

<p>Basically anywhere something like this would work:</p>

<pre class="lang-py prettyprint-override"><code>>>> float('9963.71')
9963.71
</code>```

However, if the numbers contain thousands separators, or a comma as the decimal separator then that won't work and you will need to pre-process the strings in some way.

>>> float('9,963.71')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): 9,963.71
```

Body:
Purpose: to read the securities data from a sqlite database, extracting (scraping) quotations from the internet and inserting them in an excel sheet with xlswriter

import os
import sqlite3
import xlsxwriter
from xlsxwriter.utility import xl_rowcol_to_cell
from urllib.request import urlopen
from bs4 import BeautifulSoup

def GetPrice(myurl):
    html = urlopen(myurl)
    soup = BeautifulSoup(html,'lxml')
    return soup.select_one('.h-price').text

db_filename = 'getdata.db'
db_is_new = not os.path.exists(db_filename)
conn = sqlite3.connect(db_filename)
workbook = xlsxwriter.Workbook("isin.xlsx")
worksheet = workbook.add_worksheet()

if db_is_new:
    print('Need db schema')
else:
    cur = conn.cursor()
    curr_row=0

    worksheet.write_string(0,0,'Isin')
    worksheet.write_string(0,1,'Description')
    worksheet.write_string(0,2,'Url')
    worksheet.write_string(0,3,'Price')
    money = workbook.add_format({'num_format': '$#,##0'})

    for row in cur.execute('SELECT * FROM tbIsin'):
        curr_row += 1
        worksheet.write_string(curr_row,0,row[1])
        worksheet.write_string(curr_row,1,row[3])
        worksheet.write_url(curr_row,2,row[2], string='LINK')
        oldval = GetPrice(row[2])
        newval=oldval.replace('.', '')
        worksheet.write(curr_row,3,newval)
        cella = xl_rowcol_to_cell(curr_row, 3)
        formula = '=VAL(%s)' % cella
        worksheet.write(curr_row,4,formula)

conn.close()
workbook.close()

My problem: the price is in text format (example 9963.71 with decimal Italian format), I can't convert it to number format. Formula I enter in the cell is correct but it gives the result #NAME?.

The best solution would be to enter the number directly into the cell

Today I solved it with a double replacement:

oldval = GetPrice (row [2])
newval = oldval.replace ('.', '')
curval = float (newval.replace (',', '.'))

Body:
If the input contains numbers as strings like this '9963.71' then you can use the XlsxWriter
strings_to_numbers constructor option to have write() convert them automatically to numbers:

workbook = xlsxwriter.Workbook('isin.xlsx', {'strings_to_numbers': True})

Basically anywhere something like this would work:

>>> float('9963.71')
9963.71

However, if the numbers contain thousands separators, or a comma as the decimal separator then that won't work and you will need to pre-process the strings in some way.

>>> float('9,963.71')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): 9,963.71


问:
Is it possible to allow only specific orientations based on view controller on iOS 13?
So with previous versions of iOS, it was possible to set which orientations were allowed on a per-viewcontroller basis using the supportedInterfaceOrientations variable.

Apple's own documentation indicates that we 'shouldn't' use the old orientation mask approach, suggesting we upgrade to traits instead.  Unfortunately, I don't actually know anything about traits yet, and while I'll obviously need to pick them up, I need to get this done.  Is there any way, with an iOS 13 app, to specify allowed orientations on a per-view controller basis?

答: So it turns out the old methods still, work, there was just a wrinkle I'd screwed up on.  Because I was using a UINavigationController as my root, instead of calling those methods directly, I needed to create a delegate for the navigation controller.</p>


问:
Programatically create SSH tunnel inside of dockerized apache airflow python operator
My program is unable to create an SSH tunnel while inside of my docker container running apache airflow. Only running the function on my local machine works fine. I have a list of servers which I use to create a tunnel, query the database, and close the connection. Normally, I'd do it the following way:

```<code>for server in servers:
    server_conn = sshtunnel.SSHTunnelForwarder(
        server,
        ssh_username=ssh_user,
        ssh_password=ssh_password,
        remote_bind_address=(localhost, db_port),
        local_bind_address=(localhost, localport)
    )
</code>```

This works as expected and I can do whatever I need from there. However, within Docker, it does not work. I realize that docker runs and binds to a port and is not actually apart of the host system, so I used network_mode="host" to help mitigate this issue. However, this does not work because my containers lose the ability to communicate with one another. Here is my docker-compose file

```<code>    postgres:
        image: postgres:9.6
        environment:
            - POSTGRES_USER=airflow
            - POSTGRES_PASSWORD=airflow
            - POSTGRES_DB=airflow
            - PGDATA=/var/lib/postgresql/data/pgdata
        volumes:
            - ~/.whale/pgdata:/var/lib/postgresql/data/pgdata
            - ./dags/docker/sql/create.sql:/docker-entrypoint-initdb.d/init.sql
        ports:
          - "5432:5432"

    webserver:
        image: hawk
        build:
            context: .
            dockerfile: ./dags/docker/Dockerfile-airflow
        restart: always
        depends_on:
            - postgres
            # - redis
        environment:
            - LOAD_EX=n
            - FERNET_KEY=46BKJoQYlPPOexq0OhDZnIlNepKFf87WFwLbfzqDDho=
            - EXECUTOR=Local
        volumes:
            - ./dags:/usr/local/airflow/dags
            # Uncomment to include custom plugins
            # - ./plugins:/usr/local/airflow/plugins
        ports:
            - "8080:8080"
            - "52023:22"
        command: webserver
        healthcheck:
            test: ["CMD-SHELL", "[ -f /usr/local/airflow/airflow-webserver.pid ]"]
            interval: 30s
            timeout: 30s
            retries: 3

</code>```

I also followed the instructions here and got to the point where I can docker exec into my container and manually type the above python snippet and get a working connection.
Additionally, I have read the airflow documentation here which covers SSH connection operators, but those only support bash commands, I will need my python function to run. I am truly confused why the python code would work while exec-ed into the system, but not when I run it via my airflow DAG. At this time, I am unable to manually put all of the connections in because there will be > 100 once this system deploys. Any help would be greatly appreciated. If more depth is needed, please let me know.

答:
I was having this same issue when opening the tunnel and trying to connect to the database in separate tasks, but got it working by doing both in the same task (Airflow doesn't persist state between task runs):

```<code>def select_from_tunnel_db():
    # Open SSH tunnel
    ssh_hook = SSHHook(ssh_conn_id='bastion-ssh-conn', keepalive_interval=60)
    tunnel = ssh_hook.get_tunnel(5432, remote_host='<db_host>', local_port=5432)
    tunnel.start()

    # Connect to DB and run query
    pg_hook = PostgresHook(
        postgres_conn_id='remote-db-conn',  # NOTE: host='localhost'
        schema='db_schema'
    )
    pg_cursor = pg_hook.get_conn().cursor()
    pg_cursor.execute('SELECT * FROM table;')
    select_val = pg_cursor.fetchall()

    return select_val

python_operator = PythonOperator(
    task_id='test_tunnel_conn',
    python_callable=select_from_tunnel_db,
    dag=dag
)
</code>```

This forwards traffic on port 5432 from the local machine to the same port on the remote db host. The SSHHook requires a working ssh connection to the endpoint you will be tunneling through and PostgresHook requires a postgres connection to 'localhost' on port 5432.

Body:
My program is unable to create an SSH tunnel while inside of my docker container running apache airflow. Only running the function on my local machine works fine. I have a list of servers which I use to create a tunnel, query the database, and close the connection. Normally, I'd do it the following way:

for server in servers:
    server_conn = sshtunnel.SSHTunnelForwarder(
        server,
        ssh_username=ssh_user,
        ssh_password=ssh_password,
        remote_bind_address=(localhost, db_port),
        local_bind_address=(localhost, localport)
    )

This works as expected and I can do whatever I need from there. However, within Docker, it does not work. I realize that docker runs and binds to a port and is not actually apart of the host system, so I used network_mode="host" to help mitigate this issue. However, this does not work because my containers lose the ability to communicate with one another. Here is my docker-compose file

    postgres:
        image: postgres:9.6
        environment:
            - POSTGRES_USER=airflow
            - POSTGRES_PASSWORD=airflow
            - POSTGRES_DB=airflow
            - PGDATA=/var/lib/postgresql/data/pgdata
        volumes:
            - ~/.whale/pgdata:/var/lib/postgresql/data/pgdata
            - ./dags/docker/sql/create.sql:/docker-entrypoint-initdb.d/init.sql
        ports:
          - "5432:5432"

    webserver:
        image: hawk
        build:
            context: .
            dockerfile: ./dags/docker/Dockerfile-airflow
        restart: always
        depends_on:
            - postgres
            # - redis
        environment:
            - LOAD_EX=n
            - FERNET_KEY=46BKJoQYlPPOexq0OhDZnIlNepKFf87WFwLbfzqDDho=
            - EXECUTOR=Local
        volumes:
            - ./dags:/usr/local/airflow/dags
            # Uncomment to include custom plugins
            # - ./plugins:/usr/local/airflow/plugins
        ports:
            - "8080:8080"
            - "52023:22"
        command: webserver
        healthcheck:
            test: ["CMD-SHELL", "[ -f /usr/local/airflow/airflow-webserver.pid ]"]
            interval: 30s
            timeout: 30s
            retries: 3

I also followed the instructions here and got to the point where I can docker exec into my container and manually type the above python snippet and get a working connection.
Additionally, I have read the airflow documentation here which covers SSH connection operators, but those only support bash commands, I will need my python function to run. I am truly confused why the python code would work while exec-ed into the system, but not when I run it via my airflow DAG. At this time, I am unable to manually put all of the connections in because there will be > 100 once this system deploys. Any help would be greatly appreciated. If more depth is needed, please let me know.

Body:
I was having this same issue when opening the tunnel and trying to connect to the database in separate tasks, but got it working by doing both in the same task (Airflow doesn't persist state between task runs):

def select_from_tunnel_db():
    # Open SSH tunnel
    ssh_hook = SSHHook(ssh_conn_id='bastion-ssh-conn', keepalive_interval=60)
    tunnel = ssh_hook.get_tunnel(5432, remote_host='<db_host>', local_port=5432)
    tunnel.start()

    # Connect to DB and run query
    pg_hook = PostgresHook(
        postgres_conn_id='remote-db-conn',  # NOTE: host='localhost'
        schema='db_schema'
    )
    pg_cursor = pg_hook.get_conn().cursor()
    pg_cursor.execute('SELECT * FROM table;')
    select_val = pg_cursor.fetchall()

    return select_val

python_operator = PythonOperator(
    task_id='test_tunnel_conn',
    python_callable=select_from_tunnel_db,
    dag=dag
)

This forwards traffic on port 5432 from the local machine to the same port on the remote db host. The SSHHook requires a working ssh connection to the endpoint you will be tunneling through and PostgresHook requires a postgres connection to 'localhost' on port 5432.


问:
UNITY 2D Dungeon Cralwer teleport from room to room
I want to make a 2D Dungeon Crawler in Unity,
The rooms will be randomly generated squares
I want my player to be able to teleport from room A to room B
All of the rooms will be spawned with prefabs
Is there any way to make a link between 2 prefabs to teleport the player from room A to room B and back?</p>

答:
I'm assuming you literally mean teleport the player.

In that case, have a 2D Collider with IsTrigger toggled on. Add a script to the collider with a OnTriggerEnter2D() method that update the position of any object that enters it.

```<code>void OnTriggerEnter2D(Collider2D obj)
{
    obj.transform.position = new Vector2(XPosition, YPosition);
}
</code>```

Body:
I'm assuming you literally mean teleport the player.

In that case, have a 2D Collider with IsTrigger toggled on. Add a script to the collider with a OnTriggerEnter2D() method that update the position of any object that enters it.

void OnTriggerEnter2D(Collider2D obj)
{
    obj.transform.position = new Vector2(XPosition, YPosition);
}


问:
What's wrong with setup and integration of python and created database using Sqlite?
I use python 3.5.2 and SQLite 3 in order to create a database and table using shell. I used following code:

import sqlite3
conn=sqlite3.connect('TestDB.db');

c = conn.cursor()

c.execute('''CREATE TABLE CLIENTS ([generated_id]INTEGER PRIMARY KEY, [Client_Name]text)''';

And it seems to work because I face with no error and the program creates Database file exactly with the characteristics above. The file exists in "C:\Python" directory but when I want to manipulate the file through the SQLite on CMD with the following commands:

.open C:\Python\TestDB.db

.database

It gives me an output of:

main: C:WINDOWS\system32\PythonTestDb.db

However normally just like others, it should have been like this:

main: C:\Python\TestDB.db

However the file doesn't even exist in following System32 directory! Because of this miss_configuration I can't manipulate the data on table and it gives me an error of:

"No such table: CLIENTS"

答:
From the SQLite documentation on its command line shell, section 2:

You might want to use a full pathname to ensure that the file is in the directory that you think it is in. Use forward-slashes as the directory separator character. In other words use "c:/work/ex1.db", not "c:\work\ex1.db".

Thus, try

```<code>.open C:/Python/TestDB.db
</code>```

(Note: the fact that Python and TestDB.db got concatenated in the filename was a giveaway. The C:WINDOWS\system32\ directory is probably the default working directory, where sqlite.exe is executed, or perhaps located.

In most programming and related things, the backslash is reserved for escaping (special) characters. Neither P nor T are special, so they were replaced with their actual value, resulting in PythonTestDB.db.)

Body:
From the SQLite documentation on its command line shell, section 2:

You might want to use a full pathname to ensure that the file is in the directory that you think it is in. Use forward-slashes as the directory separator character. In other words use "c:/work/ex1.db", not "c:\work\ex1.db".

Thus, try

.open C:/Python/TestDB.db

(Note: the fact that Python and TestDB.db got concatenated in the filename was a giveaway. The C:WINDOWS\system32\ directory is probably the default working directory, where sqlite.exe is executed, or perhaps located.

In most programming and related things, the backslash is reserved for escaping (special) characters. Neither P nor T are special, so they were replaced with their actual value, resulting in PythonTestDB.db.)


问:
Static to non-static refactoring, can't have both?
I have a refactoring situation that I cannot find an elegant solution for...

Disclaimer:
Keep in mind that I am oversimplifying this example to reduce clutter, and not disclose things I am not allowed to disclose :)
As such, please do not assume that this is the ONLY code in my giant codebase, and offer solutions that cut corners or change parts of the design that I mention cannot be changed due to outside constraints.

The facts:

I have a utility class, it has a bunch of static methods, they utilize a singleton resource:

```<code>public final class Utility
{
   private static final Resource RES = Resource.getInstance();

   private Utility() {}  // Prevent instantiating Utility

   public static boolean utilMethodOne() { return RES.isSomething(); }
   public static int utilMethodTwo() { RES.getNumThings(); }
   ...
   public static void utilMethodInfinity() { ... }
}
</code>```

Utility is in a library JAR that is used by several applications in a large codebase -- let's say on the order of 10,000 calls to its static methods, e.g.:   if(Utility.utilMethodOne()) { ... }

Resource is an outside class from another library JAR.

Resource also has a method Resource.getInstance(String name) that will return a named instance, which may relate to a different underlying resource based on the name (internally it keeps the named resources in a Map<String,Resource>).

Resource.getInstance() returns the equivalent of Resoruce.getInstance(""), aka the default instance.

The situation:

The Utility needs to be enhanced to now execute against one of several resources, so my plan is to make the Utility an instantiable class with a non-static Resource member variable.  Something like this:

```<code>public final class Utility
{
   private Resource res;

   public Utility(String resName)
   {
      this.res =  = Resource.getInstance(resName);
   }

   public boolean utilMethodOne() { return this.res.isSomething(); }
   public int utilMethodTwo() { this.res.getNumThings(); }
   ...
   public void utilMethodInfinity() { ... }
}
</code>```

Now all this is great, and I can start creating Utility objects that access their specified resource instead of just the default one.  However, as I mentioned, there are 10-100K method calls that are now invalid as they were calling static methods!

The problem:

My plan was to keep the static methods in Utility, and have them use the default instance from Resource, while adding in non-static variants for the instantiated Utility objects that use their "local" resource reference.

```<code>   // Best of both worlds:
   public static boolean utilMethodOne() { return RES.isSomething(); }
   public boolean utilMethodOne() { return this.res.isSomething(); }
</code>```

Maybe I can't have my cake & eat it too:

```<code>error: method utilMethodOne() is already defined in class Utility
   public static boolean utilMethodOne(String sql)
</code>```

So it seems I am going to have to either...

Introduce a whole new BetterUtility class for places that want to use the named-resources.

Update 10,000 places to instantiate & use the revised Utility object.

...?  (hint: this is where your suggestions come in!)

I really don't like 1 or 2 for a variety of reasons, so I need to ensure there is no better 3 option before settling.  Is there any way to retain a single class that can provide both the static & non-static interfaces in this case?

UPDATE 2020-06-01:

I am coming to the realization that this magical option 3 doesn't exist.  So out of my original two options I think #2 is best as it's just one time "just get it out of the way and be done with it" type effort.  Also incorporated some of your suggestions in the design(s).

So now that I have a direction on this, I am left with [hopefully only] one more key decision...

Update all the calls to create new objects

```<code>// For a one-off call, do it inline
boolean foo = new Utility("res1").utilMethodOne();

// Or when used multiple times, re-use the object
Utility util = new Utility("res1");
boolean foo = util.utilMethodOne();
int bar = util.utilMethodTwo();
...
</code>```

Given the amount/frequency of usage, this seems like a whole lot of wasted efforts creating short-lived objects.

Follow the pattern that Resource itself uses, creating my own named-singleton map of Utilities (1:1 with their respectively named Resource)

```<code>public final class Utility
{
   private static final Map<String,Utility> NAMED_INSTANCES = new HashMap<>();

   private Resource res;

   private Utility(String resName)
   {
      this.res = Resource.getInstance(resName);
   }

   public static Utility getInstance(String resName)
   {
      synchronized(NAMED_INSTANCES)
      {
         Utility instance = NAMED_INSTANCES.get(resName);
         if(instance == null)
         {
            instance = new Utility(resName);
            NAMED_INSTANCES.put(resName, instance);
         }

         return instance;
      }
   }

   public boolean utilMethodOne() { return this.res.isSomething(); }
   public int utilMethodTwo() { this.res.getNumThings(); }
   ...
   public void utilMethodInfinity() { ... }
}

// Now the calls can use
Utility.getInstance("res1")

// In place of
new Utility("res1")
</code>```

So essentially this boils down to object creation vs. a synchronization + map lookup at each usage.  Probably a little bit of premature optimization here, but I'll probably have to stick with this decision long term.

UPDATE 2020-06-29:

Didn't want to leave an "Internet dead end" here...
I did eventually get all the call sites updated as described above (including option #2 from the 2020-06-01 update).  It has made it through all testing and been running in production for a week or so now in various applications.

答:
It seems that you may want to turn the Utility into a singleton map that will have the same static methods that access the singleton without any arguments on for the function invocations (just like you have now)

The singleton will support a static method of adding a new resource, you will then add it to the map.

In addition you can overload the existing methods to also accept an argument resource name, that will then use a particular resource from the map, otherwise will use the default entry from the map.

Body:
I have a refactoring situation that I cannot find an elegant solution for...

Disclaimer:
Keep in mind that I am oversimplifying this example to reduce clutter, and not disclose things I am not allowed to disclose :)
As such, please do not assume that this is the ONLY code in my giant codebase, and offer solutions that cut corners or change parts of the design that I mention cannot be changed due to outside constraints.

The facts:

I have a utility class, it has a bunch of static methods, they utilize a singleton resource:

public final class Utility
{
   private static final Resource RES = Resource.getInstance();

   private Utility() {}  // Prevent instantiating Utility

   public static boolean utilMethodOne() { return RES.isSomething(); }
   public static int utilMethodTwo() { RES.getNumThings(); }
   ...
   public static void utilMethodInfinity() { ... }
}

Utility is in a library JAR that is used by several applications in a large codebase -- let's say on the order of 10,000 calls to its static methods, e.g.:   if(Utility.utilMethodOne()) { ... }

Resource is an outside class from another library JAR.

Resource also has a method Resource.getInstance(String name) that will return a named instance, which may relate to a different underlying resource based on the name (internally it keeps the named resources in a Map<String,Resource>).

Resource.getInstance() returns the equivalent of Resoruce.getInstance(""), aka the default instance.

The situation:

The Utility needs to be enhanced to now execute against one of several resources, so my plan is to make the Utility an instantiable class with a non-static Resource member variable.  Something like this:

public final class Utility
{
   private Resource res;

   public Utility(String resName)
   {
      this.res =  = Resource.getInstance(resName);
   }

   public boolean utilMethodOne() { return this.res.isSomething(); }
   public int utilMethodTwo() { this.res.getNumThings(); }
   ...
   public void utilMethodInfinity() { ... }
}

Now all this is great, and I can start creating Utility objects that access their specified resource instead of just the default one.  However, as I mentioned, there are 10-100K method calls that are now invalid as they were calling static methods!

The problem:

My plan was to keep the static methods in Utility, and have them use the default instance from Resource, while adding in non-static variants for the instantiated Utility objects that use their "local" resource reference.

   // Best of both worlds:
   public static boolean utilMethodOne() { return RES.isSomething(); }
   public boolean utilMethodOne() { return this.res.isSomething(); }

Maybe I can't have my cake & eat it too:

error: method utilMethodOne() is already defined in class Utility
   public static boolean utilMethodOne(String sql)

So it seems I am going to have to either...

Introduce a whole new BetterUtility class for places that want to use the named-resources.

Update 10,000 places to instantiate & use the revised Utility object.

...?  (hint: this is where your suggestions come in!)

I really don't like 1 or 2 for a variety of reasons, so I need to ensure there is no better 3 option before settling.  Is there any way to retain a single class that can provide both the static & non-static interfaces in this case?

UPDATE 2020-06-01:

I am coming to the realization that this magical option 3 doesn't exist.  So out of my original two options I think #2 is best as it's just one time "just get it out of the way and be done with it" type effort.  Also incorporated some of your suggestions in the design(s).

So now that I have a direction on this, I am left with [hopefully only] one more key decision...

Update all the calls to create new objects

// For a one-off call, do it inline
boolean foo = new Utility("res1").utilMethodOne();

// Or when used multiple times, re-use the object
Utility util = new Utility("res1");
boolean foo = util.utilMethodOne();
int bar = util.utilMethodTwo();
...

Given the amount/frequency of usage, this seems like a whole lot of wasted efforts creating short-lived objects.

Follow the pattern that Resource itself uses, creating my own named-singleton map of Utilities (1:1 with their respectively named Resource)

public final class Utility
{
   private static final Map<String,Utility> NAMED_INSTANCES = new HashMap<>();

   private Resource res;

   private Utility(String resName)
   {
      this.res = Resource.getInstance(resName);
   }

   public static Utility getInstance(String resName)
   {
      synchronized(NAMED_INSTANCES)
      {
         Utility instance = NAMED_INSTANCES.get(resName);
         if(instance == null)
         {
            instance = new Utility(resName);
            NAMED_INSTANCES.put(resName, instance);
         }

         return instance;
      }
   }

   public boolean utilMethodOne() { return this.res.isSomething(); }
   public int utilMethodTwo() { this.res.getNumThings(); }
   ...
   public void utilMethodInfinity() { ... }
}

// Now the calls can use
Utility.getInstance("res1")

// In place of
new Utility("res1")

So essentially this boils down to object creation vs. a synchronization + map lookup at each usage.  Probably a little bit of premature optimization here, but I'll probably have to stick with this decision long term.

UPDATE 2020-06-29:

Didn't want to leave an "Internet dead end" here...
I did eventually get all the call sites updated as described above (including option #2 from the 2020-06-01 update).  It has made it through all testing and been running in production for a week or so now in various applications.