问:
Aside element on the SIDE - html question
I'm new to html and im just trying out some stuff.  I tried to use the aside element to have a little box on the right side of the screen but could not get it right, eventually I used margins to move it to the right spot but there would be a big empty space on the left side and it would all look messed up on displays with very low or very large displays and screen resolutions.

html {
        border-style: double;
        border-color: black;
        border-radius: 12px;
        margin-top: 24px;
        margin-right: 24px;
        margin-left: 24px;
        margin-bottom: 24px;
    }
    aside {
        border-style: double;
        border-color: black;
        border-radius: 12px;
        object-position: right;
        margin-left: 1000px;
        margin-right: auto;
        margin-top: auto;
        margin-bottom: auto;
    }
    h1 {
        font-family: Arial, Helvetica, sans-serif;
    }
    h2 {
        font-family: Arial, Helvetica, sans-serif;
    }
    p {
        font-family: Arial, Helvetica, sans-serif;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
    <header>
        <title>Software Boi</title>
    </header>
    <body>
        <h1>Website <strong>title</strong></h1>
        <h2>Aside element test</h2>
        <article>
        <aside>
            <h2><strong>How Do I...</strong></h2>
            <p>*Have a box on the right side like this</p>
            <p>*But without the gap/break next to it</p>
        </aside>
        <h3>E.g this should be to the left the box not underneath it</h3>
        <button onclick="window.location.href = 'https://github.com/tootloose'">buttons are cool</button>
        </article>
    </body>
</html></code>```

IMAGE:

答:
Can you try this:

```<code>aside {
  border-style: double;
  border-color: black;
  border-radius: 12px;
  object-position: right;
  float: right;
}
</code>```

Instead of:

```<code>aside {
  border-style: double;
  border-color: black;
  border-radius: 12px;
  object-position: right;
  margin-left: 1000px;
  margin-right: auto;
  margin-top: auto;
  margin-bottom: auto;
}
</code>```

Body:
I'm new to html and im just trying out some stuff.  I tried to use the aside element to have a little box on the right side of the screen but could not get it right, eventually I used margins to move it to the right spot but there would be a big empty space on the left side and it would all look messed up on displays with very low or very large displays and screen resolutions.

html {
        border-style: double;
        border-color: black;
        border-radius: 12px;
        margin-top: 24px;
        margin-right: 24px;
        margin-left: 24px;
        margin-bottom: 24px;
    }
    aside {
        border-style: double;
        border-color: black;
        border-radius: 12px;
        object-position: right;
        margin-left: 1000px;
        margin-right: auto;
        margin-top: auto;
        margin-bottom: auto;
    }
    h1 {
        font-family: Arial, Helvetica, sans-serif;
    }
    h2 {
        font-family: Arial, Helvetica, sans-serif;
    }
    p {
        font-family: Arial, Helvetica, sans-serif;
    }

        <title>Software Boi</title>

Website title

Aside element test

How Do I...

*Have a box on the right side like this

*But without the gap/break next to it

E.g this should be to the left the box not underneath it

        <button onclick="window.location.href = 'https://github.com/tootloose'">buttons are cool</button>

IMAGE:

Body:
Can you try this:

aside {
  border-style: double;
  border-color: black;
  border-radius: 12px;
  object-position: right;
  float: right;
}

Instead of:

aside {
  border-style: double;
  border-color: black;
  border-radius: 12px;
  object-position: right;
  margin-left: 1000px;
  margin-right: auto;
  margin-top: auto;
  margin-bottom: auto;
}


来源: stackexchange

问:
Generating report in Node JS
I want to generate a report(i.e pdf or any format that can be print) from the data in system. Its like i need to generate weekly report. Format of report will be the same but data will be change with time. Is there any way to perform this task in Node JS ? I m using Mongo DB. And React JS in front end. Thank you so much.

答:
Hi you can use this npm package to convert your data into pdf format. Just by giving id of the tag that contains your data.

You can download it in pdf format. and print it as well.

https://www.npmjs.com/package/dom-to-pdf

ContentLicense: CC BY-SA 4.0

Title: Generating report in Node JS


问:
Load a text file with values into a tuple in Python
I have text file file.txt with values like this:

```<code>word1
word2
word3
word4
word5
</code>```

What I want is a tuple like this in Python 3:

```<code>my_tuple = ('word1','word2','word3','word4','word5')
</code>```

Any advice?

答:
```<code>with open('file.txt','r') as f:
    my_tuple=tuple(line.strip('\n') for line in f)

print(my_tuple)
# ('word1','word2','word3','word4','word5')
</code>```

Body:
I have text file file.txt with values like this:

word1
word2
word3
word4
word5

What I want is a tuple like this in Python 3:

my_tuple = ('word1','word2','word3','word4','word5')

Any advice?


问:
how to determine why ios app crashes on iOS 13 at start
I am having a hard time trying to determine why my app crashes when being downloaded via testflight on iOS devices. If I upload it via xcode to simulator or physical devices it works as expected; when downloaded via testflight to ios13 devices (ios12 are ok) it crashes at the very startup, it seems when asking for permissions.

The only permissions asked are notification and microphone, however after the crash I went to the settings panel and see that microphone has not been granted, while notification is.
So I supposed that there was a problem with mic permission and deleted it form Info.plist: nothing changed, it crashes nonetheless so, maybe it's not the mic.

Also i have exported the ipa for adhoc distribution and to my huge surprise OTA installation via https on a local webserver works without problems.

Any ideas how can I determine what's going on? Btw in the testflight crash report there is no stacktrace or whatever helpful info, just the info about the device (model, memory battery, etc.)

答:
You can simply find out the exact issue by getting you device crash log in:

Organizer ->Select your app -> Crashes

or you can download device log to get the exact issue by following below steps:


问:
Using @babel/register for a React app in Node v13
I have an app built using create-react-app and it has an entrypoint that used something like this —

require('babel-register')({
  ignore: [/(node_modules)/],
  presets: ['es2015', 'react-app'],
  plugins: [
    'syntax-dynamic-import',
    'dynamic-import-node',
    'react-loadable/babel'
  ]
});
require('./index');
```

<p>I'm in the process of upgrading Node (from v8 to v13.5) and decided to upgrade Babel too. Using Babel 7, the above piece of code was rewritten as —</p>

<pre class="lang-js prettyprint-override"><code>require('@babel/register')({
  ignore: [/(node_modules)/],
  presets: ['@babel/preset-env', 'react-app'],
  plugins: [
    '@babel/plugin-syntax-dynamic-import',
    'dynamic-import-node',
    'react-loadable/babel'
  ],
});
require('./index');
</code>```

Now when I run this, I get the error —

```<code>internal/modules/cjs/loader.js:1160
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /my-app/node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js
require() of ES modules is not supported.
require() of /my-app/node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js from /my-app/server/controllers/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename asyncToGenerator.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /my-app/node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/package.json.
</code>```

I'm guessing this is because preset-env is using modules support as it is detecting it in my version of Node (v13.6.0). If that's how I can fix this issue, how do I force it to use the es2015 preset? They've long been deprecated in favor of preset-env.

答:
If you are using geolib library. Please try upgrading your geolib dependency to 3.2.x. The "type": "module" flag has been removed from 3.1.x -> 3.2.x

or try changing he node version to 12.11.1, 12.12.0

Refer the discussion here https://github.com/manuelbieh/geolib/issues/208

Body:
I have an app built using create-react-app and it has an entrypoint that used something like this —

require('babel-register')({
  ignore: [/(node_modules)/],
  presets: ['es2015', 'react-app'],
  plugins: [
    'syntax-dynamic-import',
    'dynamic-import-node',
    'react-loadable/babel'
  ]
});
require('./index');

I'm in the process of upgrading Node (from v8 to v13.5) and decided to upgrade Babel too. Using Babel 7, the above piece of code was rewritten as —

require('@babel/register')({
  ignore: [/(node_modules)/],
  presets: ['@babel/preset-env', 'react-app'],
  plugins: [
    '@babel/plugin-syntax-dynamic-import',
    'dynamic-import-node',
    'react-loadable/babel'
  ],
});
require('./index');

Now when I run this, I get the error —

internal/modules/cjs/loader.js:1160
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /my-app/node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js
require() of ES modules is not supported.
require() of /my-app/node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js from /my-app/server/controllers/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename asyncToGenerator.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /my-app/node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/package.json.

I'm guessing this is because preset-env is using modules support as it is detecting it in my version of Node (v13.6.0). If that's how I can fix this issue, how do I force it to use the es2015 preset? They've long been deprecated in favor of preset-env.


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

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

The desired output:

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

How to do that in Python?

答:
Use the zip funciton</p>

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

Body:
So, I have 2 lists:

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

The desired output:

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

How to do that in Python?

Body:
Use the zip funciton

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


问:
SQLAlchemy: add a relationship using id instead of object?
Is it possible to add to a SQLAlchemy relationship using ids rather than objects?

For example, consider two declarative SQLAlchemy classes, Review and Artist, with a relationship between them:

```<code>class Review(Base):
    artist_id = Column(Integer, ForeignKey('artist.id'))
    artist = relationship(Artist, backref=backref('reviews', order_by=id))
    # etc.

class Artist(Base):
    # etc.
</code>```

With a list of review ids to add to an artist, I seem to need to look up the artist from the id, then add the artist object to the review, like this:

```<code>for review_id in review_ids:
    review = session.query(Review).filter(Review.id==review_id).first()
    artist.reviews.append(review)
</code>```

I'm sure it would be more efficient to skip the lookup and just add the ids, but is this possible?

答:
Your best bet is probably to compose an update expression against the backing tables.  Otherwise, you can't really modify a Review without actually querying for it (and that's what your doing; you aren't actually modifying the Artist at all).

Assuming Review.id is the primary key, That would roughly be:

```<code>conn = session.connection()
conn.execute(Review.__table__
                .update()
                .values(artist_id=artist_id)
                .where(Review.id.in_(review_ids))
            )
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to add to a SQLAlchemy relationship using ids rather than objects?

For example, consider two declarative SQLAlchemy classes, Review and Artist, with a relationship between them:

class Review(Base):
    artist_id = Column(Integer, ForeignKey('artist.id'))
    artist = relationship(Artist, backref=backref('reviews', order_by=id))
    # etc.

class Artist(Base):
    # etc.

With a list of review ids to add to an artist, I seem to need to look up the artist from the id, then add the artist object to the review, like this:

for review_id in review_ids:
    review = session.query(Review).filter(Review.id==review_id).first()
    artist.reviews.append(review)

I'm sure it would be more efficient to skip the lookup and just add the ids, but is this possible?

Body:
Your best bet is probably to compose an update expression against the backing tables.  Otherwise, you can't really modify a Review without actually querying for it (and that's what your doing; you aren't actually modifying the Artist at all).

Assuming Review.id is the primary key, That would roughly be:

conn = session.connection()
conn.execute(Review.__table__
                .update()
                .values(artist_id=artist_id)
                .where(Review.id.in_(review_ids))
            )


问:
How to display radio buttons as

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

here are my radio buttons.

and I want to show them like this.

div as radio

This is what I have tried but did not work.

HTML

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

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

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

CSS

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

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

答:
Here is one way you can customize your radio buttons.

.radio-toolbar .radio-item {
  position: relative;
  display: inline-block;
  vertical-align: top;
  margin: 15px 5px;
}

.radio-item input[type="radio"] {
  position: absolute;
  width: 0;
  height: 0;
  top: 0;
  left: 0;
}
.radio-item label {
  padding: 10px;
  color: #fff;
  border-radius: 10px;
  background-color: grey;
  border: 1px solid #000;
}

.radio-item input[type="radio"]:checked ~ label {
  border-color: #f00;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="radio-toolbar">
  <div class="radio-item">
    <input type="radio" id="radioone" name="product" value="first">
    <label for="radioone">50</label>
  </div>
  <div class="radio-item">
    <input type="radio" id="radiotwo" name="product" value="second">
    <label for="radiotwo">100</label>
  </div>
  <div class="radio-item">
    <input type="radio" id="radiothree" name="product" value="third">
    <label for="radiothree">500</label>
  </div>
</div></code>```

Please let me know if this helps.

Title: How to display radio buttons as <div>

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

here are my radio buttons.

and I want to show them like this.

div as radio

This is what I have tried but did not work.

HTML

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

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

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

CSS

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

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

Body:
Here is one way you can customize your radio buttons.

.radio-toolbar .radio-item {
  position: relative;
  display: inline-block;
  vertical-align: top;
  margin: 15px 5px;
}

.radio-item input[type="radio"] {
  position: absolute;
  width: 0;
  height: 0;
  top: 0;
  left: 0;
}
.radio-item label {
  padding: 10px;
  color: #fff;
  border-radius: 10px;
  background-color: grey;
  border: 1px solid #000;
}

.radio-item input[type="radio"]:checked ~ label {
  border-color: #f00;
}

<div class="radio-toolbar">
  <div class="radio-item">
    <input type="radio" id="radioone" name="product" value="first">
    <label for="radioone">50</label>
  </div>
  <div class="radio-item">
    <input type="radio" id="radiotwo" name="product" value="second">
    <label for="radiotwo">100</label>
  </div>
  <div class="radio-item">
    <input type="radio" id="radiothree" name="product" value="third">
    <label for="radiothree">500</label>
  </div>
</div>

Please let me know if this helps.


问:
"Unable to obtain your identity" error in Git
I set up user.email and user.name successfully, but whenever I try to commit to a repo Git still displays an error saying that it can't recognize my identity. What could be wrong?

This is what git config --list command prints out:

```<code>user.name=myname
user.email=myemail@myemail.com
core.repositoryformatversion=0
core.filemode=true
core.bare=false
core.logallrefupdates=true
</code>```

Edit: Error reads Unable to obtain your identity: *** Please tell me who you are. Run git config --global user.email "you@example.com" git config --global user.name "Your Name" to set your account's default identity. Omit --global to set identity only in this repository. fatal: unable to auto-detect email address (got 'root@computername.'(none))

cat ~/.gitconfig command outputs this:

```<code>[user]
    name = myname
    email = myemail@myemail.com
</code>```

cat .git/config outputs this:

```<code>[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[gui]
    wmstate = normal
    geometry = 1855x1026+65+24 262 188
</code>```

答:
1-open your git terminal

2-enter  git config --list in your git bash

3-it displays your complete git data

4- check your

user.name= your name

user.email=your email id

5- if data is not correct update it using

git config --local user.name "your username"

git config --local user.email "your email"

Body:
I set up user.email and user.name successfully, but whenever I try to commit to a repo Git still displays an error saying that it can't recognize my identity. What could be wrong?

This is what git config --list command prints out:

user.name=myname
user.email=myemail@myemail.com
core.repositoryformatversion=0
core.filemode=true
core.bare=false
core.logallrefupdates=true

Edit: Error reads Unable to obtain your identity: *** Please tell me who you are. Run git config --global user.email "you@example.com" git config --global user.name "Your Name" to set your account's default identity. Omit --global to set identity only in this repository. fatal: unable to auto-detect email address (got 'root@computername.'(none))

cat ~/.gitconfig command outputs this:

[user]
    name = myname
    email = myemail@myemail.com

cat .git/config outputs this:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[gui]
    wmstate = normal
    geometry = 1855x1026+65+24 262 188


问:
Flutter: Display Change Log / Release Notes / "What's new" after upgrade to new app version
I'm currently searching for a while how I can implement the following feature with Flutter for Android and IOS apps:
When the application is opened the first time after a version update I'd like to show a dialog with the information what's new in the new version / what has been fixed etc. - some kind of release notes.

I know various ways to show this dialog on application start; but how can I ensure that this is done only one time after the app version changed?
I was thinking about storing the various version messages as texts on the remote backend and give them an unique ID; via shared preferences or other persistance the last shown message ID could be stored and compared to the last available one.
But I see this feature in so many apps that I suppose there's a "standard way" to do this or maybe a package which supports this.

Kind regards
Michael

答:
I don't know if there is a standard way of doing it, but here is a simple way to do it.

Include "package_info" plugin in your project.

```<code>import 'package:package_info/package_info.dart';

PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
String runningVersion = packageInfo.version;
//compare runningVersion to the one saved in sharedPrefs
//if they don't match show the message
//then save runningVersion to sharedPrefs
});
</code>```

Body:
I don't know if there is a standard way of doing it, but here is a simple way to do it.

Include "package_info" plugin in your project.

import 'package:package_info/package_info.dart';

PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
String runningVersion = packageInfo.version;
//compare runningVersion to the one saved in sharedPrefs
//if they don't match show the message
//then save runningVersion to sharedPrefs
});


问:
Scaling nodejs app while assigning unique ports
I'm trying to scale my game servers (nodejs) where instances should have unique ports assigned to them and where instances are separate (no load balancing of any kind) and are aware what port is assigned to them (ideally by env variable?).
I've tried using docker swarm but it has no option to specify port range and I couldn't find any way to allocate or to pass the allocated port to the instance so it's aware of the port its running on e.g via env variable.

Ideal solution would look like:

```<code>Instance 1: hostIP:1000
Instance 2: hostIP:1001
Instance 3: hostIP:1002
... etc
</code>```

Now, I've managed to make this work by using regular Docker (non-swarm) by binding to host network and passing env variable PORT, but this way I'd have to manually spin up as many game servers as I'd need.

My node app uses "process.env.PORT" to bind to host's IP address:port

Any opinion on what solutions I could use to scale my app?

答:
You could try different approaches.

Use docker compose and external service for extracting data from docker.sock as suggested here How to get docker mapped ports from node.js application?

Use redis or any key-value storage service to store port information and get it with every new instance launch. The most simple solution is to use redis incr command to get next free number but it has some limitations

Body:
I'm trying to scale my game servers (nodejs) where instances should have unique ports assigned to them and where instances are separate (no load balancing of any kind) and are aware what port is assigned to them (ideally by env variable?).
I've tried using docker swarm but it has no option to specify port range and I couldn't find any way to allocate or to pass the allocated port to the instance so it's aware of the port its running on e.g via env variable.

Ideal solution would look like:

Instance 1: hostIP:1000
Instance 2: hostIP:1001
Instance 3: hostIP:1002
... etc

Now, I've managed to make this work by using regular Docker (non-swarm) by binding to host network and passing env variable PORT, but this way I'd have to manually spin up as many game servers as I'd need.

My node app uses "process.env.PORT" to bind to host's IP address:port

Any opinion on what solutions I could use to scale my app?


问:
Python selecting closest negative and positive values to zero from a list
I have many lists. Each list constains three floats. I need to select a negative and positive closest to zero from each list.
Here is the example:

```<code>list1= [-18.987536121749894, 9.154936510174036, -4.626424654409895]
list2= [-4.626424654409895, 9.154936510174036, 2.355498340416582]
list3= [-0.5, 0.1, 0.005]
</code>```

My expected output:

```<code>list1_op= [-4.626424654409895, 9.154936510174036]
list2_op= [-4.626424654409895, 2.355498340416582]
list3_op= [-0.5, 0.005]
</code>```

My code:

```<code>while loop:
     ...
     ...
    pdif = fun(mf1,mf2,mf3)   # mf1 and mf2 are extreme points, mf3 is middle point between them
    asign = np.sign(pdif) # check for sign change in Pdif list
    signchange = ((np.roll(asign, 1) - asign) != 0).astype(int)
    print(pdif)
    if abs(pdif[2])<0.01:
        print("Optimal point reached")
        break
    else:
        if signchange.sum()>0: # If yes then there is a merging point
            if (pdif[2]<abs(pdif[0]))&(signchange[1]==1):
                mf1 = mf3
            elif (pdif[2]<abs(pdif[1]))&(signchange[2]==1):
                mf2 = mf3
            mf3 = np.array([mf1,mf2]).mean()
</code>```

I have no idea how to start.

答:
Find the largest number less than zero and the smallest number greater than zero.

```<code>import numpy as np
a = [-18.987536121749894, 9.154936510174036, -4.626424654409895]
b = [-4.626424654409895, 9.154936510174036, 2.355498340416582]
c = [-0.5, 0.1, 0.005]
for thing in (a,b,c):
    thing = np.array(thing)
    x = thing[thing<0].max()
    y = thing[thing>0].min()
    ix = np.where(np.isclose(thing,x))[0]
    iy = np.where(np.isclose(thing,y))[0]
    print(f'{x},{y},{ix},{iy}')
    # or
    indices = np.where(np.any(np.isclose(thing[:,None],[x,y]),axis=-1))
    print(f'indices:{indices[0]}')
</code>```

Will throw a ValueError if there are no positive or no negative numbers in the list being tested.

Body:
I have many lists. Each list constains three floats. I need to select a negative and positive closest to zero from each list.
Here is the example:

list1= [-18.987536121749894, 9.154936510174036, -4.626424654409895]
list2= [-4.626424654409895, 9.154936510174036, 2.355498340416582]
list3= [-0.5, 0.1, 0.005]

My expected output:

list1_op= [-4.626424654409895, 9.154936510174036]
list2_op= [-4.626424654409895, 2.355498340416582]
list3_op= [-0.5, 0.005]

My code:

while loop:
     ...
     ...
    pdif = fun(mf1,mf2,mf3)   # mf1 and mf2 are extreme points, mf3 is middle point between them
    asign = np.sign(pdif) # check for sign change in Pdif list
    signchange = ((np.roll(asign, 1) - asign) != 0).astype(int)
    print(pdif)
    if abs(pdif[2])<0.01:
        print("Optimal point reached")
        break
    else:
        if signchange.sum()>0: # If yes then there is a merging point
            if (pdif[2]<abs(pdif[0]))&(signchange[1]==1):
                mf1 = mf3
            elif (pdif[2]<abs(pdif[1]))&(signchange[2]==1):
                mf2 = mf3
            mf3 = np.array([mf1,mf2]).mean()

I have no idea how to start.

Body:
Find the largest number less than zero and the smallest number greater than zero.

import numpy as np
a = [-18.987536121749894, 9.154936510174036, -4.626424654409895]
b = [-4.626424654409895, 9.154936510174036, 2.355498340416582]
c = [-0.5, 0.1, 0.005]
for thing in (a,b,c):
    thing = np.array(thing)
    x = thing[thing<0].max()
    y = thing[thing>0].min()
    ix = np.where(np.isclose(thing,x))[0]
    iy = np.where(np.isclose(thing,y))[0]
    print(f'{x},{y},{ix},{iy}')
    # or
    indices = np.where(np.any(np.isclose(thing[:,None],[x,y]),axis=-1))
    print(f'indices:{indices[0]}')

Will throw a ValueError if there are no positive or no negative numbers in the list being tested.


问:
Inserting static time on sheets app
I'm trying to insert the current time as a static value in Google sheets on a mobile device.

The keyboard shortcut Ctrl + Shift + ; works on the desktop but not the mobile app and "=NOW()" works to insert the time but as a dynamic value.

Is there a script I can use to cut and paste the dynamic value as a static value?

答:
As of today, Google Sheets App has an icon for inserting static DateTime.

You have to select the entire column or cell format as Date Time from the Format menu first.

Format > Number > Date time

Title: Inserting static time on sheets app


问:
Developing API - how to make it secured?
I'm putting together read and write methods to my database and exposing them via URL (I'm using CodeIgniter framework and using URL segments to pass parameters to these methods). The original idea was to have my Ajax script call these methods. However, now I am thinking I could potentially expose these methods to any developer.

What should I do to make sure only authorized developers use my API? I'm thinking they should pass an API key and possibly password to each method call. If I were to provide them with such details, would that be secure enough?

Also, I'm thinking that I should support POST instead of GET as some of the required parameters may not fit in nicely with URL segments. Thoughts?

答:
Implementing OAuth http://oauth.net/documentation/getting-started/ would work for what you're trying to do.  I'm not certain of what type of data you're securing, but I agree with TradyBlix this probably best.  I've implemented it before, it's not too hard to figure out, it's well documented with many APIs that handle user-data utilizing it.

Another thing you should think about is limiting API Keys to domains, so a developer can only use their API key from their own domain-essentially preventing an unauthorized developer from gaining access, at least without gaining access to an authorized domain and corresponding key.


问:
How to execute python program and save output in different file names automatically
I have a Python program which processes images and save the resulting output to a file. I am receiving the input and output file names via console using input(). But I want to save the output automatically with the file name as something like "input_file_name_out". Note the string "_out" attached to the input file name

This will help me get user input only for Input file names thereby saving little time for the user since he doesn't need to think everytime what should be the output file name

Sample code snippet

```<code>if __name__ == "__main__":

    in_file = input()
    out_file = input()

    processed = process_image(in_file,out_file)
</code>```

Expected code snippet

```<code>if __name__ == "__main__":

    in_file = input()
    # out_file = input() ------Not getting the file name from user thereby supplying only one argument to the below function

        processed = process_image(in_file)

# And within the function
def process_image(img):
    .
    .
    .
    out_file = img+"_out.jpg" ##### What should come here to achieve my requirement ########
    cv2.imwrite(out_file,processed_image)
</code>```

答:
Well that's simple!
Just take the "in_file" string you asked for, and concat "_out" to the end and pass it as the out_file.

If you only process ".jpg"

```<code>cv2.imwrite(in_file[:-4]+"_out.jpg",processed_image)
</code>```

if its variable:

```<code>cv2.imwrite(in_file[:-4]+"_out"+in_file[-4:],processed_image)
</code>```

Body:
I have a Python program which processes images and save the resulting output to a file. I am receiving the input and output file names via console using input(). But I want to save the output automatically with the file name as something like "input_file_name_out". Note the string "_out" attached to the input file name

This will help me get user input only for Input file names thereby saving little time for the user since he doesn't need to think everytime what should be the output file name

Sample code snippet

if __name__ == "__main__":

    in_file = input()
    out_file = input()

    processed = process_image(in_file,out_file)

Expected code snippet

if __name__ == "__main__":

    in_file = input()
    # out_file = input() ------Not getting the file name from user thereby supplying only one argument to the below function

        processed = process_image(in_file)

# And within the function
def process_image(img):
    .
    .
    .
    out_file = img+"_out.jpg" ##### What should come here to achieve my requirement ########
    cv2.imwrite(out_file,processed_image)

Body:
Well that's simple!
Just take the "in_file" string you asked for, and concat "_out" to the end and pass it as the out_file.

If you only process ".jpg"

cv2.imwrite(in_file[:-4]+"_out.jpg",processed_image)

if its variable:

cv2.imwrite(in_file[:-4]+"_out"+in_file[-4:],processed_image)


问:
Updated vector elements do not print
The code below is not printing the updated vector elements after replacing the elements that are less than the mean of the first and last element.

How may this code be improved upon, the user inputs array of specified length and replaces each element that is smaller than the mean of the first and last element with the mean.

Is there a better way to pass the vector to the function, or more efficient way to manage memory?

```<code>#include <iostream>
#include <vector>

std::vector<double> getData()
{
    int n;
    std::vector<double> intputData;
    std::cout << "Enter array length\n";
    std::cin >> n;
    std::cout << "Enter the numbers\n";
    for(int i = 0; i < n; i++){
        int tmpIn;
        std::cin >> tmpIn;
        intputData.push_back(tmpIn);
    }
    return intputData;
}

void modifyData(std::vector<double> &data_mo)
{
    double f=data_mo[0];
    double l=data_mo[data_mo.size() - 1];
    double av = (f + l)/2;
    for (auto j: data_mo)
    {
        if(j < av){
            j = av;
        }
    }
}

void printData(std::vector<double> &data_pr)
{
    for (auto i: data_pr)
    {
        std::cout << i << " ";
    }
    std::cout << '\n';
}

int main(){

    std::vector<double> data_ma = getData();
    modifyData(data_ma);
    printData(data_ma);

    return 0;
}
</code>```

答:
modifyData needs it's range-based for loop to modify the elements by reference, otherwise your modifications are working on copies of the elements and not the elements themselves.

change

```<code>for (auto j: data_mo)
</code>```

to

```<code>for (auto &j: data_mo)
</code>```

Also, a simple improvement is to make printData take it's parameter by const reference because the vector does not get changed.

```<code>void printData(const std::vector<double> &data_pr)
</code>```

Title: Updated vector elements do not print

Body:
The code below is not printing the updated vector elements after replacing the elements that are less than the mean of the first and last element.

How may this code be improved upon, the user inputs array of specified length and replaces each element that is smaller than the mean of the first and last element with the mean.

Is there a better way to pass the vector to the function, or more efficient way to manage memory?

#include <iostream>
#include <vector>

std::vector<double> getData()
{
    int n;
    std::vector<double> intputData;
    std::cout << "Enter array length\n";
    std::cin >> n;
    std::cout << "Enter the numbers\n";
    for(int i = 0; i < n; i++){
        int tmpIn;
        std::cin >> tmpIn;
        intputData.push_back(tmpIn);
    }
    return intputData;
}

void modifyData(std::vector<double> &data_mo)
{
    double f=data_mo[0];
    double l=data_mo[data_mo.size() - 1];
    double av = (f + l)/2;
    for (auto j: data_mo)
    {
        if(j < av){
            j = av;
        }
    }
}

void printData(std::vector<double> &data_pr)
{
    for (auto i: data_pr)
    {
        std::cout << i << " ";
    }
    std::cout << '\n';
}

int main(){

    std::vector<double> data_ma = getData();
    modifyData(data_ma);
    printData(data_ma);

    return 0;
}

Body:
modifyData needs it's range-based for loop to modify the elements by reference, otherwise your modifications are working on copies of the elements and not the elements themselves.

change

for (auto j: data_mo)

to

for (auto &j: data_mo)

Also, a simple improvement is to make printData take it's parameter by const reference because the vector does not get changed.

void printData(const std::vector<double> &data_pr)


问:
BEM and css frameworks
How to use BEM methodology with css frameworks, for instance Bootstrap? If I have following markup structure is it ok? :

```<code> <div class="hero">
    <div class="container">
       <div class="row">
        <div class="col-md-8 mx-auto">
          <h1 class="hero__title"></h1>
        </div>
      </div>
    </div>
  </div>
</code>```

or shouild I structure document like this:

```<code><div class="hero">
  <div class="hero__container">
    <div class="hero__row">
      <div class="hero__row-inner">
        <h1 class="hero__title"></h1>
      </div>
     </div>
   </div>
</div>
</code>```

答:
you shouldn't try to apply the BEM methodology for utility classes like "container, row, col" and more, but you can try helper situations col col--xs-12 or img img--cover

You can check more utility classes in the bootstrap doc; https://getbootstrap.com/docs/4.4/utilities/borders/

```<code><div class="hero">
  <div class="container">
       <div class="row">
        <div class="col-md-8 mx-auto">
          <h1 class="hero__title"></h1>
        </div>
      </div>
    </div>
</div>
</code>```

You had better use it as your first code blocks.

Title: BEM and css frameworks

Body:
How to use BEM methodology with css frameworks, for instance Bootstrap? If I have following markup structure is it ok? :

or shouild I structure document like this:

Body:
you shouldn't try to apply the BEM methodology for utility classes like "container, row, col" and more, but you can try helper situations col col--xs-12 or img img--cover

You can check more utility classes in the bootstrap doc; https://getbootstrap.com/docs/4.4/utilities/borders/

<div class="hero">
  <div class="container">
       <div class="row">
        <div class="col-md-8 mx-auto">
          <h1 class="hero__title"></h1>
        </div>
      </div>
    </div>
</div>

You had better use it as your first code blocks.


问:
TypeError when assigning a random value from a list to a variable?
I have a list and I want to assign a random element from that list to a new variable five times in order to generate a hand of cards. I've searched, and I can't seem to understand why my random.choice is causing errors.

```<code>import random

cards = { '2' '3' '4' '5' '6' '7' '8' '9' 'J' 'Q' 'K' 'A' }

for newCard in range(5):
        newDraw = random.choice(cards)
        playerdeck.append(newDraw)
        if newDraw in playerdeck:
                playermatches = playermatches + 1
        newDraw = oldDraw
</code>```

When I try to run it I get this error:

```<code>Traceback (most recent call last):
  File "C:\Users\Nathaniel\Desktop\Fcard.py", line 6, in <module>
    newDraw = random.choice(cards)
  File "C:\Python32\lib\random.py", line 253, in choice
    return seq[i]
TypeError: 'set' object does not support indexing
</code>```

答:
You used { and } rather than [ and ] to define cards. Therefore, it is a set. sets are not ordered, and therefore it makes no sense to try to index into it. random.choice needs to index into a collection to pull an item out of it. Anyway, a quick fix is to replace this:

```<code>random.choice(cards)
</code>```

With this:

```<code>random.choice(list(cards))
</code>```

Edit: Also add commas between the elements in the set.

Body:
I have a list and I want to assign a random element from that list to a new variable five times in order to generate a hand of cards. I've searched, and I can't seem to understand why my random.choice is causing errors.

import random

cards = { '2' '3' '4' '5' '6' '7' '8' '9' 'J' 'Q' 'K' 'A' }

for newCard in range(5):
        newDraw = random.choice(cards)
        playerdeck.append(newDraw)
        if newDraw in playerdeck:
                playermatches = playermatches + 1
        newDraw = oldDraw

When I try to run it I get this error:

Traceback (most recent call last):
  File "C:\Users\Nathaniel\Desktop\Fcard.py", line 6, in <module>
    newDraw = random.choice(cards)
  File "C:\Python32\lib\random.py", line 253, in choice
    return seq[i]
TypeError: 'set' object does not support indexing

Body:
You used { and } rather than [ and ] to define cards. Therefore, it is a set. sets are not ordered, and therefore it makes no sense to try to index into it. random.choice needs to index into a collection to pull an item out of it. Anyway, a quick fix is to replace this:

random.choice(cards)

With this:

random.choice(list(cards))

Edit: Also add commas between the elements in the set.


问:
Xampp -mysql in xampp starts and stops after a while
when I click to start MySQL it start but after a while it suddenly stop. Here is the response that show in Xampp control panel.

Status change detected: running
Status change detected: stopped

答:
follow these steps below :

1-windows + R (opens run window)

2-type in services.msc

3-check if the service mysql is set as disabled. (change it to automatic)

or

1-quit the XAMPP

2-cut the All files in C:\xampp\mysql\backup

3-paste and replace files in C:\xampp\mysql\data

4-run as administrator the XAMPP


问:
Nested JSON - Join sub-object
How can I remove sub-objects?   </p>

```<code>[{
    "id": "1",
    "desc": "SOME PRODUCT",
    "codigo": "CODE-28",
    "codigoBarras": "2000000001",
    "unidade": "PCT",
    "price": "24.15",
    "current_inventory": [{
        "2kg": "5",
        "5kg": "5",
        "10kg": "5",
        "20kg": "5",
        "productId": "1"
     }]
 }]

[{
    "id": "1",
    "desc": "SOME PRODUCT",
    "codigo": "CODE-28",
    "codigoBarras": "2000000001",
    "unidade": "PCT",
    "price": "24.15",
    "current_inventory_2kg": "5",
    "current_inventory_5kg": "5",
    "current_inventory_10kg": "5",
    "current_inventory_20kg": "5",
}]
</code>```

答:
Use Object.keys() and a forEach loop

var x =[
    {
        "id": "1",
        "desc": "SOME PRODUCT",
        "codigo": "CODE-28",
        "codigoBarras": "2000000001",
        "unidade": "PCT",
        "price": "24.15",
        "current_inventory": [
            {
                "2kg": "5",
                "5kg": "5",
                "10kg": "5",
                "20kg": "5",
                "productId": "1"
            }
        ]
    }
]
x[0].current_inventory.forEach(e=>{
Object.keys(e).forEach(j=>{
x[0]['current_inventory_'+j]=e[j];
})
delete x[0].current_inventory
})
console.log(x)```

Title: Nested JSON - Join sub-object

Body:
How can I remove sub-objects?

[{
    "id": "1",
    "desc": "SOME PRODUCT",
    "codigo": "CODE-28",
    "codigoBarras": "2000000001",
    "unidade": "PCT",
    "price": "24.15",
    "current_inventory": [{
        "2kg": "5",
        "5kg": "5",
        "10kg": "5",
        "20kg": "5",
        "productId": "1"
     }]
 }]

[{
    "id": "1",
    "desc": "SOME PRODUCT",
    "codigo": "CODE-28",
    "codigoBarras": "2000000001",
    "unidade": "PCT",
    "price": "24.15",
    "current_inventory_2kg": "5",
    "current_inventory_5kg": "5",
    "current_inventory_10kg": "5",
    "current_inventory_20kg": "5",
}]


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

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

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

答:
Your code works fine. try this</p>

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<form id="form" action="submit">
    <input id="email" type="email"/>
    <button type="submit">Go</button>
    <p id="email-message"></p>
</form>

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

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

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

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

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

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

          </form>

Body:
Your code works fine. try this

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<form id="form" action="submit">
    <input id="email" type="email"/>
    <button type="submit">Go</button>
    <p id="email-message"></p>
</form>

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

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


问:
isEqualToString not returning true
The "Stopping" statement never gets printed even if you type 'stop' when running the program. Is the initWithUTF8String: method introducing extra formatting?

```<code>int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    char holderText[256];

    fgets(holderText, 256, stdin);
    NSString *words = [[NSString alloc] initWithUTF8String:holderText];

    if ([words isEqualToString:@"stop"]) {

        NSLog(@"STOPPING");

    }
    NSLog(@"This is what you typed: %@", words);

    [pool drain];
    return 0;
}
</code>```

答:
fgets will include the trailing newline in the string it gives you (except in the case where it wouldn't fit in the buffer but that's not so here), so it will be "stop\n" rather than "stop".

Changing the log line to:

```<code>NSLog(@"This is what you typed: [%@]", words);
</code>```

should hopefully make it clear what's happening.

Either modify the comparison to take this into account, or trim the newline off before comparing.

Title: isEqualToString not returning true

Body:
The "Stopping" statement never gets printed even if you type 'stop' when running the program. Is the initWithUTF8String: method introducing extra formatting?

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    char holderText[256];

    fgets(holderText, 256, stdin);
    NSString *words = [[NSString alloc] initWithUTF8String:holderText];

    if ([words isEqualToString:@"stop"]) {

        NSLog(@"STOPPING");

    }
    NSLog(@"This is what you typed: %@", words);

    [pool drain];
    return 0;
}

Body:
fgets will include the trailing newline in the string it gives you (except in the case where it wouldn't fit in the buffer but that's not so here), so it will be "stop\n" rather than "stop".

Changing the log line to:

NSLog(@"This is what you typed: [%@]", words);

should hopefully make it clear what's happening.

Either modify the comparison to take this into account, or trim the newline off before comparing.


问:
d3-zoom mouseup event workaround
I'm aware that starting with v4 d3-zoom swallows up certain events for some reasons I don't fully understand. I've read some discussions about this, and I know that if I stopPropagation() on mousedown, then the zoom behavior won't get a chance to consume the event, and mouseup will consequently fire. The problem with that is that then the zoom doesnt work.

I haven't found a workaround for the case of needing to handle the mouseup event AND still have the zoom work. I'm particularly interested in the dragging case only. When the user does mousedown and starts to drag the canvas, I want to change the cursor to a clenched-hand, and when the user stops dragging and lets go of the mouse I want to change the cursor back.

How is this possible to do with the new d3-zoom behavior without resorting to a timeout? 'click' event is also not an option since that doesn't fire if there's a mousemove event in between.

答:
I am concluding from your question that you are not able to track mouseup event after dragging the canvas. If that is the case then we can use events provided by "zoom" functionality - zoomstart and zoomend.

We can simply add that to zoom behavior and track when the user starts zoom and ends zoom. And in this way we can easily change cursor property.

Please find below code snippet and working code as well. Please let me know if i am missing anything.

var margin = {
    top: -5,
    right: -5,
    bottom: -5,
    left: -5
  },
  width = 460 - margin.left - margin.right,
  height = 300 - margin.top - margin.bottom;

var zoom = d3.zoom()
  .scaleExtent([1, 10])
  .on("zoom", zoomed)
  .on("start", function() {
    document.getElementsByTagName("svg")[0].style.cursor = "grab";
  })
  .on("end", function() {
    document.getElementsByTagName("svg")[0].style.cursor = "default";
  })

console.log(zoom.scaleExtent()[0], zoom.scaleExtent()[1]);

var drag = d3.drag()
  .subject(function(d) {
    return d;
  })
  .on("start", dragstarted)
  .on("drag", dragged)
  .on("end", dragended);

var slider = d3.select("body").append("p").append("input")
  .datum({})
  .attr("type", "range")
  .attr("value", zoom.scaleExtent()[0])
  .attr("min", zoom.scaleExtent()[0])
  .attr("max", zoom.scaleExtent()[1])
  .attr("step", (zoom.scaleExtent()[1] - zoom.scaleExtent()[0]) / 100)
  .on("input", slided);

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.right + ")")
  .call(zoom);

var rect = svg.append("rect")
  .attr("width", width)
  .attr("height", height)
  .style("fill", "none")
  .style("pointer-events", "all");

var container = svg.append("g");

container.append("g")
  .attr("class", "x axis")
  .selectAll("line")
  .data(d3.range(0, width, 10))
  .enter().append("line")
  .attr("x1", function(d) {
    return d;
  })
  .attr("y1", 0)
  .attr("x2", function(d) {
    return d;
  })
  .attr("y2", height);

container.append("g")
  .attr("class", "y axis")
  .selectAll("line")
  .data(d3.range(0, height, 10))
  .enter().append("line")
  .attr("x1", 0)
  .attr("y1", function(d) {
    return d;
  })
  .attr("x2", width)
  .attr("y2", function(d) {
    return d;
  });

dots = [{
  x: 100,
  y: 100,
}]

dot = container.append("g")
  .attr("class", "dot")
  .selectAll("circle")
  .data(dots)
  .enter().append("circle")
  .attr("r", 5)
  .attr("cx", function(d) {
    return d.x;
  })
  .attr("cy", function(d) {
    return d.y;
  })
  .call(drag);

function dottype(d) {
  d.x = +d.x;
  d.y = +d.y;
  return d;
}

function zoomed(event) {
  const currentTransform = d3.event.transform;
  container.attr("transform", currentTransform);
  slider.property("value", currentTransform.k);
}

function dragstarted(d) {
  d3.event.sourceEvent.stopPropagation();
  d3.select(this).classed("dragging", true);
}

function dragged(d) {
  d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
}

function dragended(d) {
  d3.select(this).classed("dragging", false);
}

function slided(d) {
  zoom.scaleTo(svg, d3.select(this).property("value"));
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dot circle {
  fill: lightsteelblue;
  stroke: steelblue;
  stroke-width: 1.5px;
}

.dot circle.dragging {
  fill: red;
  stroke: brown;
}

.axis line {
  fill: none;
  stroke: #ddd;
  shape-rendering: crispEdges;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <title></title>

```
</div>
</div>
</p>
```var zoom = d3.zoom()
             .scaleExtent([1, 10])
             .on("zoom", zoomed)
             .on("start", function() {
               document.getElementsByTagName("svg")[0].style.cursor = "grab";
             })
             .on("end", function() {
               document.getElementsByTagName("svg")[0].style.cursor = "default";
             })
```

Title: d3-zoom mouseup event workaround

Body:
I am concluding from your question that you are not able to track mouseup event after dragging the canvas. If that is the case then we can use events provided by "zoom" functionality - zoomstart and zoomend.

We can simply add that to zoom behavior and track when the user starts zoom and ends zoom. And in this way we can easily change cursor property.

Please find below code snippet and working code as well. Please let me know if i am missing anything.

var margin = {
    top: -5,
    right: -5,
    bottom: -5,
    left: -5
  },
  width = 460 - margin.left - margin.right,
  height = 300 - margin.top - margin.bottom;

var zoom = d3.zoom()
  .scaleExtent([1, 10])
  .on("zoom", zoomed)
  .on("start", function() {
    document.getElementsByTagName("svg")[0].style.cursor = "grab";
  })
  .on("end", function() {
    document.getElementsByTagName("svg")[0].style.cursor = "default";
  })

console.log(zoom.scaleExtent()[0], zoom.scaleExtent()[1]);

var drag = d3.drag()
  .subject(function(d) {
    return d;
  })
  .on("start", dragstarted)
  .on("drag", dragged)
  .on("end", dragended);

var slider = d3.select("body").append("p").append("input")
  .datum({})
  .attr("type", "range")
  .attr("value", zoom.scaleExtent()[0])
  .attr("min", zoom.scaleExtent()[0])
  .attr("max", zoom.scaleExtent()[1])
  .attr("step", (zoom.scaleExtent()[1] - zoom.scaleExtent()[0]) / 100)
  .on("input", slided);

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.right + ")")
  .call(zoom);

var rect = svg.append("rect")
  .attr("width", width)
  .attr("height", height)
  .style("fill", "none")
  .style("pointer-events", "all");

var container = svg.append("g");

container.append("g")
  .attr("class", "x axis")
  .selectAll("line")
  .data(d3.range(0, width, 10))
  .enter().append("line")
  .attr("x1", function(d) {
    return d;
  })
  .attr("y1", 0)
  .attr("x2", function(d) {
    return d;
  })
  .attr("y2", height);

container.append("g")
  .attr("class", "y axis")
  .selectAll("line")
  .data(d3.range(0, height, 10))
  .enter().append("line")
  .attr("x1", 0)
  .attr("y1", function(d) {
    return d;
  })
  .attr("x2", width)
  .attr("y2", function(d) {
    return d;
  });

dots = [{
  x: 100,
  y: 100,
}]

dot = container.append("g")
  .attr("class", "dot")
  .selectAll("circle")
  .data(dots)
  .enter().append("circle")
  .attr("r", 5)
  .attr("cx", function(d) {
    return d.x;
  })
  .attr("cy", function(d) {
    return d.y;
  })
  .call(drag);

function dottype(d) {
  d.x = +d.x;
  d.y = +d.y;
  return d;
}

function zoomed(event) {
  const currentTransform = d3.event.transform;
  container.attr("transform", currentTransform);
  slider.property("value", currentTransform.k);
}

function dragstarted(d) {
  d3.event.sourceEvent.stopPropagation();
  d3.select(this).classed("dragging", true);
}

function dragged(d) {
  d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
}

function dragended(d) {
  d3.select(this).classed("dragging", false);
}

function slided(d) {
  zoom.scaleTo(svg, d3.select(this).property("value"));
}

.dot circle {
  fill: lightsteelblue;
  stroke: steelblue;
  stroke-width: 1.5px;
}

.dot circle.dragging {
  fill: red;
  stroke: brown;
}

.axis line {
  fill: none;
  stroke: #ddd;
  shape-rendering: crispEdges;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <style>

  </style>
  <title></title>
</head>

<body>
  <script src="https://d3js.org/d3.v4.min.js"></script>
</body>

</html>

var zoom = d3.zoom()
             .scaleExtent([1, 10])
             .on("zoom", zoomed)
             .on("start", function() {
               document.getElementsByTagName("svg")[0].style.cursor = "grab";
             })
             .on("end", function() {
               document.getElementsByTagName("svg")[0].style.cursor = "default";
             })


问:
Django RF - How to insert into pivot table using name instead of id without querying the id?
For example I have the ff:

models:

```<code>class Store(models.Model):
    name = models.CharField(max_length = 20)

class Product(models.Model):
    name = models.CharField(max_length = 20)

class StoreProducts(models.Model):
    store = models.ForeignKey(Store)
    product = models.ForeignKey(Product)
    qty = models.IntegerField()
</code>```

serializer:

```<code>class StoreProductsSerializer(serializers.ModelSerializer):
    class Meta:
        model = StoreProducts
        fields = ('store', 'product', 'qty')
</code>```

And defined values:

```<code>Store (id, name):
 1, store_1
 2, store_2

Product (id, name):
 1, product_1
 2, product_2
</code>```

Now in the views, I want to add into the StoreProducts from post request without querying the ids of Store and Product like this:

```<code>data = {
'store': 'store_1',
'product': 'product_1',
'qty': 1
}

serializer = StoreProductsSerializer(data=data)
    if serializer.is_valid():
        serializer.save()
</code>```

Is this possible and how? Thanks

答:
You have to use nested serializers in that case. DRF does not provide create and update functionality with nested serializers, so you will have to take care of that as well.

```<code>class StoreSerializer(serializers.ModelSerializer):
    class Meta:
        model = Store
        fields = ('name',)

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ('name',)

class StoreProductsSerializer(serializers.ModelSerializer):
    store = StoreSerializer()
    product = ProductSerializer()

    class Meta:
        model = StoreProducts
        fields = ('store', 'product', 'qty')

    def create(self, validated_data):
        store = Store.objects.create(validated_data.pop('store'))
        product = Product.objects.create(validated_data.pop('product'))
        return super().create({**validated_data, 'store': store, 'product': product})
</code>```

Body:
For example I have the ff:

models:

class Store(models.Model):
    name = models.CharField(max_length = 20)

class Product(models.Model):
    name = models.CharField(max_length = 20)

class StoreProducts(models.Model):
    store = models.ForeignKey(Store)
    product = models.ForeignKey(Product)
    qty = models.IntegerField()

serializer:

class StoreProductsSerializer(serializers.ModelSerializer):
    class Meta:
        model = StoreProducts
        fields = ('store', 'product', 'qty')

And defined values:

Store (id, name):
 1, store_1
 2, store_2

Product (id, name):
 1, product_1
 2, product_2

Now in the views, I want to add into the StoreProducts from post request without querying the ids of Store and Product like this:

data = {
'store': 'store_1',
'product': 'product_1',
'qty': 1
}

serializer = StoreProductsSerializer(data=data)
    if serializer.is_valid():
        serializer.save()

Is this possible and how? Thanks

Body:
You have to use nested serializers in that case. DRF does not provide create and update functionality with nested serializers, so you will have to take care of that as well.

class StoreSerializer(serializers.ModelSerializer):
    class Meta:
        model = Store
        fields = ('name',)

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ('name',)

class StoreProductsSerializer(serializers.ModelSerializer):
    store = StoreSerializer()
    product = ProductSerializer()

    class Meta:
        model = StoreProducts
        fields = ('store', 'product', 'qty')

    def create(self, validated_data):
        store = Store.objects.create(validated_data.pop('store'))
        product = Product.objects.create(validated_data.pop('product'))
        return super().create({**validated_data, 'store': store, 'product': product})


问:
How can I load data into an S3 bucket from a Twilio function?
I've written the following Twilio function to load data into an S3 bucket.

However, no data ever gets to S3 at all.

What's wrong?

exports.handler = function(context, event, callback) {
    callback(null,
        putFile(
            getParams(context, event)
        )
    );
};

function getParams(context, event) {
    return {
        Bucket: 'my-bucket',
        Key: 'my-file.json',
        Body: JSON.stringify(event),
        ContentType: 'application/json'
    };
}

function putFile(params) {
    var aws = require('aws-sdk');
    var s3 = new aws.S3();

    s3.putObject(params, (err, res) => {
        if (err) console.log(`s3-err: ${err}`);
        if (res) console.log(`s3-res: ${JSON.stringify(res)}`);
    });
}```

答:
The asnwer to my question is here:
https://www.twilio.com/docs/runtime/functions/invocation#callback-and-asynchronous-limitations

Callback and Asynchronous Limitations

It is important to note that when the callback function is invoked, it
  will terminate all execution of your Function. This includes any
  asynchronous processes you may have kicked off during during the
  execution of your handler.

For this reason, if you are using libraries that are natively
  asynchronous, you need to nest your call to the callback function
  inside the promise handler.

So, basically, callback(); needs to be placed inside the successful response of the request to S3.

I failed to do that in my code snippet above, as I simply logged the response. When I placed the callback(); out, I instructed the process to terminate, and any API request to uploading data to S3 would never complete.

Here's a simplified snippet that works:

```<code>exports.handler = function (context, event, callback) {
    S3.upload(getParams(context, event), function (error, data) {
        if (error) {
            callback(error);
        } else {
            callback(null, "Data Uploaded");
        }
    });
};
</code>```

This is it. Hope it helps others. Cheers! =)

Body:
The asnwer to my question is here:
https://www.twilio.com/docs/runtime/functions/invocation#callback-and-asynchronous-limitations

Callback and Asynchronous Limitations

It is important to note that when the callback function is invoked, it
  will terminate all execution of your Function. This includes any
  asynchronous processes you may have kicked off during during the
  execution of your handler.

For this reason, if you are using libraries that are natively
  asynchronous, you need to nest your call to the callback function
  inside the promise handler.

So, basically, callback(); needs to be placed inside the successful response of the request to S3.

I failed to do that in my code snippet above, as I simply logged the response. When I placed the callback(); out, I instructed the process to terminate, and any API request to uploading data to S3 would never complete.

Here's a simplified snippet that works:

exports.handler = function (context, event, callback) {
    S3.upload(getParams(context, event), function (error, data) {
        if (error) {
            callback(error);
        } else {
            callback(null, "Data Uploaded");
        }
    });
};

This is it. Hope it helps others. Cheers! =)


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

Code

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

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

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

Thanks in Advance

答:
Try this one:</p>

```<code>guard let url = URL(string: "your web pdf file link here or you can set from local directory path")
else { return }
UIApplication.shared.open(url)
</code>```

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

Code

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

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

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

Thanks in Advance

Body:
Try this one:

guard let url = URL(string: "your web pdf file link here or you can set from local directory path")
else { return }
UIApplication.shared.open(url)


问:
Need help determining how to approach building my project
I'd like to create something similar to a family tree online app (like geni.com). I'm unsure what languages I should use to build it with. My IT strong points aren't in programming and this project is going to require me to sit down and learn some languages. My problem right now is that I don't know what languages I should use.

So with the idea of a family tree online app in mind here are some of the specifications.
- I do not want to use flash.
- The app needs to be zoomable and scrollable (sort of like google maps)
- The app needs to be able to add content without reloading the page. Perhaps there's a little "+" sign and when I click it, I can add a tag/title/description/picture
- The app needs to be able to save your work for that user to retrieve later on.
- The layout that a user is able to create in is sort of widget based where the user can add a new bubble and then in that bubble they are able to add text or content.

I started programming this with HTML5 canvas and Javascript, but I'm stuck on creating a connection to the database that isn't directly from Javascript (because that seems very insecure to me). But I'm not just stumped on how to interact securely with the database (I don't even have a database picked out), but also I'm concerned that I won't be able to build out the app with just javascript and may need something else like ajax or something but I'm unfamiliar with what each language does nowadays.

答:
If you are starting from scratch, then the best language to use is the one you are most comfortable with. Alternately, if you don't plan to be developing the whole thing yourself and you already have some other interested parties on board then the best language to use is the one that the majority of you are comfortable with.  If it's just you and you do not yet have any favorites, then look around and play with a few - it's the only way to find out if you will actually like / be effective with them.

That being said, a few of the more likely candidates these days are:

JavaScript: Long gone are the days when this language was simply a way to put the D in DHTML. These days JavaScript is a viable client and server-side language. (Others here have already recommended Node.js -- I'd also recommend NPM (node package manager) to handle your dependencies). With a little bit of planning you can reuse most of your application code on both the client and the server side.  On the downside, most of the server side technology is very new (only a few years old at most) and so you may find yourself implementing tools for use in your application rather than your application itself.  Finding servers that support it will also be harder, again on account of it's age.

Perl: At the opposite end of the spectrum of age, we find Perl - the first commonly deployed language used to make web applications it still powers a great variety of useful websites out there (include new ones such as Pinboard.)  The tools that are popular on CPAN have been vetted under fire. The good news is that it is not going anywhere anytime soon.  The bad news is, you might have to search a little harder to find a module that supports [that newest, baddest thing that just came out yesterday].

PHP: The BASIC (or Perl, depending on who you ask) of the modern web, PHP was designed from the ground up to do one thing - make building dynamic web pages easier.  Its popularity means that there is quite a lot of server support (PHP + Apache + MySQL is the Model T Ford of web servers -- everyone can afford one) and an enormous amount of pre-built code available for perusal.  However, like BASIC, PHP's strength is also its greatest weakness.  Almost anyone can write something that works in PHP ... how well it works depends on who wrote it. The caveat emptor that applies to all code snippets found on the web applies in spades to snippets of code written in PHP.

Python: The language that made programing fun again (at least for those who can see past the significant whitespace and lack of blocks / anonymous functions and overlook < 3.x's issues with non-ASCII out of the box.)  It's a general-purpose, flexible and multi-paradigm language with quite a substantial standard library (but without .NET or Java's incredible bloat).  In addition, quite a large amount of work has been done in it, so there is a good chance that what you need has been already developed by somebody else. Plus, it can make you fly.

Ruby (with or without Rails): The language that made the web fun, coupled, if you so desire, with the framework that made MVC cool.  There is lots of documentation out there, and a great community, with many prebuilt tools (called gems) from which to pick and choose - free and cheap servers are not as common as their PHP counterparts, but they are likely to be of higher quality (when chosen at random).

All that being said, they are all great languages for web development. What matters is not what we think you should use ... but what you are most likely to be effective with.  All of the languages listed above are mainstream (or will be in the next two years), easy-to-learn and easy-to-write languages.  You cannot go wrong, no matter what you choose to start off with.

Alternately, if you want something a little more difficult, or less mainstream ... I am working with .NET applications at work, and with Lisp (SBCL)-based services in my spare time.  I have heard great things about Lua and Java too ... there are at least two C++ web frameworks out there ... and I'm sure that there is somebody is having fun building a web service in COBOL with a FORTRAN backend. ;-)


问:
Compare date in Oracle when some value is null?
I want to get records that have an expired_date less than "31/12/2015", but some value of expired_date field is null in the database. This is my SQL:

```<code>"AND TO_DATE(EXPIRED_DATE,'DD/MM/YYYY') < TO_DATE('31/12/2015','DD/MM/YYYY')"
</code>```

so I have got an error

```<code>"day of the month must between 1 and the last day of the month"
</code>```

How can I get just records that have an expired_date < '31/12/2015'?

EDIT: The problem is not the null value, but my format in my DB. I store "22-APR-15" and mistake is trying to assign it to 'DD/MM/YYYY' by to_date function

答:
Your code ...E(EXPIRED_DATE,'DD/MM/YYY')... has 3 YYY for date instead of 4 YYYY. Tried below and it works

```<code>with da(date_a) as (
    select '03/04/2015' from dual
    union all select '03/04/2015' from dual
    union all select '03/04/2017' from dual
    union all select '03/04/2015' from dual
    union all select '03/04/2016' from dual
    union all select NULL from dual
)
SELECT * FROM da WHERE   TO_DATE(date_a,'DD/MM/YYYY') < TO_DATE('31/12/2015', 'DD/MM/YYYY');
</code>```

Even when your date column is in date format it will still work

```<code>with da(date_a) as (
    select '03/04/2015' from dual
    union all select '03/04/2015' from dual
    union all select '03/04/2017' from dual
    union all select '03/04/2015' from dual
    union all select '03/04/2016' from dual
    union all select NULL from dual
)
SELECT to_date(date_a, 'DD/MM/YYYY')  date_a  FROM da WHERE   TO_DATE(date_a,'DD/MM/YYYY') < TO_DATE('31/12/2015', 'DD/MM/YYYY');
</code>```

db<>fiddle

Body:
I want to get records that have an expired_date less than "31/12/2015", but some value of expired_date field is null in the database. This is my SQL:

"AND TO_DATE(EXPIRED_DATE,'DD/MM/YYYY') < TO_DATE('31/12/2015','DD/MM/YYYY')"

so I have got an error

"day of the month must between 1 and the last day of the month"

How can I get just records that have an expired_date < '31/12/2015'?

EDIT: The problem is not the null value, but my format in my DB. I store "22-APR-15" and mistake is trying to assign it to 'DD/MM/YYYY' by to_date function

Body:
Your code ...E(EXPIRED_DATE,'DD/MM/YYY')... has 3 YYY for date instead of 4 YYYY. Tried below and it works

with da(date_a) as (
    select '03/04/2015' from dual
    union all select '03/04/2015' from dual
    union all select '03/04/2017' from dual
    union all select '03/04/2015' from dual
    union all select '03/04/2016' from dual
    union all select NULL from dual
)
SELECT * FROM da WHERE   TO_DATE(date_a,'DD/MM/YYYY') < TO_DATE('31/12/2015', 'DD/MM/YYYY');

Even when your date column is in date format it will still work

with da(date_a) as (
    select '03/04/2015' from dual
    union all select '03/04/2015' from dual
    union all select '03/04/2017' from dual
    union all select '03/04/2015' from dual
    union all select '03/04/2016' from dual
    union all select NULL from dual
)
SELECT to_date(date_a, 'DD/MM/YYYY')  date_a  FROM da WHERE   TO_DATE(date_a,'DD/MM/YYYY') < TO_DATE('31/12/2015', 'DD/MM/YYYY');

db<>fiddle


问:
spiliting the string in c# but an term consist of " , " so i dont want it to be split ? I have tried this
```<code>string mystr = clause.Replace("\"", "");

whereArray = mystr.TrimEnd(']').TrimStart('[').Split(',');
</code>```

so in whereArray i get this

```<code>"DigitalMedia","=","Snapchat","AND","Impressions","IN","14,15,24"
</code>```

so Basically i want like this

```<code>whereArray[0] = "DigitalMedia"

whereArray [1] = "="

whereArray [2] = "Snapchat"

whereArray [3] = "AND"

whereArray [4] = "Impressions"

whereArray [5] = "IN"

whereArray [6] = "14,15,24"
</code>```

and trying this

```<code>whereArray = mystr.TrimEnd(']').TrimStart('[').Split(',');
</code>```

this is what i get

答: i used this regex "(?:^|,)(\"(?:[^\"]+|\"\")\"|[^,])" , but i still left with this kind of string with me " \" myCharacter " so i run i loop and i remove the \" by whereArray[i].Remove(0, 2); so for now it worked..i am finding more better way!

Body:
string mystr = clause.Replace("\"", "");

whereArray = mystr.TrimEnd(']').TrimStart('[').Split(',');

so in whereArray i get this

"DigitalMedia","=","Snapchat","AND","Impressions","IN","14,15,24"

so Basically i want like this

whereArray[0] = "DigitalMedia"

whereArray [1] = "="

whereArray [2] = "Snapchat"

whereArray [3] = "AND"

whereArray [4] = "Impressions"

whereArray [5] = "IN"

whereArray [6] = "14,15,24"

and trying this

whereArray = mystr.TrimEnd(']').TrimStart('[').Split(',');

this is what i get


问:
Why won't my nested React components render?
I'm having a problem with my React component. The nested children of my component ControlPanel don't seem to be rendering. Here is my code:

```<code>class App extends Component {
  render() {
    return (
      <div className="App">
        <ControlPanel>
          <CustomerDisplay />
        </ControlPanel>
      </div>
    );
  }
}
</code>```

I have the following two lines at the top of this file:

```<code>import ControlPanel from './components/control_panel';

import CustomerDisplay from './components/customer_display';
</code>```

And here is my ControlPanel Component:

```<code>import React from 'react';
import CSSModules from 'react-css-modules';
import styles from './styles.scss';

const ControlPanel = () => {
    return (
      <div className="control_panel" id="control_panel">

      </div>
    );
}

export default CSSModules(ControlPanel, styles);
</code>```

I have tried:

Calling the component as a full HTML tag (opening & closing)

Nesting the CustomerDisplay component in the ControlPanel component (in the ControlPanel's index.jsx file)

I know that nesting component's is possible. I've seen it done. For some reason it just won't work for me.

答:
```<code>function FancyBorder(props) {
  return (
    <div className={'FancyBorder FancyBorder-' + props.color}>
      {props.children}
    </div>
  );
}

export default function WelcomeDialog() {
  return (
    <FancyBorder color="blue">
        <h1 className="Dialog-title">
           Welcome
        </h1>
        <p className="Dialog-message">
           Thank you for visiting our spacecraft!
        </p>
    </FancyBorder>
  );
}

</code>```

Anything inside the<FancyBorder>JSX tag gets passed into the FancyBorder component as childrenprop. Since FancyBorder renders {props.children} inside a
, the passed elements appear in the final output.

This is what I was looking after, check it out here
 https://reactjs.org/docs/composition-vs-inheritance.html

Body:
I'm having a problem with my React component. The nested children of my component ControlPanel don't seem to be rendering. Here is my code:

class App extends Component {
  render() {
    return (

        <ControlPanel>
          <CustomerDisplay />
        </ControlPanel>

    );
  }
}

I have the following two lines at the top of this file:

import ControlPanel from './components/control_panel';

import CustomerDisplay from './components/customer_display';

And here is my ControlPanel Component:

import React from 'react';
import CSSModules from 'react-css-modules';
import styles from './styles.scss';

const ControlPanel = () => {
    return (

    );
}

export default CSSModules(ControlPanel, styles);

I have tried:

Calling the component as a full HTML tag (opening & closing)

Nesting the CustomerDisplay component in the ControlPanel component (in the ControlPanel's index.jsx file)

I know that nesting component's is possible. I've seen it done. For some reason it just won't work for me.

Body:
function FancyBorder(props) {
  return (
    <div className={'FancyBorder FancyBorder-' + props.color}>
      {props.children}
    </div>
  );
}

export default function WelcomeDialog() {
  return (
    <FancyBorder color="blue">
        <h1 className="Dialog-title">
           Welcome
        </h1>
        <p className="Dialog-message">
           Thank you for visiting our spacecraft!
        </p>
    </FancyBorder>
  );
}

Anything inside the<FancyBorder>JSX tag gets passed into the FancyBorder component as childrenprop. Since FancyBorder renders {props.children} inside a <div>, the passed elements appear in the final output.

This is what I was looking after, check it out here
 https://reactjs.org/docs/composition-vs-inheritance.html


问:
ModelState Validation in MVC
the class has a property UserId which type of ApplicationUser and its required, and of course we can not pass it from view to controller because of security reasons.

Now when the controller checks the state of model the model is not in a correct state because there is no UserId Value and it returns the view back, if I use the view model the class has more than 50 properties and assigning the values from view model to class and then save it it is very tedious and difficult to do it for saving editing and so on, any advice to come out from this problem

thanks

答:
anyhow thanks for the cooperation for solving this problem
the easiest way that i found to return a UserId from a class, just one line of code is required inside class constructor

```<code>public constructor()
{
  UserId =  ClaimsPrincipal.Current.Identity.GetUserId();
}
</code>```

Title: ModelState Validation in MVC

Body:
anyhow thanks for the cooperation for solving this problem
the easiest way that i found to return a UserId from a class, just one line of code is required inside class constructor

public constructor()
{
  UserId =  ClaimsPrincipal.Current.Identity.GetUserId();
}


问:
Newly added array objects works the same
Please help. I have this code. I have a feeling that v-for caches (or wrongly work with it) my data array. Newly added objects (with "Add" button) are edited like the same. Try to add some rows and put some text or change a checkbox and you will see.

答:
```<code>// Update this fn to:
addMessenger() {
            this.data.profile.vsAppMessengers.push({...this.data.profile.messengerTemplate});
},
</code>```

Issue was: the object is copied by reference. To read more: https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0

Updated fiddle link: https://jsfiddle.net/shivampesitbng/6hoL0jts/2/

Body:
// Update this fn to:
addMessenger() {
            this.data.profile.vsAppMessengers.push({...this.data.profile.messengerTemplate});
},

Issue was: the object is copied by reference. To read more: https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0

Updated fiddle link: https://jsfiddle.net/shivampesitbng/6hoL0jts/2/


问:
Django - logout view customisation fail

Although the original question is cleared out, there's a new related question which is quite interesting: (please let me know if my theory is remotely correct...)

Please checkout my urlpatterns below:

from django.contrib.auth import views as auth_views
from boutique.models import Category
from django.urls import path, include
from . import views

app_name = 'users'
urlpatterns = [

    # to customise login view
    path('login/', auth_views.LoginView.as_view(extra_context = {'categories': Category.objects.get_categories_with_item()})),
    # path('login/', views.NewLoginView.as_view()),

    # to customise default logout view
    path('logout/', auth_views.LogoutView.as_view(), {'categories': Category.objects.get_categories_with_item()}),

    # include django authentication urls
    path('', include('django.contrib.auth.urls')),

```

<p>As you probably noticed that there are two different ways to pass in <code>extra_context</code>, the interesting thing is: The method used on <code>LogoutView</code> can not be used on <code>LoginView</code>!! However, The method used on <code>LoginView</code> does work on <code>LogoutView</code>.</p>

<p>I think the possible explanation and yet to be confirmed by you lot is that they inherit different views:</p>

<p><code>LoginView</code>:</p>

<pre class="lang-py prettyprint-override"><code>class LoginView(SuccessURLAllowedHostsMixin, FormView):
    """
    Display the login form and handle the login action.
    """
    form_class = AuthenticationForm
    authentication_form = None
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'registration/login.html'
    redirect_authenticated_user = False
    extra_context = None

    ...

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        current_site = get_current_site(self.request)
        context.update({
            self.redirect_field_name: self.get_redirect_url(),
            'site': current_site,
            'site_name': current_site.name,
            **(self.extra_context or {})
        })
        return context
</code>```

LogoutView:

class LogoutView(SuccessURLAllowedHostsMixin, TemplateView):
    """
    Log out the user and display the 'You are logged out' message.
    """
    next_page = None
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'registration/logged_out.html'
    extra_context = None

    ...

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        current_site = get_current_site(self.request)
        context.update({
            'site': current_site,
            'site_name': current_site.name,
            'title': _('Logged out'),
            **(self.extra_context or {})
        })
        return context

```

<p>I think the reason that <code>LoginView</code> has to pass the <code>extra_context</code> as a positional argument into <code>.as_view()</code> is that it doesn't inherit from <code>TemplateView</code>:</p>

<pre class="lang-py prettyprint-override"><code>class TemplateView(TemplateResponseMixin, ContextMixin, View):
    """
    Render a template. Pass keyword arguments from the URLconf to the context.
    """
    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)

</code>```

which has a get method to get context data... if i'm not mistaken.

Could anyone confirm this?

I'm quite new to python and django framework. Thanks a lot!!!

The Original question has been answered

Please checkout the answers in the comments session --

I'm fairly new to Django and in order to pass in more context to logout view I tried 2 methods to customise the logout view:

Method 1:

from django.contrib.auth import views as auth_views
from boutique.models import Category

app_name = 'users'
urlpatterns = [
    ...
    path('logout/', auth_views.LogoutView.as_view(), {'categories': Category.objects.all()}),

    # I also tried this:
    # path('logout/', auth_views.LogoutView.as_view({'categories': Category.objects.all()}),

    # I also tried this:
    # path('logout-customised-url/', auth_views.LogoutView.as_view(), {'categories': Category.objects.all()}),
    # This is working tho it wouldn't be automatically redirect to this path when logged out
```

<h2>Method 2:</h2>

<pre class="lang-py prettyprint-override"><code>    ...
    path('logout/', views.NewLogoutView.as_view()),
    # NewLogoutView code below:
</code>```

views.py

from boutique.models import Category
from django.contrib.auth.views import LogoutView

class NewLogoutView(LogoutView):

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['categories'] = Category.objects.all()
        return context
```

Still not working, and the outcome is exactly the same: if a customised url is in use such as 'logged-out/' instead of 'logout/', and you type out the url, it renders the correct page with the extra context. However, wouldn't go to the page when users log out normally...

Is there any workaround? Thanks!

答:
You need to pass extra_context in your urls.py inorder to send extra context to logout view. read more about passing extra context to a view from in url definition.

```<code>path(
    'logout/',
    auth_views.LogoutView.as_view(),
    {'extra_context':{'categories': Category.objects.all()}}
),
</code>```

Title: Django - logout view customisation fail

Body:
Although the original question is cleared out, there's a new related question which is quite interesting: (please let me know if my theory is remotely correct...)

Please checkout my urlpatterns below:

from django.contrib.auth import views as auth_views
from boutique.models import Category
from django.urls import path, include
from . import views

app_name = 'users'
urlpatterns = [

    # to customise login view
    path('login/', auth_views.LoginView.as_view(extra_context = {'categories': Category.objects.get_categories_with_item()})),
    # path('login/', views.NewLoginView.as_view()),

    # to customise default logout view
    path('logout/', auth_views.LogoutView.as_view(), {'categories': Category.objects.get_categories_with_item()}),

    # include django authentication urls
    path('', include('django.contrib.auth.urls')),

As you probably noticed that there are two different ways to pass in extra_context, the interesting thing is: The method used on LogoutView can not be used on LoginView!! However, The method used on LoginView does work on LogoutView.

I think the possible explanation and yet to be confirmed by you lot is that they inherit different views:

LoginView:

class LoginView(SuccessURLAllowedHostsMixin, FormView):
    """
    Display the login form and handle the login action.
    """
    form_class = AuthenticationForm
    authentication_form = None
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'registration/login.html'
    redirect_authenticated_user = False
    extra_context = None

    ...

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        current_site = get_current_site(self.request)
        context.update({
            self.redirect_field_name: self.get_redirect_url(),
            'site': current_site,
            'site_name': current_site.name,
            **(self.extra_context or {})
        })
        return context

LogoutView:

class LogoutView(SuccessURLAllowedHostsMixin, TemplateView):
    """
    Log out the user and display the 'You are logged out' message.
    """
    next_page = None
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'registration/logged_out.html'
    extra_context = None

    ...

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        current_site = get_current_site(self.request)
        context.update({
            'site': current_site,
            'site_name': current_site.name,
            'title': _('Logged out'),
            **(self.extra_context or {})
        })
        return context

I think the reason that LoginView has to pass the extra_context as a positional argument into .as_view() is that it doesn't inherit from TemplateView:

class TemplateView(TemplateResponseMixin, ContextMixin, View):
    """
    Render a template. Pass keyword arguments from the URLconf to the context.
    """
    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)

which has a get method to get context data... if i'm not mistaken.

Could anyone confirm this?

I'm quite new to python and django framework. Thanks a lot!!!

The Original question has been answered

Please checkout the answers in the comments session --

I'm fairly new to Django and in order to pass in more context to logout view I tried 2 methods to customise the logout view:

Method 1:

from django.contrib.auth import views as auth_views
from boutique.models import Category

app_name = 'users'
urlpatterns = [
    ...
    path('logout/', auth_views.LogoutView.as_view(), {'categories': Category.objects.all()}),

    # I also tried this:
    # path('logout/', auth_views.LogoutView.as_view({'categories': Category.objects.all()}),

    # I also tried this:
    # path('logout-customised-url/', auth_views.LogoutView.as_view(), {'categories': Category.objects.all()}),
    # This is working tho it wouldn't be automatically redirect to this path when logged out

Method 2:

    ...
    path('logout/', views.NewLogoutView.as_view()),
    # NewLogoutView code below:

views.py

from boutique.models import Category
from django.contrib.auth.views import LogoutView

class NewLogoutView(LogoutView):

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['categories'] = Category.objects.all()
        return context

Still not working, and the outcome is exactly the same: if a customised url is in use such as 'logged-out/' instead of 'logout/', and you type out the url, it renders the correct page with the extra context. However, wouldn't go to the page when users log out normally...

Is there any workaround? Thanks!

Body:
You need to pass extra_context in your urls.py inorder to send extra context to logout view. read more about passing extra context to a view from in url definition.

path(
    'logout/',
    auth_views.LogoutView.as_view(),
    {'extra_context':{'categories': Category.objects.all()}}
),


问:
Setting up email Notification on Azure DevOps
I have Self-hosted agents on my Azure DevOps on which the execution is scheduled from ADO every night using the release pipelines which i've created. I would want to send out email notification with the results to a Distribution List after the completion of the execution. How can i achieve this??

I want this summary page to be sent as an attachment -

答:
Setting up email Notification on Azure DevOps

AFAIK, Azure devops does not support add attachment in email Notification directly.

As workaround, we could use a powershell script to get test results with REST API then send emails:

To get test results with RESI API Releases - Get Task Log:

```<code>GET https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/releases/{releaseId}/environments/{environmentId}/deployPhases/{releaseDeployPhaseId}/tasks/{taskId}/logs?api-version=5.0-preview.2
</code>```

Then use powershell scripts to read the details of the test result file (.trx) and create a formatted email message to sent to the defined recipients:

You could check this thread Send Test Result Email After Running Automated Tests with Release Management for some details.

Hope this helps.

Body:
Setting up email Notification on Azure DevOps

AFAIK, Azure devops does not support add attachment in email Notification directly.

As workaround, we could use a powershell script to get test results with REST API then send emails:

To get test results with RESI API Releases - Get Task Log:

GET https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/releases/{releaseId}/environments/{environmentId}/deployPhases/{releaseDeployPhaseId}/tasks/{taskId}/logs?api-version=5.0-preview.2

Then use powershell scripts to read the details of the test result file (.trx) and create a formatted email message to sent to the defined recipients:

You could check this thread Send Test Result Email After Running Automated Tests with Release Management for some details.

Hope this helps.


问:
Is there any method for PaymentResponse api to check response of payment?
As we can check the status that either payment api is supported or not. Using window object:

window.PaymentRequest

Is there any way to check after payment what is status of PaymentResponse using only window object?

I don't have access to the code of  payment and I am trying to check status using window object only.

答:
You can get the response back. See this

```<code>// global
const { PaymentRequest } = window;

// Selectors
const buttons = document.querySelectorAll('button');

// config
const paymentMethods = [
  {
    supportedMethods: ['basic-card']
  }
];

const paymentDetails = {
  total: {
    label: 'What you pay',
    amount: {
      currency: 'USD',
      value: 10
    }
  }
};

const paymentRequest = PaymentRequest && new PaymentRequest(
  paymentMethods,
  paymentDetails
);

const addItemToCart = ({target}) => {
  paymentRequest
  .show()
  .then(paymentResponse => {
    return paymentResponse.complete().then(response => {
      console.log(response)
    });
  })
  .catch(reason => console.error(`Error occurred: ${reason}`));
};

buttons.forEach(button => button.addEventListener('click', addItemToCart));
</code>```

Here's a codepen link

https://codepen.io/elmahdim/pen/yodVzw?editors=1111

Body:
You can get the response back. See this

// global
const { PaymentRequest } = window;

// Selectors
const buttons = document.querySelectorAll('button');

// config
const paymentMethods = [
  {
    supportedMethods: ['basic-card']
  }
];

const paymentDetails = {
  total: {
    label: 'What you pay',
    amount: {
      currency: 'USD',
      value: 10
    }
  }
};

const paymentRequest = PaymentRequest && new PaymentRequest(
  paymentMethods,
  paymentDetails
);

const addItemToCart = ({target}) => {
  paymentRequest
  .show()
  .then(paymentResponse => {
    return paymentResponse.complete().then(response => {
      console.log(response)
    });
  })
  .catch(reason => console.error(`Error occurred: ${reason}`));
};

buttons.forEach(button => button.addEventListener('click', addItemToCart));

Here's a codepen link

https://codepen.io/elmahdim/pen/yodVzw?editors=1111


问:
Load a text file with values into a tuple in Python
I have text file file.txt with values like this:

```<code>word1
word2
word3
word4
word5
</code>```

What I want is a tuple like this in Python 3:

```<code>my_tuple = ('word1','word2','word3','word4','word5')
</code>```

Any advice?

答:
```<code>with open('file.txt','r') as f:
     tup = tuple(f.read().split('\n'))

tup
('word1', 'word2', 'word3', 'word4', 'word5')
</code>```

Body:
I have text file file.txt with values like this:

word1
word2
word3
word4
word5

What I want is a tuple like this in Python 3:

my_tuple = ('word1','word2','word3','word4','word5')

Any advice?