问:
CondingBat Python puzzle results in "Timed out"
I am trying to solve this CodingBat problem:

We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each). Return the number of small bars to use, assuming we always use big bars before small bars. Return -1 if it can't be done.

I understand the logic of the problem but whenever I try to run it, I get a Timed Out exception. So can anyone tell me what I'm doing wrong?

```<code>def make_chocolate(small, big, goal):

  total = 0

  if goal < 5:
    big = 0
  for i in xrange(big):
    total += 5
    if total == goal:
      return 0
    elif total+5>goal:
      break
  for k in xrange(small):
    total +=1
    if total == goal:
      return (k+1)

  return -1
</code>```

答:
```<code>def make_chocolate(small, big, goal):
    if goal - 5 * big == 0:
        return 0
    elif (goal - 5 * big) < 0:
        return -1 if (goal % 5) > small else goal % 5
    elif (goal - 5 * big) > small:
        return -1
    else:
        return (goal - 5 * big)
</code>```

Body:
I am trying to solve this CodingBat problem:

We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each). Return the number of small bars to use, assuming we always use big bars before small bars. Return -1 if it can't be done.

I understand the logic of the problem but whenever I try to run it, I get a Timed Out exception. So can anyone tell me what I'm doing wrong?

def make_chocolate(small, big, goal):

  total = 0

  if goal < 5:
    big = 0
  for i in xrange(big):
    total += 5
    if total == goal:
      return 0
    elif total+5>goal:
      break
  for k in xrange(small):
    total +=1
    if total == goal:
      return (k+1)

  return -1


来源: stackexchange

问:
how to pass hindi fonts from clients to server using ajax request
I am using ajax request to send a value from client side to server side to insert in mysql database using ajax request. The value is in hindi language (हिन्दी मतलब जाने). But on client side when i alert it i get the hindi text as shown above but after the server side request is processed it gets inserted in the database as %u0939%u093F%u0928%u094D%u0926%u0940 %u092E%u0924%...

i have used in the client side

```<code>request1h[k].setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8;");
request1h[k].send(requestDatah);
</code>```

and on the server side header with php

```<code><?php header("Content-Type: text/html; charset=utf-8");
mysqli_set_charset($con,"utf8");
</code>```

then i read about utf8_encode and used that on the post value also

```<code>$value1 = utf8_decode($_POST['values']);
</code>```

but still i can't insert the hindi text in the database as it is. Please help me what to do ?

答:
Use btoa function for Encode a string in base-64: It returns the value as a string, representing the strings encoded base-64.

By default, built-in functions in JavaScript, such as btoa and atob, do not support Unicode strings, as both functions treat all its characters as 16-bit-encoded strings. so you have to use first encodeURIComponent function.

base64_encode = function(str = "") {
  return btoa(unescape(encodeURIComponent(str)));
};

function log(message) {
  var client = new XMLHttpRequest();
  client.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      json = JSON.parse(this.response);
      console.log(json.form);
    }
  };
  client.open("POST", '//httpbin.org/post');
  client.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  client.send(message);
}
data = "key_name=" + base64_encode("हिन्दी मतलब जाने");
log(data);```
</div>
</div>
</p>

<p>If you need to decode that base64 to value in PHP file where you post data, use this:</p>

<pre class="lang-php prettyprint-override"><code>// this will return 'हिन्दी मतलब जाने'
$value = base64_decode($_POST['key_name']);
</code>```

And when you enter data into the database, make sure that the character set utf8_general_ci in your table must be set.

If this is your problem, you can convert the table using the following query:

ALTER TABLE `YOUR_TABLE_NAME` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
```

ContentLicense: CC BY-SA 3.0

Body:
I am using ajax request to send a value from client side to server side to insert in mysql database using ajax request. The value is in hindi language (हिन्दी मतलब जाने). But on client side when i alert it i get the hindi text as shown above but after the server side request is processed it gets inserted in the database as %u0939%u093F%u0928%u094D%u0926%u0940 %u092E%u0924%...

i have used in the client side

request1h[k].setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8;");
request1h[k].send(requestDatah);

and on the server side header with php

<?php header("Content-Type: text/html; charset=utf-8");
mysqli_set_charset($con,"utf8");

then i read about utf8_encode and used that on the post value also

$value1 = utf8_decode($_POST['values']);

but still i can't insert the hindi text in the database as it is. Please help me what to do ?

Body:
Use btoa function for Encode a string in base-64: It returns the value as a string, representing the strings encoded base-64.

By default, built-in functions in JavaScript, such as btoa and atob, do not support Unicode strings, as both functions treat all its characters as 16-bit-encoded strings. so you have to use first encodeURIComponent function.

base64_encode = function(str = "") {
  return btoa(unescape(encodeURIComponent(str)));
};

function log(message) {
  var client = new XMLHttpRequest();
  client.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      json = JSON.parse(this.response);
      console.log(json.form);
    }
  };
  client.open("POST", '//httpbin.org/post');
  client.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  client.send(message);
}
data = "key_name=" + base64_encode("हिन्दी मतलब जाने");
log(data);

If you need to decode that base64 to value in PHP file where you post data, use this:

// this will return 'हिन्दी मतलब जाने'
$value = base64_decode($_POST['key_name']);

And when you enter data into the database, make sure that the character set utf8_general_ci in your table must be set.

If this is your problem, you can convert the table using the following query:

ALTER TABLE `YOUR_TABLE_NAME` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

ContentLicense: CC BY-SA 4.0


问:
How to run cocos creator's android build in the background
Actually i have a poker game developed in Cocos Creator(v2.0.9) using JavaScript. The game uses web socket. So when the android application is in background, web socket also pause due to this the game misses broadcast fired by server. Every time we need to reconnect whenever the app resumes which causes difficulty to the user. And also the actions and scheduler pauses.

So, i want that my app still run in background to maintain the game state.

答:
I was working on a poker game too, and we handled this same situation in the following way.

Instead of trying to listen to server messages in background, you could do this, when your app resumes, ask for a packet from server that contains the current state of the game, and all the data that you need to populate your scene. And after you receive that data, process that data, populate your scene and then the normal loop of your game can resume.

Note: After re-connection, make sure your game waits for the sync up data before processing any other data, that you might receive as soon your game connects with the server.


问:
Error while using body.json() for parsing response from http.get()
Tried using body.json() to assign data to an array of object but as it returns a promise tried this. But browser throws error telling me json() is not a function.

getRecipes() {
  this.http.get('https://recipe-book-1be52.firebaseio.com/recipes.json').subscribe(
    (response: Response) => {
      response.json().then(
        (data) => {
          this.recServ.setRecipes(data)
        }
      );
    }
  )
}
```

答: angular httpClient already does the .json() for you</p>


答:
Below code snippet may help you</p>

```<code>  getRecipes() {
    this.http.get('https://recipe-book-1be52.firebaseio.com/recipes.json').subscribe(
      (response: Response) => {
            this.recServ.setRecipes(JSON.parse(JSON.stringify(response)));
      }
    )}
</code>```

Title: Error while using body.json() for parsing response from http.get()

Body:
Tried using body.json() to assign data to an array of object but as it returns a promise tried this. But browser throws error telling me json() is not a function.

getRecipes() {
  this.http.get('https://recipe-book-1be52.firebaseio.com/recipes.json').subscribe(
    (response: Response) => {
      response.json().then(
        (data) => {
          this.recServ.setRecipes(data)
        }
      );
    }
  )
}

Body:
Below code snippet may help you

  getRecipes() {
    this.http.get('https://recipe-book-1be52.firebaseio.com/recipes.json').subscribe(
      (response: Response) => {
            this.recServ.setRecipes(JSON.parse(JSON.stringify(response)));
      }
    )}


问:
Relation between Users and cryptodata Sequelize database
I'm trying to build a relation between the users and his favorite cryptocurrency.

Meaning, multiple Users can have the same crypto as their favorites.

Coin.js

```<code>module.exports = (sequelize, DataTypes) => {
    const Coin = sequelize.define('Coin', {
        cryptoName: DataTypes.STRING,
    })

    Coin.associate = function(models) {
     Coin.belongsToMany(models.CoinsUserRelations, {foreignKey: 'CoinID', through: 'CoinsUserRelations'})
    }

return Coin
</code>```

}

User.js

```<code>module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('User', {
        firstName: DataTypes.STRING,
        lastName: DataTypes.STRING,
        email: {
           type: DataTypes.STRING,
           unique: true
        },
        password: DataTypes.STRING
        }, {
          hooks: {
           beforeSave: hashPassword
          }
     })

     User.associate = function(models) {
      User.belongsToMany(models.CoinsUserRelations, {foreignKey: 'UserID', through: 'CoinsUserRelations'})
     }
     return User
  }
</code>```

These are my 2 tables at the moment and now I'm trying to build a relation between them. and I keep receiving this error on my console which I do not understand why.

I've edited multiple time to resolve the issue, This was the result with the help of Anatoly

CoinsUserRelations.js

```<code>module.exports = (sequelize, DataTypes) => {
    const CoinsUsersRelations = sequelize.define('CoinsUsersRelations', {
        UserID: {
            type: DataTypes.INTEGER,
        },
        CoinID: {
            type: DataTypes.INTEGER,
        }
    })

    return CoinsUsersRelations
  }
</code>```

I'm really unsure on why I get this error if I'm actually defining the model before creating the relations..

Index.js

```<code>const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
const config = require('../config/config')
const db = {}

const sequelize = new Sequelize(
    config.db.database,
    config.db.user,
    config.db.password,
    config.db.options
)

fs
    .readdirSync(__dirname)
    .filter((file) =>
        file !== 'index.js'
    )
    .forEach((file) => {
        const model = sequelize.import(path.join(__dirname, file))
        db[model.name] = model
    })
Object.keys(db).forEach(function (modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db)
  }
})

db.sequelize = sequelize
db.Sequelize = Sequelize

module.exports = db
</code>```

Edit part for a bug called SequelizeEagerLoadingError

```<code>module.exports = {
    async getUserFavoriteCrypto (req, res) {
        try {
            const coins = await db.Users.findOne({
                where: {
                    UserID : req.query.userId
                },
                attributes: ['UserID'],
                include: [{
                    model: db.Coins,
                    required: false
                }]
            })
            console.log(coins)
            res.send({
                coins: coins
            })
        } catch (err) {
            res.status(400).send({
                error: err
            })
        }
    }
}
</code>```

答: You should register all models and only after that all their associations in one place. See my answer on a similar problem</p>

Body:
I'm trying to build a relation between the users and his favorite cryptocurrency.

Meaning, multiple Users can have the same crypto as their favorites.

Coin.js

module.exports = (sequelize, DataTypes) => {
    const Coin = sequelize.define('Coin', {
        cryptoName: DataTypes.STRING,
    })

    Coin.associate = function(models) {
     Coin.belongsToMany(models.CoinsUserRelations, {foreignKey: 'CoinID', through: 'CoinsUserRelations'})
    }

return Coin

}

User.js

module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('User', {
        firstName: DataTypes.STRING,
        lastName: DataTypes.STRING,
        email: {
           type: DataTypes.STRING,
           unique: true
        },
        password: DataTypes.STRING
        }, {
          hooks: {
           beforeSave: hashPassword
          }
     })

     User.associate = function(models) {
      User.belongsToMany(models.CoinsUserRelations, {foreignKey: 'UserID', through: 'CoinsUserRelations'})
     }
     return User
  }

These are my 2 tables at the moment and now I'm trying to build a relation between them. and I keep receiving this error on my console which I do not understand why.

I've edited multiple time to resolve the issue, This was the result with the help of Anatoly

CoinsUserRelations.js

module.exports = (sequelize, DataTypes) => {
    const CoinsUsersRelations = sequelize.define('CoinsUsersRelations', {
        UserID: {
            type: DataTypes.INTEGER,
        },
        CoinID: {
            type: DataTypes.INTEGER,
        }
    })

    return CoinsUsersRelations
  }

I'm really unsure on why I get this error if I'm actually defining the model before creating the relations..

Index.js

const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
const config = require('../config/config')
const db = {}

const sequelize = new Sequelize(
    config.db.database,
    config.db.user,
    config.db.password,
    config.db.options
)

fs
    .readdirSync(__dirname)
    .filter((file) =>
        file !== 'index.js'
    )
    .forEach((file) => {
        const model = sequelize.import(path.join(__dirname, file))
        db[model.name] = model
    })
Object.keys(db).forEach(function (modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db)
  }
})

db.sequelize = sequelize
db.Sequelize = Sequelize

module.exports = db

Edit part for a bug called SequelizeEagerLoadingError

module.exports = {
    async getUserFavoriteCrypto (req, res) {
        try {
            const coins = await db.Users.findOne({
                where: {
                    UserID : req.query.userId
                },
                attributes: ['UserID'],
                include: [{
                    model: db.Coins,
                    required: false
                }]
            })
            console.log(coins)
            res.send({
                coins: coins
            })
        } catch (err) {
            res.status(400).send({
                error: err
            })
        }
    }
}


问:
Nullable in objective c
Is there a way to make nullable struct in objective C like in C# you can use Nullable<T>?

I need a CGPoint to be null when there is no applicable value. I cannot allocate a random invalid value for this like (-5000, -5000) because all values are valid for this.

答: What if you define a CGPoint using CGPointMake(NAN, NAN) similar to CGRectNull?  Surely with NAN's for coordinates, it's not still a valid point.</p>

Title: Nullable in objective c


问:
How can I play a sound activated by a number of actions per time?
How can I call a function, for example Play a sound, if I do 3 blinks in a space of 2 seconds?

```<code>if blinking_ratio > 5.7:
    cv2.putText(frame, "BLINKING", (50, 150), font, 7, (255, 0, 0))
    winsound.PlaySound("campainha.wav.wav", winsound.SND_FILENAME)
</code>```

Here if I blink, the sound plays... I want to play, only if I blink 3 times in 2 secs for example...

答:
You could set up a Time class by using

```<code>class Time(datetime.tzinfo):
  def utcoffset(self, x):
    return datetime.timedelta(hours=-5) + self.dst(x)

  def dst(self, x):
    date = datetime.datetime(x.year, 3, 8)
    self.dston = date + datetime.timedelta(days=6-date.weekday())
    date = datetime.datetime(x.year, 11, 1)
    self.dstoff = date + datetime.timedelta(days=6-date.weekday())
    if self.dston <= x.replace(tzinfo=None) < self.dstoff:
      return datetime.timedelta(hours=1)
    else:
      return datetime.timedelta(0)

  def tzname(self, x):
    return 'Time'

def timeStamp():
  return datetime.datetime.now(tz=Time()).strftime('%Y-%m-%d %H:%M:%S')
</code>```

From this, you could do something like

```<code>while . . .:
  start = timeStamp()
  blinkOnce()
  end = timeStamp()
  if start - end < 2:
    pass
  else:
    break
</code>```

Of course you would adjust the second code segment to whatever conditions you want to be met, but the end is just some pseudocode that you could edit accordingly.

Body:
How can I call a function, for example Play a sound, if I do 3 blinks in a space of 2 seconds?

if blinking_ratio > 5.7:
    cv2.putText(frame, "BLINKING", (50, 150), font, 7, (255, 0, 0))
    winsound.PlaySound("campainha.wav.wav", winsound.SND_FILENAME)

Here if I blink, the sound plays... I want to play, only if I blink 3 times in 2 secs for example...

Body:
You could set up a Time class by using

class Time(datetime.tzinfo):
  def utcoffset(self, x):
    return datetime.timedelta(hours=-5) + self.dst(x)

  def dst(self, x):
    date = datetime.datetime(x.year, 3, 8)
    self.dston = date + datetime.timedelta(days=6-date.weekday())
    date = datetime.datetime(x.year, 11, 1)
    self.dstoff = date + datetime.timedelta(days=6-date.weekday())
    if self.dston <= x.replace(tzinfo=None) < self.dstoff:
      return datetime.timedelta(hours=1)
    else:
      return datetime.timedelta(0)

  def tzname(self, x):
    return 'Time'

def timeStamp():
  return datetime.datetime.now(tz=Time()).strftime('%Y-%m-%d %H:%M:%S')

From this, you could do something like

while . . .:
  start = timeStamp()
  blinkOnce()
  end = timeStamp()
  if start - end < 2:
    pass
  else:
    break

Of course you would adjust the second code segment to whatever conditions you want to be met, but the end is just some pseudocode that you could edit accordingly.


问:
Simulate Oracle SPOOL in Java
HI,

I am converting a shell script to a Java program. The shell scripts runs an sql statement and spool the file to an external text file. I want to simulate this in Java. (The output file must be in the exact same format as it was generated in running the comman in SQL+). Can anyone give me some guidelines such as formatting spacing ... for the file

Thanks

答:
First, is this a fixed query, or an arbitrary one? If it's fixed, you'll have an easier time. Arbitrary queries will have to be run via dbms_sql, so you can return column attributes. That's messy.

Second, keep in mind that SQL*Plus formatting is controllable by settings in the client. Things like line length, page size, column widths, headers, etc. are all able to be changed from execution to execution.

That said, assuming it's a fixed query, then I'd:

open a cursor for the query

If there's data, print the column headers (including the '------' lines)

loop through the cursor, printing each value for the record in proper format

close the cursor

You should be able to format your output by examining the output from SQL*Plus and copying that.

Title: Simulate Oracle SPOOL in Java


问:
Github Pages site not detecting index.html
I created a GitHub pages repository. For some reason when I name it
https://[username].github.io, it doesn't work, but it works when I name it https://[username].github.io/index.html.

Why?

答:
I also encountered the same problem today (05/28/2020). Suppose that you have done everything right (instructions in https://pages.github.com/), you should have a repo named username.github.io and index.html set up.

What worked for me was that I chose a Jekyll theme. First, go to Settings of the repo. In GitHub Pages section, look for Theme Chooser then click on Choose a Theme. It will redirect you to a GitHub page that has multiple themes that you can choose from. Choose a theme that you like then click Select Theme. After doing these steps, I refreshed my username.github.io and the page worked correctly.


问:
TF Keras ModelCheckpoint filepath batch number
I am using ModelCheckpoint to save checkpoints every 500 batches in every epoch. It is documented here https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/ModelCheckpoint.

How would I set filepath to include the batch number? I know I can use {epoch} and parameters in logs.

答:
This might be helpful but the question is not clear. Under Callback class, there are numerous functions for your desired requirement.

Sample Code

```<code>class WeightsSaver(Callback):
  def __init__(self, N):
    self.N = N
    self.epoch = 0

  def on_epoch_end(self, epoch, logs={}):
    if self.epoch % self.N == 0:
        name = ('weights%04d.hdf5') % self.epoch
        self.model.save_weights(name)
    self.epoch += 1

callbacks_list = [WeightsSaver(10)] #save every 10 models
model.fit(train_X,train_Y,epochs=n_epochs,callbacks=callbacks_list)
</code>```

Body:
This might be helpful but the question is not clear. Under Callback class, there are numerous functions for your desired requirement.

Sample Code

class WeightsSaver(Callback):
  def __init__(self, N):
    self.N = N
    self.epoch = 0

  def on_epoch_end(self, epoch, logs={}):
    if self.epoch % self.N == 0:
        name = ('weights%04d.hdf5') % self.epoch
        self.model.save_weights(name)
    self.epoch += 1

callbacks_list = [WeightsSaver(10)] #save every 10 models
model.fit(train_X,train_Y,epochs=n_epochs,callbacks=callbacks_list)


问:
SQL function appears to be stuck in loop
I am currently working on a function that should be returning 3 business days prior to the date sent as an argument to the function.

I am somewhat new to functions in SQL and I believe my logic is sound but I am stuck.

I have 2 tables I made. One contains all the weekend dates and one contains all the holiday dates. The function is meant to take in a single date and then using 2 while loops calculate 3 business days prior to the date submitted and then return that new date into my select statement.

Here is the function in quesion:

```<code>FUNCTION [dbo].[lessThreeBD](@WORKING_DT DATE)
RETURNS DATE
AS
BEGIN
DECLARE @ThreeBD DATE
DECLARE @COUNTER INT
SET @COUNTER = 0

WHILE @COUNTER < 4
SET @ThreeBD = @WORKING_DT
BEGIN
    WHILE CASE WHEN (SELECT TOP 1 HOL.DATE from DATABASE.dbo.Holidays HOL where HOL.DATE = CAST(@WORKING_DT AS DATE)) IS NULL THEN 'NOT HOLIDAY' ELSE 'HOLIDAY' END = 'HOLIDAY'
    OR CASE WHEN (SELECT TOP 1 WKND.DATE from DATABASE.dbo.Weekends WKND where WKND.DATE = CAST(@WORKING_DT AS DATE)) IS NULL THEN 'WEEKDAY' ELSE 'WEEKEND' END = 'WEEKEND'
    BEGIN
        SET @WORKING_DT = DATEADD(DAY, -1, @WORKING_DT)
    END
    SET @WORKING_DT = DATEADD(DAY, -1, @WORKING_DT)
    SET @COUNTER  = @COUNTER + 1
SET @ThreeBD = @WORKING_DT
END
RETURN @ThreeBD
END
</code>```

However when I test this with a single date it appears to be locked up:

Test line:

```<code>SELECT DATABASE.dbo.lessThreeBD('2020-05-24') AS TESTING
</code>```

This line should return the 20th.

Any idea what I might be doing wrong here?

Keep in mind that both the holiday and weekend tables work perfectly fine. I have already tested the case statements and I get the expected results with each case statement.

答:
This

```<code>WHILE @COUNTER < 4
SET @ThreeBD = @WORKING_DT
</code>```

is equivilent to

```<code>WHILE @COUNTER < 4
BEGIN
  SET @ThreeBD = @WORKING_DT
END
</code>```

which is an infinite loop.

Always use BEGIN / END with control flow statements in TSQL.

```<code>WHILE @COUNTER < 4
BEGIN
  SET @ThreeBD = @WORKING_DT
  BEGIN
. . .
</code>```

Except, perhaps, for common idioms like

```<code>if @@trancount > 0 rollback;
</code>```

Body:
I am currently working on a function that should be returning 3 business days prior to the date sent as an argument to the function.

I am somewhat new to functions in SQL and I believe my logic is sound but I am stuck.

I have 2 tables I made. One contains all the weekend dates and one contains all the holiday dates. The function is meant to take in a single date and then using 2 while loops calculate 3 business days prior to the date submitted and then return that new date into my select statement.

Here is the function in quesion:

FUNCTION [dbo].[lessThreeBD](@WORKING_DT DATE)
RETURNS DATE
AS
BEGIN
DECLARE @ThreeBD DATE
DECLARE @COUNTER INT
SET @COUNTER = 0

WHILE @COUNTER < 4
SET @ThreeBD = @WORKING_DT
BEGIN
    WHILE CASE WHEN (SELECT TOP 1 HOL.DATE from DATABASE.dbo.Holidays HOL where HOL.DATE = CAST(@WORKING_DT AS DATE)) IS NULL THEN 'NOT HOLIDAY' ELSE 'HOLIDAY' END = 'HOLIDAY'
    OR CASE WHEN (SELECT TOP 1 WKND.DATE from DATABASE.dbo.Weekends WKND where WKND.DATE = CAST(@WORKING_DT AS DATE)) IS NULL THEN 'WEEKDAY' ELSE 'WEEKEND' END = 'WEEKEND'
    BEGIN
        SET @WORKING_DT = DATEADD(DAY, -1, @WORKING_DT)
    END
    SET @WORKING_DT = DATEADD(DAY, -1, @WORKING_DT)
    SET @COUNTER  = @COUNTER + 1
SET @ThreeBD = @WORKING_DT
END
RETURN @ThreeBD
END

However when I test this with a single date it appears to be locked up:

Test line:

SELECT DATABASE.dbo.lessThreeBD('2020-05-24') AS TESTING

This line should return the 20th.

Any idea what I might be doing wrong here?

Keep in mind that both the holiday and weekend tables work perfectly fine. I have already tested the case statements and I get the expected results with each case statement.

Body:
This

WHILE @COUNTER < 4
SET @ThreeBD = @WORKING_DT

is equivilent to

WHILE @COUNTER < 4
BEGIN
  SET @ThreeBD = @WORKING_DT
END

which is an infinite loop.

Always use BEGIN / END with control flow statements in TSQL.

WHILE @COUNTER < 4
BEGIN
  SET @ThreeBD = @WORKING_DT
  BEGIN
. . .

Except, perhaps, for common idioms like

if @@trancount > 0 rollback;


问:
Is there a function instead of a line.new() or label.new() that can be used in the strategy?
Problem 1: In the study, the variables fibEntry and fibProfit give weird values from the beginning. Those values are way below the bar set. When the conditions from the script are true then the variables give the correct values.

Problem 2: In the strategy,  the script triggers entry at the open bar value because of that weird value of fibEntry which is way below the bar set. And on every other day the script triggers fibProfit at the close bar value.

Problem 3: In the strategy, even when the conditions are true, the script is ignoring that.

I can't use drawings because I need those values for the strategy.

I did try with:

strategy.entry(id="Long", long=true, when=barstate.isconfirmed and fibEntry)

and

strategy.entry(id="Long", long=true, when=dayofmonth != dayofmonth[1] and fibEntry)

Here is the code:

```<code>//@version=4

study(title="first baby study",overlay=true)

// Step 1. Highs and lows

pHigh = pivothigh(1,1)
pLow = pivotlow(1,1)

// Step 2. Fibonacci

// Step 2.1 Fibonacci Top

fibTop = 0.00

if pHigh > pHigh[2] or pHigh > pHigh[3] or pHigh > pHigh[4] or pHigh > pHigh[5]

    if close[1] > open[1]

        fibTop := close[1]

    if open[1] > close[1]

        fibTop := open[1]

// Step 2.2. Fibonacci Bottom

fibBottom = 0.00

if pLow > pLow[2] or pLow > pLow[3] or pLow > pLow[4] or pLow > pLow[5]

    if close[1] > open[1]

        fibBottom := open[1]

    if open[1] > close[1]

        fibBottom := close[1]

// Step 2.3. Fibonacci 0.272 - Entry Levl

var float fibEntry = na

if fibBottom[1]
    fibEntry := fibTop - 0.272 * (fibTop - fibBottom[1])
else
    if fibBottom[2]
        fibEntry := fibTop - 0.272 * (fibTop - fibBottom[2])
    else
        if fibBottom[3]
            fibEntry := fibTop - 0.272 * (fibTop - fibBottom[3])
        else
            if fibBottom[4]
                fibEntry := fibTop - 0.272 * (fibTop - fibBottom[4])
            else
                if fibBottom[5]
                    fibEntry := fibTop - 0.272 * (fibTop - fibBottom[5])

// Step 2.4. Fibonacci -0.272 - Take Profit Level

var float fibProfit = na

if fibBottom[1]
    fibProfit := (fibTop - fibBottom[1]) * 0.272 + fibTop
else
    if fibBottom[2]
        fibProfit := (fibTop - fibBottom[2]) * 0.272 + fibTop
    else
        if fibBottom[3]
            fibProfit := (fibTop - fibBottom[3]) * 0.272 + fibTop
        else
            if fibBottom[4]
                fibProfit := (fibTop - fibBottom[4]) * 0.272 + fibTop
            else
                if fibBottom[5]
                    fibProfit := (fibTop - fibBottom[5]) * 0.272 + fibTop

// // Step 3. Enter Trade

// strategy.entry(id="Long", long=true, when=fibEntry)

// // Step 4. Take Profit

// strategy.close(id="Long", when=fibProfit)

// Step 5. Plotting

plot(fibEntry, color=#ffe504)
plot(fibProfit, color=#00ff0a)
plot(fibTop, color=color.green, offset=-1)
plot(fibBottom, color=color.red, offset=-1)
plot(pHigh, color=color.green, transp=50,style=plot.style_circles, linewidth=5, offset=-1)
plot(pLow, color=color.red, transp=50, style=plot.style_circles, linewidth=5, offset=-1)
</code>```

This is my first study/strategy, hopefully, someone will help. Thanks

答:
This will probably get you closer to your goal. We init the variables to na and make sure they come out of the main if blocks with a value:

```<code>// Step 2.1 Fibonacci Top

float fibTop = na
if pHigh > pHigh[2] or pHigh > pHigh[3] or pHigh > pHigh[4] or pHigh > pHigh[5]
    if close[1] > open[1]
        fibTop := close[1]
    else
        fibTop := open[1]

// Step 2.2. Fibonacci Bottom

float fibBottom = na
if pLow > pLow[2] or pLow > pLow[3] or pLow > pLow[4] or pLow > pLow[5]
    if close[1] > open[1]
        fibBottom := open[1]
    else
        fibBottom := close[1]
</code>```

Body:
Problem 1: In the study, the variables fibEntry and fibProfit give weird values from the beginning. Those values are way below the bar set. When the conditions from the script are true then the variables give the correct values.

Problem 2: In the strategy,  the script triggers entry at the open bar value because of that weird value of fibEntry which is way below the bar set. And on every other day the script triggers fibProfit at the close bar value.

Problem 3: In the strategy, even when the conditions are true, the script is ignoring that.

I can't use drawings because I need those values for the strategy.

I did try with:

strategy.entry(id="Long", long=true, when=barstate.isconfirmed and fibEntry)

and

strategy.entry(id="Long", long=true, when=dayofmonth != dayofmonth[1] and fibEntry)

Here is the code:

//@version=4

study(title="first baby study",overlay=true)

// Step 1. Highs and lows

pHigh = pivothigh(1,1)
pLow = pivotlow(1,1)

// Step 2. Fibonacci

// Step 2.1 Fibonacci Top

fibTop = 0.00

if pHigh > pHigh[2] or pHigh > pHigh[3] or pHigh > pHigh[4] or pHigh > pHigh[5]

    if close[1] > open[1]

        fibTop := close[1]

    if open[1] > close[1]

        fibTop := open[1]

// Step 2.2. Fibonacci Bottom

fibBottom = 0.00

if pLow > pLow[2] or pLow > pLow[3] or pLow > pLow[4] or pLow > pLow[5]

    if close[1] > open[1]

        fibBottom := open[1]

    if open[1] > close[1]

        fibBottom := close[1]

// Step 2.3. Fibonacci 0.272 - Entry Levl

var float fibEntry = na

if fibBottom[1]
    fibEntry := fibTop - 0.272 * (fibTop - fibBottom[1])
else
    if fibBottom[2]
        fibEntry := fibTop - 0.272 * (fibTop - fibBottom[2])
    else
        if fibBottom[3]
            fibEntry := fibTop - 0.272 * (fibTop - fibBottom[3])
        else
            if fibBottom[4]
                fibEntry := fibTop - 0.272 * (fibTop - fibBottom[4])
            else
                if fibBottom[5]
                    fibEntry := fibTop - 0.272 * (fibTop - fibBottom[5])

// Step 2.4. Fibonacci -0.272 - Take Profit Level

var float fibProfit = na

if fibBottom[1]
    fibProfit := (fibTop - fibBottom[1]) * 0.272 + fibTop
else
    if fibBottom[2]
        fibProfit := (fibTop - fibBottom[2]) * 0.272 + fibTop
    else
        if fibBottom[3]
            fibProfit := (fibTop - fibBottom[3]) * 0.272 + fibTop
        else
            if fibBottom[4]
                fibProfit := (fibTop - fibBottom[4]) * 0.272 + fibTop
            else
                if fibBottom[5]
                    fibProfit := (fibTop - fibBottom[5]) * 0.272 + fibTop

// // Step 3. Enter Trade

// strategy.entry(id="Long", long=true, when=fibEntry)

// // Step 4. Take Profit

// strategy.close(id="Long", when=fibProfit)

// Step 5. Plotting

plot(fibEntry, color=#ffe504)
plot(fibProfit, color=#00ff0a)
plot(fibTop, color=color.green, offset=-1)
plot(fibBottom, color=color.red, offset=-1)
plot(pHigh, color=color.green, transp=50,style=plot.style_circles, linewidth=5, offset=-1)
plot(pLow, color=color.red, transp=50, style=plot.style_circles, linewidth=5, offset=-1)

This is my first study/strategy, hopefully, someone will help. Thanks

Body:
This will probably get you closer to your goal. We init the variables to na and make sure they come out of the main if blocks with a value:

// Step 2.1 Fibonacci Top

float fibTop = na
if pHigh > pHigh[2] or pHigh > pHigh[3] or pHigh > pHigh[4] or pHigh > pHigh[5]
    if close[1] > open[1]
        fibTop := close[1]
    else
        fibTop := open[1]

// Step 2.2. Fibonacci Bottom

float fibBottom = na
if pLow > pLow[2] or pLow > pLow[3] or pLow > pLow[4] or pLow > pLow[5]
    if close[1] > open[1]
        fibBottom := open[1]
    else
        fibBottom := close[1]


问:
Bloc, Flutter and Navigation
So like most, i'm new to Bloc and flutter and dart and wrapping my head around. I've googled, looked through the posts here but haven't found really any answers.

So this is about navigation with bloc and flutter. Take the example of a Login. So there is a login page with a bloc behind it and at some point someone presses a button to login.

So we can call a function in the bloc that does the validation. I think this is against the strict approach but i see people doing this. But then if login is successful how do you navigate to the next screen? You're not supposed to navigate in a bloc?

But if that login page is using a StreamBuilder to change state then you cannot add a navigate in a builder either can you? You can't return navigation, you return widgets.

The initstate is somewhere you could navigate, but can you have a stream builder in an initstate that listens for state changes in the bloc?

It's all a little confusing right now but i'm persevering as this is supposed to be the way forward...

thanks
Paul

答:
First of all: if no business logic then no needs to go to YourBloc class.

But from time to time some user's activity required to perform some logic in Bloc class and then Bloc class has to decide what to do next: just rebuild widgets or show dialog or even navigate to next route. In such case you have to send some State to UI to finish the action.
Then another problem appear: what shall I do with widgets when Bloc send State to show toast?

And this is the main issue with all of this story.

A lot of answers and articles recommend to use flutter_block. This library has BlocBuilder and BlocListener. With those classes you can solve some issues but not 100% of them.

In my case I used BlocConsumer which manage BlocBuilder and BlocListener and provide brilliant way to manage states.

From the documentation:

```<code>BlocConsumer<BlocA, BlocAState>(
  listenWhen: (previous, current) {
    // return true/false to determine whether or not
    // to invoke listener with state
  },
  listener: (context, state) {
    // do stuff here based on BlocA's state
  },
  buildWhen: (previous, current) {
    // return true/false to determine whether or not
    // to rebuild the widget with state
  },
  builder: (context, state) {
    // return widget here based on BlocA's state
  }
)
</code>```

As you can see with BlocConsumer you can filter states: you can easily define states to rebuild widgets and states to show some popups or navigate to next screen.

Title: Bloc, Flutter and Navigation

Body:
First of all: if no business logic then no needs to go to YourBloc class.

But from time to time some user's activity required to perform some logic in Bloc class and then Bloc class has to decide what to do next: just rebuild widgets or show dialog or even navigate to next route. In such case you have to send some State to UI to finish the action.
Then another problem appear: what shall I do with widgets when Bloc send State to show toast?

And this is the main issue with all of this story.

A lot of answers and articles recommend to use flutter_block. This library has BlocBuilder and BlocListener. With those classes you can solve some issues but not 100% of them.

In my case I used BlocConsumer which manage BlocBuilder and BlocListener and provide brilliant way to manage states.

From the documentation:

BlocConsumer<BlocA, BlocAState>(
  listenWhen: (previous, current) {
    // return true/false to determine whether or not
    // to invoke listener with state
  },
  listener: (context, state) {
    // do stuff here based on BlocA's state
  },
  buildWhen: (previous, current) {
    // return true/false to determine whether or not
    // to rebuild the widget with state
  },
  builder: (context, state) {
    // return widget here based on BlocA's state
  }
)

As you can see with BlocConsumer you can filter states: you can easily define states to rebuild widgets and states to show some popups or navigate to next screen.


问:
Laravel after_or_equal validation returns wrong status code for date before today
does anyone have similar issue?

I have a route to the controller method with specific request. Inside the request I am validating the date format like this:

'date' => 'required|date_format:Y-m-d|after_or_equal:today'

when I send in Postman the date which is today or later everything is fine and code 200 is returned. When I send the date before today api sends also 200 code but it never hits the method code (tried to check with dd) but returns the home page of the api.

Steps To Reproduce:

Create api route

create controller and method with custom request

set authorize() return value to true

set rule() return value to ['date' => 'required|date_format:y-m-d|after_or_equal:today']

send request to the api (i.e. using Postman) with date before today and after

I am using Laravel framework 7.13.0

答: You need to set the proper JSON request headers so that laravel returns a JSON response with errors instead of a redirect.</p>


问:
How to remove unnecessary single quotation marks (') from column names in a R data frame?
unfortunately I have got colnames, which all have additional single quotation marks like here:

```<code>x <- data.frame(c(11,21,31),c(12,22,32),c(13,23,33))
colnames(x) <- c("'A'","'B'","'C'")
</code>```

So my question is, if I can get rid of those "'" for my entire data frame?
Preferably not retyping the colnames, and using tidyR code?
Thanks!

答:
We can use trimws in base R

```<code>names(x) <-  trimws(names(x), whitespace = "'")
x
#   A  B  C
#1 11 12 13
#2 21 22 23
#3 31 32 33
</code>```

Body:
unfortunately I have got colnames, which all have additional single quotation marks like here:

x <- data.frame(c(11,21,31),c(12,22,32),c(13,23,33))
colnames(x) <- c("'A'","'B'","'C'")

So my question is, if I can get rid of those "'" for my entire data frame?
Preferably not retyping the colnames, and using tidyR code?
Thanks!

Body:
We can use trimws in base R

names(x) <-  trimws(names(x), whitespace = "'")
x
#   A  B  C
#1 11 12 13
#2 21 22 23
#3 31 32 33


问:
Why am I getting this? "NameError: name 'Response' is not defined"
I'm trying to get data from another of my servers. The other server is just an html file with "Hello World" I can reach my homepage fine, but when I go to /farmdata, I get this error:

NameError: name 'Response' is not defined"

```<code>from flask import Flask, render_template
import requests

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/farmdata')
def farmdata():
    r = requests.get('http://74.114.75.91:8080')
    r.url
    r.encoding
    return Response(
        r.text,
        status=r.status_code,
        content_type=r.headers['content-type'],
    )

if __name__== '__main__':
    app.run(debug=True, port=80, host='0.0.0.0')
</code>```

Edit - to anyone else with the problem, this was the solution.

```<code>from flask import Flask, render_template, Response
</code>```

答:
You have never defined Response. If you want to use flask.Response, you either have to import flask and then access it via flask.Response, or from flask import Response and then simply use Response.

In your code, you import Flask from the flask module, and that's where you get Flask from. If you remove the from flask import Flask line, you'll get a NameError complaining about Flask not being defined as well.

In Python, a name is defined if:

you defined it via variable assignment [or with a def or a class statement, which is pretty much the same] (like app in your example)

you imported it from another module explicitly (like Flask)

it's defined on startup (like list)

Body:
I'm trying to get data from another of my servers. The other server is just an html file with "Hello World" I can reach my homepage fine, but when I go to /farmdata, I get this error:

NameError: name 'Response' is not defined"

from flask import Flask, render_template
import requests

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/farmdata')
def farmdata():
    r = requests.get('http://74.114.75.91:8080')
    r.url
    r.encoding
    return Response(
        r.text,
        status=r.status_code,
        content_type=r.headers['content-type'],
    )

if __name__== '__main__':
    app.run(debug=True, port=80, host='0.0.0.0')

Edit - to anyone else with the problem, this was the solution.

from flask import Flask, render_template, Response


问:
Is it possible to get the number of times an article has been cited?
I am using Entrez to search for articles on Pubmed.  Is it possible to use Entrez to also determine the number of citations for each article that is found using my search parameters?  If not, is there an alternative method that I can use?  My googling hasn't turned up much, so far.

NOTE:  number of citations references (in my context) the number of times that the specific article in question has been cited in OTHER articles.

One thing that I have found: https://gist.github.com/mcfrank/c1ec74df1427278cbe53
which may indicate that I can get the citation number for articles that are also in the Pubmed DB, but it was unclear (to me) how I can use this to determine the number of citations for each article.

The following is the code that I am currently using (I'd like to include a 'print' line of the number of citations):

```<code>#search pubmed

from Bio import Entrez
from Bio import Medline

search_string = r'("Blah Blah")'

Entrez.email = "hello_world@example.com"
handle = Entrez.egquery(term=search_string)
record = Entrez.read(handle)
count = 0
for row in record["eGQueryResult"]:
        if row["DbName"]=="pubmed":
            print("Number of articles found with requested search parameters:", row["Count"])
            count = row["Count"]

handle = Entrez.esearch(db="pubmed", term=search_string, retmax=count)
record = Entrez.read(handle)
handle.close()
idlist = record["IdList"]

handle = Entrez.efetch(db="pubmed", id=idlist, rettype="medline", retmode="text")
records = Medline.parse(handle)

records = list(records)
x=1
for record in records:
    print("(" + str(x) + ")")
    print("Title:", record.get("TI", "?"))
    print("Authors: ", ", ".join(record.get("AU", "?")))
    print("Pub Date:", record.get("DP", "?"))
    print("Journal:", record.get("JT", "?"))
    print("DOI:", record.get("LID", "?")[:-6])
    #print("number of citations:", get.number_of_citations) #<--what I am requesting help about
    print("\n")
    x += 1
</code>```

答:
I solved this by writing script that crawls through the actual website where the publication is hosted (using the DOI to find the web address), and then the script parses out the citation amount from the xmlx data of the site. This method works for the specific journal I am interested in (only), unfortunately. </p>

<p>An alternative is to use WebOfScience, if anyone is interested.  It does this and gives a lot more citation data, such as citations per year as well as total citation number and a lot more data.  The downside is that WebOfScience is not a free service.  </p>

Body:
I am using Entrez to search for articles on Pubmed.  Is it possible to use Entrez to also determine the number of citations for each article that is found using my search parameters?  If not, is there an alternative method that I can use?  My googling hasn't turned up much, so far.

NOTE:  number of citations references (in my context) the number of times that the specific article in question has been cited in OTHER articles.

One thing that I have found: https://gist.github.com/mcfrank/c1ec74df1427278cbe53
which may indicate that I can get the citation number for articles that are also in the Pubmed DB, but it was unclear (to me) how I can use this to determine the number of citations for each article.

The following is the code that I am currently using (I'd like to include a 'print' line of the number of citations):

#search pubmed

from Bio import Entrez
from Bio import Medline

search_string = r'("Blah Blah")'

Entrez.email = "hello_world@example.com"
handle = Entrez.egquery(term=search_string)
record = Entrez.read(handle)
count = 0
for row in record["eGQueryResult"]:
        if row["DbName"]=="pubmed":
            print("Number of articles found with requested search parameters:", row["Count"])
            count = row["Count"]

handle = Entrez.esearch(db="pubmed", term=search_string, retmax=count)
record = Entrez.read(handle)
handle.close()
idlist = record["IdList"]

handle = Entrez.efetch(db="pubmed", id=idlist, rettype="medline", retmode="text")
records = Medline.parse(handle)

records = list(records)
x=1
for record in records:
    print("(" + str(x) + ")")
    print("Title:", record.get("TI", "?"))
    print("Authors: ", ", ".join(record.get("AU", "?")))
    print("Pub Date:", record.get("DP", "?"))
    print("Journal:", record.get("JT", "?"))
    print("DOI:", record.get("LID", "?")[:-6])
    #print("number of citations:", get.number_of_citations) #<--what I am requesting help about
    print("\n")
    x += 1

Body:
I solved this by writing script that crawls through the actual website where the publication is hosted (using the DOI to find the web address), and then the script parses out the citation amount from the xmlx data of the site. This method works for the specific journal I am interested in (only), unfortunately.

An alternative is to use WebOfScience, if anyone is interested.  It does this and gives a lot more citation data, such as citations per year as well as total citation number and a lot more data.  The downside is that WebOfScience is not a free service.


问:
Javascript. Pretty date with months and years
I got the below script to convert dates into pretty dates. It works perfectly
fine but only to a level of weeks. I need it to work fine for months and perhaps years to.

How can I modify this code to work?

```<code>function prettyDate(time) {

    var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
        diff = (((new Date()).getTime() - date.getTime()) / 1000),
        day_diff = Math.floor(diff / 86400);

    if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 ){

        return;

        }

    return day_diff == 0 && (
            diff < 60 && "just now" ||
            diff < 120 && "1 minute ago" ||
            diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
            diff < 7200 && "1 hour ago" ||
            diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
        day_diff == 1 && "Yesterday" ||
        day_diff < 7 && day_diff + " days ago" ||
        day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}
</code>```

答:
I use a combination of a dateDiff extension for dates and this (toAge) extension:</p>

```<code>Date.prototype.toAge = function() {
// all comparisons are based on GMT time

var s = "";
var span = 0;
var uom = "";

// get the current time in GMT
var oDiff = this.dateDiff(new Date(new Date().toUTCString().replace(" UTC", "").replace(" GMT", "")));

if (oDiff.TotalMinutes < 59) {
    span = Math.round(oDiff.TotalMinutes);
    uom = "min";
}
else {
    if (oDiff.TotalHours < 23.5) {
        span = Math.round(oDiff.TotalHours);
        uom = "hour";
    }
    else {
        span = Math.round(oDiff.TotalDays);
        uom = "day";
    }
}

if (span < 0) span = 0;

s = span + " " + uom;
if (span > 1) s += "s";
s += " ago";

return s;
}
</code>```

Body:
I got the below script to convert dates into pretty dates. It works perfectly
fine but only to a level of weeks. I need it to work fine for months and perhaps years to.

How can I modify this code to work?

function prettyDate(time) {

    var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
        diff = (((new Date()).getTime() - date.getTime()) / 1000),
        day_diff = Math.floor(diff / 86400);

    if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 ){

        return;

        }

    return day_diff == 0 && (
            diff < 60 && "just now" ||
            diff < 120 && "1 minute ago" ||
            diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
            diff < 7200 && "1 hour ago" ||
            diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
        day_diff == 1 && "Yesterday" ||
        day_diff < 7 && day_diff + " days ago" ||
        day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}

Body:
I use a combination of a dateDiff extension for dates and this (toAge) extension:

Date.prototype.toAge = function() {
// all comparisons are based on GMT time

var s = "";
var span = 0;
var uom = "";

// get the current time in GMT
var oDiff = this.dateDiff(new Date(new Date().toUTCString().replace(" UTC", "").replace(" GMT", "")));

if (oDiff.TotalMinutes < 59) {
    span = Math.round(oDiff.TotalMinutes);
    uom = "min";
}
else {
    if (oDiff.TotalHours < 23.5) {
        span = Math.round(oDiff.TotalHours);
        uom = "hour";
    }
    else {
        span = Math.round(oDiff.TotalDays);
        uom = "day";
    }
}

if (span < 0) span = 0;

s = span + " " + uom;
if (span > 1) s += "s";
s += " ago";

return s;
}


问:
How to update flask frontend instantly when MongoDb database updates?
I am updating a MongoDb database from a streaming application. And I want the changes in the database to reflect in the frontend.

On the frontend, I am currently queering the database, but I have to refresh manually to get new updates. Refreshing periodically is not a good option as the updates can be too quick many times a sec or even very slow a few times an hour.

I came across SSE(server sent events). But don't know if it can be used in my case.

答:
What I was searching for is a good PUSH based method. Where the backend server can change to a frontend client.

What I used:
A PULL based method instead.
Usually, in such cases, AJAX requests with a setInterval() in javascript can be used. In this case, one doesn't have to refresh the whole page. But just use an ajax request periodically to check for updates at regular intervals. And in case of an update can append/fill the corresponding Html in the concerned .

Here is what I used:

```<code>function update(){ // This functions is called repeatedly
    $.ajax({
        url: "/update/",
        type: "POST",
        success: function(resp){
            $('div.stats').html(resp.data); // append/fill to appropriate div
        }
    });
}

var myVar = setInterval(update, 1000); // update every 1sec
</code>```

This is very commonly used to the method.
This kind of served my purpose.

Also there are ways to have a PUSH based approach instead. See COMET programming. But I could not find a proper tool to do that in sync with the web frameworks.

Body:
What I was searching for is a good PUSH based method. Where the backend server can change to a frontend client.

What I used:
A PULL based method instead.
Usually, in such cases, AJAX requests with a setInterval() in javascript can be used. In this case, one doesn't have to refresh the whole page. But just use an ajax request periodically to check for updates at regular intervals. And in case of an update can append/fill the corresponding Html in the concerned .

Here is what I used:

function update(){ // This functions is called repeatedly
    $.ajax({
        url: "/update/",
        type: "POST",
        success: function(resp){
            $('div.stats').html(resp.data); // append/fill to appropriate div
        }
    });
}

var myVar = setInterval(update, 1000); // update every 1sec

This is very commonly used to the method.
This kind of served my purpose.

Also there are ways to have a PUSH based approach instead. See COMET programming. But I could not find a proper tool to do that in sync with the web frameworks.


问:
how do i display a different page using the browser?
New to angular. I noticed that by default the app.component.html is displayed when we first create an angular project and view on on localhost:4200/
I learned in a tutorial that in order to make another page, lets say an "Explore Page" similar to how instagram how an explore page, I would create the page as a component.

My Question is, now that i created that explore page component, how would I display that site on the browser?
without using routing or having to go through the initial page first

答:
Without using routing, if you want to display a component, you can use its selector

Sample:

```<code>// src/app/app.component.html
<app-explore-page></app-explore-page>
</code>```

or

```<code>// src/index.html
...
<body>
    <app-explore-page></app-explore-page>
</body>

// src/app/app.module.ts
...
bootstrap: [ExplorerPageComponent]
</code>```

Body:
Without using routing, if you want to display a component, you can use its selector

Sample:

// src/app/app.component.html
<app-explore-page></app-explore-page>

or

// src/index.html
...
<body>
    <app-explore-page></app-explore-page>
</body>

// src/app/app.module.ts
...
bootstrap: [ExplorerPageComponent]


答:
I think the issue is here:

WHILE @COUNTER < 4
SET @ThreeBD = @WORKING_DT
BEGIN

this SET command is being executed in an infinite loop.

Title: SQL function appears to be stuck in loop


问:
How do I get a value of datetime.today() in Python that is "timezone aware"?
I am trying to subtract one date value from the value of datetime.datetime.today() to calculate how long ago something was. But it complains:

TypeError: can't subtract offset-naive and offset-aware datetimes
```

The return value from datetime.datetime.today() doesn't seem to be "timezone aware", while my other date value is. How do I get a return value from datetime.datetime.today() that is timezone aware?

The ideal solution would be for it to automatically know the timezone.

Right now, it's giving me the time in local time, which happens to be PST, i.e. UTC - 8 hours. Worst case, is there a way I can manually enter a timezone value into the datetime object returned by datetime.datetime.today() and set it to UTC-8?

答:
Tyler from 'howchoo' made a really great article that helped me get a better idea of the Datetime Objects, link below

Working with Datetime

essentially, I just added the following to the end of both my datetime objects

```<code>.replace(tzinfo=pytz.utc)
</code>```

Example:

```<code>import pytz
import datetime from datetime

date = datetime.now().replace(tzinfo=pytz.utc)
</code>```

Body:
I am trying to subtract one date value from the value of datetime.datetime.today() to calculate how long ago something was. But it complains:

TypeError: can't subtract offset-naive and offset-aware datetimes

The return value from datetime.datetime.today() doesn't seem to be "timezone aware", while my other date value is. How do I get a return value from datetime.datetime.today() that is timezone aware?

The ideal solution would be for it to automatically know the timezone.

Right now, it's giving me the time in local time, which happens to be PST, i.e. UTC - 8 hours. Worst case, is there a way I can manually enter a timezone value into the datetime object returned by datetime.datetime.today() and set it to UTC-8?

Body:
Tyler from 'howchoo' made a really great article that helped me get a better idea of the Datetime Objects, link below

Working with Datetime

essentially, I just added the following to the end of both my datetime objects

.replace(tzinfo=pytz.utc)

Example:

import pytz
import datetime from datetime

date = datetime.now().replace(tzinfo=pytz.utc)


问:
Merging two almost identical strings
I have two objects, one which is a list of tuples with (int, str), like this:

```<code>first_input = [
    (0  ,  "Lorem ipsum dolor sit amet, consectetur"),
    (1  ,  " adipiscing elit"),
    (0  ,  ". In pellentesque\npharetra ex, at varius sem suscipit ac. "),
    (-1 ,  "Suspendisse luctus\ncondimentum velit a laoreet. "),
    (0  ,  "Donec dolor urna, tempus sed nulla vitae, dignissim varius neque.")
]
# Note that the strings contain newlines `\n` on purpose.
</code>```

The other object is a string, which is the result of a series of operations(*) which, by design, will result in a concatenation of all the strings above but with some additional newlines \n inserted.

(* : that can't be done while conserving the list of tuples structure, obviously)

For instance:

```<code>second_input = "Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit. In pellentesque\npharetra ex, at varius sem\nsuscipit ac. Suspendisse luctus\ncondimentum velit a laoreet. Donec dolor urna, tempus sed\nnulla vitae, dignissim varius neque."
# Note that there are 3 new newlines,  here ^ for instance
# but also in "sem\nsuscipit" and "sed\nnulla"
</code>```

My goal is to go back to the first structure, but keeping the additional newlines. So in my example, I would get:

```<code>expected_output = [
    (0  ,  "Lorem ipsum dolor sit amet,\nconsectetur"),  # new newline here
    (1  ,  " adipiscing elit"),
    (0  ,  ". In pellentesque\npharetra ex, at varius sem\nsuscipit ac. "), # new newline here
    (-1 ,  "Suspendisse luctus\ncondimentum velit a laoreet. "),
    (0  ,  "Donec dolor urna, tempus sed\nnulla vitae, dignissim varius neque.") # new newline here
]
</code>```

Do you have a smart way to do it, other than reconstructing the string with a character by character comparison?

(NB: I don't care in which of the two tuples it ends if a new \n is at the limit of a string. E.g. getting [(0, "foo\n"), (1, "bar")] or [(0, "foo"), (1, "\nbar")] doesn't matter.)

Edit: what I want to avoid, is to do something like this:

```<code>position=0
output = []
for tup in first_input:
    reconstructed_string = ""
    for letter in tup[1]:
        if letter == second_input[position]:
            reconstructed_string = reconstructed_string + letter
        else:
            reconstructed_string = reconstructed_string + second_input[position]
        position +=1
    output.append((tup[0], reconstructed_string))
# Note: this is hastily written to give you an idea, I have no idea if it would work properly, probably not
# Well, it does seem to work without bug, at least in my example. That's unexpected lol. Anyway, if you can think of a better solution...!
</code>```

That is, going through each character of the strings and compare them to reconstruct the strings character by character.

答:
I think the easiest way would be to translate whatever operations you are performing on the combined string back to the pieces, but I guess you already thought of this.
Instead, one could not insert any newline characters but generate a list of positions at which they would be entered. Keeping track of the length of the string bits, this could look like this, assuming the positions at which a ' ' is to be replaced by '\n' are stored in the variable posis:

```<code> import numpy as np
 posis = [27,98187,227] # position of the newlines in your sample, length of full string as last entry
 lengths = [len(string) for _, string in first_input]
 covered_distance = 0 # lengths of all strings we looked at already
 j = 0  # iterating index for positions
 output = []
 rel_pos = posis[0]-covered_distance # initialize relative position in the current string
 inserted_newlines = 0 # keep track of newlines we added already
 for i, [n, string] in enumerate(first_input):
     while rel_pos < lengths[i]:
         string = string[:rel_pos+inserted_newlines]+'\n'\
                 +string[rel_pos+inserted_newlines+1:]  # replace the character at the relative position
         j += 1 # advance to the next newline to be inserted
         rel_pos = posis[j]-covered_distance # update the relative position
         inserted_newlines += 1  # keep track of inserted newlines
     output.append((n, string))  # store resulting string
     covered_distance += lengths[i]  # update the number of characters we passed
     rel_pos = posis[j]-covered_distance
</code>```

This is not very beautiful but it works for the sample, in order to do proper testing I would need some more information on possible cases and maybe the operations determining the newline positions.

Title: Merging two almost identical strings

Body:
I have two objects, one which is a list of tuples with (int, str), like this:

first_input = [
    (0  ,  "Lorem ipsum dolor sit amet, consectetur"),
    (1  ,  " adipiscing elit"),
    (0  ,  ". In pellentesque\npharetra ex, at varius sem suscipit ac. "),
    (-1 ,  "Suspendisse luctus\ncondimentum velit a laoreet. "),
    (0  ,  "Donec dolor urna, tempus sed nulla vitae, dignissim varius neque.")
]
# Note that the strings contain newlines `\n` on purpose.

The other object is a string, which is the result of a series of operations(*) which, by design, will result in a concatenation of all the strings above but with some additional newlines \n inserted.

(* : that can't be done while conserving the list of tuples structure, obviously)

For instance:

second_input = "Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit. In pellentesque\npharetra ex, at varius sem\nsuscipit ac. Suspendisse luctus\ncondimentum velit a laoreet. Donec dolor urna, tempus sed\nnulla vitae, dignissim varius neque."
# Note that there are 3 new newlines,  here ^ for instance
# but also in "sem\nsuscipit" and "sed\nnulla"

My goal is to go back to the first structure, but keeping the additional newlines. So in my example, I would get:

expected_output = [
    (0  ,  "Lorem ipsum dolor sit amet,\nconsectetur"),  # new newline here
    (1  ,  " adipiscing elit"),
    (0  ,  ". In pellentesque\npharetra ex, at varius sem\nsuscipit ac. "), # new newline here
    (-1 ,  "Suspendisse luctus\ncondimentum velit a laoreet. "),
    (0  ,  "Donec dolor urna, tempus sed\nnulla vitae, dignissim varius neque.") # new newline here
]

Do you have a smart way to do it, other than reconstructing the string with a character by character comparison?

(NB: I don't care in which of the two tuples it ends if a new \n is at the limit of a string. E.g. getting [(0, "foo\n"), (1, "bar")] or [(0, "foo"), (1, "\nbar")] doesn't matter.)

Edit: what I want to avoid, is to do something like this:

position=0
output = []
for tup in first_input:
    reconstructed_string = ""
    for letter in tup[1]:
        if letter == second_input[position]:
            reconstructed_string = reconstructed_string + letter
        else:
            reconstructed_string = reconstructed_string + second_input[position]
        position +=1
    output.append((tup[0], reconstructed_string))
# Note: this is hastily written to give you an idea, I have no idea if it would work properly, probably not
# Well, it does seem to work without bug, at least in my example. That's unexpected lol. Anyway, if you can think of a better solution...!

That is, going through each character of the strings and compare them to reconstruct the strings character by character.

Body:
I think the easiest way would be to translate whatever operations you are performing on the combined string back to the pieces, but I guess you already thought of this.
Instead, one could not insert any newline characters but generate a list of positions at which they would be entered. Keeping track of the length of the string bits, this could look like this, assuming the positions at which a ' ' is to be replaced by '\n' are stored in the variable posis:

 import numpy as np
 posis = [27,98187,227] # position of the newlines in your sample, length of full string as last entry
 lengths = [len(string) for _, string in first_input]
 covered_distance = 0 # lengths of all strings we looked at already
 j = 0  # iterating index for positions
 output = []
 rel_pos = posis[0]-covered_distance # initialize relative position in the current string
 inserted_newlines = 0 # keep track of newlines we added already
 for i, [n, string] in enumerate(first_input):
     while rel_pos < lengths[i]:
         string = string[:rel_pos+inserted_newlines]+'\n'\
                 +string[rel_pos+inserted_newlines+1:]  # replace the character at the relative position
         j += 1 # advance to the next newline to be inserted
         rel_pos = posis[j]-covered_distance # update the relative position
         inserted_newlines += 1  # keep track of inserted newlines
     output.append((n, string))  # store resulting string
     covered_distance += lengths[i]  # update the number of characters we passed
     rel_pos = posis[j]-covered_distance

This is not very beautiful but it works for the sample, in order to do proper testing I would need some more information on possible cases and maybe the operations determining the newline positions.


问:
Rebus Circuit Breaker Implementation?
I have been working quite a bit with Rebus lately and so far it has been great.

One area of concern is when we have thousands or hundreds of thousands of messages that are being processed and a dependent service, like the database or RabbitMQ, is down.

In that case, we do not want all of the messages in the error queue. I would like to know if Rebus has any kind of built-in circuit-breaker mechanism? Something like I reach a 10% failure rate threshold over a period of 60 seconds and want to disable the endpoint for a set period of time in case the infrastructure is down and needs to recover.

答:
Dude, that's a brilliant idea!

It could even be made without touching the internals of Rebus, simply by hooking a decorator into the IErrorHandler, which would detect the error rate and then set the number of workers to 0 for a while.

If it's something you're interested in, you can raise it as an issue on GitHub.

Title: Rebus Circuit Breaker Implementation?


问:
openid attribute exchange
I'm trying to use JanRain openid, I've already added some of the required fields like email, nickname etc.. and some optional fields, but the openid provider doesn't send me back any information except the user's openid url.

I'm trying on localhost.  Any suggestions?

答:
Not every OpenID Provider would be able to reply for all your attribute requests since they might not have those information. Ever OpenID Provider specifies the attributes that they support for attribute exchange. </p>

<p>for example : Google supports only 5 attributes: firstname, lastname, email, language and country. You can find more info here. </p>

Title: openid attribute exchange

Body:
Not every OpenID Provider would be able to reply for all your attribute requests since they might not have those information. Ever OpenID Provider specifies the attributes that they support for attribute exchange.

for example : Google supports only 5 attributes: firstname, lastname, email, language and country. You can find more info here.


问:
Change Onclick Button Event to Page Onload Javascript
i have onclick button script alert, which is the alert displayed when i click the button. i need to modify the script, so the alert displayed when i load the page.

Button code :

```<code><button type="button" class="btn btn-success swalDefaultSuccess">
                  Launch Success Toast
</button>
</code>```

Javascript :

```<code><script type="text/javascript">
  $(function() {
    const Toast = Swal.mixin({
      toast: true,
      position: 'top-end',
      showConfirmButton: false,
      timer: 3000
    });

    $('.swalDefaultSuccess').click(function() {
      Toast.fire({
        type: 'success',
        title: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr.'
      })
    });

</script>
</code>```

anyone can help?
thanks

答:
There are many ways to get the page load event.

Explanation:
These examples below will register an event that will listen to document/window loads. They must be specified somewhere(preferred inside ) in page source.

This will show an alert when page loads document and related contents(images, etc)

```<code><script>
$(function(){
$(window).on('load', function(){
    Toast.fire({
        type: 'success',
        title: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr.'
    })
});
});
</script>
</code>```

Document ready will run after document is ready.

```<code><script>
$(function(){
$(document).ready(function(){
        Toast.fire({
            type: 'success',
            title: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr.'
        })
    });
});
</script>
</code>```

See https://learn.jquery.com/using-jquery-core/document-ready/

Vanilla Js

```<code><script>
document.addEventListener("DOMContentLoaded", function() {
  Toast.fire({
    type: 'success',
    title: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr.'
  })
});
</script>
</code>```

Alert on page Loading

```

Body:
i have onclick button script alert, which is the alert displayed when i click the button. i need to modify the script, so the alert displayed when i load the page.

Button code :

<button type="button" class="btn btn-success swalDefaultSuccess">
                  Launch Success Toast
</button>

Javascript :

anyone can help?
thanks

Body:
There are many ways to get the page load event.

Explanation:
These examples below will register an event that will listen to document/window loads. They must be specified somewhere(preferred inside ) in page source.

This will show an alert when page loads document and related contents(images, etc)

<script>
$(function(){
$(window).on('load', function(){
    Toast.fire({
        type: 'success',
        title: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr.'
    })
});
});
</script>

Document ready will run after document is ready.

<script>
$(function(){
$(document).ready(function(){
        Toast.fire({
            type: 'success',
            title: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr.'
        })
    });
});
</script>

See https://learn.jquery.com/using-jquery-core/document-ready/

Vanilla Js

<script>
document.addEventListener("DOMContentLoaded", function() {
  Toast.fire({
    type: 'success',
    title: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr.'
  })
});
</script>

<html>
  <head>
    <script>
      document.addEventListener("DOMContentLoaded", function() {
        alert("DOM loaded");
      });
    </script>
  </head>
  <body>
    <p>Alert on page Loading</p>
  </body>
</html>


问:
Incorrect line position with HTML Canvas when lineWidth is not set to 1
```<code>  function drawModule() {
    const lineWidth = 1
    context.lineWidth = lineWidth
    context.translate(0.5, 0.5)

    for (let k = 0; k < self.geometryParsed.length; k++) {
      const geometry = self.geometryParsed[k].geom
      const type = self.geometryParsed[k].typ

      context.beginPath()
      context.strokeStyle = self.unitMixTable[type]
      context.moveTo(
        Math.round(geometry[0].x),
        Math.round(geometry[0].y)
      )
      for (let i = 1; i < geometry.length; i++) {
        context.lineTo(
          Math.round(geometry[i].x),
          Math.round(geometry[i].y)
        )
        context.stroke()
      }
      context.closePath()
      context.fillStyle = 'white'
      context.fill()
    }
    context.translate(-0.5, -0.5)
  }
</code>```

Here is the code I use for drawing some polygons in the canvas, and it works as expected without problem. But when the lineWidth is 2, for example, the positions and opacity of the lines are slightly distorted.

picture of the result:

lineWidth = 1

lineWidth = 2

As you can see in red circle of the figure when lineWidth is 2, the lines are not aligned even if they share same x point. And in the rightmost rectange of each group, colors of the lines are not same.

What might the problem be? is there any point am I missing? thanks in advance!

reproduce: https://codepen.io/coldsewoo/pen/mdeZBev

答:
The fill is the root cause of your problems

const geometryParsed = [
  {
    geom: [{ x:78, y:132 }, { x:59, y:132 }, { x:59, y:183 }, { x:78, y:183 }, { x:78, y:132 }]
  },
  {
    geom: [{ x:97, y:132 }, { x:78, y:132 }, { x:78, y:166 }, { x:97, y:166 }, { x:97, y:132 }]
  },
];

const canv = document.getElementById("canvas");
const context = canv.getContext("2d");

context.translate(-50, -100)
context.lineWidth = 2;
for (let k = 0; k < geometryParsed.length; k++) {
  const geometry = geometryParsed[k].geom;
  context.beginPath();
  context.moveTo(geometry[0].x, geometry[0].y);
  for (let i = 1; i < geometry.length; i++) {
    context.lineTo(geometry[i].x, geometry[i].y);
  }
  context.stroke();
}

context.translate(80, 0)
context.lineWidth = 4;
for (let k = 0; k < geometryParsed.length; k++) {
  const geometry = geometryParsed[k].geom;
  context.beginPath();
  context.moveTo(geometry[0].x, geometry[0].y);
  for (let i = 1; i < geometry.length; i++) {
    context.lineTo(geometry[i].x, geometry[i].y);
  }
  context.stroke();
  context.fillStyle = "white";
  context.fill();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas" width="476px" height="170px"></canvas></code>```

Body:
  function drawModule() {
    const lineWidth = 1
    context.lineWidth = lineWidth
    context.translate(0.5, 0.5)

    for (let k = 0; k < self.geometryParsed.length; k++) {
      const geometry = self.geometryParsed[k].geom
      const type = self.geometryParsed[k].typ

      context.beginPath()
      context.strokeStyle = self.unitMixTable[type]
      context.moveTo(
        Math.round(geometry[0].x),
        Math.round(geometry[0].y)
      )
      for (let i = 1; i < geometry.length; i++) {
        context.lineTo(
          Math.round(geometry[i].x),
          Math.round(geometry[i].y)
        )
        context.stroke()
      }
      context.closePath()
      context.fillStyle = 'white'
      context.fill()
    }
    context.translate(-0.5, -0.5)
  }

Here is the code I use for drawing some polygons in the canvas, and it works as expected without problem. But when the lineWidth is 2, for example, the positions and opacity of the lines are slightly distorted.

picture of the result:

lineWidth = 1

lineWidth = 2

As you can see in red circle of the figure when lineWidth is 2, the lines are not aligned even if they share same x point. And in the rightmost rectange of each group, colors of the lines are not same.

What might the problem be? is there any point am I missing? thanks in advance!

reproduce: https://codepen.io/coldsewoo/pen/mdeZBev

Body:
The fill is the root cause of your problems

const geometryParsed = [
  {
    geom: [{ x:78, y:132 }, { x:59, y:132 }, { x:59, y:183 }, { x:78, y:183 }, { x:78, y:132 }]
  },
  {
    geom: [{ x:97, y:132 }, { x:78, y:132 }, { x:78, y:166 }, { x:97, y:166 }, { x:97, y:132 }]
  },
];

const canv = document.getElementById("canvas");
const context = canv.getContext("2d");

context.translate(-50, -100)
context.lineWidth = 2;
for (let k = 0; k < geometryParsed.length; k++) {
  const geometry = geometryParsed[k].geom;
  context.beginPath();
  context.moveTo(geometry[0].x, geometry[0].y);
  for (let i = 1; i < geometry.length; i++) {
    context.lineTo(geometry[i].x, geometry[i].y);
  }
  context.stroke();
}

context.translate(80, 0)
context.lineWidth = 4;
for (let k = 0; k < geometryParsed.length; k++) {
  const geometry = geometryParsed[k].geom;
  context.beginPath();
  context.moveTo(geometry[0].x, geometry[0].y);
  for (let i = 1; i < geometry.length; i++) {
    context.lineTo(geometry[i].x, geometry[i].y);
  }
  context.stroke();
  context.fillStyle = "white";
  context.fill();
}

<canvas id="canvas" width="476px" height="170px"></canvas>


问:
Spring reactive transaction gets committed on cancel producing partial commits
My project uses spring-data-mongodb, everything is reactive. There is a bean with a transactional method using declarative transactions. The relevant code fragments follow:

```<code>@Configuration
public class Config {

    @Bean
    public ReactiveMongoTransactionManager reactiveMongoTransactionManager() {
        return new ReactiveMongoTransactionManager(reactiveMongoDbFactory());
    }

    ...
}

@Service
public class MyService {
    private final ReactiveMongoOperations mongoOperations;

    ...

    @Transactional
    public Mono<User> saveUser(User user) {
        return mongoOperations.insert(user).then(anotherInsertOnMongoOperations()).thenReturn(user);
    }
}
</code>```

Nothing unusual here.

I can see in logs that the transactions get started before documents get inserted, and after that they are committed:

```<code>DEBUG o.s.d.m.ReactiveMongoTransactionManager -  About to start transaction for session [ClientSessionImpl@62de8058 id = {"id": {"$binary": "fye2h5JkRh6yL3MTqtC0Xw==", "$type": "04"}}, causallyConsistent = true, txActive = false, txNumber = 1, error = d != java.lang.Boolean].
DEBUG o.s.d.m.ReactiveMongoTransactionManager -  Started transaction for session [ClientSessionImpl@62de8058 id = {"id": {"$binary": "fye2h5JkRh6yL3MTqtC0Xw==", "$type": "04"}}, causallyConsistent = true, txActive = true, txNumber = 2, error = d != java.lang.Boolean].
</code>```

... inserts follow, then ...

```<code>DEBUG o.s.d.m.ReactiveMongoTransactionManager -  Initiating transaction commit
DEBUG o.s.d.m.ReactiveMongoTransactionManager -  About to commit transaction for session [ClientSessionImpl@62de8058 id = {"id": {"$binary": "fye2h5JkRh6yL3MTqtC0Xw==", "$type": "04"}}, causallyConsistent = true, txActive = true, txNumber = 2, error = d != java.lang.Boolean].
</code>```

But sometimes, as I can see by the contents of the database, only the first of the inserts is persisted, and the second is lost. After trying to model the situation, I found that this 'loss' happens when the whole reactive pipeline gets cancelled (not every time, but I was able to produce a test that reproduced the situation with high probability).

I added .doOnSuccessOrError() and .doOnCancel() with some logging after the final operator of my method. In the 'normal' case (without a cancel), doOnSuccessOrError logs successfully. But when a cancellation happens, sometimes the sequence of the events in the log is like this:

A transaction is initiated

An insert happens

A cancel occurs

nothing gets logged by the final doOnSuccessOrError(), and something is logged in the onCancel() there (so the cancellation seems to happen 'right in the middle' of the execution of the business method)

... but the transaction still gets committed!

TransactionAspectSupport.ReactiveTransactionSupport contains the following code (used for this case):

```<code>                            return Mono.<Object, ReactiveTransactionInfo>usingWhen(
                                    Mono.just(it),
                                    txInfo -> {
                                        try {
                                            return (Mono<?>) invocation.proceedWithInvocation();
                                        }
                                        catch (Throwable ex) {
                                            return Mono.error(ex);
                                        }
                                    },
                                    this::commitTransactionAfterReturning,
                                    (txInfo, err) -> Mono.empty(),
                                    this::commitTransactionAfterReturning)
</code>```

The last argument is onCancel handler.

This means that on cancel, the transaction actually gets committed.

The question is: why? When a cancellation happens due to reasons external to a reactive pipeline, there is a probability that some operations inside a transaction have completed and some haven't (and never will). Committing at such a moment produces a partial commit which violates the atomicity requirement.

It seems more logical to initiate a rollback instead. But I suppose that the authors of spring-tx did this choice on purpose. I wonder, what is the reason for this?

P.S. To verify my point, I patched spring-tx 5.2.3 (by the way, that's the version used by the project) so that the code looks like this:

```<code>                            return Mono.<Object, ReactiveTransactionInfo>usingWhen(
                                    Mono.just(it),
                                    txInfo -> {
                                        try {
                                            return (Mono<?>) invocation.proceedWithInvocation();
                                        }
                                        catch (Throwable ex) {
                                            return Mono.error(ex);
                                        }
                                    },
                                    this::commitTransactionAfterReturning,
                                    (txInfo, err) -> Mono.empty(),
                                    this::rollbackTransactionDueToCancel)

    private Mono<Void> rollbackTransactionDueToCancel(@Nullable ReactiveTransactionInfo txInfo) {
        if (txInfo != null && txInfo.getReactiveTransaction() != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Rolling transaction back for [" + txInfo.getJoinpointIdentification() + "] due to cancel");
            }
            return txInfo.getTransactionManager().rollback(txInfo.getReactiveTransaction());
        }
        return Mono.empty();
    }
</code>```

(basically, just changed the on-cancel behavior to rollback), and with this patch my tests do not produce any inconsistent data anymore.

答:
It turns out that indeed there is a possibility for a reactive Spring transaction to be committed half the way due to an unexpected cancel: https://github.com/spring-projects/spring-framework/issues/25091

The problem is due to the 'commit-on-cancel' policy. Spring guys are planning to switch it to 'rollback-on-cancel' policy in Spring 5.3. For now, the options are:

If some your transactions contain more than one write, use a custom build of spring-tx library with a fix like the following https://github.com/rpuch/spring-framework/commit/95c2872c0c3a8bebec06b413001148b28bc78f2a that switches to 'rollback-on-cancel' policy to avoid such unleasant surprises. But this would mean that perfectly valid Reactor operators (that use cancellation signal as a part of their normal functioning) would become unusable downstream from transactional operators (as a cancellation routinely issued by them will roll back a transaction).

If all your transactions have maximum one write each, then you are safe to stay with an unpatched Spring version. But please note that Spring guys are (currently) going to flip the policy in 5.3.

Here is an article on the matter: https://blog.rpuch.com/2020/05/25/spring-reactive-transactions-atomicity-violation.html (disclaimer: I'm the author of the article).

Body:
My project uses spring-data-mongodb, everything is reactive. There is a bean with a transactional method using declarative transactions. The relevant code fragments follow:

@Configuration
public class Config {

    @Bean
    public ReactiveMongoTransactionManager reactiveMongoTransactionManager() {
        return new ReactiveMongoTransactionManager(reactiveMongoDbFactory());
    }

    ...
}

@Service
public class MyService {
    private final ReactiveMongoOperations mongoOperations;

    ...

    @Transactional
    public Mono<User> saveUser(User user) {
        return mongoOperations.insert(user).then(anotherInsertOnMongoOperations()).thenReturn(user);
    }
}

Nothing unusual here.

I can see in logs that the transactions get started before documents get inserted, and after that they are committed:

DEBUG o.s.d.m.ReactiveMongoTransactionManager -  About to start transaction for session [ClientSessionImpl@62de8058 id = {"id": {"$binary": "fye2h5JkRh6yL3MTqtC0Xw==", "$type": "04"}}, causallyConsistent = true, txActive = false, txNumber = 1, error = d != java.lang.Boolean].
DEBUG o.s.d.m.ReactiveMongoTransactionManager -  Started transaction for session [ClientSessionImpl@62de8058 id = {"id": {"$binary": "fye2h5JkRh6yL3MTqtC0Xw==", "$type": "04"}}, causallyConsistent = true, txActive = true, txNumber = 2, error = d != java.lang.Boolean].

... inserts follow, then ...

DEBUG o.s.d.m.ReactiveMongoTransactionManager -  Initiating transaction commit
DEBUG o.s.d.m.ReactiveMongoTransactionManager -  About to commit transaction for session [ClientSessionImpl@62de8058 id = {"id": {"$binary": "fye2h5JkRh6yL3MTqtC0Xw==", "$type": "04"}}, causallyConsistent = true, txActive = true, txNumber = 2, error = d != java.lang.Boolean].

But sometimes, as I can see by the contents of the database, only the first of the inserts is persisted, and the second is lost. After trying to model the situation, I found that this 'loss' happens when the whole reactive pipeline gets cancelled (not every time, but I was able to produce a test that reproduced the situation with high probability).

I added .doOnSuccessOrError() and .doOnCancel() with some logging after the final operator of my method. In the 'normal' case (without a cancel), doOnSuccessOrError logs successfully. But when a cancellation happens, sometimes the sequence of the events in the log is like this:

A transaction is initiated

An insert happens

A cancel occurs

nothing gets logged by the final doOnSuccessOrError(), and something is logged in the onCancel() there (so the cancellation seems to happen 'right in the middle' of the execution of the business method)

... but the transaction still gets committed!

TransactionAspectSupport.ReactiveTransactionSupport contains the following code (used for this case):

                            return Mono.<Object, ReactiveTransactionInfo>usingWhen(
                                    Mono.just(it),
                                    txInfo -> {
                                        try {
                                            return (Mono<?>) invocation.proceedWithInvocation();
                                        }
                                        catch (Throwable ex) {
                                            return Mono.error(ex);
                                        }
                                    },
                                    this::commitTransactionAfterReturning,
                                    (txInfo, err) -> Mono.empty(),
                                    this::commitTransactionAfterReturning)

The last argument is onCancel handler.

This means that on cancel, the transaction actually gets committed.

The question is: why? When a cancellation happens due to reasons external to a reactive pipeline, there is a probability that some operations inside a transaction have completed and some haven't (and never will). Committing at such a moment produces a partial commit which violates the atomicity requirement.

It seems more logical to initiate a rollback instead. But I suppose that the authors of spring-tx did this choice on purpose. I wonder, what is the reason for this?

P.S. To verify my point, I patched spring-tx 5.2.3 (by the way, that's the version used by the project) so that the code looks like this:

                            return Mono.<Object, ReactiveTransactionInfo>usingWhen(
                                    Mono.just(it),
                                    txInfo -> {
                                        try {
                                            return (Mono<?>) invocation.proceedWithInvocation();
                                        }
                                        catch (Throwable ex) {
                                            return Mono.error(ex);
                                        }
                                    },
                                    this::commitTransactionAfterReturning,
                                    (txInfo, err) -> Mono.empty(),
                                    this::rollbackTransactionDueToCancel)

    private Mono<Void> rollbackTransactionDueToCancel(@Nullable ReactiveTransactionInfo txInfo) {
        if (txInfo != null && txInfo.getReactiveTransaction() != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Rolling transaction back for [" + txInfo.getJoinpointIdentification() + "] due to cancel");
            }
            return txInfo.getTransactionManager().rollback(txInfo.getReactiveTransaction());
        }
        return Mono.empty();
    }

(basically, just changed the on-cancel behavior to rollback), and with this patch my tests do not produce any inconsistent data anymore.


问:
Combine two columns containing lists of first and last names into one column that has a list of full names
My dataframe has many columns. Two of them are first and last, which contain lists of first and last names, respectively. Some of the names are missing and have blank strings in their place. But the first item in the first list matches up with the first item in the last list.

```<code>     first                                         last
0    ['john','alex','james','mike','sarah']        ['smith','','connor','michaels','fort']
1    ['stephen','', 'brittany', 'mandy']           ['chambers','ronalds','','moore']
2    ['guy', 'alec', 'tyrone', 'joe','','amy']     ['lafluer','baldwin','james','montana','','adams']
</code>```

I want to combine these lists into one column to get the column name, which contains a list of both the first and last names. So in this example the result would be:

```<code>     name
0    ['john smith','alex ','james ','mike michaels','sarah fort']
1    ['stephen chambers',' ronalds', 'brittany ', 'mandy moore']
2    ['guy lafluer', 'alec baldwin', 'tyrone james', 'joe montana',' ','amy adams']
</code>```

Combining two string columns in pandas is easy, with df['col3'] = df['col1'] + df['col2'], but I am not sure how to do that and get two lists together in this way.

答:
You can use zip with list comprehension:

```<code>df['name'] = df.apply(lambda x: [m + ' ' + n for m,n in zip(x['first'], x['last'])], 1)
</code>```

OR

```<code>df['name'] = df.apply(lambda x: [' '.join(x) for x in zip(x['first'],x['last'])], 1)
</code>```

Body:
My dataframe has many columns. Two of them are first and last, which contain lists of first and last names, respectively. Some of the names are missing and have blank strings in their place. But the first item in the first list matches up with the first item in the last list.

     first                                         last
0    ['john','alex','james','mike','sarah']        ['smith','','connor','michaels','fort']
1    ['stephen','', 'brittany', 'mandy']           ['chambers','ronalds','','moore']
2    ['guy', 'alec', 'tyrone', 'joe','','amy']     ['lafluer','baldwin','james','montana','','adams']

I want to combine these lists into one column to get the column name, which contains a list of both the first and last names. So in this example the result would be:

     name
0    ['john smith','alex ','james ','mike michaels','sarah fort']
1    ['stephen chambers',' ronalds', 'brittany ', 'mandy moore']
2    ['guy lafluer', 'alec baldwin', 'tyrone james', 'joe montana',' ','amy adams']

Combining two string columns in pandas is easy, with df['col3'] = df['col1'] + df['col2'], but I am not sure how to do that and get two lists together in this way.

Body:
You can use zip with list comprehension:

df['name'] = df.apply(lambda x: [m + ' ' + n for m,n in zip(x['first'], x['last'])], 1)

OR

df['name'] = df.apply(lambda x: [' '.join(x) for x in zip(x['first'],x['last'])], 1)


问:
How to center flutter text with other widgets in row
I created a row with a BackButton and a TextWidget.
I want to center the text to the middle of the screen. Actually flutter centeres the text to the containers width, but the containers width isnt the same as the screen width, because there is the backbutton. How do i fix that?

```<code>  Expanded getTitle() {
    return new Expanded(
        child: new Text("Einloggen", style: new TextStyle(fontSize: 18.0), textAlign: TextAlign.center)
    );
  }

  BackButton getBackButton() {
    return new BackButton(

    );
  }

  Row getHeader() {
    return new Row(
      children: <Widget>[
        getBackButton(),
        getTitle()
      ],
    );
  }
  @override
  Widget build(BuildContext context) {
    final double statusBarHeight = MediaQuery.of(context).padding.top;
    return new Material(
      child: new Container(
        padding: new EdgeInsets.fromLTRB(0.0, statusBarHeight, 0.0, 0.0),
        child: new Column(
          children: <Widget>[
            getHeader()
          ],
        ),
      ),
    );
  }
</code>```

答:
Based on your code

```<code>  Widget getTitle() {
    return const Text('Einloggen',
        style: TextStyle(fontSize: 18.0), textAlign: TextAlign.center);
  }

  BackButton getBackButton() {
    return const BackButton();
  }

  Row getHeader() {
    return  Row(
      children: <Widget>[
        Expanded(
          child: getBackButton(),
        ),
        const Spacer(),
        getTitle(),
        const Spacer(flex: 2)
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    final double statusBarHeight = MediaQuery.of(context).padding.top;
    return Material(
      child: Container(
        padding: EdgeInsets.fromLTRB(0.0, statusBarHeight, 0.0, 0.0),
        child: Column(
          children: <Widget>[getHeader()],
        ),
      ),
    );
  }
</code>```

Body:
I created a row with a BackButton and a TextWidget.
I want to center the text to the middle of the screen. Actually flutter centeres the text to the containers width, but the containers width isnt the same as the screen width, because there is the backbutton. How do i fix that?

  Expanded getTitle() {
    return new Expanded(
        child: new Text("Einloggen", style: new TextStyle(fontSize: 18.0), textAlign: TextAlign.center)
    );
  }

  BackButton getBackButton() {
    return new BackButton(

    );
  }

  Row getHeader() {
    return new Row(
      children: <Widget>[
        getBackButton(),
        getTitle()
      ],
    );
  }
  @override
  Widget build(BuildContext context) {
    final double statusBarHeight = MediaQuery.of(context).padding.top;
    return new Material(
      child: new Container(
        padding: new EdgeInsets.fromLTRB(0.0, statusBarHeight, 0.0, 0.0),
        child: new Column(
          children: <Widget>[
            getHeader()
          ],
        ),
      ),
    );
  }

Body:
Based on your code

  Widget getTitle() {
    return const Text('Einloggen',
        style: TextStyle(fontSize: 18.0), textAlign: TextAlign.center);
  }

  BackButton getBackButton() {
    return const BackButton();
  }

  Row getHeader() {
    return  Row(
      children: <Widget>[
        Expanded(
          child: getBackButton(),
        ),
        const Spacer(),
        getTitle(),
        const Spacer(flex: 2)
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    final double statusBarHeight = MediaQuery.of(context).padding.top;
    return Material(
      child: Container(
        padding: EdgeInsets.fromLTRB(0.0, statusBarHeight, 0.0, 0.0),
        child: Column(
          children: <Widget>[getHeader()],
        ),
      ),
    );
  }