问:
arrange number with 5 digits from the biggest to lowest in c only with 'if'
I have a question.
I working in c and I need to take a number from the user with 5 digits and sort it from the biggest number to the lowest  only with 'if'
I tried to do with 5 variables but the code getting huge.
there some easy way to do it only with 'ifs'???

for example, I get the number: 87953
the output should be : 98753.

(in the pic it only one situation).
enter image description here

答:
For the case, that you also need it with some more digits (try 100):</p>

```<code>#include <stdio.h>

#define NRDIGITS 5

int main(void) {
    printf("#include<stdio.h>\n\nint main(int argc, char **argv) {\n\tchar *s = argv[1];\n");
    for (int i = 0; i < NRDIGITS-1; i++)
        for (int j = 0; j < NRDIGITS; j++)
            printf("\tif(s[%d]<s[%d]){s[%d]^=s[%d];s[%d]^=s[%d];s[%d]^=s[%d];}\n",
                                        j, j+1, j, j+1, j+1, j, j, j+1);
    printf("\tputs(s);\n}\n");
}
</code>```

Body:
For the case, that you also need it with some more digits (try 100):

#include <stdio.h>

#define NRDIGITS 5

int main(void) {
    printf("#include<stdio.h>\n\nint main(int argc, char **argv) {\n\tchar *s = argv[1];\n");
    for (int i = 0; i < NRDIGITS-1; i++)
        for (int j = 0; j < NRDIGITS; j++)
            printf("\tif(s[%d]<s[%d]){s[%d]^=s[%d];s[%d]^=s[%d];s[%d]^=s[%d];}\n",
                                        j, j+1, j, j+1, j+1, j, j, j+1);
    printf("\tputs(s);\n}\n");
}


来源: stackexchange

问:
correctly rotate or flip images [invoices,forms] to its correct orientation in python
I am trying to rotate the images which contains invoice and forms into its correct orientation . I am trying to find the angle and then rotating the image .few images are getting rotated correctly only .Below is the code and images which i have tried to rotate in correct orientation the first image is rotating correctly and other is rotating incorrect

```<code>
import numpy as np
import cv2
import math
from scipy import ndimage

img_before = cv2.imread('rotate_me.png')

cv2.imshow("Before", img_before)
key = cv2.waitKey(0)

img_gray = cv2.cvtColor(img_before, cv2.COLOR_BGR2GRAY)
img_edges = cv2.Canny(img_gray, 100, 100, apertureSize=3)
lines = cv2.HoughLinesP(img_edges, 1, math.pi / 180.0, 100, minLineLength=100, maxLineGap=5)

angles = []

for x1, y1, x2, y2 in lines[0]:
    cv2.line(img_before, (x1, y1), (x2, y2), (255, 0, 0), 3)
    angle = math.degrees(math.atan2(y2 - y1, x2 - x1))
    angles.append(angle)

median_angle = np.median(angles)
img_rotated = ndimage.rotate(img_before, median_angle)

print "Angle is {}".format(median_angle)
cv2.imwrite('rotated.jpg', img_rotated)

</code>```

first image-[left side inverted] ---after rotation correctly rotating
second image --right side inverted-- wrong rotation
Both image having -90 degree angle . The final output must be like the image3

https://i.stack.imgur.com/XpFVy.png

https://i.stack.imgur.com/bGI3k.png

https://i.stack.imgur.com/jHNgD.png

答:
Instead of finding the lines, I suggest finding the colored area.

If the area is in the right side of the image, the image is needed to be rotated.

Finding the colored area can be done as follows:

Compute absolute difference between each two color channels, and sum the result.

The result has high values where there is color (not black/white).

Apply threshold - values below the threshold will be zero (considered to be black/white), and above threshold will be 255 (colored pixels).

Find the largest cluster in the threshold image using connectedComponentsWithStats.

If the center of the largest white cluster is in the right side, rotate the image.

Here is a code sample:

```<code>import numpy as np
import cv2

im = cv2.imread("rotate_me1.png", cv2.IMREAD_UNCHANGED);

# Compute difference between each two color channels for finding colored pixels.
cdiff = cv2.absdiff(im[:,:,0], im[:,:,1])//3 + cv2.absdiff(im[:,:,0], im[:,:,2])//3 + cv2.absdiff(im[:,:,1], im[:,:,2])//3;
ret, cmask = cv2.threshold(cdiff, 10, 255, cv2.THRESH_BINARY)

# Find clusters.
# https://answers.opencv.org/question/194566/removing-noise-using-connected-components/
nlabel,labels,stats,centroids = cv2.connectedComponentsWithStats(cmask, connectivity=8)

# Find second largest cluster (the largest is the background?):
stats[np.argmax(stats[:, cv2.CC_STAT_AREA])] = 0
idx_max_size = np.argmax(stats[:, cv2.CC_STAT_AREA])
center = centroids[idx_max_size]

# True if the center of the centroid is at the right side of the image
is_center_at_right_side = center[0] > im.shape[1]//2

if is_center_at_right_side:
    rotated_im = im[::-1, ::-1, :].copy()  # Reverse left/right and up/down
    cv2.imshow('rotated_im', rotated_im)

# Draw green circle at the center (for testing)
cv2.circle(im, (int(center[0]), int(center[1])), 10, (0, 255, 0), thickness=10)

cv2.imshow('cmask', cmask)
cv2.imshow('im', im)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Example for cmask:

Marking center of largest cluster with green circle:

Rotated image:

Update:

Rotate by 90 degree:

```<code># https://stackoverflow.com/questions/2259678/easiest-way-to-rotate-by-90-degrees-an-image-using-opencv
if is_center_at_right_side:
    rotated_im = cv2.rotate(im, cv2.ROTATE_90_COUNTERCLOCKWISE)
else:
    rotated_im = cv2.rotate(im, cv2.ROTATE_90_CLOCKWISE)
</code>```

Result:

ContentLicense: CC BY-SA 4.0

Body:
I am trying to rotate the images which contains invoice and forms into its correct orientation . I am trying to find the angle and then rotating the image .few images are getting rotated correctly only .Below is the code and images which i have tried to rotate in correct orientation the first image is rotating correctly and other is rotating incorrect

import numpy as np
import cv2
import math
from scipy import ndimage

img_before = cv2.imread('rotate_me.png')

cv2.imshow("Before", img_before)
key = cv2.waitKey(0)

img_gray = cv2.cvtColor(img_before, cv2.COLOR_BGR2GRAY)
img_edges = cv2.Canny(img_gray, 100, 100, apertureSize=3)
lines = cv2.HoughLinesP(img_edges, 1, math.pi / 180.0, 100, minLineLength=100, maxLineGap=5)

angles = []

for x1, y1, x2, y2 in lines[0]:
    cv2.line(img_before, (x1, y1), (x2, y2), (255, 0, 0), 3)
    angle = math.degrees(math.atan2(y2 - y1, x2 - x1))
    angles.append(angle)

median_angle = np.median(angles)
img_rotated = ndimage.rotate(img_before, median_angle)

print "Angle is {}".format(median_angle)
cv2.imwrite('rotated.jpg', img_rotated)

first image-[left side inverted] ---after rotation correctly rotating
second image --right side inverted-- wrong rotation
Both image having -90 degree angle . The final output must be like the image3

https://i.stack.imgur.com/XpFVy.png

https://i.stack.imgur.com/bGI3k.png

https://i.stack.imgur.com/jHNgD.png

Body:
Instead of finding the lines, I suggest finding the colored area.

If the area is in the right side of the image, the image is needed to be rotated.

Finding the colored area can be done as follows:

Compute absolute difference between each two color channels, and sum the result.

The result has high values where there is color (not black/white).

Apply threshold - values below the threshold will be zero (considered to be black/white), and above threshold will be 255 (colored pixels).

Find the largest cluster in the threshold image using connectedComponentsWithStats.

If the center of the largest white cluster is in the right side, rotate the image.

Here is a code sample:

import numpy as np
import cv2

im = cv2.imread("rotate_me1.png", cv2.IMREAD_UNCHANGED);

# Compute difference between each two color channels for finding colored pixels.
cdiff = cv2.absdiff(im[:,:,0], im[:,:,1])//3 + cv2.absdiff(im[:,:,0], im[:,:,2])//3 + cv2.absdiff(im[:,:,1], im[:,:,2])//3;
ret, cmask = cv2.threshold(cdiff, 10, 255, cv2.THRESH_BINARY)

# Find clusters.
# https://answers.opencv.org/question/194566/removing-noise-using-connected-components/
nlabel,labels,stats,centroids = cv2.connectedComponentsWithStats(cmask, connectivity=8)

# Find second largest cluster (the largest is the background?):
stats[np.argmax(stats[:, cv2.CC_STAT_AREA])] = 0
idx_max_size = np.argmax(stats[:, cv2.CC_STAT_AREA])
center = centroids[idx_max_size]

# True if the center of the centroid is at the right side of the image
is_center_at_right_side = center[0] > im.shape[1]//2

if is_center_at_right_side:
    rotated_im = im[::-1, ::-1, :].copy()  # Reverse left/right and up/down
    cv2.imshow('rotated_im', rotated_im)

# Draw green circle at the center (for testing)
cv2.circle(im, (int(center[0]), int(center[1])), 10, (0, 255, 0), thickness=10)

cv2.imshow('cmask', cmask)
cv2.imshow('im', im)
cv2.waitKey(0)
cv2.destroyAllWindows()

Example for cmask:

Marking center of largest cluster with green circle:

Rotated image:

Update:

Rotate by 90 degree:

# https://stackoverflow.com/questions/2259678/easiest-way-to-rotate-by-90-degrees-an-image-using-opencv
if is_center_at_right_side:
    rotated_im = cv2.rotate(im, cv2.ROTATE_90_COUNTERCLOCKWISE)
else:
    rotated_im = cv2.rotate(im, cv2.ROTATE_90_CLOCKWISE)

Result:


问:
How can i append a space in each side of a string?
i have a NSString object named as myString.i need to append a space in each side of my string.
can any one tell me the good way to do it?</p>

答:
```<code>myString = [NSString stringWithFormat:@" %@ ", myString];
</code>```

ContentLicense: CC BY-SA 3.0


问:
Function returning a value from a MySQL database in Twisted
I have a MySQL database that contains several tables that have a structure like this:

CREATE TABLE IF NOT EXISTS `table1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `key1` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE (`key1`)
);

```

<p>In my Python program that uses the Twisted framework, I need to perform a series
of mostly identical operations with each one of these tables:</p>

<ol>
<li>Check if a given value is present in the <code>key</code> column of the table.</li>
<li>If it is, return its corresponding <code>id</code>.</li>
<li>If it is not, insert that value into the table and return its corresponding <code>id</code>.</li>
</ol>

<p>Since the operations are essentially identical, it would make sense for this
action to be performed by a function that takes the table and the key names,
as well as the value as arguments and returns the id.</p>

<p>How can I do this? I can't do</p>

<pre class="lang-py prettyprint-override"><code>import MySQLdb

from twisted.python import log
from twisted.enterprise.adbapi import ConnectionPool
from twisted.internet.defer import inlineCallbacks

class ReconnectingConnectionPool(ConnectionPool):
    def _runInteraction(self, interaction, *args, **kw):
        try:
            return ConnectionPool._runInteraction(
                self, interaction, *args, **kw)
        except MySQLdb.OperationalError as e:   # pylint: disable=no-member
            if e[0] not in (2003, 2006, 2013):
                raise e
            conn = self.connections.get(self.threadID())
            self.disconnect(conn)
            # Try the interaction again
            return ConnectionPool._runInteraction(
                self, interaction, *args, **kw)

dbh = ReconnectingConnectionPool(
    'MySQLdb',
    db='database',
    user='user',
    passwd='password'
)

@inlineCallbacks
def get_id(table, column, entry):
    try:
        r = yield dbh.runQuery("SELECT `id` FROM `{}` WHERE `{}` = '{}'".format(table, column, entry))
        if r:
            id = r[0][0]
        else:
            yield dbh.runQuery("INSERT INTO `{}` (`{}`) VALUES ('{}')".format(table, column, entry))
            r = yield dbh.runQuery('SELECT LAST_INSERT_ID()')
            id = int(r[0][0])
    except Exception as e:
        log.msg(e)
        id = 0
    return id
</code>```

because the function get_id is a generator and those can't return values directly.

Should I use defer.returnValue(id) instead of return id? Or should I use dbh.runQuery('query').addCallback(get_result)
where get_result is a function like this

def get_result(value):
    return value
```

Or should I do something else?

答:
the get_id function itself will returns a deferred since you use inlineCallbacks to wrap it.

then you call your function with:

get_id().addCallback(your_callback_to_retrive_the_id)

in your get_id function if you are using python3 you can use return  or defer.returnValue statement to return the result.

In python2 you can only use defer.returnValue

```<code>from __future__ import print_function

from twisted.internet import reactor
from twisted.internet.defer import Deferred, returnValue, inlineCallbacks

def runQuery(query):
    # suppose this will fetch the result from database
    d = Deferred()

    # simulate the delay waiting for the database to give the results
    # using reactor.callLater
    reactor.callLater(0.3, d.callback, 1); # 1 here is the (result)
    return d

@inlineCallbacks
def get_id(table, column, entry):
    r = yield runQuery("foobar")
    # r is the result from the database
    #if python3
    return r # or returnValue(r)

    # if python2
    # returnValue(r)

# every time you call a function that is wrapped with inlineCallbacks
# the return value of that function is Deferred

d = get_id('messages', 'message', 'Foo')
d.addCallback(lambda r: print("Result: %r" % (r, )))

reactor.run()
</code>```

Body:
I have a MySQL database that contains several tables that have a structure like this:

CREATE TABLE IF NOT EXISTS `table1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `key1` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE (`key1`)
);

In my Python program that uses the Twisted framework, I need to perform a series
of mostly identical operations with each one of these tables:

Check if a given value is present in the key column of the table.

If it is, return its corresponding id.

If it is not, insert that value into the table and return its corresponding id.

Since the operations are essentially identical, it would make sense for this
action to be performed by a function that takes the table and the key names,
as well as the value as arguments and returns the id.

How can I do this? I can't do

import MySQLdb

from twisted.python import log
from twisted.enterprise.adbapi import ConnectionPool
from twisted.internet.defer import inlineCallbacks

class ReconnectingConnectionPool(ConnectionPool):
    def _runInteraction(self, interaction, *args, **kw):
        try:
            return ConnectionPool._runInteraction(
                self, interaction, *args, **kw)
        except MySQLdb.OperationalError as e:   # pylint: disable=no-member
            if e[0] not in (2003, 2006, 2013):
                raise e
            conn = self.connections.get(self.threadID())
            self.disconnect(conn)
            # Try the interaction again
            return ConnectionPool._runInteraction(
                self, interaction, *args, **kw)

dbh = ReconnectingConnectionPool(
    'MySQLdb',
    db='database',
    user='user',
    passwd='password'
)

@inlineCallbacks
def get_id(table, column, entry):
    try:
        r = yield dbh.runQuery("SELECT `id` FROM `{}` WHERE `{}` = '{}'".format(table, column, entry))
        if r:
            id = r[0][0]
        else:
            yield dbh.runQuery("INSERT INTO `{}` (`{}`) VALUES ('{}')".format(table, column, entry))
            r = yield dbh.runQuery('SELECT LAST_INSERT_ID()')
            id = int(r[0][0])
    except Exception as e:
        log.msg(e)
        id = 0
    return id

because the function get_id is a generator and those can't return values directly.

Should I use defer.returnValue(id) instead of return id? Or should I use dbh.runQuery('query').addCallback(get_result)
where get_result is a function like this

def get_result(value):
    return value

Or should I do something else?

Body:
the get_id function itself will returns a deferred since you use inlineCallbacks to wrap it.

then you call your function with:

get_id().addCallback(your_callback_to_retrive_the_id)

in your get_id function if you are using python3 you can use return  or defer.returnValue statement to return the result.

In python2 you can only use defer.returnValue

from __future__ import print_function

from twisted.internet import reactor
from twisted.internet.defer import Deferred, returnValue, inlineCallbacks

def runQuery(query):
    # suppose this will fetch the result from database
    d = Deferred()

    # simulate the delay waiting for the database to give the results
    # using reactor.callLater
    reactor.callLater(0.3, d.callback, 1); # 1 here is the (result)
    return d

@inlineCallbacks
def get_id(table, column, entry):
    r = yield runQuery("foobar")
    # r is the result from the database
    #if python3
    return r # or returnValue(r)

    # if python2
    # returnValue(r)

# every time you call a function that is wrapped with inlineCallbacks
# the return value of that function is Deferred

d = get_id('messages', 'message', 'Foo')
d.addCallback(lambda r: print("Result: %r" % (r, )))

reactor.run()


问:
Flag patients lost to follow-up after their first event
I’m trying to find patients who lost to follow-up (either permanently or temporarily) after their first event. So, we have an event date (edate) and total days of being registered for each year (regdays_09 to regdays_12). I want to flag patients who registered less than 365 days per year or have missing registered year. I much appreciate any help with this. </p>

```<code>data Want;
informat edate date7.;
format edate date7.;
input ID edate regdays_09 regdays_10 regdays_11 regdays_12 flag
CARDS;
100 06jan09 365  365  365   365  0
101 10APR09 365  365   .      .  1
102 23Mar09 180   .    .      .  1
103 03Sep09 365   .   365   365  1
104 20Aug09 300   .     .   365  1
run;
</code>```

答:
If I understand you correctly:</p>

```<code>data have;
informat edate date7.;
format edate date7.;
input ID edate regdays_09 regdays_10 regdays_11 regdays_12;
CARDS;
100 06jan09 365  365  365   365
101 10APR09 365  365   .      .
102 23Mar09 180   .    .      .
103 03Sep09 365   .   365   365
104 20Aug09 300   .     .   365
run;

data want;
   set have;
   flag = (sum(of regdays:) ne 4*365);
run;
</code>```

Body:
I’m trying to find patients who lost to follow-up (either permanently or temporarily) after their first event. So, we have an event date (edate) and total days of being registered for each year (regdays_09 to regdays_12). I want to flag patients who registered less than 365 days per year or have missing registered year. I much appreciate any help with this.

data Want;
informat edate date7.;
format edate date7.;
input ID edate regdays_09 regdays_10 regdays_11 regdays_12 flag
CARDS;
100 06jan09 365  365  365   365  0
101 10APR09 365  365   .      .  1
102 23Mar09 180   .    .      .  1
103 03Sep09 365   .   365   365  1
104 20Aug09 300   .     .   365  1
run;

Body:
If I understand you correctly:

data have;
informat edate date7.;
format edate date7.;
input ID edate regdays_09 regdays_10 regdays_11 regdays_12;
CARDS;
100 06jan09 365  365  365   365
101 10APR09 365  365   .      .
102 23Mar09 180   .    .      .
103 03Sep09 365   .   365   365
104 20Aug09 300   .     .   365
run;

data want;
   set have;
   flag = (sum(of regdays:) ne 4*365);
run;


问:
Linux : Ethtool Command
I am trying to get interface speed by using command ethtool_cmd_speed(&cmd);
But when i try to compile it , it is throwing error like

undefined reference to `ethtool_cmd_speed'. I want to know is there any other command which can be used to get interface speed ?

And it is compiling for newer version of linux, but when i try to compile it in older version, it is giving error. so can anyone tell me how can i get speed of interface ?

答: An undefined reference means you're not linking with a required library.  However, the function in question is defined as static __inline__, as already noted, so there is no symbol to link against.  That means you've included the wrong header or perhaps declared the function yourself.  Just include linux/ethtool.h.

Title: Linux : Ethtool Command


问:
How to add slide up animation for an image?
I am building a Wordpress Theme and am using Envira to have a responsive Gallery. I want to add some CSS and javascript/jquery to add an animation to my three pictures in that gallery. I want them to appear and slide up from the bottom when scrolling to the section of that page. Here's an example of what I am looking for:

https://www.beau-rivage.ch

Basically, when you scroll down, you see those three pictures/slides coming up. I tried to google this but couldn't find any code that worked for me. So currently I do not have any code to share for this animation and the Envira Gallery pictures are just added via a shortcode. Can anyone help me and point me in the right direction?

Would much appreciate your support!

答:
You can use animate.css (https://daneden.github.io/animate.css/) and wow.js combination if you don't want to write code manually.
Check https://wowjs.uk/ examples.


问:
How to insert object array into MongoDb collection
I'm implementing user recovery system using NodeJS and mongoose. I need insert deleted user complains into deleted users collection. How to do that? when i delete user from collection that particular data should insert another collection name deleted users. It simmiler to user recovery system.
My Module deletedUser.js

const mongoose = require('mongoose')

/**
 * Data model for deletedUser.
 */

const Schema = mongoose.Schema
const deletedUserSchema = new Schema({
    _id: {
        type: mongoose.Schema.Types.ObjectId,
        createIndex: true,
        required: true,
        auto: true
    },
    email: {
        type: String,
        required: true,
        unique: true,
        match: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
    },
    password: String,
    username: String,
    firstname: String,
    lastname: String,
    telephone: String,

    //address
    line1: String,
    line2: String,
    line3: String,

    nic: String,

    broadcasts: [],
    selling: [],
    complains: [],
    bookmarks: [],
    sellerReply: [],
    finalized: [],

    overallrate: Number,
    ratings: [],

    profileImage: String,
    replying:[],

    purchaseHistory: [],
    salesHistory: [],
    latestLog: Date,

    longitude: Number,
    latitude: Number,
    // expire_at: {type: Date, default: Date.now, expires: 3600*24*100}

})
module.exports = mongoose.model('deletedUser', deletedUserSchema, 'deletedUser')```
</div>
</div>
</p>

<p>And this is my attempts so far</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// save deleted user data
router.post('/delete/:Id', async (req, res) => {
    const selectedUser = await User.findById(req.params.Id);
    // const deleteduser = new deletedUser({})
    // res.json(selectedUser._id);
    let testdata = [];
    // selectedUser.complains=this.testdata;
    console.log("When deleted"+selectedUser.complains)
    const deleteduser = new deletedUser({
        _id: selectedUser._id,
        email: selectedUser.email,
        password: selectedUser.password,
        username: selectedUser.username,
        firstname: selectedUser.firstname,
        lastname: selectedUser.lastname,
        telephone: selectedUser.telephone,
        line1: selectedUser.line1,
        line2: selectedUser.line2,
        line3: selectedUser.line3,
        nic: selectedUser.nic,
        broadcasts: selectedUser.broadcasts,
        selling: selectedUser.selling,
        complains: testdata.push(selectedUser.complains),
        bookmarks: selectedUser.bookmarks,
        sellerReply: selectedUser.sellerReply,
        finalized: selectedUser.finalized,
        overallrate: selectedUser.overallrate,
        ratings: selectedUser.ratings,
        profileImage: selectedUser.profileImage,
        replying: selectedUser.replying,
        purchaseHistory: selectedUser.purchaseHistory,
        salesHistory: selectedUser.salesHistory,
        latestLog: selectedUser.latestLog,
        longitude: selectedUser.longitude,
        latitude: selectedUser.latitude

    });
    deleteduser.save().then(data => {
        res.json(data);
    }).catch(err => {
        res.json({ message: err })
    });

});</code>```

答:
The current approach you have seems pretty okay to me, however, you can reduce the code involved with document.toObject method:

```<code>router.post('/delete/:Id', async (req, res) => {
  const selectedUser = await User.findById(req.params.Id);

  console.log("When deleted"+selectedUser.complains)

  // use toObject to convert the user model into a normal javascript object
  const deleteduser = new deletedUser(selectedUser.toObject());
  deleteduser.save().then(data => {
      res.json(data);
  }).catch(err => {
      res.json({ message: err })
  });

});
</code>```

Body:
I'm implementing user recovery system using NodeJS and mongoose. I need insert deleted user complains into deleted users collection. How to do that? when i delete user from collection that particular data should insert another collection name deleted users. It simmiler to user recovery system.
My Module deletedUser.js

const mongoose = require('mongoose')

/**
 * Data model for deletedUser.
 */

const Schema = mongoose.Schema
const deletedUserSchema = new Schema({
    _id: {
        type: mongoose.Schema.Types.ObjectId,
        createIndex: true,
        required: true,
        auto: true
    },
    email: {
        type: String,
        required: true,
        unique: true,
        match: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
    },
    password: String,
    username: String,
    firstname: String,
    lastname: String,
    telephone: String,

    //address
    line1: String,
    line2: String,
    line3: String,

    nic: String,

    broadcasts: [],
    selling: [],
    complains: [],
    bookmarks: [],
    sellerReply: [],
    finalized: [],

    overallrate: Number,
    ratings: [],

    profileImage: String,
    replying:[],

    purchaseHistory: [],
    salesHistory: [],
    latestLog: Date,

    longitude: Number,
    latitude: Number,
    // expire_at: {type: Date, default: Date.now, expires: 3600*24*100}

})
module.exports = mongoose.model('deletedUser', deletedUserSchema, 'deletedUser')

And this is my attempts so far

// save deleted user data
router.post('/delete/:Id', async (req, res) => {
    const selectedUser = await User.findById(req.params.Id);
    // const deleteduser = new deletedUser({})
    // res.json(selectedUser._id);
    let testdata = [];
    // selectedUser.complains=this.testdata;
    console.log("When deleted"+selectedUser.complains)
    const deleteduser = new deletedUser({
        _id: selectedUser._id,
        email: selectedUser.email,
        password: selectedUser.password,
        username: selectedUser.username,
        firstname: selectedUser.firstname,
        lastname: selectedUser.lastname,
        telephone: selectedUser.telephone,
        line1: selectedUser.line1,
        line2: selectedUser.line2,
        line3: selectedUser.line3,
        nic: selectedUser.nic,
        broadcasts: selectedUser.broadcasts,
        selling: selectedUser.selling,
        complains: testdata.push(selectedUser.complains),
        bookmarks: selectedUser.bookmarks,
        sellerReply: selectedUser.sellerReply,
        finalized: selectedUser.finalized,
        overallrate: selectedUser.overallrate,
        ratings: selectedUser.ratings,
        profileImage: selectedUser.profileImage,
        replying: selectedUser.replying,
        purchaseHistory: selectedUser.purchaseHistory,
        salesHistory: selectedUser.salesHistory,
        latestLog: selectedUser.latestLog,
        longitude: selectedUser.longitude,
        latitude: selectedUser.latitude

    });
    deleteduser.save().then(data => {
        res.json(data);
    }).catch(err => {
        res.json({ message: err })
    });

});

Body:
The current approach you have seems pretty okay to me, however, you can reduce the code involved with document.toObject method:

router.post('/delete/:Id', async (req, res) => {
  const selectedUser = await User.findById(req.params.Id);

  console.log("When deleted"+selectedUser.complains)

  // use toObject to convert the user model into a normal javascript object
  const deleteduser = new deletedUser(selectedUser.toObject());
  deleteduser.save().then(data => {
      res.json(data);
  }).catch(err => {
      res.json({ message: err })
  });

});


问:
Xcode 4 Supported Device Orientations
I recently upgraded to Xcode 4. Previously in Xcode 3 to set the allowed device orientations you had to edit the shouldAutorotateToInterfaceOrientation: method in the application delegate. But now in Xcode 4 I see there is an option in Targets -> Summary where you can select different orientations.

Which alternative will rule over the other?

Cheers,

Peter

答:
Your memory is slightly faulty; shouldAutorotateToInterfaceOrientation: is in custom subclasses of UIViewController. So it allows each view controller to say which orientations it works in individually. So you can have an app that overwhelmingly works in portrait or landscape, but has a view view controllers that only work in portrait, for example — which is useful if you're incorporating off-the-shelf code.

The supported device orientations in targets -> summary go into your Info.plist, to provide metadata to the OS without it having to launch your app.

Ideally the two should agree, and I don't think either one overrides the other. The summary information should summarise all of your various view controllers, but I'd be surprised if you got anything other than the odd weird launch behaviour if you fill it in incorrectly.

Title: Xcode 4 Supported Device Orientations


问:
Equality of F# record Types when consumed from C#
I have the following record type in an F# lib:

```<code>type Rating = {
        Id : string
        AverageRating : decimal
        ValueRange : int
        Label : string }
</code>```

And as expected, the following test passes in an F# test lib:

```<code>[Fact]
let ``ShouldConsiderTwoInstancesOfAClassToBeTheSame`` () =

    let a = {Rating.Id = "id"
             AverageRating = 4.3m
             ValueRange = 10
             Label = "label"}

    let b = {Rating.Id = "id"
             AverageRating = 4.3m
             ValueRange = 10
             Label = "label"}

    a = b |> should equal true
    a.Equals b |> should equal true
    a <> b |> should equal false
    System.Object.ReferenceEquals(a, b) |> should equal false
</code>```

However, the following test in C# fails...both of the first 2 assertions fail, though the third assertion passes fine:

```<code>    [Test]
    public void ShouldConsiderTwoInstancesOfAClassToBeTheSame()
    {
        var a = new Rating("id", 4.3m, 10, "label");
        var b = new Rating("id", 4.3m, 10, "label");

        Assert.True(a == b);
        Assert.False(a != b);
        Assert.True(a.Equals(b));
        Assert.False(ReferenceEquals(a, b));
    }
</code>```

Is there a way to get the structural equality that record types provide out of the box when consuming from C# using just the operators, or do you need to call Equals() ?

答:
In idiomatic C#, reference types are not expected to test positive for structural equality. IEquatable as a contract makes more semantic sense.

Equality, by default, means equality of reference. F# is quite different in this regard - it uses structural equality for comparisons.
If you look at what F# does for a = b, it calls

```<code>a.Equals(b, GenericEqualityComparer);
</code>```

However, for a type with an == operator implemented,  the C# compiler knows to pick the operator's method.

```<code>push.0 //ldloc, ldfld, etc.
push.1
call bool Rating::op_Equality(valuetype Rating, valuetype Rating)
</code>```

What generally happens for a == b, is:

```<code>push.0
push.1
ceq
</code>```

ceq is much faster than any of the method call alternatives, and is the default equality comparison, which gives you equality of reference.

Other core .NET types may not explicitly implement == and !=, but the JIT has specific implementation details to perform equality comparison for those intrinsic types (signed, fp, etc.), so they still equate correctly.

If an == comparison is semantically important to you, you can implement the operators yourself:

```<code>type Rating = {
    Id : string
    AverageRating : decimal
    ValueRange : int
    Label : string
} with
    static member op_Equality (a: Rating, b: Rating) =
      a.Equals b
    static member op_Inequality (a: Rating, b: Rating) =
          not (a.Equals b)
</code>```

And your tests should work again.

Body:
I have the following record type in an F# lib:

type Rating = {
        Id : string
        AverageRating : decimal
        ValueRange : int
        Label : string }

And as expected, the following test passes in an F# test lib:

[Fact]
let ``ShouldConsiderTwoInstancesOfAClassToBeTheSame`` () =

    let a = {Rating.Id = "id"
             AverageRating = 4.3m
             ValueRange = 10
             Label = "label"}

    let b = {Rating.Id = "id"
             AverageRating = 4.3m
             ValueRange = 10
             Label = "label"}

    a = b |> should equal true
    a.Equals b |> should equal true
    a <> b |> should equal false
    System.Object.ReferenceEquals(a, b) |> should equal false

However, the following test in C# fails...both of the first 2 assertions fail, though the third assertion passes fine:

    [Test]
    public void ShouldConsiderTwoInstancesOfAClassToBeTheSame()
    {
        var a = new Rating("id", 4.3m, 10, "label");
        var b = new Rating("id", 4.3m, 10, "label");

        Assert.True(a == b);
        Assert.False(a != b);
        Assert.True(a.Equals(b));
        Assert.False(ReferenceEquals(a, b));
    }

Is there a way to get the structural equality that record types provide out of the box when consuming from C# using just the operators, or do you need to call Equals() ?

Body:
In idiomatic C#, reference types are not expected to test positive for structural equality. IEquatable as a contract makes more semantic sense.

Equality, by default, means equality of reference. F# is quite different in this regard - it uses structural equality for comparisons.
If you look at what F# does for a = b, it calls

a.Equals(b, GenericEqualityComparer);

However, for a type with an == operator implemented,  the C# compiler knows to pick the operator's method.

push.0 //ldloc, ldfld, etc.
push.1
call bool Rating::op_Equality(valuetype Rating, valuetype Rating)

What generally happens for a == b, is:

push.0
push.1
ceq

ceq is much faster than any of the method call alternatives, and is the default equality comparison, which gives you equality of reference.

Other core .NET types may not explicitly implement == and !=, but the JIT has specific implementation details to perform equality comparison for those intrinsic types (signed, fp, etc.), so they still equate correctly.

If an == comparison is semantically important to you, you can implement the operators yourself:

type Rating = {
    Id : string
    AverageRating : decimal
    ValueRange : int
    Label : string
} with
    static member op_Equality (a: Rating, b: Rating) =
      a.Equals b
    static member op_Inequality (a: Rating, b: Rating) =
          not (a.Equals b)

And your tests should work again.


问:
Using split on an input string
I'm a beginner to Python 3 and when I try this code it works:

```<code>a = input('Enter three digits separated by space:')
b = a.split()
mylist = [int(i) for i in b]
print(mylist)
</code>```

Output:

Enter three digits separated by space:2 3 4
[2, 3, 4]
```

<p>However I get errors when I try this:</p>

```a = input('Enter three digits separated by space:')
b = a.split()
mylist = [int(i**2) for i in b]
print(mylist)
```

<blockquote>
  <p>Error: TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'</p>
</blockquote>

<p>In fact this works as well:</p>

```list1 = [2,3,4]
mylist = [int(i**2) for i in list1]
print(mylist)
```

What am I doing wrong?

答:
Error in your code: you are trying to raise power before converting it to int

```<code>int(i**2)
#should be
int(i)**2
</code>```

Another approach, using map function.

Syntax: map(func, iterable)

In python, String is iterable which means you can iterate over it. For example:

```<code>for i in "hello":
   print(i)

#output will be:
    h
    e
    l
    l
    o
</code>```

Another simple concept before moving to map function: split() function will return the list.

```<code>print(type("hello".split()))
#output will be
<class 'list'>
</code>```

Lets use map function to answer your question:

```<code>a = map(int, input('Enter three digits separated by space:').split())

mylist = [i**2 for i in a]
print(mylist)
</code>```

Explanation:

The input() function will ask user to enter three numbers separated by space and that
will be a string, now you can use split function over the string returned by input().

Here, split function will return a list.

Now, map function comes into the picture, it will take each element
from the list returned at step 2 and map it to the function,     in
this case, it will map each element of the list to int.

Variable a is map object, and map object is iterable, so you can
apply for loop or list comprehension(you used list comprehension) to get desired output

Title: Using split on an input string

Body:
I'm a beginner to Python 3 and when I try this code it works:

a = input('Enter three digits separated by space:')
b = a.split()
mylist = [int(i) for i in b]
print(mylist)

Output:

Enter three digits separated by space:2 3 4
[2, 3, 4]

However I get errors when I try this:

a = input('Enter three digits separated by space:')
b = a.split()
mylist = [int(i**2) for i in b]
print(mylist)

Error: TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

In fact this works as well:

list1 = [2,3,4]
mylist = [int(i**2) for i in list1]
print(mylist)

What am I doing wrong?

Body:
Error in your code: you are trying to raise power before converting it to int

int(i**2)
#should be
int(i)**2

Another approach, using map function.

Syntax: map(func, iterable)

In python, String is iterable which means you can iterate over it. For example:

for i in "hello":
   print(i)

#output will be:
    h
    e
    l
    l
    o

Another simple concept before moving to map function: split() function will return the list.

print(type("hello".split()))
#output will be
<class 'list'>

Lets use map function to answer your question:

a = map(int, input('Enter three digits separated by space:').split())

mylist = [i**2 for i in a]
print(mylist)

Explanation:

The input() function will ask user to enter three numbers separated by space and that
will be a string, now you can use split function over the string returned by input().

Here, split function will return a list.

Now, map function comes into the picture, it will take each element
from the list returned at step 2 and map it to the function,     in
this case, it will map each element of the list to int.

Variable a is map object, and map object is iterable, so you can
apply for loop or list comprehension(you used list comprehension) to get desired output


问:
spyder alternative for f1 matlab help feature
In matlab whenever the cursor is on a function, ex: for or plot etc..., and you hit f1, a small window opens with the basic syntax and usage. Is something like that there for python spyder.

ctrl+i is not useful for general commands like for or int.

I searched a lot online... And I am new to Python and am going through a huge piece of code and would appreciate finding a shortcut for the same.

答:
Have a look at Kite https://kite.com/. It's a plugin for Spyder and other editors.
You can put Kite's window next to Spyder's window and it gives you the Documentation relative to what your cursor in Spyder is on. It's a bit like Ctrl+i but works for all commands.
I am also transitioning from Matlab and I find it useful. </p>


问:
Transform multi-row string to csv in Python
What is the best way to take this string:

```<code>1
2
3
4
a
b
c
d
1
2
3
4
a
b
c
d
1
2
3
4
a
b
c
d
</code>```

and transform to a CSV containing 6 columns?

Desired output

Is a CSV which will be imported into Pandas:

```<code>1,a,1,a,1,a
2,b,2,b,2,b
</code>```

etc..

Updated desired output as per comments to 6 rows.

Updated.  I can get the first row like this if I assign the string to l variable:

```<code>l.split()[0::4]

['1', 'a', '1', 'a', '1', 'a']
</code>```

答:
```<code>with open('data.txt', 'r') as f:
    data = f.read().split("\n")
    for i in range(4):
        d = list()
        for j in range(i, len(data), 4):
            d.append(data[j])
        with open('data.csv', 'a') as csv:
            csv.write(','.join(d)+"\n")
</code>```

Body:
What is the best way to take this string:

1
2
3
4
a
b
c
d
1
2
3
4
a
b
c
d
1
2
3
4
a
b
c
d

and transform to a CSV containing 6 columns?

Desired output

Is a CSV which will be imported into Pandas:

1,a,1,a,1,a
2,b,2,b,2,b

etc..

Updated desired output as per comments to 6 rows.

Updated.  I can get the first row like this if I assign the string to l variable:

l.split()[0::4]

['1', 'a', '1', 'a', '1', 'a']


问:
Android multiple firebase projects using firebase-crashlytics
Is it possible on android to programmatically initialize firebase-crashlytics SDK so it would not use the data in google-services.json ?

I am asking this because we use two firebase projects and currently google-services.json is of the project we use for Push notifications and AdMob integration, and I cannot replace it with google-services.json of the second project we have set up for crashlytics.

I have already tried using FirebaseOptions from my Application onCreate as follows:

```<code> FirebaseOptions options = new FirebaseOptions.Builder()
                .setApplicationId("firebase_crashlytics_application_id")
                .setApiKey("firebase_crashlytics_api_key")
                .setProjectId("firebase_crashlytics_project_id")
                .build();
 FirebaseApp.initializeApp(this, options, "crashlytics");
</code>```

So far no luck - firebase crashlytics is not properly initialized.

答: Great question. You can set this up by following these steps.</p>

Body:
Is it possible on android to programmatically initialize firebase-crashlytics SDK so it would not use the data in google-services.json ?

I am asking this because we use two firebase projects and currently google-services.json is of the project we use for Push notifications and AdMob integration, and I cannot replace it with google-services.json of the second project we have set up for crashlytics.

I have already tried using FirebaseOptions from my Application onCreate as follows:

 FirebaseOptions options = new FirebaseOptions.Builder()
                .setApplicationId("firebase_crashlytics_application_id")
                .setApiKey("firebase_crashlytics_api_key")
                .setProjectId("firebase_crashlytics_project_id")
                .build();
 FirebaseApp.initializeApp(this, options, "crashlytics");

So far no luck - firebase crashlytics is not properly initialized.


问:
What is the right way to get the list of DNS servers responsible for certain host?
I use following steps:

Query A records for host, some servers return NS records in authority section, so I extract them from that section, if any.

Query NS records, extract them from answer section.

The problem is with "subdomains" (CNAME), for example:

> dig www.microsoft.com A

```<code>;; ANSWER SECTION:
www.microsoft.com.      696     IN      CNAME   toggle.www.ms.akadns.net.
toggle.www.ms.akadns.net. 119   IN      CNAME   g.www.ms.akadns.net.
g.www.ms.akadns.net.    263     IN      CNAME   lb1.www.ms.akadns.net.
lb1.www.ms.akadns.net.  31      IN      A       65.55.12.249
</code>```

> dig www.microsoft.com NS

```<code>;; ANSWER SECTION:
www.microsoft.com.      619     IN      CNAME   toggle.www.ms.akadns.net.
toggle.www.ms.akadns.net. 42    IN      CNAME   g.www.ms.akadns.net.
g.www.ms.akadns.net.    186     IN      CNAME   lb1.www.ms.akadns.net.

;; AUTHORITY SECTION:
akadns.net.             174     IN      SOA     internal.akadns.net. hostmaster.akamai.com. 1304057105 90000 90000 90000 180
</code>```

> dig lb1.www.ms.akadns.net A

```<code>;; ANSWER SECTION:
lb1.www.ms.akadns.net.  79      IN      A       65.55.12.249
</code>```

> dig lb1.www.ms.akadns.net NS

```<code>;; AUTHORITY SECTION:
akadns.net.             176     IN      SOA     internal.akadns.net. hostmaster.akamai.com. 1304057402 90000 90000 90000 180
</code>```

As you can see, there are no NS records returned. How to overcome this problem?

答:
Your algorithm is wrong.  Here's the right one.

For each successively shorter superdomain S of the target domain name T, starting with T itself:

Perform an NS lookup on S.  If the answer is not a non-empty resource record set, go to step 3.  Otherwise you have a set of intermediate domain names D[].

Perform A and AAAA lookups on each name in D[].  This will give you a set of IP addresses.  You have your answer.  END.

Optionally perform a SOA lookup on S.  If the answer is a non-empty resource record set, you are about to cross an administrative boundary having found no non-empty NS resource record set thus far.  You may choose, according to exactly what you are trying to find out, to ABEND.

Remember that you have to make queries to your own resolving proxy DNS server, not to the external content DNS servers, so that you get a complete answer rather than a partial one.  Also remember that you have to follow CNAME chains when inspecting responses.  The response to your dig www.microsoft.com. NS query above, for example, is a CNAME chain leading to an empty NS resource record set for lb1.www.ms.akadns.net..

Body:
I use following steps:

Query A records for host, some servers return NS records in authority section, so I extract them from that section, if any.

Query NS records, extract them from answer section.

The problem is with "subdomains" (CNAME), for example:

> dig www.microsoft.com A

;; ANSWER SECTION:
www.microsoft.com.      696     IN      CNAME   toggle.www.ms.akadns.net.
toggle.www.ms.akadns.net. 119   IN      CNAME   g.www.ms.akadns.net.
g.www.ms.akadns.net.    263     IN      CNAME   lb1.www.ms.akadns.net.
lb1.www.ms.akadns.net.  31      IN      A       65.55.12.249

> dig www.microsoft.com NS

;; ANSWER SECTION:
www.microsoft.com.      619     IN      CNAME   toggle.www.ms.akadns.net.
toggle.www.ms.akadns.net. 42    IN      CNAME   g.www.ms.akadns.net.
g.www.ms.akadns.net.    186     IN      CNAME   lb1.www.ms.akadns.net.

;; AUTHORITY SECTION:
akadns.net.             174     IN      SOA     internal.akadns.net. hostmaster.akamai.com. 1304057105 90000 90000 90000 180

> dig lb1.www.ms.akadns.net A

;; ANSWER SECTION:
lb1.www.ms.akadns.net.  79      IN      A       65.55.12.249

> dig lb1.www.ms.akadns.net NS

;; AUTHORITY SECTION:
akadns.net.             176     IN      SOA     internal.akadns.net. hostmaster.akamai.com. 1304057402 90000 90000 90000 180

As you can see, there are no NS records returned. How to overcome this problem?


问:
Can I write my simple Python code in a better way?
I should rewrite my own function in a better way. The function takes an iterator and a sequence of boolean functions and returns an iterator of the elements in the input iterator which returns a truthy value.

```<code>def allTrue (iterator, funz):
for i in iterator:
    count = 0
    for f in funz:
        if f(i):
            count = count+1
        if count==len(funz):
            yield i
</code>```

I tried to write this:

```<code>def allTrue2 (iterator, funz):
    return (filter (f , iterator) for f in funz)
</code>```

But it's wrong. How could I improve the code?

Output:

```<code>print(list(allTrue(range(50),
               (lambda x: x % 3 == 0,
                lambda x: x > 10,
                lambda x: x < 44)
               )))

>>> [12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42]
</code>```

答:
And if you want a one-liner, just for completeness:

```<code>def allTrue (iterator, funz):
    return (i for i in iterator if all(f(i) for f in funz))
</code>```

Note that this returns a generator, so it has the same effect as using yield.

Body:
I should rewrite my own function in a better way. The function takes an iterator and a sequence of boolean functions and returns an iterator of the elements in the input iterator which returns a truthy value.

def allTrue (iterator, funz):
for i in iterator:
    count = 0
    for f in funz:
        if f(i):
            count = count+1
        if count==len(funz):
            yield i

I tried to write this:

def allTrue2 (iterator, funz):
    return (filter (f , iterator) for f in funz)

But it's wrong. How could I improve the code?

Output:

print(list(allTrue(range(50),
               (lambda x: x % 3 == 0,
                lambda x: x > 10,
                lambda x: x < 44)
               )))

>>> [12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42]

Body:
And if you want a one-liner, just for completeness:

def allTrue (iterator, funz):
    return (i for i in iterator if all(f(i) for f in funz))

Note that this returns a generator, so it has the same effect as using yield.


问:
Parse JSON data from file using C#
I'm trying to parse a json file, but it's being kinda hard to do. I'm using Visual Studio 2019.

I need to take some data from the file.

Here's the Json file's data I need to extract:

```<code>{
    "Id": "92cb6271-005e-48e9-a319-a606b8b6e1ef",
    "DefaultPosition": {
        "PositionId": "35ed169a-1208-4d8a-8faa-d2627d5790ed",
        "EntityDetails": {
            "DateCreated": "2019-09-17T15:25:52.4942161-03:00",
            "DateModified": "2019-09-17T15:45:28.896274-03:00",
            "CreatedBy": {
                "Id": "1abb5047-8580-4be1-909d-41138035e4c9",
                "ItemDisplayText": "Laurete Araujo",
                "ItemType": "Users"
            },
            "ModifiedBy": {
                "Id": "1abb5047-8580-4be1-909d-41138035e4c9",
                "ItemDisplayText": "Laurete Araujo",
                "ItemType": "Users"
            },
            "Owner": {
                "Id": "1abb5047-8580-4be1-909d-41138035e4c9",
                "ItemDisplayText": "Laurete Araujo",
                "ItemType": "Users"
            }
        },
        "NameComponents": {
        "FullName": "ABRAHÃO DOS SANTOS",
        "FamilyName": "SANTOS",
        "FirstName": "ABRAHÃO DOS"
        },
        "MaritalStatus": {
        "Id": "97d7a9dd-a7c4-4076-829c-7ec63b0e3fe7",
        "DisplayTitle": "Marital Status",
        "ItemDisplayText": "Married",
        "ItemType": "LookupListEntries"
        }
}
</code>```

This is the C# code I'm trying to use, but it's giving me issues:

```<code>public void JsonParser(string file)
{
    string fullname;
    string gender;
    string nationality;
    string maritalstatus;

    var json = System.IO.File.ReadAllText(file);

    var objects = Newtonsoft.Json.Linq.JArray.Parse(json); // parse as array

    foreach (JObject root in objects)
    {
        foreach (KeyValuePair<String, JToken> app in root)
        {
            var appName = app.Key;
            fullname = (String)app.Value["FullName"];

            if (app.Key == "Gender")
            {
                gender = (String)app.Value["ItemDisplayText"];
                Console.WriteLine(gender);
            }

            Console.WriteLine(fullname);
            Console.WriteLine("\n");
        }
    }
}
</code>```

When I run the code and I try to import the file from where I want to extract the data, this error appears:

Newtonsoft.Json.JsonReaderException: 'Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1.'

Thank you!

答:
Since the file has { } as the root, that means you cannot use JArray because it isn't an array.  It is a single object.  Instead, you should do this:

```<code>        var root = Newtonsoft.Json.Linq.JObject.Parse(json);
        foreach (KeyValuePair<String, JToken> app in root)
        {
            var appName = app.Key;
            fullname = (String)app.Value["FullName"];

            if (app.Key == "Gender")
            {
                gender = (String)app.Value["ItemDisplayText"];
                Console.WriteLine(gender);
            }

            Console.WriteLine(fullname);
            Console.WriteLine("\n");

        }
</code>```

Edit - Better answer

The better answer here is, if this isn't dynamic, declare your c# classes that it will deserialize into and then you can run all this like so:

```<code>public class CreatedBy
{
    public string Id { get; set; }
    public string ItemDisplayText { get; set; }
    public string ItemType { get; set; }
}

public class ModifiedBy
{
    public string Id { get; set; }
    public string ItemDisplayText { get; set; }
    public string ItemType { get; set; }
}

public class Owner
{
    public string Id { get; set; }
    public string ItemDisplayText { get; set; }
    public string ItemType { get; set; }
}

public class EntityDetails
{
    public DateTime DateCreated { get; set; }
    public DateTime DateModified { get; set; }
    public CreatedBy CreatedBy { get; set; }
    public ModifiedBy ModifiedBy { get; set; }
    public Owner Owner { get; set; }
}

public class NameComponents
{
    public string FullName { get; set; }
    public string FamilyName { get; set; }
    public string FirstName { get; set; }
}

public class MaritalStatus
{
    public string Id { get; set; }
    public string DisplayTitle { get; set; }
    public string ItemDisplayText { get; set; }
    public string ItemType { get; set; }
}

public class DefaultPosition
{
    public string PositionId { get; set; }
    public EntityDetails EntityDetails { get; set; }
    public NameComponents NameComponents { get; set; }
    public MaritalStatus MaritalStatus { get; set; }
}

public class RootObject
{
    public string Id { get; set; }
    public DefaultPosition DefaultPosition { get; set; }
}
</code>```

...

```<code>  var root = JsonConvert.DeserializeObject<RootObject>(json);

  var fullname = root.DefaultPosition.NameComponents.FullName;
</code>```

Title: Parse JSON data from file using C#

Body:
I'm trying to parse a json file, but it's being kinda hard to do. I'm using Visual Studio 2019.

I need to take some data from the file.

Here's the Json file's data I need to extract:

{
    "Id": "92cb6271-005e-48e9-a319-a606b8b6e1ef",
    "DefaultPosition": {
        "PositionId": "35ed169a-1208-4d8a-8faa-d2627d5790ed",
        "EntityDetails": {
            "DateCreated": "2019-09-17T15:25:52.4942161-03:00",
            "DateModified": "2019-09-17T15:45:28.896274-03:00",
            "CreatedBy": {
                "Id": "1abb5047-8580-4be1-909d-41138035e4c9",
                "ItemDisplayText": "Laurete Araujo",
                "ItemType": "Users"
            },
            "ModifiedBy": {
                "Id": "1abb5047-8580-4be1-909d-41138035e4c9",
                "ItemDisplayText": "Laurete Araujo",
                "ItemType": "Users"
            },
            "Owner": {
                "Id": "1abb5047-8580-4be1-909d-41138035e4c9",
                "ItemDisplayText": "Laurete Araujo",
                "ItemType": "Users"
            }
        },
        "NameComponents": {
        "FullName": "ABRAHÃO DOS SANTOS",
        "FamilyName": "SANTOS",
        "FirstName": "ABRAHÃO DOS"
        },
        "MaritalStatus": {
        "Id": "97d7a9dd-a7c4-4076-829c-7ec63b0e3fe7",
        "DisplayTitle": "Marital Status",
        "ItemDisplayText": "Married",
        "ItemType": "LookupListEntries"
        }
}

This is the C# code I'm trying to use, but it's giving me issues:

public void JsonParser(string file)
{
    string fullname;
    string gender;
    string nationality;
    string maritalstatus;

    var json = System.IO.File.ReadAllText(file);

    var objects = Newtonsoft.Json.Linq.JArray.Parse(json); // parse as array

    foreach (JObject root in objects)
    {
        foreach (KeyValuePair<String, JToken> app in root)
        {
            var appName = app.Key;
            fullname = (String)app.Value["FullName"];

            if (app.Key == "Gender")
            {
                gender = (String)app.Value["ItemDisplayText"];
                Console.WriteLine(gender);
            }

            Console.WriteLine(fullname);
            Console.WriteLine("\n");
        }
    }
}

When I run the code and I try to import the file from where I want to extract the data, this error appears:

Newtonsoft.Json.JsonReaderException: 'Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1.'

Thank you!

Body:
Since the file has { } as the root, that means you cannot use JArray because it isn't an array.  It is a single object.  Instead, you should do this:

        var root = Newtonsoft.Json.Linq.JObject.Parse(json);
        foreach (KeyValuePair<String, JToken> app in root)
        {
            var appName = app.Key;
            fullname = (String)app.Value["FullName"];

            if (app.Key == "Gender")
            {
                gender = (String)app.Value["ItemDisplayText"];
                Console.WriteLine(gender);
            }

            Console.WriteLine(fullname);
            Console.WriteLine("\n");

        }

Edit - Better answer

The better answer here is, if this isn't dynamic, declare your c# classes that it will deserialize into and then you can run all this like so:

public class CreatedBy
{
    public string Id { get; set; }
    public string ItemDisplayText { get; set; }
    public string ItemType { get; set; }
}

public class ModifiedBy
{
    public string Id { get; set; }
    public string ItemDisplayText { get; set; }
    public string ItemType { get; set; }
}

public class Owner
{
    public string Id { get; set; }
    public string ItemDisplayText { get; set; }
    public string ItemType { get; set; }
}

public class EntityDetails
{
    public DateTime DateCreated { get; set; }
    public DateTime DateModified { get; set; }
    public CreatedBy CreatedBy { get; set; }
    public ModifiedBy ModifiedBy { get; set; }
    public Owner Owner { get; set; }
}

public class NameComponents
{
    public string FullName { get; set; }
    public string FamilyName { get; set; }
    public string FirstName { get; set; }
}

public class MaritalStatus
{
    public string Id { get; set; }
    public string DisplayTitle { get; set; }
    public string ItemDisplayText { get; set; }
    public string ItemType { get; set; }
}

public class DefaultPosition
{
    public string PositionId { get; set; }
    public EntityDetails EntityDetails { get; set; }
    public NameComponents NameComponents { get; set; }
    public MaritalStatus MaritalStatus { get; set; }
}

public class RootObject
{
    public string Id { get; set; }
    public DefaultPosition DefaultPosition { get; set; }
}

...

  var root = JsonConvert.DeserializeObject<RootObject>(json);

  var fullname = root.DefaultPosition.NameComponents.FullName;


问:
Typescript: How to type combined reducers?
I am migrating my small React Native project from pure Javascript to Typescript. While it went well so far, I now have problems with Redux.

The reducer I'm struggling with is radioButtonSelectedReducer. In the application, there are two radio buttons. If the first one is clicked, it gives string "itemOne" and if the second one is clicked, it gives string "itemTwo". Therefore, radioButtonSelected must be of type string, I thought. But it gives the error: radioButtonSelected: string; -->

```<code>"The expected type comes from property 'radioButtonSelected' which is declared here on type 'ReducersMapObject<IApplicationState, AnyAction>'"
</code>```

I am such a Typescript newbie and don't know what to do with this message.

```<code>imports ...

export interface IApplicationState {
  radioButtonSelected: string;
  searchBarInput: string;
  searchBarResult: string;
}

const rootReducer = combineReducers<IApplicationState>({
  radioButtonSelected: radioButtonSelectedReducer,
  searchBarInput: searchBarInputReducer,
  searchBarResult: searchBarResultReducer,
});

export type RootState = ReturnType<typeof rootReducer>;
</code>```

When I leave combineReducers() without <IApplicationState> and call RootState in mapStateToProps(), it gives the error:

```<code>  error TS2339: Property 'itemSelected' does not exist on type 'CombinedState<{ radioButtonSelected: { itemSele
cted: string; }; searchBarInput: { inputValue: any; }; searchBarResult: { returnValue: any; }; }>'.
</code>```

Here is the snippet from the component that implements the radio buttons:

```<code>...

function mapStateToProps(state: RootState) {
  return {
    itemSelected: state.itemSelected,
  };
}
</code>```

答:
You shouldn't have to declare IApplicationState or pass it as a generic to combineReducers().  In fact, that's explicitly the point of type RootState = ReturnType<typeof rootReducer>.  It infers what the combined state type is, so you don't have to declare it or keep updating it.

Please refer to the Redux docs page on "Usage with TypeScript" for more details.

Body:
I am migrating my small React Native project from pure Javascript to Typescript. While it went well so far, I now have problems with Redux.

The reducer I'm struggling with is radioButtonSelectedReducer. In the application, there are two radio buttons. If the first one is clicked, it gives string "itemOne" and if the second one is clicked, it gives string "itemTwo". Therefore, radioButtonSelected must be of type string, I thought. But it gives the error: radioButtonSelected: string; -->

"The expected type comes from property 'radioButtonSelected' which is declared here on type 'ReducersMapObject<IApplicationState, AnyAction>'"

I am such a Typescript newbie and don't know what to do with this message.

imports ...

export interface IApplicationState {
  radioButtonSelected: string;
  searchBarInput: string;
  searchBarResult: string;
}

const rootReducer = combineReducers<IApplicationState>({
  radioButtonSelected: radioButtonSelectedReducer,
  searchBarInput: searchBarInputReducer,
  searchBarResult: searchBarResultReducer,
});

export type RootState = ReturnType<typeof rootReducer>;

When I leave combineReducers() without <IApplicationState> and call RootState in mapStateToProps(), it gives the error:

  error TS2339: Property 'itemSelected' does not exist on type 'CombinedState<{ radioButtonSelected: { itemSele
cted: string; }; searchBarInput: { inputValue: any; }; searchBarResult: { returnValue: any; }; }>'.

Here is the snippet from the component that implements the radio buttons:

...

function mapStateToProps(state: RootState) {
  return {
    itemSelected: state.itemSelected,
  };
}


问:
Change svg color of a specific path
I have an SVG image (World map) in my root folder and I'm adding it to my background of my website using css background-image: url(.....) .
 My issue is my SVG image has about 200 paths (each country in the world). I want to modify just specific colors of specific country. I'm loadin ti to my page doing </p>

```<code><link href="css/signin2.css" rel="stylesheet">
</code>```

<p>and </p>

```<code>body {
  display: flex;
  align-items: center;
  background-image: url("../resources/world-pacific.svg");
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}
</code>```

答:
You cannot change the colors within an SVG if you are importing it as an image or background image. My suggestions are:

Change the colors in an SVG editing program like Adobe Illustrator. (recommended)

Or if you want to be able to dynamically change the specific countries, load it in as inline <svg>. But, you will need to clean up the XML code within the SVG file and provide classes for the specific paths you want to affect. (I would not recommend this route since you have 200 paths)

Title: Change svg color of a specific path

Body:
I have an SVG image (World map) in my root folder and I'm adding it to my background of my website using css background-image: url(.....) .
 My issue is my SVG image has about 200 paths (each country in the world). I want to modify just specific colors of specific country. I'm loadin ti to my page doing

<link href="css/signin2.css" rel="stylesheet">

and

body {
  display: flex;
  align-items: center;
  background-image: url("../resources/world-pacific.svg");
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}


问:
SyntaxError in Platform
I have a SyntaxError in the Platform line but I cant see why.

Is it because the code should be wrapped in a class instead of a function?

```<code>function AccountItem({ title }) {
    account = title.join('\n')

    return (
        {Platform.OS === 'ios' ? (
            <TextInput
                style={styles.title}
                value={account}
                multiline
                editable={false}
                scrollEnabled={false}
            />
        ) : (
            <Text
                selectable
                style={styles.title}
                >
                {account}
            </Text>
            )
        }
    )
}
</code>```

答:
I think curly braces can only be used in the context of jsx. In other words, when they're inside some tags.

If you write curlies in a simple JavaScript context the parser expects an object literal, something like this:

```<code>({ propA, propB })
</code>```

Rewriting it like below should make your example work:

```<code>return Platform.OS === 'ios' ? (
        <TextInput
            style={styles.title}
            value={account}
            multiline
            editable={false}
            scrollEnabled={false}
        />
    ) : (
        <Text
            selectable
            style={styles.title}
            >
            {account}
        </Text>
    )
</code>```

Title: SyntaxError in Platform

Body:
I have a SyntaxError in the Platform line but I cant see why.

Is it because the code should be wrapped in a class instead of a function?

function AccountItem({ title }) {
    account = title.join('\n')

    return (
        {Platform.OS === 'ios' ? (
            <TextInput
                style={styles.title}
                value={account}
                multiline
                editable={false}
                scrollEnabled={false}
            />
        ) : (
            <Text
                selectable
                style={styles.title}
                >
                {account}
            </Text>
            )
        }
    )
}

Body:
I think curly braces can only be used in the context of jsx. In other words, when they're inside some tags.

If you write curlies in a simple JavaScript context the parser expects an object literal, something like this:

({ propA, propB })

Rewriting it like below should make your example work:

return Platform.OS === 'ios' ? (
        <TextInput
            style={styles.title}
            value={account}
            multiline
            editable={false}
            scrollEnabled={false}
        />
    ) : (
        <Text
            selectable
            style={styles.title}
            >
            {account}
        </Text>
    )


问:
Spring Integration Java DSL behavior of using multiple ".channel()"
I'm testing the behavior of the .channel() method and I've observed things that I don't understand.

```<code>@Bean
    public IntegrationFlow flow() {
        return IntegrationFlows.from("my-gateway")
                .channel("first-channel")
                .channel("second-channel")
                .get();
    }
</code>```

If I place print statements in "first-channel", they aren't printed. But some of the business logic still appears to happen. Edit: Added code for service activators

```<code>@ServiceActivator(inputChannel = "first-channel")
   public Message testFlow(Message message) {
   System.out.println("Entered First Channel " + "\n" + "Message Header: " + message.getHeaders() + "\n" + "Message Payload" + "\n" + message.getPayload());
return message;
</code>```

}

```<code>@ServiceActivator(inputChannel = "second-channel")
   public Message testFlow(Message message) {
   System.out.println("Entered Second Channel " + "\n" + "Message Header: " + message.getHeaders() + "\n" + "Message Payload" + "\n" + message.getPayload());
return message;
</code>```

}

application.properties:

```<code>logging.level.root=TRACE
</code>```

Am I allowed to pass a message through multiple channels in the same java dsl IntegrationFlow? Or are all IntegrationFlows restricted to one channel/ServiceActivator each?

Edit: Only the second print statement appears in the logs. Why is that?

答:
No, you definitely can build a flow with multiple channels and you even can have a configuration like that. A bridge() is placed in between then internally by the framework. Image you need to dump messages from direct call to some queue or vise versa. Or your message channel even can be based on some persistent storage for messages like JMS, AMQP etc.

The MessageChannel abstraction is a first-class citizen in Spring Integration and that comes from the canonical integration model described in the EIP: https://www.enterpriseintegrationpatterns.com/patterns/messaging/MessageChannel.html

The importance of such an implementation between endpoints comes handy when see how those endpoints are loosely-coupled and the target MessageChannel implementation may dictate us some behavior change in the middle of the flow.

Another aspect as an argument that it is valid to have a flow like you define is a ChannelInterceptor. You still may have definition with just channel names, but ChannelInterceptor can be applied to them globally according its pattern option.

The opposite is also true: you can declare a flow just only with endpoints and the framework places channel in between internally.

Please, see docs for more info: https://docs.spring.io/spring-integration/docs/5.2.3.RELEASE/reference/html/dsl.html#java-dsl

Body:
I'm testing the behavior of the .channel() method and I've observed things that I don't understand.

@Bean
    public IntegrationFlow flow() {
        return IntegrationFlows.from("my-gateway")
                .channel("first-channel")
                .channel("second-channel")
                .get();
    }

If I place print statements in "first-channel", they aren't printed. But some of the business logic still appears to happen. Edit: Added code for service activators

@ServiceActivator(inputChannel = "first-channel")
   public Message testFlow(Message message) {
   System.out.println("Entered First Channel " + "\n" + "Message Header: " + message.getHeaders() + "\n" + "Message Payload" + "\n" + message.getPayload());
return message;

}

@ServiceActivator(inputChannel = "second-channel")
   public Message testFlow(Message message) {
   System.out.println("Entered Second Channel " + "\n" + "Message Header: " + message.getHeaders() + "\n" + "Message Payload" + "\n" + message.getPayload());
return message;

}

application.properties:

logging.level.root=TRACE

Am I allowed to pass a message through multiple channels in the same java dsl IntegrationFlow? Or are all IntegrationFlows restricted to one channel/ServiceActivator each?

Edit: Only the second print statement appears in the logs. Why is that?


问:
Why is two-way databinding in AngularJS an antipattern?
AngularJS offers two-way databinding.

I built several AngularJS apps and found two-way databinding to be a powerful feature, that increased my productivity.

Recently however I come more and more across posts and articles that claim that two-way databinding is an antipattern.

Examples:

https://medium.com/este-js-framework/whats-wrong-with-angular-js-97b0a787f903#.py84tbylf

https://www.dotnetrocks.com/?show=1147

https://www.youtube.com/watch?v=DslsyqnyjQE

Angular2 two-way data binding

Most of the resources argue in favour of "Unidirectional Dataflow" like it is promoted by React/Flux.

Also Angular2 announced for some time that there will be no two-way binding... but the latest documentation shows that it is actually offering two-way databinding via ngModel again (implemented on top of property- and event-binding)

However I do not yet fully understand the problems that relate to two-way databinding in AngularJS.

Other client technologies (i.e. swing, eclipse-rcp, winforms, wpf ...) also offer two-way databinding, and I never stumbled over the claim that it is an anti-pattern ...

Is there a canonical example that easily illustrates the problems that might result from two-way databinding in AngularJS?

The video I linked above seems to hint that $scope.watch is the problem ... but the example can be implemented without $scope.watch by binding to a function exposed on the $scope.

If you avoid using $scope (i.e. using controller as), what problems remain with two-way databinding?

答: Two-way data binding can be its own problem: a model can update a view which can update a model which can update another model... Unidirectional data flow is more predictable.</p>


问:
clicking through saved checkbox states
The below works to save the states of my checkboxes, then sets the items saved back to checked when called in my load__() function; however I need to instead of just setting to checked, I need to actually have them .click() through in my load__() function as the data is not being served otherwise.

```<code>  function checkSaver() {
      user = JSON.parse(localStorage.getItem(user));

      var inputs = document.querySelectorAll('input[type="checkbox"]');
      user.userAchkData = [];

      inputs.forEach(function(input){
        user.userAchkData.push({ id: input.id, checked: input.checked });
      });

      localStorage.setItem(username, JSON.stringify(user));
      console.log(JSON.stringify(user));

    }
</code>```

```<code>    function load_() {
      // get saved latest checkbox states, recheck
      user = JSON.parse(localStorage.getItem(user));
      var inputs = user.userAchkData;

      inputs.forEach(function(input){
        if (input.id) {
            // I need to click through the found checked here
            document.getElementById(input.id).checked = input.checked;
        }
      });
</code>```

答:
You can check if they're checked and then programmatically trigger a click:

```<code>if (input.id) {
   // I need to click through the found checked here
   const element = document.getElementById(input.id);
   element.checked = input.checked;
   if (input.checked) element.click();
}
</code>```

I fiddled around a bit and got to a simple working example for checking saved checkboxes. Maybe you can adapt this to your needs:

const container = document.getElementById('checkboxes');
const data = JSON.parse(localStorage.getItem('checkboxes')) || new Array(3).fill(false);

window.addEventListener('DOMContentLoaded', () => {
  [...container.children].forEach((child, i) => { child.checked = data[i]; });
});

container.onchange = ({ target }) => {
  data[target.dataset.id] = target.checked;
  localStorage.setItem('checkboxes', JSON.stringify(data));
};
```

<pre class="lang-html prettyprint-override"><code><div id="checkboxes">
<input type="checkbox" data-id="0">
<input type="checkbox" data-id="1">
<input type="checkbox" data-id="2">
</div>
</code>```

Title: clicking through saved checkbox states

Body:
The below works to save the states of my checkboxes, then sets the items saved back to checked when called in my load__() function; however I need to instead of just setting to checked, I need to actually have them .click() through in my load__() function as the data is not being served otherwise.

  function checkSaver() {
      user = JSON.parse(localStorage.getItem(user));

      var inputs = document.querySelectorAll('input[type="checkbox"]');
      user.userAchkData = [];

      inputs.forEach(function(input){
        user.userAchkData.push({ id: input.id, checked: input.checked });
      });

      localStorage.setItem(username, JSON.stringify(user));
      console.log(JSON.stringify(user));

    }

    function load_() {
      // get saved latest checkbox states, recheck
      user = JSON.parse(localStorage.getItem(user));
      var inputs = user.userAchkData;

      inputs.forEach(function(input){
        if (input.id) {
            // I need to click through the found checked here
            document.getElementById(input.id).checked = input.checked;
        }
      });

Body:
You can check if they're checked and then programmatically trigger a click:

if (input.id) {
   // I need to click through the found checked here
   const element = document.getElementById(input.id);
   element.checked = input.checked;
   if (input.checked) element.click();
}

I fiddled around a bit and got to a simple working example for checking saved checkboxes. Maybe you can adapt this to your needs:

const container = document.getElementById('checkboxes');
const data = JSON.parse(localStorage.getItem('checkboxes')) || new Array(3).fill(false);

window.addEventListener('DOMContentLoaded', () => {
  [...container.children].forEach((child, i) => { child.checked = data[i]; });
});

container.onchange = ({ target }) => {
  data[target.dataset.id] = target.checked;
  localStorage.setItem('checkboxes', JSON.stringify(data));
};

<div id="checkboxes">
<input type="checkbox" data-id="0">
<input type="checkbox" data-id="1">
<input type="checkbox" data-id="2">
</div>


问:
MESI Protocol & std::atomic - Does it ensure all writes are immediately visible to other threads?
In regards to std::atomic, the C++11 standard states that stores to an atomic variable will become visible to loads of that variable in a "reasonable amount of time".

From 29.3p13:

Implementations should make atomic stores visible to atomic loads within a reasonable amount of time.

However I was curious to know what actually happens when dealing with specific CPU architectures which are based on the MESI cache coherency protocol (x86, x86-64, ARM, etc..).

If my understanding of the MESI protocol is correct, a core will always read the value previously written/being written by another core immediately, possibly by snooping it. (because writing a value means issuing a RFO request which in turn invalidates other cache lines)

Does it mean that when a thread A stores a value into an std::atomic, another thread B which does a load on that atomic successively will in fact always observe the new value written by A on MESI architectures? (Assuming no other threads are doing operations on that atomic)

By “successively” I mean after thread A has issued the atomic store. (Modification order has been updated)

答:
I'll answer for what happens on real implementations on real CPUs, because an answer based only on the standard can barely say anything useful about time or "immediacy".

MESI is just an implementation detail that ISO C++ doesn't have anything to say about.  The guarantees provided by ISO C++ only involve order, not actual time.  ISO C++ is intentionally non-specific to avoid assuming that it will execute on a "normal" CPU.  An implementation on a non-coherent machine that required explicit flushes for store visibility might be theoretically possible (although probably horrible for performance of release / acquire and seq-cst operations)

C++ is non-specific enough about timing to even allow an implementation on a single-core cooperative multi-tasking system (no pre-emption), with the compiler inserting voluntary yields occasionally.  (Infinite loops without any volatile accesses or I/O are UB).  C++ on a system where only one thread can actually be executing at once is totally fine and possible, assuming you consider a scheduler timeslice to still be a "reasonable" amount of time.  (Or less if you yield or otherwise block.)

Even the model of formalism ISO C++ uses to give the guarantees it does about ordering is very different from the way hardware ISAs define their memory models.  C++ formal guarantees are purely in terms of happens-before and synchronizes-with, not "re"-ordering litmus tests or any kind of stuff like that.  e.g. How to achieve a StoreLoad barrier in C++11? is impossible to answer for pure ISO C++ formalism.  The "option C" in that Q&A serves to show just how weak the C++ guarantees are; that case with store then load of two different SC variables is not sufficient to imply happens-before based on it, according to the C++ formalism, even though there has to be a total order of all SC operations.  But it is sufficient in real life on systems with coherent cache and only local (within each CPU core) memory reordering, even AArch64 where the SC load right after the SC store does still essentially give us a StoreLoad barrier.

when a thread A stores a value into an std::atomic

It depends what you mean by "doing" a store.

If you mean committing from the store buffer into L1d cache, then yes, that's the moment when a store becomes globally visible, on a normal machine that uses MESI to give all CPU cores a coherent view of memory.

Although note that on some ISAs, some other threads are allowed to see stores before they become globally visible via cache.  (i.e. the hardware memory model may not be "multi-copy atomic", and allow IRIW reordering.  POWER is the only example I know of that does this in real life.  See Will two atomic writes to different locations in different threads always be seen in the same order by other threads? for details on the HW mechanism: Store forwarding for retired aka graduated stores between SMT threads.)

If you mean executing locally so later loads in this thread can see it, then no.  std::atomic can use a memory_order weaker than seq_cst.

All mainstream ISAs have memory-ordering rules weak enough to allow for a store buffer to decouple instruction execution from commit to cache.  This also allows speculative out-of-order execution by giving stores somewhere private to live after execution, before we're sure that they were on the correct path of execution.  (Stores can't commit to L1d until after the store instruction retires from the out-of-order part of the back end, and thus is known to be non-speculative.)

If you want to wait for your store to be visible to other threads before doing any later loads, use atomic_thread_fence(memory_order_seq_cst);.  (Which on "normal" ISAs with standard choice of C++ -> asm mappings will compile to a full barrier).

On most ISAs, a seq_cst store (the default) will also stall all later loads (and stores) in this thread until the store is globally visible.  But on AArch64, STLR is a sequential-release store and execution of later loads/stores doesn't have to stall unless / until a LDAR (acquire load) is about to execute while the STLR is still in the store buffer.  This implements SC semantics as weakly as possible, assuming AArch64 hardware actually works that way instead of just treating it as a store + full barrier.

But note that only blocking later loads/stores is necessary; out-of-order exec of ALU instructions on registers can still continue.  But if you were expecting some kind of timing effect due to dependency chains of FP operations, for example, that's not something you can depend on in C++.

Even if you do use seq_cst so nothing happens in this thread before the store is visible to others, that's still not instant.  Inter-core latency on real hardware can be on the order of maybe 40ns on mainstream modern Intel x86, for example.  (This thread doesn't have to stall that long on a memory barrier instruction; some of that time is the cache miss on the other thread trying to read the line that was invalidated by this core's RFO to get exclusive ownership.)  Or of course much cheaper for logical cores that share the L1d cache of a physical core: What are the latency and throughput costs of producer-consumer sharing of a memory location between hyper-siblings versus non-hyper siblings?


问:
Creating Eclipse CDT using CMake on Windows
I am trying to create a simple helloworld Eclipse CDT project using the CMake GUI. The CMake file looks like this:

```<code>cmake_minimum_required(VERSION "3.11.1")

project("HelloWorld")

add_executable("HelloWorldMain" "Main.cpp")

install(TARGETS "${PROJECT_NAME}" DESTINATION bin)
install(FILES "Main.cpp" DESTINATION src)
</code>```

The only c/c++ compiler I have is MSVC so I set that as the CMAKE_CXX_COMPILER but I get an error when configuring as shown here:

I know this file exists, but how do I get it to find it?

答:
I ended up not using the GUI. Instead I used the VS x64 Native Tools Command Prompt then ran the cmake command:

```<code>cmake -G "Eclipse CDT4 - NMake Makefiles" -DCMAKE_BUILD_TYPE=Debug -DCMAKE_ECLIPSE_GENERATE_SOURCE_PROJECT=TRUE -DCMAKE_ECLIPSE_MAKE_ARGUMENTS=-j8 ../
</code>```

Body:
I am trying to create a simple helloworld Eclipse CDT project using the CMake GUI. The CMake file looks like this:

cmake_minimum_required(VERSION "3.11.1")

project("HelloWorld")

add_executable("HelloWorldMain" "Main.cpp")

install(TARGETS "${PROJECT_NAME}" DESTINATION bin)
install(FILES "Main.cpp" DESTINATION src)

The only c/c++ compiler I have is MSVC so I set that as the CMAKE_CXX_COMPILER but I get an error when configuring as shown here:

I know this file exists, but how do I get it to find it?

Body:
I ended up not using the GUI. Instead I used the VS x64 Native Tools Command Prompt then ran the cmake command:

cmake -G "Eclipse CDT4 - NMake Makefiles" -DCMAKE_BUILD_TYPE=Debug -DCMAKE_ECLIPSE_GENERATE_SOURCE_PROJECT=TRUE -DCMAKE_ECLIPSE_MAKE_ARGUMENTS=-j8 ../


问:
Closest spatial position from Lat and Long
I have an application that uses the DotSpatial framework to connect to a usb GPS on my laptop. I essentially use it when driving out on site to know where I am.

The application also includes a ShapeFile map as background so that I know where I am.

What I have is:

I have a database with each road devided into 5m increments with a lat.long location and a road name. (So Col 1 = UniqueID, Col 2 = Location Distance in m (I.e. 0, 5, 10 ...), Col 3 = Road Name, Col 4 = Lat, Col 5 = Long)

The database is SQLite and have one that I created in Access as well.

The full DotSpatial framework

What I need to do is the following:

Work out based on my current lat/long (which I get from the GPS receiver and the GPS.NET part of the software) what the nearest Location Distance in m is from the lat/long locations in the database.

If there are any other suggestions please let me know.

P.S the application needs to be portable so dont want to mess around with SQL Server or PostgrSQL with posGIS etc.

答:
Since you want to get the nearest distance in metres from your current lat/long, the first thing you need to do is perform a coordinate transform.

Most GPS receivers work in WGS84, and assuming this, you can use a library such as Proj4 (.NET wrapper) to convert both your current position and the road position to metres (projected coordinates; either into WGS84 projected, or a local coordinate system based on your geographic location. UTM zones can work quite well, or OSGB if you're based in the UK).

You can find a projection best suited for your needs here (however, as I write this, it's currently down... hence my lack of helpful links at this time. I will edit when it's accessible again).

If you need more help with the GIS side of this, consider paying a visit to GIS.SE

Once you have your locations in metres, get the distance between them:

```<code>double distanceX = currentXmetres - roadXmetres;
double distanceY = currentYmetres - roadYmetres;

double Distance = Math.Abs( Math.Sqrt( (distanceX * distanceX) + (distanceY * distanceY) ) );
</code>```

Now you can query your database with the value of Distance and find the closest location:

```<code>SELECT * FROM table
ORDER BY ABS(Distance - Col 2)
LIMIT 1
</code>```

Note: I don't know the actual name of your table, or columns, so replace "table" and "Col 2" accordingly.

Body:
Since you want to get the nearest distance in metres from your current lat/long, the first thing you need to do is perform a coordinate transform.

Most GPS receivers work in WGS84, and assuming this, you can use a library such as Proj4 (.NET wrapper) to convert both your current position and the road position to metres (projected coordinates; either into WGS84 projected, or a local coordinate system based on your geographic location. UTM zones can work quite well, or OSGB if you're based in the UK).

You can find a projection best suited for your needs here (however, as I write this, it's currently down... hence my lack of helpful links at this time. I will edit when it's accessible again).

If you need more help with the GIS side of this, consider paying a visit to GIS.SE

Once you have your locations in metres, get the distance between them:

double distanceX = currentXmetres - roadXmetres;
double distanceY = currentYmetres - roadYmetres;

double Distance = Math.Abs( Math.Sqrt( (distanceX * distanceX) + (distanceY * distanceY) ) );

Now you can query your database with the value of Distance and find the closest location:

SELECT * FROM table
ORDER BY ABS(Distance - Col 2)
LIMIT 1

Note: I don't know the actual name of your table, or columns, so replace "table" and "Col 2" accordingly.


问:
How can i use Firebase App distribution without google account?
I am a Fabric user it works flawless for app distribution purpose. Recently I migrated my Fabric app to Firebase platform (as Google is removing Fabric) for app distribution with my testers. I followed their doc https://firebase.google.com/docs/app-distribution/ios/distribute-console and got email for app setup, but when I process it shows sign in with Google button. This is really useless how can my tester sign in without his google account as he only has our office domain email address?

I am unable to download with my domain email and can not share with our testers. How can I fix this?

Thanks,

答: Todd from Firebase. Right now it is mandatory that each tester has a Google account. This allows us to simplify the tester management process.</p>


问:
Google Analytics Custom Campaigns not reporting Revenue
I have created custom campaigns and completed standard ecommerce transactions with the UTM parameters set in the URL when the user hits the site initially, but my campaigns continue to say 0 revenue. My transactions are showing in Google Analytics, but they are not being attributed to the campaign. Can I have some help on the potential holes in my setup? Any insight will help.

Ecommerce Product and Revenue expected on the Campaigns

Campaigns that have no Revenue attributed to them

答:
I found my issue, cache. I have done hard refreshes before every test, but I went into Chrome tools and clear EVERYTHING. Cookie, cache, everything. And Cross-Domain tracking for Custom Campaigns started working! For reference here are the scripts for the two sites:

```<code>Site 1:

ga('create','UA-xxxxxxx-x'','auto', { 'allowLinker': true });
ga('require', 'linker');
ga('linker:autoLink', ['site2.com']);
ga('require','ecommerce','ecommerce.js');
ga('send','pageview');

Site2:

ga('create', 'UA-xxxxxxx-x', 'auto', { 'name': 'client', 'allowLinker': true });
ga('client.require', 'linker');
ga('client.linker:autoLink', ['site1.com']);
ga('client.require', 'ecommerce', 'ecommerce.js');
ga('client.send', 'pageview');
</code>```

Also, I added site1.com and site2.com to the Referral Exclusion List in GA and the UA key for site 1 and site 2 are the same.

Body:
I found my issue, cache. I have done hard refreshes before every test, but I went into Chrome tools and clear EVERYTHING. Cookie, cache, everything. And Cross-Domain tracking for Custom Campaigns started working! For reference here are the scripts for the two sites:

Site 1:

ga('create','UA-xxxxxxx-x'','auto', { 'allowLinker': true });
ga('require', 'linker');
ga('linker:autoLink', ['site2.com']);
ga('require','ecommerce','ecommerce.js');
ga('send','pageview');

Site2:

ga('create', 'UA-xxxxxxx-x', 'auto', { 'name': 'client', 'allowLinker': true });
ga('client.require', 'linker');
ga('client.linker:autoLink', ['site1.com']);
ga('client.require', 'ecommerce', 'ecommerce.js');
ga('client.send', 'pageview');

Also, I added site1.com and site2.com to the Referral Exclusion List in GA and the UA key for site 1 and site 2 are the same.