问:
mongoengine dereferencing nested documents
I have a several comples mongo models. For example, a User that references a Role with some properties. Now when I retrieve users, I want the role property to be populated with those of the referenced role object, not the object id.

from mongoengine import *

connect('test_database')

class Role(Document):
    name = StringField(required=True)
    description = StringField(required=True)

class User(Document):
    role = ReferenceField(Role, reverse_delete_rule=DENY)

r = Role(name='test', description='foo').save()
User(role=r).save()

print(User.objects().select_related()[0].to_mongo().to_dict())

# prints: {'_id': ObjectId('5c769af4e98fc24f4a82fd99'), 'role': ObjectId('5c769af4e98fc24f4a82fd98')}
# want:   {'_id': '5c769af4e98fc24f4a82fd99', 'role': {'name' : 'test', 'description' : 'foo'}}

```

How do I go about achieving this, for any complex mongoengine object?

答: Mongoengine does not provide anything out of the box but you can either define a method (e.g to_dict(self)) on your Document class, or use a serialisation library like marshmallow-mongoengine </p>

Body:
I have a several comples mongo models. For example, a User that references a Role with some properties. Now when I retrieve users, I want the role property to be populated with those of the referenced role object, not the object id.

from mongoengine import *

connect('test_database')

class Role(Document):
    name = StringField(required=True)
    description = StringField(required=True)

class User(Document):
    role = ReferenceField(Role, reverse_delete_rule=DENY)

r = Role(name='test', description='foo').save()
User(role=r).save()

print(User.objects().select_related()[0].to_mongo().to_dict())

# prints: {'_id': ObjectId('5c769af4e98fc24f4a82fd99'), 'role': ObjectId('5c769af4e98fc24f4a82fd98')}
# want:   {'_id': '5c769af4e98fc24f4a82fd99', 'role': {'name' : 'test', 'description' : 'foo'}}

How do I go about achieving this, for any complex mongoengine object?


来源: stackexchange

问:
Jekyll does not render the webpge in localhost
I have a github page, and I want to build a local enviroment to develop it using gulp. I've installed both Jekyll and gulp, and when I execute
    gulp
I get the following output in the terminal

```<code>Onurcans-MacBook-Air:onurcanbektas.github.io onurcanbektas$ gulp
[17:42:02] Using gulpfile /Volumes/Junction/Academia/wwwhome/onurcanbektas.github.io/onurcanbektas.github.io/gulpfile.js
[17:42:02] Starting 'js'...
[17:42:02] Finished 'js' after 11 ms
[17:42:02] Starting 'sass'...
[17:42:02] Finished 'sass' after 2.03 ms
[17:42:02] Starting 'stylus'...
[17:42:02] Finished 'stylus' after 2.92 ms
[17:42:02] Starting 'browser-sync'...
[17:42:02] Finished 'browser-sync' after 46 ms
[17:42:02] Starting 'watch'...
[17:42:02] Finished 'watch' after 38 ms
[17:42:02] Starting 'default'...
[17:42:02] Finished 'default' after 53 μs
[BS] 0 file changed ()
[BS] Local URL: http://localhost:3000
[BS] External URL: http://192.168.1.113:3000
[BS] Serving files from: ./
[BS] 1 file changed (main.css)
[BS] 1 file changed (main.js)
</code>```

However, the output of the webpage in the browser is

Moreover, when I run gulp, I only see /asset/css/main.css file there, and noting else; that is why, I changed base directory to "./" from "_site" in the orijinal gulpfile.js

Some information about my setup: I use OSX El capitan 11.1.2

```<code>$ruby -v
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin15]

$ gem -v
3.0.3

$ gem env
- GEM PATHS:
 - /usr/local/lib/ruby/gems/2.6.0
 - /Users/onurcanbektas/.gem/ruby/2.6.0
 - /usr/local/Cellar/ruby/2.6.3/lib/ruby/gems/2.6.0
</code>```

The gulpfile.js:

```<code>    var gulp        = require('gulp'),
    plumber     = require('gulp-plumber'),
    browserSync = require('browser-sync'),
    stylus      = require('gulp-stylus'),
    uglify      = require('gulp-uglify'),
    concat      = require('gulp-concat'),
    sass        = require('gulp-sass'),
    jeet        = require('jeet'),
    rupture     = require('rupture'),
    koutoSwiss  = require('kouto-swiss'),
    prefixer    = require('autoprefixer-stylus'),
    imagemin    = require('gulp-imagemin'),
    cp          = require('child_process');

var messages = {
    jekyllBuild: '<span style="color: grey">Running:</span> $ jekyll build'
};

var jekyllCommand = (/^win/.test(process.platform)) ? 'jekyll.bat' : 'jekyll';

/**
 * Build the Jekyll Site
 */
gulp.task('jekyll-build', function (done) {
    browserSync.notify(messages.jekyllBuild);
     cp.spawn(jekyllCommand, ['build'], {stdio: 'inherit'})
        .on('close', done);
});

/**
 * Rebuild Jekyll & do page reload
 */
gulp.task('jekyll-rebuild', ['jekyll-build'], function () {
    browserSync.reload();
});

/**
 * Wait for jekyll-build, then launch the Server
 */
gulp.task('browser-sync', function() {
    gulp.task('jekyll-build');
    browserSync({
        server: {
            baseDir: './',
        }
    });
});

/**
 * Stylus task
 */
gulp.task('stylus', function(){
        gulp.src('src/styl/main.styl')
        .pipe(plumber())
        .pipe(stylus({
            use:[koutoSwiss(), prefixer(), jeet(),rupture()],
            compress: true
        }))
        .pipe(gulp.dest('_site/assets/css/'))
        .pipe(browserSync.reload({stream:true}))
    .pipe(gulp.dest('assets/css'));
});

/**
 * Javascript Task
 */
gulp.task('js', function(){
     gulp.src('src/js/**/*.js')
        .pipe(plumber())
        .pipe(concat('main.js'))
        .pipe(uglify())
        .pipe(gulp.dest('assets/js/'))
        .pipe(browserSync.reload({stream:true}))
    .pipe(gulp.dest('_site/assets/js/'));
});

gulp.task('sass', function () {
     gulp.src('assets/css/main.scss')
        .pipe(sass({
            includePaths: ['css'],
            onError: browserSync.notify
        }))
        .pipe(plumber())
        .pipe(gulp.dest('_site/assets/css'))
        .pipe(browserSync.reload({stream:true}))
        .pipe(gulp.dest('assets/css'));
});

/**
 * Imagemin Task
 */
gulp.task('imagemin', function() {
    return gulp.src('src/img/**/*.{jpg,png,gif}')
        .pipe(plumber())
        .pipe(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))
        .pipe(gulp.dest('assets/img/'));
});

/**
 * Watch stylus files for changes & recompile
 * Watch html/md files, run jekyll & reload BrowserSync
 */
gulp.task('watch', function () {
    gulp.watch('src/styl/**/*.styl', ['stylus']);
    gulp.watch('src/js/**/*.js', ['js']);
    gulp.watch('src/css/**/*.css', ['sass']);
    gulp.watch('src/img/**/*.{jpg,png,gif}', ['imagemin']);
    gulp.watch(['*.html', '_includes/*.html', '_layouts/*.html', '_posts/*'], ['jekyll-rebuild']);
});

/**
 * Default task, running just `gulp` will compile the stylus,
 * compile the jekyll site, launch BrowserSync & watch files.
 */

/**var connect = require('gulp-connect');

gulp.task('connect', function() {
  connect.server({
    root: './',
    livereload: true
  })
});*/

gulp.task('default', ['js', 'sass', 'stylus', 'browser-sync', 'watch']);
</code>```

答:
I solved this problem by following this installation and creating a style.scss file in

./asses/css/style.scss
  with the content

```<code>---
---

@charset "UTF-8";
</code>```

Then by running

bundle exec jekyll serve

Everyting went fine.

ContentLicense: CC BY-SA 4.0

Body:
I have a github page, and I want to build a local enviroment to develop it using gulp. I've installed both Jekyll and gulp, and when I execute
    gulp
I get the following output in the terminal

Onurcans-MacBook-Air:onurcanbektas.github.io onurcanbektas$ gulp
[17:42:02] Using gulpfile /Volumes/Junction/Academia/wwwhome/onurcanbektas.github.io/onurcanbektas.github.io/gulpfile.js
[17:42:02] Starting 'js'...
[17:42:02] Finished 'js' after 11 ms
[17:42:02] Starting 'sass'...
[17:42:02] Finished 'sass' after 2.03 ms
[17:42:02] Starting 'stylus'...
[17:42:02] Finished 'stylus' after 2.92 ms
[17:42:02] Starting 'browser-sync'...
[17:42:02] Finished 'browser-sync' after 46 ms
[17:42:02] Starting 'watch'...
[17:42:02] Finished 'watch' after 38 ms
[17:42:02] Starting 'default'...
[17:42:02] Finished 'default' after 53 μs
[BS] 0 file changed ()
[BS] Local URL: http://localhost:3000
[BS] External URL: http://192.168.1.113:3000
[BS] Serving files from: ./
[BS] 1 file changed (main.css)
[BS] 1 file changed (main.js)

However, the output of the webpage in the browser is

Moreover, when I run gulp, I only see /asset/css/main.css file there, and noting else; that is why, I changed base directory to "./" from "_site" in the orijinal gulpfile.js

Some information about my setup: I use OSX El capitan 11.1.2

$ruby -v
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin15]

$ gem -v
3.0.3

$ gem env
- GEM PATHS:
 - /usr/local/lib/ruby/gems/2.6.0
 - /Users/onurcanbektas/.gem/ruby/2.6.0
 - /usr/local/Cellar/ruby/2.6.3/lib/ruby/gems/2.6.0

The gulpfile.js:

    var gulp        = require('gulp'),
    plumber     = require('gulp-plumber'),
    browserSync = require('browser-sync'),
    stylus      = require('gulp-stylus'),
    uglify      = require('gulp-uglify'),
    concat      = require('gulp-concat'),
    sass        = require('gulp-sass'),
    jeet        = require('jeet'),
    rupture     = require('rupture'),
    koutoSwiss  = require('kouto-swiss'),
    prefixer    = require('autoprefixer-stylus'),
    imagemin    = require('gulp-imagemin'),
    cp          = require('child_process');

var messages = {
    jekyllBuild: 'Running: $ jekyll build'
};

var jekyllCommand = (/^win/.test(process.platform)) ? 'jekyll.bat' : 'jekyll';

/**
 * Build the Jekyll Site
 */
gulp.task('jekyll-build', function (done) {
    browserSync.notify(messages.jekyllBuild);
     cp.spawn(jekyllCommand, ['build'], {stdio: 'inherit'})
        .on('close', done);
});

/**
 * Rebuild Jekyll & do page reload
 */
gulp.task('jekyll-rebuild', ['jekyll-build'], function () {
    browserSync.reload();
});

/**
 * Wait for jekyll-build, then launch the Server
 */
gulp.task('browser-sync', function() {
    gulp.task('jekyll-build');
    browserSync({
        server: {
            baseDir: './',
        }
    });
});

/**
 * Stylus task
 */
gulp.task('stylus', function(){
        gulp.src('src/styl/main.styl')
        .pipe(plumber())
        .pipe(stylus({
            use:[koutoSwiss(), prefixer(), jeet(),rupture()],
            compress: true
        }))
        .pipe(gulp.dest('_site/assets/css/'))
        .pipe(browserSync.reload({stream:true}))
    .pipe(gulp.dest('assets/css'));
});

/**
 * Javascript Task
 */
gulp.task('js', function(){
     gulp.src('src/js/**/*.js')
        .pipe(plumber())
        .pipe(concat('main.js'))
        .pipe(uglify())
        .pipe(gulp.dest('assets/js/'))
        .pipe(browserSync.reload({stream:true}))
    .pipe(gulp.dest('_site/assets/js/'));
});

gulp.task('sass', function () {
     gulp.src('assets/css/main.scss')
        .pipe(sass({
            includePaths: ['css'],
            onError: browserSync.notify
        }))
        .pipe(plumber())
        .pipe(gulp.dest('_site/assets/css'))
        .pipe(browserSync.reload({stream:true}))
        .pipe(gulp.dest('assets/css'));
});

/**
 * Imagemin Task
 */
gulp.task('imagemin', function() {
    return gulp.src('src/img/**/*.{jpg,png,gif}')
        .pipe(plumber())
        .pipe(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))
        .pipe(gulp.dest('assets/img/'));
});

/**
 * Watch stylus files for changes & recompile
 * Watch html/md files, run jekyll & reload BrowserSync
 */
gulp.task('watch', function () {
    gulp.watch('src/styl/**/*.styl', ['stylus']);
    gulp.watch('src/js/**/*.js', ['js']);
    gulp.watch('src/css/**/*.css', ['sass']);
    gulp.watch('src/img/**/*.{jpg,png,gif}', ['imagemin']);
    gulp.watch(['*.html', '_includes/*.html', '_layouts/*.html', '_posts/*'], ['jekyll-rebuild']);
});

/**
 * Default task, running just `gulp` will compile the stylus,
 * compile the jekyll site, launch BrowserSync & watch files.
 */

/**var connect = require('gulp-connect');

gulp.task('connect', function() {
  connect.server({
    root: './',
    livereload: true
  })
});*/

gulp.task('default', ['js', 'sass', 'stylus', 'browser-sync', 'watch']);

Body:
I solved this problem by following this installation and creating a style.scss file in

./asses/css/style.scss
  with the content

---
---

@charset "UTF-8";

Then by running

bundle exec jekyll serve

Everyting went fine.


问:
Why is this ifelse statement producing NAs?
I am trying to create a new variable based on other variables in my dataset. I have used ifelse to do similar tasks, however when I have tried it this time I am getting NA when the condition is not met.

The variables I want to base the new variable on are all binary - "Yes" or "No". I want to the new variable to be coded "Yes" if any of the other variables are "Yes" and "No" if none of them are coded "Yes". When I run the ifelse, I get the expected number of "Yes", but what I would expect to be "No" is NA.

I have tried the following:

```<code>data$new <- ifelse(var1=="Yes" | var2=="Yes" | var3=="Yes","Yes","No")
</code>```

Any help would be greatly appreciated. I have changed the names of the data and put three variables in the example. There are actually 22 variables in total with very similar names, I tried to simplify the example. If seeing the actual data / code would be helpful I'll add this in.

Thanks!

答:
try complete.cases() to omit NA's while creating the variable</p>

```<code>df$new <- ifelse((var1 =="Yes"| var2=="Yes"|var3=="Yes")& complete.cases(df), "Yes", "No")

</code>```

Body:
I am trying to create a new variable based on other variables in my dataset. I have used ifelse to do similar tasks, however when I have tried it this time I am getting NA when the condition is not met.

The variables I want to base the new variable on are all binary - "Yes" or "No". I want to the new variable to be coded "Yes" if any of the other variables are "Yes" and "No" if none of them are coded "Yes". When I run the ifelse, I get the expected number of "Yes", but what I would expect to be "No" is NA.

I have tried the following:

data$new <- ifelse(var1=="Yes" | var2=="Yes" | var3=="Yes","Yes","No")

Any help would be greatly appreciated. I have changed the names of the data and put three variables in the example. There are actually 22 variables in total with very similar names, I tried to simplify the example. If seeing the actual data / code would be helpful I'll add this in.

Thanks!

Body:
try complete.cases() to omit NA's while creating the variable

df$new <- ifelse((var1 =="Yes"| var2=="Yes"|var3=="Yes")& complete.cases(df), "Yes", "No")


问:
Python multiprocessing: print() inside apply_async()
print() inside the function that is passed to multiprocessing's apply_async() does not print out anything.

I want to eventually use apply_async to process a large text file in chunks. Therefore, I want the script to print out on the screen how many lines have been processed. However, I don't see any print out at all.

I've attached a toy code. Each foo() call should tell me what process is being used. In my actual code, I will call foo() on each chunk, and it will tell me how many lines of text in that chunk I've processed.

import os
from multiprocessing import Pool

def foo(x,y):
    print(f'Process: {os.getpid()}')
    return(x*y)

def bar(x):
    p = Pool()
    result_list = []
    for i in range(30):
        p.apply_async(foo, args=(i,i*x), callback=result_list.append)
    p.close()
    p.join()
    return(result_list)

if __name__ == '__main__':
    print(bar(2))
```

I got a print out of the multiplication x*y result, but I didn't see any print out that tells me the process id.

Can anyone help me please?

答:
Your sys.stdout is likely block buffered, which means a small number of prints can get buffered without filling the buffer (and therefore the buffer is never flushed to the screen/file). Normally, Python flushes the buffers on exit so this isn't an issue.

Problem is, to avoid a bunch of tricky issues with doubled-cleanup, when using multiprocessing, the workers exit using os._exit, which bypasses all cleanup procedures (including flushing stdio buffers). If you want to be sure the output is emitted, tell print to flush the output immediately by changing:

```<code>print(f'Process: {os.getpid()}')
</code>```

to:

```<code>print(f'Process: {os.getpid()}', flush=True)
</code>```

Body:
print() inside the function that is passed to multiprocessing's apply_async() does not print out anything.

I want to eventually use apply_async to process a large text file in chunks. Therefore, I want the script to print out on the screen how many lines have been processed. However, I don't see any print out at all.

I've attached a toy code. Each foo() call should tell me what process is being used. In my actual code, I will call foo() on each chunk, and it will tell me how many lines of text in that chunk I've processed.

import os
from multiprocessing import Pool

def foo(x,y):
    print(f'Process: {os.getpid()}')
    return(x*y)

def bar(x):
    p = Pool()
    result_list = []
    for i in range(30):
        p.apply_async(foo, args=(i,i*x), callback=result_list.append)
    p.close()
    p.join()
    return(result_list)

if __name__ == '__main__':
    print(bar(2))

I got a print out of the multiplication x*y result, but I didn't see any print out that tells me the process id.

Can anyone help me please?

Body:
Your sys.stdout is likely block buffered, which means a small number of prints can get buffered without filling the buffer (and therefore the buffer is never flushed to the screen/file). Normally, Python flushes the buffers on exit so this isn't an issue.

Problem is, to avoid a bunch of tricky issues with doubled-cleanup, when using multiprocessing, the workers exit using os._exit, which bypasses all cleanup procedures (including flushing stdio buffers). If you want to be sure the output is emitted, tell print to flush the output immediately by changing:

print(f'Process: {os.getpid()}')

to:

print(f'Process: {os.getpid()}', flush=True)


问:
XNA Rectangle intersection
I recently started on XNA development and having some (very limited) experience with it in the past, I decided to try and make a Pong clone to see how much I could remember. Most of what I knew came back to me, but I am having problems with collision detection between the bats and the ball. I have 3 rectangles set to update position along with the sprites that I am using, and when the ball rectangle intersects with a bat rectangle, I multiply the X speed of the ball by -1. However this produces an unusual effect by which the ball bounces around the bat as shown in this video.What am I doing wrong here?

Here is the code for this project (poor, I know):

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Pong
{

public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    System.Random generator = new Random();

    Texture2D ball;
    Texture2D bat1;
    Texture2D bat2;
    Texture2D middle;

    Vector2 midPos;
    Vector2 bat1Pos;
    Vector2 bat2Pos;
    Vector2 ballPos;
    Vector2 ballVelo;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    protected override void Initialize()
    {
        base.Initialize();
    }

    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        //Load sprites
        ball = Content.Load<Texture2D>(@"sprites/pongball");
        bat1 = Content.Load<Texture2D>(@"sprites/pongbat");
        bat2 = Content.Load<Texture2D>(@"sprites/pongbat");
        middle = Content.Load<Texture2D>(@"sprites/pongmiddle");

        //Set default sprite positions
        midPos.X = (Window.ClientBounds.Width / 2) - 5;
        midPos.Y = 0;

        bat1Pos.X = 10;
        bat1Pos.Y = (Window.ClientBounds.Height/2) - 50;

        bat2Pos.X = Window.ClientBounds.Width - 20;
        bat2Pos.Y = (Window.ClientBounds.Height/2) - 50;

        ballPos.X = (Window.ClientBounds.Width / 2) - 5;
        ballPos.Y = (Window.ClientBounds.Height / 2) - 5;

        //Generate random ball velocity
        ballVelo.X = generator.Next(5,10);
        ballVelo.Y = generator.Next(4, 7);
    }

    protected override void UnloadContent()
    {

    }

    protected override void Update(GameTime gameTime)
    {

        //Update rectangle values
        Rectangle bat1Rect = new Rectangle((int)bat1Pos.X, (int)bat1Pos.Y, 10, 100);
        Rectangle bat2Rect = new Rectangle((int)bat2Pos.X, (int)bat2Pos.Y, 10, 100);
        Rectangle ballRect = new Rectangle((int)ballPos.X, (int)ballPos.Y, 10, 100);

        //Move ball
        ballPos += ballVelo;

        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();
        if (Keyboard.GetState().IsKeyDown(Keys.Escape))
            this.Exit();

        //Bat 1 movement and restriction
        if (Keyboard.GetState().IsKeyDown(Keys.Up))
            bat1Pos.Y -= 4;

        if (Keyboard.GetState().IsKeyDown(Keys.Down))
            bat1Pos.Y += 4;

        if (bat1Pos.Y <= 0)
            bat1Pos.Y = 0;

        if (bat1Pos.Y >= Window.ClientBounds.Height - 100)
            bat1Pos.Y = Window.ClientBounds.Height - 100;

        //Bat 2 movement and restriction
        if (Keyboard.GetState().IsKeyDown(Keys.W))
            bat2Pos.Y -= 4;

        if (Keyboard.GetState().IsKeyDown(Keys.S))
            bat2Pos.Y += 4;

        if (bat2Pos.Y <= 0)
            bat2Pos.Y = 0;

        if (bat2Pos.Y >= Window.ClientBounds.Height - 100)
            bat2Pos.Y = Window.ClientBounds.Height - 100;

        //Ball movement restrictions
        if (ballPos.X <= 0)
            ballVelo.X *= -1;

        if (ballPos.Y <= 0)
            ballVelo.Y *= -1;

        if (ballPos.X >= Window.ClientBounds.Width - 5)
            ballVelo.X *= -1;

        if (ballPos.Y >= Window.ClientBounds.Height - 5)
            ballVelo.Y *= -1;

        //Collision detection between bats and ball
        if (ballRect.Intersects(bat1Rect))
        {
            ballVelo.X *= -1;
        }

        if (ballRect.Intersects(bat2Rect))
        {
            ballVelo.X *= -1;
        }

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Black);

        spriteBatch.Begin();
        spriteBatch.Draw(middle, midPos, Color.White);
        spriteBatch.Draw(bat1, bat1Pos, Color.White);
        spriteBatch.Draw(bat2, bat2Pos, Color.White);
        spriteBatch.Draw(ball, ballPos, Color.White);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}
}
</code>```

答:
One way around this would be to do make the following change to your ballRect.Intersect(barXRect)) if statements:

```<code>    if (ballRect.Intersects(bat1Rect))
    {
        ballVelo.X = Math.Abs(ballVelo.X) * -1;
    }

    if (ballRect.Intersects(bat2Rect))
    {
        ballVelo.X = Math.Abs(ballVelo.X);
    }
</code>```

This way the left bar will only send the ball right, and the right bar will only send it left.  I may have the bars around the wrong way, so it might be best to double check, but it just means moving the * -1 to the other bat.

ContentLicense: CC BY-SA 3.0

Title: XNA Rectangle intersection

Body:
I recently started on XNA development and having some (very limited) experience with it in the past, I decided to try and make a Pong clone to see how much I could remember. Most of what I knew came back to me, but I am having problems with collision detection between the bats and the ball. I have 3 rectangles set to update position along with the sprites that I am using, and when the ball rectangle intersects with a bat rectangle, I multiply the X speed of the ball by -1. However this produces an unusual effect by which the ball bounces around the bat as shown in this video.What am I doing wrong here?

Here is the code for this project (poor, I know):

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Pong
{

public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    System.Random generator = new Random();

    Texture2D ball;
    Texture2D bat1;
    Texture2D bat2;
    Texture2D middle;

    Vector2 midPos;
    Vector2 bat1Pos;
    Vector2 bat2Pos;
    Vector2 ballPos;
    Vector2 ballVelo;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    protected override void Initialize()
    {
        base.Initialize();
    }

    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        //Load sprites
        ball = Content.Load<Texture2D>(@"sprites/pongball");
        bat1 = Content.Load<Texture2D>(@"sprites/pongbat");
        bat2 = Content.Load<Texture2D>(@"sprites/pongbat");
        middle = Content.Load<Texture2D>(@"sprites/pongmiddle");

        //Set default sprite positions
        midPos.X = (Window.ClientBounds.Width / 2) - 5;
        midPos.Y = 0;

        bat1Pos.X = 10;
        bat1Pos.Y = (Window.ClientBounds.Height/2) - 50;

        bat2Pos.X = Window.ClientBounds.Width - 20;
        bat2Pos.Y = (Window.ClientBounds.Height/2) - 50;

        ballPos.X = (Window.ClientBounds.Width / 2) - 5;
        ballPos.Y = (Window.ClientBounds.Height / 2) - 5;

        //Generate random ball velocity
        ballVelo.X = generator.Next(5,10);
        ballVelo.Y = generator.Next(4, 7);
    }

    protected override void UnloadContent()
    {

    }

    protected override void Update(GameTime gameTime)
    {

        //Update rectangle values
        Rectangle bat1Rect = new Rectangle((int)bat1Pos.X, (int)bat1Pos.Y, 10, 100);
        Rectangle bat2Rect = new Rectangle((int)bat2Pos.X, (int)bat2Pos.Y, 10, 100);
        Rectangle ballRect = new Rectangle((int)ballPos.X, (int)ballPos.Y, 10, 100);

        //Move ball
        ballPos += ballVelo;

        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();
        if (Keyboard.GetState().IsKeyDown(Keys.Escape))
            this.Exit();

        //Bat 1 movement and restriction
        if (Keyboard.GetState().IsKeyDown(Keys.Up))
            bat1Pos.Y -= 4;

        if (Keyboard.GetState().IsKeyDown(Keys.Down))
            bat1Pos.Y += 4;

        if (bat1Pos.Y <= 0)
            bat1Pos.Y = 0;

        if (bat1Pos.Y >= Window.ClientBounds.Height - 100)
            bat1Pos.Y = Window.ClientBounds.Height - 100;

        //Bat 2 movement and restriction
        if (Keyboard.GetState().IsKeyDown(Keys.W))
            bat2Pos.Y -= 4;

        if (Keyboard.GetState().IsKeyDown(Keys.S))
            bat2Pos.Y += 4;

        if (bat2Pos.Y <= 0)
            bat2Pos.Y = 0;

        if (bat2Pos.Y >= Window.ClientBounds.Height - 100)
            bat2Pos.Y = Window.ClientBounds.Height - 100;

        //Ball movement restrictions
        if (ballPos.X <= 0)
            ballVelo.X *= -1;

        if (ballPos.Y <= 0)
            ballVelo.Y *= -1;

        if (ballPos.X >= Window.ClientBounds.Width - 5)
            ballVelo.X *= -1;

        if (ballPos.Y >= Window.ClientBounds.Height - 5)
            ballVelo.Y *= -1;

        //Collision detection between bats and ball
        if (ballRect.Intersects(bat1Rect))
        {
            ballVelo.X *= -1;
        }

        if (ballRect.Intersects(bat2Rect))
        {
            ballVelo.X *= -1;
        }

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Black);

        spriteBatch.Begin();
        spriteBatch.Draw(middle, midPos, Color.White);
        spriteBatch.Draw(bat1, bat1Pos, Color.White);
        spriteBatch.Draw(bat2, bat2Pos, Color.White);
        spriteBatch.Draw(ball, ballPos, Color.White);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}
}

Body:
One way around this would be to do make the following change to your ballRect.Intersect(barXRect)) if statements:

    if (ballRect.Intersects(bat1Rect))
    {
        ballVelo.X = Math.Abs(ballVelo.X) * -1;
    }

    if (ballRect.Intersects(bat2Rect))
    {
        ballVelo.X = Math.Abs(ballVelo.X);
    }

This way the left bar will only send the ball right, and the right bar will only send it left.  I may have the bars around the wrong way, so it might be best to double check, but it just means moving the * -1 to the other bat.


问:
Create a list from 0 to N
How can I create easily a range of consecutive integers in dart? For example:</p>

```<code>// throws a syntax error :)
var list = [1..10];
</code>```

答:
I have been using a modified version of Alexandre Ardhuin's which tries to mimic the range() provided by python Edit: found out optional positional arguments are a thing updated code below

```<code>range(int stop, {int start: 0, int step: 1}){
  if (step == 0)
    throw Exception("Step cannot be 0");

  return start < stop == step > 0
  ? List<int>.generate(((start-stop)/step).abs().ceil(), (int i) => start + (i * step))
  : [];
}
</code>```

Example Usage:

```<code>range(16, start:-5, step: 8);
// [-5, 3, 11]
range(5);
// [0, 1, 2, 3, 4]
</code>```

Unfortunately I have not entirely mimicked the easier syntax of python (range(start, stop[, step])) as dart doesn't have operator overloading or optional positional arguments.

Another option using list comprehension which resembles Maryan's solution

```<code>listCompRange(int start, int stop, int step) {
  if (step == 0)
    throw Exception("Step cannot be 0");
  if (start == stop)
    return [];
  bool forwards = start < stop;
  return forwards == step > 0
  ? forwards
    ? [for (int i = 0; i*step < stop-start; i++) start + (i * step)]
    : [for (int i = 0; i*step > stop-start; i++) start + (i * step)]
  : [];
}
</code>```

Example Usage:

```<code>listCompRange(0, 5, 1);
// [0, 1, 2, 3, 4]
</code>```

I benchmarked both of these options with the following methods

```<code>benchMarkRange(){
  List<List<int>> temp = List<List<int>>();
  Stopwatch timer = Stopwatch();
  timer.start();
  for (int i = 0; i < 500; i++){
    temp.add(range(-30, start: -10, step: -2));
  }
  timer.stop();
  print("Range function\n${timer.elapsed}\n");
  return temp;
}

benchMarkListComprehension(){
  List<List<int>> temp = List<List<int>>();
  Stopwatch timer = Stopwatch();
  timer.start();
  for (int i = 0; i < 500; i++){
    temp.add(listCompRange(-10, -30, -2));
  }
  timer.stop();
  print("List comprehension\n${timer.elapsed}\n");
  return temp;
}
</code>```

which yielded these results slightly favoring the generator.

```<code>Range function
0:00:00.011953
0:00:00.011558
0:00:00.011473
0:00:00.011615

List comprehension
0:00:00.016281
0:00:00.017403
0:00:00.017496
0:00:00.016878
</code>```

however when I changed the function to generate from -10 to -30 with a step of -2 the results slightly favored the list comprehension.

```<code>List comprehension
0:00:00.001352
0:00:00.001328
0:00:00.001300
0:00:00.001335

Range function
0:00:00.001371
0:00:00.001466
0:00:00.001438
0:00:00.001372
</code>```

Updated code with positional rather than named parameters

```<code>range(int a, [int stop, int step]) {
  int start;

  if (stop == null) {
    start = 0;
    stop = a;
  } else {
    start = a;
  }

  if (step == 0)
    throw Exception("Step cannot be 0");

  if (step == null)
    start < stop
    ? step = 1    // walk forwards
    : step = -1;  // walk backwards

  // return [] if step is in wrong direction
  return start < stop == step > 0
  ? List<int>.generate(((start-stop)/step).abs().ceil(), (int i) => start + (i * step))
  : [];
}
</code>```

Usage: range(int a, [int stop, int step])

If stop is not included a becomes stop and start will default to 0
If a and stop are both provided a becomes start
if not provided step will default to 1 or -1 depending on whether start or stop is larger

```<code>range(4);
// [0, 1, 2, 3]
range(4, 10);
// [4, 5, 6, 7, 8, 9]
range(4, 10, 2);
// [4, 6, 8]
range(-4);
// [0, -1, -2, -3]
range(10, 4);
// [10, 9, 8, 7, 6, 5]
range(10,10);
// []
range(1, 2, -1);
// []
range(x, y, 0);
// Exception
</code>```

Title: Create a list from 0 to N

Body:
How can I create easily a range of consecutive integers in dart? For example:

// throws a syntax error :)
var list = [1..10];

Body:
I have been using a modified version of Alexandre Ardhuin's which tries to mimic the range() provided by python Edit: found out optional positional arguments are a thing updated code below

range(int stop, {int start: 0, int step: 1}){
  if (step == 0)
    throw Exception("Step cannot be 0");

  return start < stop == step > 0
  ? List<int>.generate(((start-stop)/step).abs().ceil(), (int i) => start + (i * step))
  : [];
}

Example Usage:

range(16, start:-5, step: 8);
// [-5, 3, 11]
range(5);
// [0, 1, 2, 3, 4]

Unfortunately I have not entirely mimicked the easier syntax of python (range(start, stop[, step])) as dart doesn't have operator overloading or optional positional arguments.

Another option using list comprehension which resembles Maryan's solution

listCompRange(int start, int stop, int step) {
  if (step == 0)
    throw Exception("Step cannot be 0");
  if (start == stop)
    return [];
  bool forwards = start < stop;
  return forwards == step > 0
  ? forwards
    ? [for (int i = 0; i*step < stop-start; i++) start + (i * step)]
    : [for (int i = 0; i*step > stop-start; i++) start + (i * step)]
  : [];
}

Example Usage:

listCompRange(0, 5, 1);
// [0, 1, 2, 3, 4]

I benchmarked both of these options with the following methods

benchMarkRange(){
  List<List<int>> temp = List<List<int>>();
  Stopwatch timer = Stopwatch();
  timer.start();
  for (int i = 0; i < 500; i++){
    temp.add(range(-30, start: -10, step: -2));
  }
  timer.stop();
  print("Range function\n${timer.elapsed}\n");
  return temp;
}

benchMarkListComprehension(){
  List<List<int>> temp = List<List<int>>();
  Stopwatch timer = Stopwatch();
  timer.start();
  for (int i = 0; i < 500; i++){
    temp.add(listCompRange(-10, -30, -2));
  }
  timer.stop();
  print("List comprehension\n${timer.elapsed}\n");
  return temp;
}

which yielded these results slightly favoring the generator.

Range function
0:00:00.011953
0:00:00.011558
0:00:00.011473
0:00:00.011615

List comprehension
0:00:00.016281
0:00:00.017403
0:00:00.017496
0:00:00.016878

however when I changed the function to generate from -10 to -30 with a step of -2 the results slightly favored the list comprehension.

List comprehension
0:00:00.001352
0:00:00.001328
0:00:00.001300
0:00:00.001335

Range function
0:00:00.001371
0:00:00.001466
0:00:00.001438
0:00:00.001372

Updated code with positional rather than named parameters

range(int a, [int stop, int step]) {
  int start;

  if (stop == null) {
    start = 0;
    stop = a;
  } else {
    start = a;
  }

  if (step == 0)
    throw Exception("Step cannot be 0");

  if (step == null)
    start < stop
    ? step = 1    // walk forwards
    : step = -1;  // walk backwards

  // return [] if step is in wrong direction
  return start < stop == step > 0
  ? List<int>.generate(((start-stop)/step).abs().ceil(), (int i) => start + (i * step))
  : [];
}

Usage: range(int a, [int stop, int step])

If stop is not included a becomes stop and start will default to 0
If a and stop are both provided a becomes start
if not provided step will default to 1 or -1 depending on whether start or stop is larger

range(4);
// [0, 1, 2, 3]
range(4, 10);
// [4, 5, 6, 7, 8, 9]
range(4, 10, 2);
// [4, 6, 8]
range(-4);
// [0, -1, -2, -3]
range(10, 4);
// [10, 9, 8, 7, 6, 5]
range(10,10);
// []
range(1, 2, -1);
// []
range(x, y, 0);
// Exception


问:
How to type an array with classes in TypeScript?
I have an app that initializes by running its method .init(params) like this:

```<code>app.init([TopBar, StatusBar, MainArea]);
</code>```

Where TopBar, StatusBar and MainArea are classes, not instances of classes. Each of these classes implements the same interface IComponent.

I want to instantiate objects from the passed classes in the .init(params) method, like this:

```<code>init(params: IComponent[]): void {
    params.map(function (component) {
        let comp = new component();
        this.components[comp.constructor.name] = comp;
    }, this);
</code>```

The issue is that as these are not instance, TypeScript doesn't know their types and throws an error:

error TS2345: Argument of type '(typeof TopBar | typeof StatusBar |
  typeof MainArea)[]' is not assignable to parameter of type
  'IComponent[]'.

How do I fix the code so that I could pass an array of classes that implement some interface to a method?

答:
Even though this is an old question: this is how you do it:</p>

```<code>interface IComponent { something(): void; }
class TopBar implements IComponent { something() { console.log('in TopBar'); }}
class StatusBar implements IComponent { something() { console.log('in StatusBar'); }}
class MainArea implements IComponent { something() { console.log('in MainArea'); }}

interface ComponentClass {
    new(): IComponent;
}

const components: { [name: string]: IComponent } = {};

function init(params: ComponentClass[]) {
    params.map((component) => {
        let comp = new component();
        components[component.name] = comp;
    });
}

init([TopBar, StatusBar, MainArea]);

for (const c in components) {
    console.log('Component: ' + c);
    components[c].something();
}
</code>```

Body:
I have an app that initializes by running its method .init(params) like this:

app.init([TopBar, StatusBar, MainArea]);

Where TopBar, StatusBar and MainArea are classes, not instances of classes. Each of these classes implements the same interface IComponent.

I want to instantiate objects from the passed classes in the .init(params) method, like this:

init(params: IComponent[]): void {
    params.map(function (component) {
        let comp = new component();
        this.components[comp.constructor.name] = comp;
    }, this);

The issue is that as these are not instance, TypeScript doesn't know their types and throws an error:

error TS2345: Argument of type '(typeof TopBar | typeof StatusBar |
  typeof MainArea)[]' is not assignable to parameter of type
  'IComponent[]'.

How do I fix the code so that I could pass an array of classes that implement some interface to a method?

Body:
Even though this is an old question: this is how you do it:

interface IComponent { something(): void; }
class TopBar implements IComponent { something() { console.log('in TopBar'); }}
class StatusBar implements IComponent { something() { console.log('in StatusBar'); }}
class MainArea implements IComponent { something() { console.log('in MainArea'); }}

interface ComponentClass {
    new(): IComponent;
}

const components: { [name: string]: IComponent } = {};

function init(params: ComponentClass[]) {
    params.map((component) => {
        let comp = new component();
        components[component.name] = comp;
    });
}

init([TopBar, StatusBar, MainArea]);

for (const c in components) {
    console.log('Component: ' + c);
    components[c].something();
}


问:
How to randomly fill the rows of the matrix?
I have a matrix with n-rows and n-columns. I need to make sure that the numbers in each row are unique.</p>

```<code>let matrix = [];
let matrixRows = 3;
let matrixColumns = 5;

for ( let i = 0; i < matrixRows; i++ ) {
    matrix[ i ] = [];
    let j = 0;
    while (j < matrixColumns) {
        matrix[ i ][ j ] = Math.floor(Math.random() * 5) + 1;
        j++;
    }
}

console.log( matrix.join('\n') );

It should look something like this

"1,2,3,4,5 \\ here is line break (new row)
1,4,2,5,3 \\ here is line break (new row)
5,4,2,3,1"
</code>```

答:
Not the most elegant, but this first creates a flat list of unique randoms and reduces that to a 2d n*m matrix:

function fillRand (n, m) {
      let rands = [];
      do {
     var rand = Math.random ();
      } while (!~rands.indexOf (rand) && rands.push (rand) < n*m);

      return rands.reduce ((mat, cur, i) => {
      let last;
         if (i%n==0) {
            mat.push ([]);
         }
       last = mat[mat.length - 1]
         last.push (cur);
         return mat;
      },[])
    }

console.log (fillRand (4,5))```

Body:
I have a matrix with n-rows and n-columns. I need to make sure that the numbers in each row are unique.

let matrix = [];
let matrixRows = 3;
let matrixColumns = 5;

for ( let i = 0; i < matrixRows; i++ ) {
    matrix[ i ] = [];
    let j = 0;
    while (j < matrixColumns) {
        matrix[ i ][ j ] = Math.floor(Math.random() * 5) + 1;
        j++;
    }
}

console.log( matrix.join('\n') );

It should look something like this

"1,2,3,4,5 \\ here is line break (new row)
1,4,2,5,3 \\ here is line break (new row)
5,4,2,3,1"


问:
Web Components, pass data to and from
My understanding is that data is passed to a custom html element via its attributes and sent out by dispatching a CustomEvent.

JavaScript objects can obviously be sent out in the event's detail field, but what if the element needs a lot of data passed into it. Is there a way to provide it with an object in JavaScript.

What if the element for instance contains a variable number of parts that needs to be initialized or changed dynamically (e.g. a table with a variable number of rows)? I can imagine setting and modifying an attribute consisting of a JSON string that is parsed inside the component, but it does not feel like an elegant way to proceed:

```<code><my-element tableRowProperties="[{p1:'v1', p2:'v2'}, {p1:'v1',p2:'v2'}, {p1:'v1',p2:'v2'}]"></my-element>
</code>```

Or can you make the element listen to events from the outside that contains a payload of data?

答:
There is a 6th way that is really similar to @Intervalia's answer above but uses a
</my-el>```

Title: Web Components, pass data to and from

Body:
My understanding is that data is passed to a custom html element via its attributes and sent out by dispatching a CustomEvent.

JavaScript objects can obviously be sent out in the event's detail field, but what if the element needs a lot of data passed into it. Is there a way to provide it with an object in JavaScript.

What if the element for instance contains a variable number of parts that needs to be initialized or changed dynamically (e.g. a table with a variable number of rows)? I can imagine setting and modifying an attribute consisting of a JSON string that is parsed inside the component, but it does not feel like an elegant way to proceed:

<my-element tableRowProperties="[{p1:'v1', p2:'v2'}, {p1:'v1',p2:'v2'}, {p1:'v1',p2:'v2'}]"></my-element>

Or can you make the element listen to events from the outside that contains a payload of data?

Body:
There is a 6th way that is really similar to @Intervalia's answer above but uses a <script> tag instead of a <template> tag.

This is the same approach used by a Markdown Element.

class MyEl extends HTMLElement {
  connectedCallback() {
    var data;

    try {
      data = JSON.parse(this.children[0].innerHTML);
    }

    catch(ex) {
      console.error(ex);
    }

    this.innerHTML = '';
    var pre = document.createElement('pre');
    pre.textContent = JSON.stringify(data,0,2);
    this.appendChild(pre);
  }
}

// Define our web component
customElements.define('my-el', MyEl);

<my-el>
  <script type="application/json">[{"a":1},{"b":"<b>Hi!</b>"},{"c":"</template>"}]</script>
</my-el>


问:
How to number of entries in one column that satisfy condition from another column?
I have a data frame like this:

```<code>head(m,20)

         snp1      snp2    r2
1   rs7278528 rs7278528 1.000
2    rs234750 rs7278528 0.841
3    rs413621 rs7278528 0.841
4    rs413624 rs7278528 0.568
5   rs4920017 rs7278528 0.841
6    rs393280 rs7278528 0.821
7   rs1788470 rs7278528 0.568
8  rs10887972 rs7278528 0.568
9    rs439861 rs7278528 0.568
10  rs1672133 rs7278528 0.841
11   rs370994 rs7278528 0.841
12   rs442981 rs7278528 0.841
...
</code>```

I would like to calculate and output in a separate column for each unique value in snp2, how many snp1 have r2 > 0.8

I tired doing this but no success:

```<code>m %>%
  group_by(snp1) %>%
  summarize(sumR2 = sumRows(snp1[r2>0.8]))
</code>```

UPDATE

this solved my problem:

```<code>t <- filter(m, r2 >= 0.8) %>% group_by(snp1) %>% mutate(ldbuds = length(r2))
</code>```

答:
if you could include reproducible example of your data would be nice!

But ths should work, if you are trying to group by snp2

```<code>m %>%
  group_by(snp2) %>%
  summarize(sumR2 = n_distinct(r2>0.8))
</code>```

Body:
I have a data frame like this:

head(m,20)

         snp1      snp2    r2
1   rs7278528 rs7278528 1.000
2    rs234750 rs7278528 0.841
3    rs413621 rs7278528 0.841
4    rs413624 rs7278528 0.568
5   rs4920017 rs7278528 0.841
6    rs393280 rs7278528 0.821
7   rs1788470 rs7278528 0.568
8  rs10887972 rs7278528 0.568
9    rs439861 rs7278528 0.568
10  rs1672133 rs7278528 0.841
11   rs370994 rs7278528 0.841
12   rs442981 rs7278528 0.841
...

I would like to calculate and output in a separate column for each unique value in snp2, how many snp1 have r2 > 0.8

I tired doing this but no success:

m %>%
  group_by(snp1) %>%
  summarize(sumR2 = sumRows(snp1[r2>0.8]))

UPDATE

this solved my problem:

t <- filter(m, r2 >= 0.8) %>% group_by(snp1) %>% mutate(ldbuds = length(r2))

Body:
if you could include reproducible example of your data would be nice!

But ths should work, if you are trying to group by snp2

m %>%
  group_by(snp2) %>%
  summarize(sumR2 = n_distinct(r2>0.8))


问:
I want to add a new row to UITableView with the click of a Button
when I click the add button it return the error 'attempt to insert row 0 into section 0, but there are only 0 rows in section 0 after the update'

```<code>import UIKit

class PlacesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var addPointTableArray = [""]
    @IBOutlet weak var addPointableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        addPointableview.delegate = self
    }

    @objc @IBAction func addPointButton(_ sender: Any) {
        addPointableview.beginUpdates()
        addPointableview.insertRows(at: [IndexPath(row: addPointTableArray.count - 1, section: 0)], with: .automatic)
        addPointableview.endUpdates()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath:    IndexPath) -> UITableViewCell {
        let cell = addPointableview.dequeueReusableCell(withIdentifier:  "addCell", for: indexPath as IndexPath) as! AddPointCellCell
        cell.addPointTextfiedl.tag = indexPath.row
        cell.addPointTextfiedl.addTarget(self, action:  #selector(addPointButton(_:)), for: UIControl.Event.touchUpInside)
        addPointableview.beginUpdates()
        addPointableview.insertRows(at: [IndexPath(row: addPointTableArray.count-1, section: 0)], with: .automatic)
        addPointableview.endUpdates()
        return cell
    }

}
</code>```

I have checked my table and add button I don't know where the error is coming from

答:
You should not be inserting rows in your cellForRow(at:) method.

You also need to update your data model so that there is data for these new indexPaths. The table view will ask for data for the cells at the new indexPaths in order to refresh, and if the data model is not updated to contain data for the new cells you may crash.

Body:
when I click the add button it return the error 'attempt to insert row 0 into section 0, but there are only 0 rows in section 0 after the update'

import UIKit

class PlacesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var addPointTableArray = [""]
    @IBOutlet weak var addPointableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        addPointableview.delegate = self
    }

    @objc @IBAction func addPointButton(_ sender: Any) {
        addPointableview.beginUpdates()
        addPointableview.insertRows(at: [IndexPath(row: addPointTableArray.count - 1, section: 0)], with: .automatic)
        addPointableview.endUpdates()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath:    IndexPath) -> UITableViewCell {
        let cell = addPointableview.dequeueReusableCell(withIdentifier:  "addCell", for: indexPath as IndexPath) as! AddPointCellCell
        cell.addPointTextfiedl.tag = indexPath.row
        cell.addPointTextfiedl.addTarget(self, action:  #selector(addPointButton(_:)), for: UIControl.Event.touchUpInside)
        addPointableview.beginUpdates()
        addPointableview.insertRows(at: [IndexPath(row: addPointTableArray.count-1, section: 0)], with: .automatic)
        addPointableview.endUpdates()
        return cell
    }

}

I have checked my table and add button I don't know where the error is coming from


问:
Detect when user focuses on document
I have a chat application for two persons and for example, one of them sends a message to the second one.

When the second one delivers and focuses on document then the browser checks if last element in parent div has class "his_message" and if it does, the browser (via socket.io) sends the message to first user (who sent message) that his partner has seen his message, otherwise: do nothing.

It is like Facebook's "seen" feature when Facebook notifies you that your chat partner has seen your message.

I used MutationObserver for implementing what i want:

```<code>const observer = new MutationObserver((mutations)=>{
    if(document.hasFocus()){
    console.log($('#output > :last-child').attr('class'));
    socket.emit('seen')
    }
 })

observer.observe(output, { attributes: true, childList: true, characterData: true, subtree: true });
</code>```

But if you test it, you will know that it is not working like I want. So what can i do to reach my aim? Thanks!

答: I assume the best way will be to associate easch message with a database column (say: is_seen) where it takes boolean value... once the focus has been made,update the value to True in database...and you can fetch that value to display as seen when the message is clicked just as in messenger app.</p>

Title: Detect when user focuses on document

Body:
I have a chat application for two persons and for example, one of them sends a message to the second one.

When the second one delivers and focuses on document then the browser checks if last element in parent div has class "his_message" and if it does, the browser (via socket.io) sends the message to first user (who sent message) that his partner has seen his message, otherwise: do nothing.

It is like Facebook's "seen" feature when Facebook notifies you that your chat partner has seen your message.

I used MutationObserver for implementing what i want:

const observer = new MutationObserver((mutations)=>{
    if(document.hasFocus()){
    console.log($('#output > :last-child').attr('class'));
    socket.emit('seen')
    }
 })

observer.observe(output, { attributes: true, childList: true, characterData: true, subtree: true });

But if you test it, you will know that it is not working like I want. So what can i do to reach my aim? Thanks!


问:
HDFS Offline Image Viewer takes hours
When I execute these commands, it is very slow and always takes five hours or more to finish.

hdfs dfsadmin -fetchImage ${t_save_fsimage_path}

# 获取下载的fsimage具体文件路径
t_fsimage_file=`ls ${t_save_fsimage_path}/fsimage*`

# 处理fsimage为可读的csv格式文件
hdfs oiv -i ${t_fsimage_file} -o ${t_save_fsimage_path}/fsimage.csv -p Delimited

# 删除fsimage.csv的首行数据
sed -i -e "1d" ${t_save_fsimage_path}/fsimage.csv

# 创建数据目录
hadoop fs -test -e ${t_save_fsimage_path}/fsimage || hdfs dfs -mkdir -p ${t_save_fsimage_path}/fsimage

# 拷贝fsimage.csv到指定的路径
hdfs dfs -copyFromLocal -f ${t_save_fsimage_path}/fsimage.csv ${t_save_fsimage_path}/fsimage/
```

答: You could either programmatically analyze the fsimage using HFSA lib or HFSA cli tool (depending on your use case).</p>

Title: HDFS Offline Image Viewer takes hours


问:
Controling and getting data from clients of applications by node.js
I want to try create simple bot for game(game has own client), which will be control character(may be mouse move and keys press) and read information from screen. Advice please ways/packets for node.js.
Any information will be useful</p>

答: robotjs is a npm module that provides all of the functionality you described in the question. The documentation on its website goes over individual walkthroughs on how to handle mouse, keyboard, and screen reading functionality.


问:
Powershell "UNC paths are not supported" but I'm using Push-Location
I am running a command line program in powershell working on our \servername\files folder as the running folder. I get a "UNC paths are not supported" error even though I am using Push-Location (which is the only solution I find while googling). The simplest code that gives me this error is as follows:</p>

```<code>Push-Location \\servername\files
cmd.exe \c ping 10.1.10.10
Pop-Location
</code>```

答:
PetSerAl is correct, you're getting this response from cmd, not Powershell. This would work if you had a PSDrive configured first, but I don't know if that is very efficient for your use case:</p>

```<code>New-PSDrive -Name S -PSProvider FileSystem -Root \\servername\files -Persist
Push-Location
Set-Location S:\
cmd.exe /c ping 10.1.1.1
Pop-Location
Get-PSDrive S | Remove-PSDrive
</code>```

Body:
I am running a command line program in powershell working on our \servername\files folder as the running folder. I get a "UNC paths are not supported" error even though I am using Push-Location (which is the only solution I find while googling). The simplest code that gives me this error is as follows:

Push-Location \\servername\files
cmd.exe \c ping 10.1.10.10
Pop-Location

Body:
PetSerAl is correct, you're getting this response from cmd, not Powershell. This would work if you had a PSDrive configured first, but I don't know if that is very efficient for your use case:

New-PSDrive -Name S -PSProvider FileSystem -Root \\servername\files -Persist
Push-Location
Set-Location S:\
cmd.exe /c ping 10.1.1.1
Pop-Location
Get-PSDrive S | Remove-PSDrive


问:
Is there a way to find text with spaces before and after string in excel?
I am trying to update some addresses and fix case sensitive errors for example "123 Nw Apple St" should be "123 NW Apple St" I would like to be able to find all "Ne","Nw","Se" and "Sw." and if possible replace them with the correct version. However, I have yet to figure out how to even find these.

I have tried a couple different methods using search and find. The problem I am running into is Nw is not always at the end of address.

A couple things I have tried;

```<code>=SEARCH(" "&"Nw"&" ",A2,1)
</code>```

and

```<code>=SEARCH(" Nw ",A2,1)
</code>```

I just need some identifier that Nw is found. If it could replace it with "NW"
that would be even better.

答:
You can use SEARCH which is case-insensitive, and nested IFERRORs, to replace the directional abbreviations.

For example:

```<code>=IFERROR(IFERROR(IFERROR(IFERROR(REPLACE(A1,SEARCH(" nw ",A1)+1,2,"NW"),
REPLACE(A1,SEARCH(" ne ",A1)+1,2,"NE")),
REPLACE(A1,SEARCH(" se ",A1)+1,2,"SE")),
REPLACE(A1,SEARCH(" sw ",A1)+1,2,"SW")),A1)
</code>```

However, if there are other issues you need to detect and correct, a VBA solution might be preferable.

Body:
I am trying to update some addresses and fix case sensitive errors for example "123 Nw Apple St" should be "123 NW Apple St" I would like to be able to find all "Ne","Nw","Se" and "Sw." and if possible replace them with the correct version. However, I have yet to figure out how to even find these.

I have tried a couple different methods using search and find. The problem I am running into is Nw is not always at the end of address.

A couple things I have tried;

=SEARCH(" "&"Nw"&" ",A2,1)

and

=SEARCH(" Nw ",A2,1)

I just need some identifier that Nw is found. If it could replace it with "NW"
that would be even better.

Body:
You can use SEARCH which is case-insensitive, and nested IFERRORs, to replace the directional abbreviations.

For example:

=IFERROR(IFERROR(IFERROR(IFERROR(REPLACE(A1,SEARCH(" nw ",A1)+1,2,"NW"),
REPLACE(A1,SEARCH(" ne ",A1)+1,2,"NE")),
REPLACE(A1,SEARCH(" se ",A1)+1,2,"SE")),
REPLACE(A1,SEARCH(" sw ",A1)+1,2,"SW")),A1)

However, if there are other issues you need to detect and correct, a VBA solution might be preferable.


问:
python __init__ method in inherited class
I would like to give a daughter class some extra attributes without having to explicitly call a new method. So is there a way of giving the inherited class an __init__ type method which does not override the __init__ method of the parent class?

I have written the code below purely to illustrate my question (hence the poor naming of attributes etc).

```<code>class initialclass():
    def __init__(self):
        self.attr1 = 'one'
        self.attr2 = 'two'

class inheritedclass(initialclass):
    def __new__(self):
        self.attr3 = 'three'

    def somemethod(self):
        print 'the method'

a = inheritedclass()

for each in a.__dict__:
    print each

#I would like the output to be:
attr1
attr2
attr3
</code>```

Thank you

答:
It's incredibly simple. Define a new __init__ method and call the parent's __init__ at the beginning.

```<code># assuming a class Base, its __init__ takes one parameter x

class Derived(Base):
    def __init__(self, x, y):
        # whatever initialization is needed so we can say Derived is-a Base
        super(Derived, self).__init__(x)
        # now, add whatever makes Derived special - do your own initialization
        self.y = y
</code>```

In Python 3, you don't have to (and therefore propably shouldn't, for simplicity) explicitly inherit from object or pass the class and self to super.

Body:
I would like to give a daughter class some extra attributes without having to explicitly call a new method. So is there a way of giving the inherited class an __init__ type method which does not override the __init__ method of the parent class?

I have written the code below purely to illustrate my question (hence the poor naming of attributes etc).

class initialclass():
    def __init__(self):
        self.attr1 = 'one'
        self.attr2 = 'two'

class inheritedclass(initialclass):
    def __new__(self):
        self.attr3 = 'three'

    def somemethod(self):
        print 'the method'

a = inheritedclass()

for each in a.__dict__:
    print each

#I would like the output to be:
attr1
attr2
attr3

Thank you

Body:
It's incredibly simple. Define a new __init__ method and call the parent's __init__ at the beginning.

# assuming a class Base, its __init__ takes one parameter x

class Derived(Base):
    def __init__(self, x, y):
        # whatever initialization is needed so we can say Derived is-a Base
        super(Derived, self).__init__(x)
        # now, add whatever makes Derived special - do your own initialization
        self.y = y

In Python 3, you don't have to (and therefore propably shouldn't, for simplicity) explicitly inherit from object or pass the class and self to super.


问:
How to set value for all the objects in array for javascript?
How to set value for all the items inside an array?

For example, I have the array: ["chin","eng","maths"]

I want to set it to {"chin" :true,"eng":true,"maths":true}

And push to firebase as a child.

答:
The simplest way is to loop through the array using for...of and add each key to an object:

const keys = ["chin", "eng", "maths"],
      output = {};

for (const key of keys) {
  output[key] = true;
}

console.log(output)```
</div>
</div>
</p>

<p>Another option is to create a 2D array of key-value pair entries using <code>map</code>. Then use <code>Object.fromEntries()</code> to create the object</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const keys = ["chin","eng","maths"]
const output = Object.fromEntries(keys.map(k => [k, true]))

console.log(output)</code>```

Body:
The simplest way is to loop through the array using for...of and add each key to an object:

const keys = ["chin", "eng", "maths"],
      output = {};

for (const key of keys) {
  output[key] = true;
}

console.log(output)

Another option is to create a 2D array of key-value pair entries using map. Then use Object.fromEntries() to create the object

const keys = ["chin","eng","maths"]
const output = Object.fromEntries(keys.map(k => [k, true]))

console.log(output)


问:
MS Access Hide Button on Startup
I'm trying to write code to only show a button during certain months of the year. I think I have the code down, but I don't know where to put it to make it work. When I put the code in "on paint", I get a 32521 error code: "You can't change the value of this property in the OnPaint event."

Here's the code:

```<code>Button.Visible = False

If ( (Month(Now) = 6) Or (Month(Now) = 7) Or (Month(Now) = 8) ) Then
Button.Visible = True
End If
</code>```

Where should I put this code to make it run right when the home screen form is opened?

答:
In your Load Event</p>

```<code>Private Sub Form_Load()

Button.Visible = False

If ( (Month(Now) = 6) Or (Month(Now) = 7) Or (Month(Now) = 8) ) Then
    Button.Visible = True
End If

End Sub
</code>```

Title: MS Access Hide Button on Startup

Body:
I'm trying to write code to only show a button during certain months of the year. I think I have the code down, but I don't know where to put it to make it work. When I put the code in "on paint", I get a 32521 error code: "You can't change the value of this property in the OnPaint event."

Here's the code:

Button.Visible = False

If ( (Month(Now) = 6) Or (Month(Now) = 7) Or (Month(Now) = 8) ) Then
Button.Visible = True
End If

Where should I put this code to make it run right when the home screen form is opened?

Body:
In your Load Event

Private Sub Form_Load()

Button.Visible = False

If ( (Month(Now) = 6) Or (Month(Now) = 7) Or (Month(Now) = 8) ) Then
    Button.Visible = True
End If

End Sub


问:
Not able to retrieve object properties when looping through objects in indexedDB
I am not able to retrieve properties when looping through objects stored in indexedDB. When i attempt to get objects trough tasksStore.get(i);, i get the error Cannot read property 'property' of undefined at IDBRequest.getTasks.onsuccess, however, if I change it to tasksStore.get(1);, it works fine, and gets object with id=1 x index's length.

I've tried checking the typeof of both ways, and they both return number.

```<code>//success handler on connection
    request.onsuccess = function(e) {
        db = request.result;

        //define store index
        tasksStore = tasksTx.objectStore("tasksStore");

        //error handler on result of the request
        db.onerror = function(e) {
            console.log("ERROR " + e.target.errorCode);
        }

        //variable for counting objects in the index
        let amountOfTasks = tasksIndex.count();

        //error handler
        amountOfTasks.onerror = function() {
            console.log("There was an error finding the amount of tasks")
        }

        //success handler
        amountOfTasks.onsuccess = function() {
            for (var i = 1; i < amountOfTasks.result; i++) {
                let getTasks = tasksStore.get(i);

                let getTasksElementContainer = document.getElementById("list-tasks");
                let createTasksList = document.createElement("li");
                createTasksList.id = "task-" + i;

                getTasks.onerror = function() {
                    console.log("There was an error looping through the tasks")
                }

                getTasks.onsuccess = function() {
                    console.log(getTasks.result.title); //getTasks.result works, getTasks.result.title does not.
                    getTasksElementContainer.appendChild(createTasksList);
                    //JSON stringify to return object in string format, and not [Object object]
                    createTasksList.innerHTML = JSON.stringify(getTasks.result.title);
                }
            }
        }
    }
</code>```

答:
When you call IDBObjectStore.get with a key that doesn't exist in your database, the resulting value is undefined. That likely explains why sometimes getTasks.result is undefined.

If you're still having trouble, you'd likely be well served by making a self-contained reproducible example. You'll probably find your own bug in the process of doing that. If not, it's easier to get more specific help on Stack Overflow if you have some code that other people can run to directly observe the problem (so including database creation and inserting data).

Body:
I am not able to retrieve properties when looping through objects stored in indexedDB. When i attempt to get objects trough tasksStore.get(i);, i get the error Cannot read property 'property' of undefined at IDBRequest.getTasks.onsuccess, however, if I change it to tasksStore.get(1);, it works fine, and gets object with id=1 x index's length.

I've tried checking the typeof of both ways, and they both return number.

//success handler on connection
    request.onsuccess = function(e) {
        db = request.result;

        //define store index
        tasksStore = tasksTx.objectStore("tasksStore");

        //error handler on result of the request
        db.onerror = function(e) {
            console.log("ERROR " + e.target.errorCode);
        }

        //variable for counting objects in the index
        let amountOfTasks = tasksIndex.count();

        //error handler
        amountOfTasks.onerror = function() {
            console.log("There was an error finding the amount of tasks")
        }

        //success handler
        amountOfTasks.onsuccess = function() {
            for (var i = 1; i < amountOfTasks.result; i++) {
                let getTasks = tasksStore.get(i);

                let getTasksElementContainer = document.getElementById("list-tasks");
                let createTasksList = document.createElement("li");
                createTasksList.id = "task-" + i;

                getTasks.onerror = function() {
                    console.log("There was an error looping through the tasks")
                }

                getTasks.onsuccess = function() {
                    console.log(getTasks.result.title); //getTasks.result works, getTasks.result.title does not.
                    getTasksElementContainer.appendChild(createTasksList);
                    //JSON stringify to return object in string format, and not [Object object]
                    createTasksList.innerHTML = JSON.stringify(getTasks.result.title);
                }
            }
        }
    }


问:
Extracting Text Values from XML in SQL
I'm working with SQL data hosted by a 3rd party, and am trying to pull some specific information for reporting. However, some of what I need to parse out is in XML format, and I'm getting stuck. I'm looking for the syntax to pull the text= values only from the XML code.

I believe the code should something like this, but most of the examples I can find online involve simpler XML hierarchy's than what I'm dealing with.

```<code><[columnnameXML].value('(/RelatedValueListBO/Items/RelatedValueListBOItem/text())[1]','varchar(max)')>
</code>```

Fails to pull any results. I've tried declaring the spacenames as well, but again...I only ever end up with NULL values pulled.

Example XML I'm dealing with:

```<code><RelatedValueListBO xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xmlns="http://tempuri.org/RelatedValueListBOSchema.xsd">
    <Items>
        <RelatedValueListBOItem groupKey="Response1" text="Response1" selected="true" />
        <RelatedValueListBOItem groupKey="Response2" text="Response2" selected="true" />
        <RelatedValueListBOItem groupKey="Response3" text="Response3" selected="true" />
    </Items>
</RelatedValueListBO>
</code>```

Ideally I'd like to pull response1; response2; response3 into a single column.  Allowing for the fact that multiple responses may exist. I believe I'm getting stuck with the basic code I've been trying due to the namespaces associated to RelatedValueListBO and the fact that what I want is grouped in groupKey, text, and selected, instead of the value I want just being under the Items node.

答:
You can use something like this to extract the value of "text" in the first node of RelatedValueListBOItem</p>

```<code>SELECT  extractvalue(value(rs), '//RelatedValueListBOItem[1]/@text')
  FROM TABLE (xmlsequence(extract(sys.xmltype('<RelatedValueListBO>
      <Items>
        <RelatedValueListBOItem groupKey="Response1" text="Response1"
    selected="true" />
    <RelatedValueListBOItem groupKey="Response2" text="Response2"
    selected="true" />
    <RelatedValueListBOItem groupKey="Response3" text="Response3"
    selected="true" />
     </Items>
    </RelatedValueListBO>'),'/RelatedValueListBO/Items'))) rs;
</code>```

Title: Extracting Text Values from XML in SQL

Body:
I'm working with SQL data hosted by a 3rd party, and am trying to pull some specific information for reporting. However, some of what I need to parse out is in XML format, and I'm getting stuck. I'm looking for the syntax to pull the text= values only from the XML code.

I believe the code should something like this, but most of the examples I can find online involve simpler XML hierarchy's than what I'm dealing with.

<[columnnameXML].value('(/RelatedValueListBO/Items/RelatedValueListBOItem/text())[1]','varchar(max)')>

Fails to pull any results. I've tried declaring the spacenames as well, but again...I only ever end up with NULL values pulled.

Example XML I'm dealing with:

<RelatedValueListBO xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xmlns="http://tempuri.org/RelatedValueListBOSchema.xsd">
    <Items>
        <RelatedValueListBOItem groupKey="Response1" text="Response1" selected="true" />
        <RelatedValueListBOItem groupKey="Response2" text="Response2" selected="true" />
        <RelatedValueListBOItem groupKey="Response3" text="Response3" selected="true" />
    </Items>
</RelatedValueListBO>

Ideally I'd like to pull response1; response2; response3 into a single column.  Allowing for the fact that multiple responses may exist. I believe I'm getting stuck with the basic code I've been trying due to the namespaces associated to RelatedValueListBO and the fact that what I want is grouped in groupKey, text, and selected, instead of the value I want just being under the Items node.

Body:
You can use something like this to extract the value of "text" in the first node of RelatedValueListBOItem

SELECT  extractvalue(value(rs), '//RelatedValueListBOItem[1]/@text')
  FROM TABLE (xmlsequence(extract(sys.xmltype('<RelatedValueListBO>
      <Items>
        <RelatedValueListBOItem groupKey="Response1" text="Response1"
    selected="true" />
    <RelatedValueListBOItem groupKey="Response2" text="Response2"
    selected="true" />
    <RelatedValueListBOItem groupKey="Response3" text="Response3"
    selected="true" />
     </Items>
    </RelatedValueListBO>'),'/RelatedValueListBO/Items'))) rs;


问:
MS Access 3 conditions in a query?
I have a total column that ranges from -7 to 7. I want to recode them in a grand total variable so everything under 0 is now 0, 1 stays 1, 2 stays 2, and 3 and everything above just stays 3. I am stuck on how to include a third condition.

This is the code I have which makes everything above 3 a 3, and keeps 1's and 2's as is. But I do not know how to make all negative numbers become a 0.

```<code>GrandTotal: IIf([total]>=3,3,[total])
</code>```

答:
chained condition, try this:</p>

```<code>GrandTotal: IIf([total]<0;0;IIf([total]>=3;3;[total]))
</code>```

Title: MS Access 3 conditions in a query?

Body:
I have a total column that ranges from -7 to 7. I want to recode them in a grand total variable so everything under 0 is now 0, 1 stays 1, 2 stays 2, and 3 and everything above just stays 3. I am stuck on how to include a third condition.

This is the code I have which makes everything above 3 a 3, and keeps 1's and 2's as is. But I do not know how to make all negative numbers become a 0.

GrandTotal: IIf([total]>=3,3,[total])

Body:
chained condition, try this:

GrandTotal: IIf([total]<0;0;IIf([total]>=3;3;[total]))


问:
How to animate Android Navigation Architecture fragment as sliding over old fragment?
In example navigation action defined in navigation graph:

```<code><action
    android:id="@+id/action_fragment1_to_fragment2"
    app:destination="@id/fragment2"
    app:enterAnim="@anim/right_slide_in"
    app:popExitAnim="@anim/left_slide_out"/>
</code>```

When Fragment2 opens and starts sliding into view from the right, Fragment1 disappears instantly (sadly). When Fragment2 is closed and starts sliding to the right, Fragment1 is nicely visible under it, giving a nice stack pop effect (comparable to iOS).

How can I keep Fragment1 visible while Fragment2 slides into view?

答:
In my own case the simplest solution was to use DialogFragment with proper animation and style.

Style:

```<code><style name="MyDialogAnimation" parent="Animation.AppCompat.Dialog">
        <item name="android:windowEnterAnimation">@anim/slide_in</item>
        <item name="android:windowExitAnimation">@anim/slide_out</item>
</style>

<style name="MyDialog" parent="ThemeOverlay.MaterialComponents.Light.BottomSheetDialog">
        <item name="android:windowIsFloating">false</item>
        <item name="android:statusBarColor">@color/transparent</item>
        <item name="android:windowAnimationStyle">@style/MyDialogAnimation</item>
</style>
</code>```

Layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:animateLayoutChanges="true"
    android:background="@color/colorWhite"
    android:fillViewport="true"
    android:fitsSystemWindows="true"
    android:layout_gravity="bottom"
    android:orientation="vertical"
    android:scrollbars="none"
    android:transitionGroup="true"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/root_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        // Your Ui here

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>
</code>```

Java:

```<code>public class MyFragmentDialog extends DialogFragment {
  @Nullable
  @Override
  public View onCreateView(
      @NonNull LayoutInflater inflater,
      @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_dialog, container, false);
  }

  @Override
  public void onStart() {
    super.onStart();
    Dialog dialog = getDialog();
    if (dialog != null) {
      int width = ViewGroup.LayoutParams.MATCH_PARENT;
      int height = ViewGroup.LayoutParams.MATCH_PARENT;
      Objects.requireNonNull(dialog.getWindow())
          .setFlags(
              WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
              WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
      Objects.requireNonNull(dialog.getWindow()).setLayout(width, height);
      dialog.getWindow().setWindowAnimations(R.style.MyDialogAnimation);
    }
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setStyle(DialogFragment.STYLE_NORMAL, R.style.MyDialog);
  }
}
</code>```

Body:
In example navigation action defined in navigation graph:

<action
    android:id="@+id/action_fragment1_to_fragment2"
    app:destination="@id/fragment2"
    app:enterAnim="@anim/right_slide_in"
    app:popExitAnim="@anim/left_slide_out"/>

When Fragment2 opens and starts sliding into view from the right, Fragment1 disappears instantly (sadly). When Fragment2 is closed and starts sliding to the right, Fragment1 is nicely visible under it, giving a nice stack pop effect (comparable to iOS).

How can I keep Fragment1 visible while Fragment2 slides into view?

Body:
In my own case the simplest solution was to use DialogFragment with proper animation and style.

Style:

<style name="MyDialogAnimation" parent="Animation.AppCompat.Dialog">
        <item name="android:windowEnterAnimation">@anim/slide_in</item>
        <item name="android:windowExitAnimation">@anim/slide_out</item>
</style>

<style name="MyDialog" parent="ThemeOverlay.MaterialComponents.Light.BottomSheetDialog">
        <item name="android:windowIsFloating">false</item>
        <item name="android:statusBarColor">@color/transparent</item>
        <item name="android:windowAnimationStyle">@style/MyDialogAnimation</item>
</style>

Layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:animateLayoutChanges="true"
    android:background="@color/colorWhite"
    android:fillViewport="true"
    android:fitsSystemWindows="true"
    android:layout_gravity="bottom"
    android:orientation="vertical"
    android:scrollbars="none"
    android:transitionGroup="true"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/root_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        // Your Ui here

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>

Java:

public class MyFragmentDialog extends DialogFragment {
  @Nullable
  @Override
  public View onCreateView(
      @NonNull LayoutInflater inflater,
      @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_dialog, container, false);
  }

  @Override
  public void onStart() {
    super.onStart();
    Dialog dialog = getDialog();
    if (dialog != null) {
      int width = ViewGroup.LayoutParams.MATCH_PARENT;
      int height = ViewGroup.LayoutParams.MATCH_PARENT;
      Objects.requireNonNull(dialog.getWindow())
          .setFlags(
              WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
              WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
      Objects.requireNonNull(dialog.getWindow()).setLayout(width, height);
      dialog.getWindow().setWindowAnimations(R.style.MyDialogAnimation);
    }
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setStyle(DialogFragment.STYLE_NORMAL, R.style.MyDialog);
  }
}


问:
Angular 6 how to get count of the particular column based on same value from an array of object
I have an array of object and also I am using foreach loop in typescript.Here as per my array it contains 2 columns having value progress:100 and others are less that 100.So here I need to calculate the count of columns having progress:100,for ex here it should be 2.Also I need to get the count of all columns having progress value is less or not 100.for ex here 2.Then I need to append into div.I have tried but its adding not counting.Here is the code below

app.component.html

```<code><div>Progress : 2{{count}}</div><div>completed : 2{{count}}</div>
</code>```

app.component.ts

```<code>declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{

      arrayVal:any;
      currentVal : any;
  title = 'projectchart';
  public array = [{"id":1,"progress":100},{"id":3,"progress":70},{"id":5,"progress":50},{"id":6,"progress":100}];
  ngOnInit(){
     let count=0;
     this.array.forEach((item, index) => {
     console.log(item.progress) ;
     count +=item.progress ;
});
     console.log(count);
  }

}
</code>```

答:
Actually, You are adding the progress value in count. Please try this..

```<code>ngOnInit(){
   let progress_count=0;
   let completed_count=0;
   this.array.forEach((item, index) => {
   if (item.progress == 100) {
    progress_count++;
   } else {
    completed_count++;
   }
});
   console.log('Progress count :',progress_count);
   console.log('Completed count :',completed_count);
}
</code>```

And use progress_count and completed_count in your HTML

Body:
I have an array of object and also I am using foreach loop in typescript.Here as per my array it contains 2 columns having value progress:100 and others are less that 100.So here I need to calculate the count of columns having progress:100,for ex here it should be 2.Also I need to get the count of all columns having progress value is less or not 100.for ex here 2.Then I need to append into div.I have tried but its adding not counting.Here is the code below

app.component.html

Progress : 2{{count}}

completed : 2{{count}}

app.component.ts

declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{

      arrayVal:any;
      currentVal : any;
  title = 'projectchart';
  public array = [{"id":1,"progress":100},{"id":3,"progress":70},{"id":5,"progress":50},{"id":6,"progress":100}];
  ngOnInit(){
     let count=0;
     this.array.forEach((item, index) => {
     console.log(item.progress) ;
     count +=item.progress ;
});
     console.log(count);
  }

}

Body:
Actually, You are adding the progress value in count. Please try this..

ngOnInit(){
   let progress_count=0;
   let completed_count=0;
   this.array.forEach((item, index) => {
   if (item.progress == 100) {
    progress_count++;
   } else {
    completed_count++;
   }
});
   console.log('Progress count :',progress_count);
   console.log('Completed count :',completed_count);
}

And use progress_count and completed_count in your HTML


问:
How do I make my ThreadPool work better with requests
I currently have this function, which does a api call, each api call is requesting different data.  I can do up to 300 concurrent api calls at a time.

Doing this does not seem to go fast, since this is just waiting for the repl I was wondering how I would make this function faster?

```<code>from multiprocessing.pool import ThreadPool
import requests

pool = ThreadPool(processes=500)
variables = VariableBaseDict
for item in variables:
    async_result = pool.apply_async(requests.get(url.json()))
    result = async_result.get()
    #do stuff with result
</code>```

答:
Your current code is not actually farming any real work off to a worker thread. You are calling requests.get(url.json()) right in the main thread, and then passing the object that returns to pool.apply_async. You should be doing pool.apply_async(requests.get, (url.json(),)) instead. That said, even if you corrected this problem, you are then immediately waiting for the reply to the call, which means you never actually run any calls concurrently. You farm one item off to a thread, wait for it to be done, then wait for the next item.

You need to:

Fix the issue where you're accidentally calling requests.get(...) in the main thread.

Either use pool.map to farm the list of work off to the worker threads concurrently, or continue using pool.apply_async, but instead of immediately calling async_result.get(), store all the async_result objects in a list, and once you've iterated over variables, iterate over the async_result list and call .get() on each item. That way you actually end up running all the calls concurrently.

So, if you used apply_async, you'd do something like this:

```<code>async_results = [pool.apply_async(requests.get, (build_url(item),)) for item in variables]
for ar in async_results:
    result = ar.get()
    # do stuff with result
</code>```

With pool.map it would be:

```<code>  results = pool.map(requests.get, [build_url(item) for item in variables])
</code>```

Body:
I currently have this function, which does a api call, each api call is requesting different data.  I can do up to 300 concurrent api calls at a time.

Doing this does not seem to go fast, since this is just waiting for the repl I was wondering how I would make this function faster?

from multiprocessing.pool import ThreadPool
import requests

pool = ThreadPool(processes=500)
variables = VariableBaseDict
for item in variables:
    async_result = pool.apply_async(requests.get(url.json()))
    result = async_result.get()
    #do stuff with result

Body:
Your current code is not actually farming any real work off to a worker thread. You are calling requests.get(url.json()) right in the main thread, and then passing the object that returns to pool.apply_async. You should be doing pool.apply_async(requests.get, (url.json(),)) instead. That said, even if you corrected this problem, you are then immediately waiting for the reply to the call, which means you never actually run any calls concurrently. You farm one item off to a thread, wait for it to be done, then wait for the next item.

You need to:

Fix the issue where you're accidentally calling requests.get(...) in the main thread.

Either use pool.map to farm the list of work off to the worker threads concurrently, or continue using pool.apply_async, but instead of immediately calling async_result.get(), store all the async_result objects in a list, and once you've iterated over variables, iterate over the async_result list and call .get() on each item. That way you actually end up running all the calls concurrently.

So, if you used apply_async, you'd do something like this:

async_results = [pool.apply_async(requests.get, (build_url(item),)) for item in variables]
for ar in async_results:
    result = ar.get()
    # do stuff with result

With pool.map it would be:

  results = pool.map(requests.get, [build_url(item) for item in variables])


问:
Generate a string from a dictionary keys (combinations) and assing a boolean value based on values
I have a structure similar, to a dictionary of dictionaries:

```<code>cont  = {

'perm': { 'r': False, 'rw': True}

'prig':  { 'sq': False, 'rot':False, 'rq':True}

'anon':  {'100': False, '500':True, '99':False; '400':False}

}
</code>```

From this structure I need to generate a string from keys, and know if the string is False or True based on the values:

Example:

```<code>'perm', 'prig', 'anon' will become: 'r,sq,100' or 'rw,sq,100' or 'r,rq,100'.
</code>```

I need to generate all permutations of the second level keys.

For each string, I need to associate a Boolean value using 'AND' are True or False.
For the example above:

```<code>False,False,False -> False;  True,False,False -> True,False,True, False -> False;
</code>```

答:
Here is my take on the assignment. It has a lot more code than the answer from @Ajax1234 but I hope it is easier to understand/read for some.

```<code>import itertools
data = {
    'test': {'a': False, 'b': True},
    'perm': {'r': False, 'rw': True},
    'prig': {'sq': False, 'rq': True},
    'anon': {'100': False, '500': True},
}

# define the order of the keys
key_order = ('perm', 'prig', 'anon', 'test')

# build a list of iterables for the 'product()' function
iterables = [
    sorted(data[k].keys())
    for k in key_order]
print(iterables)

print()
print('{:3s} {:20s} {:30s} {}'.format('i', 'elements', 'value of elements', 'AND'))

for i, elements in enumerate(itertools.product(*iterables)):
    # get the values for all the elements, in the correct order
    values = [
        data[k][sub_k]
        for k, sub_k in zip(key_order, elements)]

    print('{:3d} {:20s} {:30s} {}'.format(
        i+1,
        ','.join(elements),
        str(values),
        all(values)))
</code>```

This code gives me the following output:

```<code>[['r', 'rw'], ['rq', 'sq'], ['100', '500'], ['a', 'b']]

i   elements             value of elements              AND
  1 r,rq,100,a           [False, True, False, False]    False
  2 r,rq,100,b           [False, True, False, True]     False
  3 r,rq,500,a           [False, True, True, False]     False
  4 r,rq,500,b           [False, True, True, True]      False
  5 r,sq,100,a           [False, False, False, False]   False
  6 r,sq,100,b           [False, False, False, True]    False
  7 r,sq,500,a           [False, False, True, False]    False
  8 r,sq,500,b           [False, False, True, True]     False
  9 rw,rq,100,a          [True, True, False, False]     False
 10 rw,rq,100,b          [True, True, False, True]      False
 11 rw,rq,500,a          [True, True, True, False]      False
 12 rw,rq,500,b          [True, True, True, True]       True
 13 rw,sq,100,a          [True, False, False, False]    False
 14 rw,sq,100,b          [True, False, False, True]     False
 15 rw,sq,500,a          [True, False, True, False]     False
 16 rw,sq,500,b          [True, False, True, True]      False
</code>```

Body:
I have a structure similar, to a dictionary of dictionaries:

cont  = {

'perm': { 'r': False, 'rw': True}

'prig':  { 'sq': False, 'rot':False, 'rq':True}

'anon':  {'100': False, '500':True, '99':False; '400':False}

}

From this structure I need to generate a string from keys, and know if the string is False or True based on the values:

Example:

'perm', 'prig', 'anon' will become: 'r,sq,100' or 'rw,sq,100' or 'r,rq,100'.

I need to generate all permutations of the second level keys.

For each string, I need to associate a Boolean value using 'AND' are True or False.
For the example above:

False,False,False -> False;  True,False,False -> True,False,True, False -> False;

Body:
Here is my take on the assignment. It has a lot more code than the answer from @Ajax1234 but I hope it is easier to understand/read for some.

import itertools
data = {
    'test': {'a': False, 'b': True},
    'perm': {'r': False, 'rw': True},
    'prig': {'sq': False, 'rq': True},
    'anon': {'100': False, '500': True},
}

# define the order of the keys
key_order = ('perm', 'prig', 'anon', 'test')

# build a list of iterables for the 'product()' function
iterables = [
    sorted(data[k].keys())
    for k in key_order]
print(iterables)

print()
print('{:3s} {:20s} {:30s} {}'.format('i', 'elements', 'value of elements', 'AND'))

for i, elements in enumerate(itertools.product(*iterables)):
    # get the values for all the elements, in the correct order
    values = [
        data[k][sub_k]
        for k, sub_k in zip(key_order, elements)]

    print('{:3d} {:20s} {:30s} {}'.format(
        i+1,
        ','.join(elements),
        str(values),
        all(values)))

This code gives me the following output:

[['r', 'rw'], ['rq', 'sq'], ['100', '500'], ['a', 'b']]

i   elements             value of elements              AND
  1 r,rq,100,a           [False, True, False, False]    False
  2 r,rq,100,b           [False, True, False, True]     False
  3 r,rq,500,a           [False, True, True, False]     False
  4 r,rq,500,b           [False, True, True, True]      False
  5 r,sq,100,a           [False, False, False, False]   False
  6 r,sq,100,b           [False, False, False, True]    False
  7 r,sq,500,a           [False, False, True, False]    False
  8 r,sq,500,b           [False, False, True, True]     False
  9 rw,rq,100,a          [True, True, False, False]     False
 10 rw,rq,100,b          [True, True, False, True]      False
 11 rw,rq,500,a          [True, True, True, False]      False
 12 rw,rq,500,b          [True, True, True, True]       True
 13 rw,sq,100,a          [True, False, False, False]    False
 14 rw,sq,100,b          [True, False, False, True]     False
 15 rw,sq,500,a          [True, False, True, False]     False
 16 rw,sq,500,b          [True, False, True, True]      False


问:
Why is the currency modifier "C" returning '?' instead of '$' in C#?
Why does the code below display '?' instead of '$'?

```<code>static void Main(string[] args)
{
    float price = 29.56f;
    Console.WriteLine(price.ToString("c"));
}
</code>```

The result is: 29,56 ?

答:
It's not an actual ? character - that's a placeholder being printed in the console because the current console font doesn't have a glyph for whatever the local currency's currency symbol is (System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol).

If you always want US Dollars, then format using the en-US culture:

```<code>CultureInfo enUS = new CultureInfo("en-US");
String priceText = price.ToString( "C", enUS );
Console.WriteLine( priceText );
</code>```

Don't use en-US for other cultures, even if they use Dollars too (e.g. Australian dollars), instead use their culture explicitly - so your program will still work if in the future the country changes their currency symbol, or if they have other formatting rules (e.g. a different decimal symbol)

```<code>CultureInfo australia = new CultureInfo("en-AU");
String priceText = price.ToString( "C", australia );
Console.WriteLine( priceText );
</code>```

Additionally, you should not use IEEE-754 types when working with currency or monetary values because it’s imprecise by design. You should always use a fixed decimal type like System.Decimal or integer cents (though you can’t use ”C” forest strings with integer cents)

Body:
Why does the code below display '?' instead of '$'?

static void Main(string[] args)
{
    float price = 29.56f;
    Console.WriteLine(price.ToString("c"));
}

The result is: 29,56 ?

Body:
It's not an actual ? character - that's a placeholder being printed in the console because the current console font doesn't have a glyph for whatever the local currency's currency symbol is (System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol).

If you always want US Dollars, then format using the en-US culture:

CultureInfo enUS = new CultureInfo("en-US");
String priceText = price.ToString( "C", enUS );
Console.WriteLine( priceText );

Don't use en-US for other cultures, even if they use Dollars too (e.g. Australian dollars), instead use their culture explicitly - so your program will still work if in the future the country changes their currency symbol, or if they have other formatting rules (e.g. a different decimal symbol)

CultureInfo australia = new CultureInfo("en-AU");
String priceText = price.ToString( "C", australia );
Console.WriteLine( priceText );

Additionally, you should not use IEEE-754 types when working with currency or monetary values because it’s imprecise by design. You should always use a fixed decimal type like System.Decimal or integer cents (though you can’t use ”C” forest strings with integer cents)