问:
Could not get to a route in asp.net core
Why can't I get to the controller in my asp.net core application. Please see code below.

```<code>using System;
using System.Threading.Tasks;
using HashingApplication;
using Microsoft.AspNetCore.Mvc;
using NgWithJwt.Models;

namespace NgWithJwt.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly ApplicationDbContext context;

        public UserController(ApplicationDbContext context)
        {
            this.context = context;
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Route("add-user")]
        public async Task<IActionResult> AddUser(AppUser model)
        {
            if (ModelState.IsValid)
            {
                var saltValue = Guid.NewGuid().ToString() + model.Password;
                var password = Encryption.Encrypt(model.Password, saltValue);

                model.SaltValue = saltValue;
                model.Password = password;
                model.CreatedDate = DateTime.Now;

                context.Add(model);
                var response = await context.SaveChangesAsync();
                if(response > 0)
                {
                    return Ok(model);
                }
            }
            return BadRequest();
        }
    }
}
</code>```

This is my class for model

```<code> public partial class AppUser
    {
        [Key]
        public int Id { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "Username is required.")]
        [DisplayName("Username")]
        public string UserName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "First Name is required")]
        [DisplayName("First Name")]
        public string FirstName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [DisplayName("Middle Name")]
        public string MiddleName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "Last Name is required")]
        [DisplayName("Last Name")]
        public string LastName { get; set; }

        [Column(TypeName = "nvarchar(max)")]
        public string SaltValue { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "Password is required")]
        [DisplayName("Password")]
        public string Password { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        public string UserType { get; set; }
        public DateTime CreatedDate { get; set; }
    }
</code>```

My server is running so I try accessing it with postman like so:

```<code>{
    "Username": "juan",
    "FirstName": "Juan",
    "MiddleName": "A.",
    "LastName": "Dela Cruz",
    "Password": "password",
    "UserType": "User"
}
</code>```

Server is running at

"https://localhost:44366/"

I use this url to post data

http://localhost:44366/api/user/add-user

This is the error I get on postman. I am using the debug mode to get to my controller break point.

答: You said the server is running at https://localhost:44366/ but you are sending requests to http://localhost:44366/

Body:
Why can't I get to the controller in my asp.net core application. Please see code below.

using System;
using System.Threading.Tasks;
using HashingApplication;
using Microsoft.AspNetCore.Mvc;
using NgWithJwt.Models;

namespace NgWithJwt.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly ApplicationDbContext context;

        public UserController(ApplicationDbContext context)
        {
            this.context = context;
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Route("add-user")]
        public async Task<IActionResult> AddUser(AppUser model)
        {
            if (ModelState.IsValid)
            {
                var saltValue = Guid.NewGuid().ToString() + model.Password;
                var password = Encryption.Encrypt(model.Password, saltValue);

                model.SaltValue = saltValue;
                model.Password = password;
                model.CreatedDate = DateTime.Now;

                context.Add(model);
                var response = await context.SaveChangesAsync();
                if(response > 0)
                {
                    return Ok(model);
                }
            }
            return BadRequest();
        }
    }
}

This is my class for model

 public partial class AppUser
    {
        [Key]
        public int Id { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "Username is required.")]
        [DisplayName("Username")]
        public string UserName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "First Name is required")]
        [DisplayName("First Name")]
        public string FirstName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [DisplayName("Middle Name")]
        public string MiddleName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "Last Name is required")]
        [DisplayName("Last Name")]
        public string LastName { get; set; }

        [Column(TypeName = "nvarchar(max)")]
        public string SaltValue { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        [Required(ErrorMessage = "Password is required")]
        [DisplayName("Password")]
        public string Password { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        public string UserType { get; set; }
        public DateTime CreatedDate { get; set; }
    }

My server is running so I try accessing it with postman like so:

{
    "Username": "juan",
    "FirstName": "Juan",
    "MiddleName": "A.",
    "LastName": "Dela Cruz",
    "Password": "password",
    "UserType": "User"
}

Server is running at

"https://localhost:44366/"

I use this url to post data

http://localhost:44366/api/user/add-user

This is the error I get on postman. I am using the debug mode to get to my controller break point.


来源: stackexchange

问:
I am trying to fetch All text(tweet like a post) from database. REACT NATIVE
I am trying to fetch All text(tweet like a post) from database.but its showing error TypeError: undefined is not a function (near '...posts.map...')

below is my code:

```<code>import React, {useEffect, useState} from 'react';
    import {ActivityIndicator, Text, View, FlatList} from 'react-native';
    import stylesheet from '../src/styles/HomeStyle';
    import AsyncStorage from '@react-native-community/async-storage';

    function FeedScreen() {
      // const [posts, setPosts] = useState('loading');
      const [posts, setPosts] = useState({
        text: '',
        id: '',
      });
      const Boiler = async () => {
        const token = await AsyncStorage.getItem('token');
        fetch('http://192.168.1.5:3000/post', {
          headers: new Headers({
            Authorization: 'Bearer ' + token,
          }),
        })
          .then(res => res.json())
          .then(res => {
            setPosts(res.posts);
          })
          .catch(err => console.log(err));
      };
      useEffect(() => {
        Boiler();
      }, []);

      return (
        <View style={stylesheet.container}>
          {posts.map(post => (
            <Text key={post.id}>{post.text}</Text>
          ))}
        </View>
      );
    }

    export default FeedScreen;
</code>```

答:
The problem is the initial value for posts is a post and not an array of posts. I also renamed Boiler as initial uppercase should be reserved for components or classes, and moved it inside the useEffect:

```<code>const FeedScreen = () => {
    const [posts, setPosts] = useState([]); // Here was the issue

    useEffect(() => {
        const boiler = async () => {
            const token = await AsyncStorage.getItem("token");
            fetch("http://192.168.1.5:3000/post", {
                headers: new Headers({
                    Authorization: "Bearer " + token
                })
            })
                .then(res => res.json())
                .then(res => {
                    setPosts(res.posts);
                })
                .catch(err => console.log(err));
        };

        boiler();
    }, []);

    return (
        <View style={stylesheet.container}>
            {posts.map(post => (
                <Text key={post.id}>{post.text}</Text>
            ))}
        </View>
    );
};

export default FeedScreen;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to fetch All text(tweet like a post) from database.but its showing error TypeError: undefined is not a function (near '...posts.map...')

below is my code:

import React, {useEffect, useState} from 'react';
    import {ActivityIndicator, Text, View, FlatList} from 'react-native';
    import stylesheet from '../src/styles/HomeStyle';
    import AsyncStorage from '@react-native-community/async-storage';

    function FeedScreen() {
      // const [posts, setPosts] = useState('loading');
      const [posts, setPosts] = useState({
        text: '',
        id: '',
      });
      const Boiler = async () => {
        const token = await AsyncStorage.getItem('token');
        fetch('http://192.168.1.5:3000/post', {
          headers: new Headers({
            Authorization: 'Bearer ' + token,
          }),
        })
          .then(res => res.json())
          .then(res => {
            setPosts(res.posts);
          })
          .catch(err => console.log(err));
      };
      useEffect(() => {
        Boiler();
      }, []);

      return (
        <View style={stylesheet.container}>
          {posts.map(post => (
            <Text key={post.id}>{post.text}</Text>
          ))}
        </View>
      );
    }

    export default FeedScreen;

Body:
The problem is the initial value for posts is a post and not an array of posts. I also renamed Boiler as initial uppercase should be reserved for components or classes, and moved it inside the useEffect:

const FeedScreen = () => {
    const [posts, setPosts] = useState([]); // Here was the issue

    useEffect(() => {
        const boiler = async () => {
            const token = await AsyncStorage.getItem("token");
            fetch("http://192.168.1.5:3000/post", {
                headers: new Headers({
                    Authorization: "Bearer " + token
                })
            })
                .then(res => res.json())
                .then(res => {
                    setPosts(res.posts);
                })
                .catch(err => console.log(err));
        };

        boiler();
    }, []);

    return (
        <View style={stylesheet.container}>
            {posts.map(post => (
                <Text key={post.id}>{post.text}</Text>
            ))}
        </View>
    );
};

export default FeedScreen;


问:
How to get the location of all text present in an image using OpenCV?
I have this image that contains text (numbers and alphabets) in it. I want to get the location of all the text and numbers present in this image. Also I want to extract all the text as well.

How do I get the coordinates as well as the all the text (numbers and alphabets) in my image? For eg 10B, 44, 16, 38, 22B etc

答:
Here's a potential approach using morphological operations to filter out non-text contours. The idea is:

Obtain binary image. Load image, grayscale, then
Otsu's threshold

Remove horizontal and vertical lines. Create horizontal and vertical kernels using cv2.getStructuringElement() then remove lines with cv2.drawContours()

Remove diagonal lines, circle objects, and curved contours. Filter using contour area cv2.contourArea()
and contour approximation cv2.approxPolyDP()
to isolate non-text contours

Extract text ROIs and OCR. Find contours and filter for ROIs then OCR using
Pytesseract.

Removed horizontal lines highlighted in green

Removed vertical lines

Removed assorted non-text contours (diagonal lines, circular objects, and curves)

Detected text regions

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

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

# Load image, grayscale, Otsu's threshold
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
clean = thresh.copy()

# Remove horizontal lines
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15,1))
detect_horizontal = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
cnts = cv2.findContours(detect_horizontal, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(clean, [c], -1, 0, 3)

# Remove vertical lines
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,30))
detect_vertical = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2)
cnts = cv2.findContours(detect_vertical, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(clean, [c], -1, 0, 3)

cnts = cv2.findContours(clean, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    # Remove diagonal lines
    area = cv2.contourArea(c)
    if area < 100:
        cv2.drawContours(clean, [c], -1, 0, 3)
    # Remove circle objects
    elif area > 1000:
        cv2.drawContours(clean, [c], -1, 0, -1)
    # Remove curve stuff
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)
    x,y,w,h = cv2.boundingRect(c)
    if len(approx) == 4:
        cv2.rectangle(clean, (x, y), (x + w, y + h), 0, -1)

open_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2))
opening = cv2.morphologyEx(clean, cv2.MORPH_OPEN, open_kernel, iterations=2)
close_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,2))
close = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, close_kernel, iterations=4)
cnts = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    x,y,w,h = cv2.boundingRect(c)
    area = cv2.contourArea(c)
    if area > 500:
        ROI = image[y:y+h, x:x+w]
        ROI = cv2.GaussianBlur(ROI, (3,3), 0)
        data = pytesseract.image_to_string(ROI, lang='eng',config='--psm 6')
        if data.isalnum():
            cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
            print(data)

cv2.imwrite('image.png', image)
cv2.imwrite('clean.png', clean)
cv2.imwrite('close.png', close)
cv2.imwrite('opening.png', opening)
cv2.waitKey()
</code>```

Body:
Here's a potential approach using morphological operations to filter out non-text contours. The idea is:

Obtain binary image. Load image, grayscale, then
Otsu's threshold

Remove horizontal and vertical lines. Create horizontal and vertical kernels using cv2.getStructuringElement() then remove lines with cv2.drawContours()

Remove diagonal lines, circle objects, and curved contours. Filter using contour area cv2.contourArea()
and contour approximation cv2.approxPolyDP()
to isolate non-text contours

Extract text ROIs and OCR. Find contours and filter for ROIs then OCR using
Pytesseract.

Removed horizontal lines highlighted in green

Removed vertical lines

Removed assorted non-text contours (diagonal lines, circular objects, and curves)

Detected text regions

import cv2
import numpy as np
import pytesseract

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

# Load image, grayscale, Otsu's threshold
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
clean = thresh.copy()

# Remove horizontal lines
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15,1))
detect_horizontal = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
cnts = cv2.findContours(detect_horizontal, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(clean, [c], -1, 0, 3)

# Remove vertical lines
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,30))
detect_vertical = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2)
cnts = cv2.findContours(detect_vertical, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(clean, [c], -1, 0, 3)

cnts = cv2.findContours(clean, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    # Remove diagonal lines
    area = cv2.contourArea(c)
    if area < 100:
        cv2.drawContours(clean, [c], -1, 0, 3)
    # Remove circle objects
    elif area > 1000:
        cv2.drawContours(clean, [c], -1, 0, -1)
    # Remove curve stuff
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)
    x,y,w,h = cv2.boundingRect(c)
    if len(approx) == 4:
        cv2.rectangle(clean, (x, y), (x + w, y + h), 0, -1)

open_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2))
opening = cv2.morphologyEx(clean, cv2.MORPH_OPEN, open_kernel, iterations=2)
close_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,2))
close = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, close_kernel, iterations=4)
cnts = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    x,y,w,h = cv2.boundingRect(c)
    area = cv2.contourArea(c)
    if area > 500:
        ROI = image[y:y+h, x:x+w]
        ROI = cv2.GaussianBlur(ROI, (3,3), 0)
        data = pytesseract.image_to_string(ROI, lang='eng',config='--psm 6')
        if data.isalnum():
            cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
            print(data)

cv2.imwrite('image.png', image)
cv2.imwrite('clean.png', clean)
cv2.imwrite('close.png', close)
cv2.imwrite('opening.png', opening)
cv2.waitKey()


问:
Class variable is undefined... despite being defined
I have a class called RouteBinder that looks like this:

class RouteBinder
    constructor: (@server, @pool) ->
    bindRoute: (name, fn, method = "post", useDb = true) ->
        @server[method]("/api/accounts/v1/" + name, (req, res, next) ->
            client = await @pool.connect() if useDb?
            await fn req, res, next, client
            await @pool.release() if useDb?
        )
```

<p>I declare it and call it like this:</p>

<pre class="lang-coffee prettyprint-override"><code>    binder = new RouteBinder server, pool

    binder.bindRoute "login", controllers.login
</code>```

(Pool is node-postgres's Pool and is declared and tested earlier like this)

    pool = new Pool

    [...]

    try
        client = await pool.connect()
        await client.query 'SELECT 1=1'
    catch e
        console.fatal "Could not connect to database: #{e}"
        return
    finally
        try client.release() if client?
        catch e
            console.fatal "Couldn't release client: #{e}"
            return

    console.info 'Database is OK!'
```

<p>When running this, I get this error:</p>

<pre class="lang-coffee prettyprint-override"><code> 02/14 18:44:34   error   (node:11855) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'connect' of undefined
    at _callee2$ (/home/vi/[redacted]_accounts/main.js:136:38)
    at tryCatch (/home/vi/[redacted]_accounts/node_modules/regenerator-runtime/runtime.js:45:40)
    at Generator.invoke [as _invoke] (/home/vi/[redacted]_accounts/node_modules/regenerator-runtime/runtime.js:271:22)
    at Generator.prototype.(anonymous function) [as next] (/home/vi/[redacted]_accounts/node_modules/regenerator-runtime/runtime.js:97:21)
    at asyncGeneratorStep (/home/vi/[redacted]_accounts/node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:24)
    at _next (/home/vi/[redacted]_accounts/node_modules/@babel/runtime/helpers/asyncToGenerator.js:25:9)
    at /home/vi/[redacted]_accounts/node_modules/@babel/runtime/helpers/asyncToGenerator.js:32:7
    at new Promise (<anonymous>)
    at /home/vi/[redacted]_accounts/node_modules/@babel/runtime/helpers/asyncToGenerator.js:21:12
    at /home/vi/[redacted]_accounts/main.js:166:26
 02/14 18:44:34   error   (node:11855) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
 02/14 18:44:34   error   (node:11855) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

I'm using CoffeeScript compiled transpiled with Babel. My .babelrc looks like this:

{
  "presets": ["@babel/env"],
  "plugins": [
    ["@babel/plugin-transform-runtime",
      {
        "regenerator": true
      }
    ]
  ]
}
```

Sorry if it's a rookie question, I'm still learning and would love all the advice I can get.

答:
I figured out my mistake. Both @pool and @server were defined, however, the inline function (handler) for @server[method] was running in the context of that function.

The solution was to bind it to the RouteBinder instance using .bind(@) (or .bind(this), if you prefer)

    bindRoute: (name, fn, method = "post", useDb = true) ->
        @server[method]("/api/accounts/v1/" + name, ((req, res, next) ->
            console.log "pool", @pool
            client = await @pool.connect() if useDb?
            await fn req, res, next, client
            await @pool.release() if useDb?
        ).bind(@))
```

Body:
I have a class called RouteBinder that looks like this:

class RouteBinder
    constructor: (@server, @pool) ->
    bindRoute: (name, fn, method = "post", useDb = true) ->
        @server[method]("/api/accounts/v1/" + name, (req, res, next) ->
            client = await @pool.connect() if useDb?
            await fn req, res, next, client
            await @pool.release() if useDb?
        )

I declare it and call it like this:

    binder = new RouteBinder server, pool

    binder.bindRoute "login", controllers.login

(Pool is node-postgres's Pool and is declared and tested earlier like this)

    pool = new Pool

    [...]

    try
        client = await pool.connect()
        await client.query 'SELECT 1=1'
    catch e
        console.fatal "Could not connect to database: #{e}"
        return
    finally
        try client.release() if client?
        catch e
            console.fatal "Couldn't release client: #{e}"
            return

    console.info 'Database is OK!'

When running this, I get this error:

 02/14 18:44:34   error   (node:11855) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'connect' of undefined
    at _callee2$ (/home/vi/[redacted]_accounts/main.js:136:38)
    at tryCatch (/home/vi/[redacted]_accounts/node_modules/regenerator-runtime/runtime.js:45:40)
    at Generator.invoke [as _invoke] (/home/vi/[redacted]_accounts/node_modules/regenerator-runtime/runtime.js:271:22)
    at Generator.prototype.(anonymous function) [as next] (/home/vi/[redacted]_accounts/node_modules/regenerator-runtime/runtime.js:97:21)
    at asyncGeneratorStep (/home/vi/[redacted]_accounts/node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:24)
    at _next (/home/vi/[redacted]_accounts/node_modules/@babel/runtime/helpers/asyncToGenerator.js:25:9)
    at /home/vi/[redacted]_accounts/node_modules/@babel/runtime/helpers/asyncToGenerator.js:32:7
    at new Promise (<anonymous>)
    at /home/vi/[redacted]_accounts/node_modules/@babel/runtime/helpers/asyncToGenerator.js:21:12
    at /home/vi/[redacted]_accounts/main.js:166:26
 02/14 18:44:34   error   (node:11855) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
 02/14 18:44:34   error   (node:11855) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I'm using CoffeeScript compiled transpiled with Babel. My .babelrc looks like this:

{
  "presets": ["@babel/env"],
  "plugins": [
    ["@babel/plugin-transform-runtime",
      {
        "regenerator": true
      }
    ]
  ]
}

Sorry if it's a rookie question, I'm still learning and would love all the advice I can get.


问:
How exactly can I find the pallindrome of a 32 bit number using ARM assembly?
I was trying to find an assembly code to find whether the given number is a palindrome. I got a code online. But I am not able to understand the 'movu' command. Can anyone explain? </p>

```<code>mov R0,1044480
mov R3,0
mov R4,31
movu R2,0x0001
mov R5,0
andu R1,R0,0xffff

.loop:
and R3,R2,R1
lsl R2,R2,1
lsl R3,R3,R4
add R5,R5,R3
sub R4,R4,2
cmp R4,0
bgt .loop
lsr R0,R0,16
lsr R5,R5,16
sub R0,R5,R0
cmp R0,0
beq .palin
mov R0,0

b .exit

.palin:
mov R0,1

.exit:
</code>```

答:
There are a couple of questions here.  Why are you doing this in assembly when you don't seem overly familiar with the instruction set?  What device are you writing this assembly code for?  Surely if you're doing assembly, you should at least have the instruction set documentation for the processor?

Now let's deal with the question itself.  movu is the mnemonic for MOV Unsigned.  This essentially works the same way as the MOV instruction, the difference being that it does not alter the status register, unlike MOV.  This way you can move a register to a destination without changing, for example the Z, C or N flags.

Body:
I was trying to find an assembly code to find whether the given number is a palindrome. I got a code online. But I am not able to understand the 'movu' command. Can anyone explain?

mov R0,1044480
mov R3,0
mov R4,31
movu R2,0x0001
mov R5,0
andu R1,R0,0xffff

.loop:
and R3,R2,R1
lsl R2,R2,1
lsl R3,R3,R4
add R5,R5,R3
sub R4,R4,2
cmp R4,0
bgt .loop
lsr R0,R0,16
lsr R5,R5,16
sub R0,R5,R0
cmp R0,0
beq .palin
mov R0,0

b .exit

.palin:
mov R0,1

.exit:


问:
I don't know only first element getting picked up by my sql query
I am using sqlite3. I am working on IMDB database. I want to extract the movies with a rating of 10.0 but it's only giving me the first result. Although, I can extract the movie_id but can't reproduce the title.</p>

```<code>sqlite> .schema
CREATE TABLE movies (
                    id INTEGER,
                    title TEXT NOT NULL,
                    year NUMERIC,
                    PRIMARY KEY(id)
                );
CREATE TABLE stars (
                movie_id INTEGER NOT NULL,
                person_id INTEGER NOT NULL,
                FOREIGN KEY(movie_id) REFERENCES movies(id),
                FOREIGN KEY(person_id) REFERENCES people(id)
            );
CREATE TABLE directors (
                movie_id INTEGER NOT NULL,
                person_id INTEGER NOT NULL,
                FOREIGN KEY(movie_id) REFERENCES movies(id),
                FOREIGN KEY(person_id) REFERENCES people(id)
            );
CREATE TABLE ratings (
                movie_id INTEGER NOT NULL,
                rating REAL NOT NULL,
                votes INTEGER NOT NULL,
                FOREIGN KEY(movie_id) REFERENCES movies(id)
            );
CREATE TABLE people (
                id INTEGER,
                name TEXT NOT NULL,
                birth NUMERIC,
                PRIMARY KEY(id)
            );
sqlite> SELECT movie_id from ratings WHERE rating = 10.0;
movie_id
10176328
10342460
10544422
10716326
10914342
11099860
2632430
2633610
3525174
5390098
8035236
8563656
sqlite> SELECT title FROM movies WHERE id = (SELECT movie_id from ratings WHERE rating = 10.0);
title
Exteriores: Mulheres Brasileiras na Diplomacia
sqlite> SELECT title FROM movies where id = '10176328';
title
Exteriores: Mulheres Brasileiras na Diplomacia
sqlite>
</code>```

答:
An alternative that may be more efficient than IN is to use EXISTS:

```<code>SELECT m.title
FROM movies AS m
WHERE EXISTS (SELECT 1 FROM ratings AS r WHERE r.rating = 10.0 AND r.movie_id = m.id)
</code>```

Body:
I am using sqlite3. I am working on IMDB database. I want to extract the movies with a rating of 10.0 but it's only giving me the first result. Although, I can extract the movie_id but can't reproduce the title.

sqlite> .schema
CREATE TABLE movies (
                    id INTEGER,
                    title TEXT NOT NULL,
                    year NUMERIC,
                    PRIMARY KEY(id)
                );
CREATE TABLE stars (
                movie_id INTEGER NOT NULL,
                person_id INTEGER NOT NULL,
                FOREIGN KEY(movie_id) REFERENCES movies(id),
                FOREIGN KEY(person_id) REFERENCES people(id)
            );
CREATE TABLE directors (
                movie_id INTEGER NOT NULL,
                person_id INTEGER NOT NULL,
                FOREIGN KEY(movie_id) REFERENCES movies(id),
                FOREIGN KEY(person_id) REFERENCES people(id)
            );
CREATE TABLE ratings (
                movie_id INTEGER NOT NULL,
                rating REAL NOT NULL,
                votes INTEGER NOT NULL,
                FOREIGN KEY(movie_id) REFERENCES movies(id)
            );
CREATE TABLE people (
                id INTEGER,
                name TEXT NOT NULL,
                birth NUMERIC,
                PRIMARY KEY(id)
            );
sqlite> SELECT movie_id from ratings WHERE rating = 10.0;
movie_id
10176328
10342460
10544422
10716326
10914342
11099860
2632430
2633610
3525174
5390098
8035236
8563656
sqlite> SELECT title FROM movies WHERE id = (SELECT movie_id from ratings WHERE rating = 10.0);
title
Exteriores: Mulheres Brasileiras na Diplomacia
sqlite> SELECT title FROM movies where id = '10176328';
title
Exteriores: Mulheres Brasileiras na Diplomacia
sqlite>

Body:
An alternative that may be more efficient than IN is to use EXISTS:

SELECT m.title
FROM movies AS m
WHERE EXISTS (SELECT 1 FROM ratings AS r WHERE r.rating = 10.0 AND r.movie_id = m.id)


问:
Is it possible to run multiple web instance in the same AWS EC2?
Background

I have followed this tutorial https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-cli-tutorial-ec2.html, composed a docker compose file, made a website A (compose of 4 containers) up and run serving 1 of my client.

However, now I have another client which I need to host another web site website B using similar strategies as above.

Here is the current running service of ECS / EC2

and here are the containers up and running, serving website A now

Questions & concerns

The website A is now situated as 1 of a service in the EC2 under my only cluster, can I use the same EC2 instance and run website B (as another service of the EC2)?

If so, how are the ports / inbound / outbound traffic being managed? Now website A already occupies port 80, 443, 27017 and 3002 of the EC2 instance for inbound traffic, if website B's containers also run in the same EC2 instances, can I still use port 80, 443, 27017 and 3002 for website B. I have read the docs of ALB (Amazon Load Balancer), seems it can fulfill the requirement, am I at the right track?

And the domain name, through route 53, I have registered a domain www.websiteA.com to serve the 1st website, I have also registered another www.websiteB.com preparing to serve website B, in my case, I guess I need to configure the new domain B pointing to the same EC2 IP?

During my deployment of website B, I do not want to affect the availability of website A, can it be maintained during the process of deploying website B's containers?

I want to clear all the concepts before kick-starting to deploy the website B, appreciate for any help, thank you

Follow-up actions

I come up decided to use AWS application load balancer to solve my issue, and have the following configurations setup.

I first look into load balancer

And configured as follows

I setup a load balancer which listens for requests using HTTP protocol with incoming port 80, whenever there are users access the web server (i.e.: the frontend container), listener will forward that request to the target group (i.e.: http-port-80-access)

And here is the target group (http-port-80-access) which contains a registered target (currently my ec2 instance running the containers), the host port of the container is 32849 which in turn made used by the associated load balancer (web-access-load-balancer) for dynamic port mapping.

I have also configured 1 more rule on top of the default rule, whenever user access url of websiteA, load balancer will forward the request to the target group (http-port-80-access).

All things set, and the healthy test also passed. I then used the following ecs-cli compose service up command to wire up the load balancer with the service

ecs-cli compose --file ./docker-compose-aws-prod.yml --cluster my-ecs-cluster-name --ecs-profile my-ecs-profile --cluster-config my-cluster --project-name my-project --ecs-params ./ecs-params.yml service up --target-group-arn arn:aws:elasticloadbalancing:us-east-2:xxxxxxxxx:targetgroup/http-port-80-access/xxxxxxxx --container-name frontend --container-port 80
```

where frontend is the service name of the frontend container of website A

However, turn out when I access www.websiteA.com through browser, nothing but ERR_CONNECTION_REFUSED, accessing www.websiteA.com:32849 did accessible, but is not what I desired.

I am wondering which part I configured wrongly

答: If you are sending traffic directly to the instance then you would have to host on a different port. You should consider using an ALB, which would allow you to use dynamic ports in ECS. The ALB can accept traffic from ports 80 and 443 for different domains and route the traffic to different containers based on things like the domain.</p>

Body:
Background

I have followed this tutorial https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-cli-tutorial-ec2.html, composed a docker compose file, made a website A (compose of 4 containers) up and run serving 1 of my client.

However, now I have another client which I need to host another web site website B using similar strategies as above.

Here is the current running service of ECS / EC2

and here are the containers up and running, serving website A now

Questions & concerns

The website A is now situated as 1 of a service in the EC2 under my only cluster, can I use the same EC2 instance and run website B (as another service of the EC2)?

If so, how are the ports / inbound / outbound traffic being managed? Now website A already occupies port 80, 443, 27017 and 3002 of the EC2 instance for inbound traffic, if website B's containers also run in the same EC2 instances, can I still use port 80, 443, 27017 and 3002 for website B. I have read the docs of ALB (Amazon Load Balancer), seems it can fulfill the requirement, am I at the right track?

And the domain name, through route 53, I have registered a domain www.websiteA.com to serve the 1st website, I have also registered another www.websiteB.com preparing to serve website B, in my case, I guess I need to configure the new domain B pointing to the same EC2 IP?

During my deployment of website B, I do not want to affect the availability of website A, can it be maintained during the process of deploying website B's containers?

I want to clear all the concepts before kick-starting to deploy the website B, appreciate for any help, thank you

Follow-up actions

I come up decided to use AWS application load balancer to solve my issue, and have the following configurations setup.

I first look into load balancer

And configured as follows

I setup a load balancer which listens for requests using HTTP protocol with incoming port 80, whenever there are users access the web server (i.e.: the frontend container), listener will forward that request to the target group (i.e.: http-port-80-access)

And here is the target group (http-port-80-access) which contains a registered target (currently my ec2 instance running the containers), the host port of the container is 32849 which in turn made used by the associated load balancer (web-access-load-balancer) for dynamic port mapping.

I have also configured 1 more rule on top of the default rule, whenever user access url of websiteA, load balancer will forward the request to the target group (http-port-80-access).

All things set, and the healthy test also passed. I then used the following ecs-cli compose service up command to wire up the load balancer with the service

ecs-cli compose --file ./docker-compose-aws-prod.yml --cluster my-ecs-cluster-name --ecs-profile my-ecs-profile --cluster-config my-cluster --project-name my-project --ecs-params ./ecs-params.yml service up --target-group-arn arn:aws:elasticloadbalancing:us-east-2:xxxxxxxxx:targetgroup/http-port-80-access/xxxxxxxx --container-name frontend --container-port 80

where frontend is the service name of the frontend container of website A

However, turn out when I access www.websiteA.com through browser, nothing but ERR_CONNECTION_REFUSED, accessing www.websiteA.com:32849 did accessible, but is not what I desired.

I am wondering which part I configured wrongly


问:
Trying to do some c programming homework and need a bit of guidance
```<code>#include <math.h>
#include <stdio.h>

int main() {
    char ch1 = 'B', ch2 = 'A';
    int result;

    printf("Enter 2 characters without spaces: ");
    scanf("%c%c", &ch1, &ch2);

    result = ch1 % ch2;
}
</code>```

I input AB and I cant seem to get the answer or result to come out.

答:
looks like you have just started with C, so in order to get any output, you have to print it using ' printf("..."); ' unless you do that,it will not be displayed by itself.

insert this statement  ' printf("%d",result); '  after  ' result = ch1 % ch2; statement'.

Body:
#include <math.h>
#include <stdio.h>

int main() {
    char ch1 = 'B', ch2 = 'A';
    int result;

    printf("Enter 2 characters without spaces: ");
    scanf("%c%c", &ch1, &ch2);

    result = ch1 % ch2;
}

I input AB and I cant seem to get the answer or result to come out.


问:
Portfolio Optimize in R with ONLY a vector of mean returns and covariance matrix
Every package that I look at seems to require time series returns for my assets.

For example I like the PortfolioAnalytics package, and I require many of the constraints offered (box constraints, group constraints, etc.). However, as far as I can tell it requires some sort of time series of returns, even if I specify my own moments (I could be wrong).

All I have are the expected returns of each of my 14 assets and the covariance matrix.

How can I do various forms of optimizations with that as my starting point? Ultimately I'd like to build a full efficient frontier as well as be able to maximize return at a given level of risk (standard deviation) given my constraints. If I had a time series this wouldn't be a problem...but alas I do not.

Thanks. I feel like this should be quite easy but I've been running in circles.

Worst case scenario is I could build a fake time series that fits the parameters of the E(R) and covariance matrix..if you think this is my solution can you offer me an easy way to do that...but that is why I am here :)

答:
How about this?

```<code>library(stockPortfolio)
library(quadprog)
library(ggplot2)
stocks <- c("SPY",  "EFA",  "IWM",  "VWO",  "LQD",  "HYG")

returns <- getReturns(stocks, freq = "week")

eff.frontier <-  function (returns,
                           short = "no",
                           max.allocation = NULL,
                           risk.premium.up = .5,
                           risk.increment = .005) {
  covariance <- cov(returns)
  print(covariance)
  n <- ncol(covariance)

  # Create initial Amat and bvec assuming only equality constraint (short-selling is allowed, no allocation constraints)
  Amat <- matrix (1, nrow = n)
  bvec <- 1
  meq <- 1

  # Then modify the Amat and bvec if short-selling is prohibited
  if (short == "no") {
    Amat <- cbind(1, diag(n))
    bvec <- c(bvec, rep(0, n))
  }

  # And modify Amat and bvec if a max allocation (concentration) is specified
  if (!is.null(max.allocation)) {
    if (max.allocation > 1 | max.allocation < 0) {
      stop("max.allocation must be greater than 0 and less than 1")
    }
    if (max.allocation * n < 1) {
      stop("Need to set max.allocation higher; not enough assets to add to 1")
    }
    Amat <- cbind(Amat, -diag(n))
    bvec <- c(bvec, rep(-max.allocation, n))
  }

  # Calculate the number of loops based on how high to vary the risk premium and by what increment
  loops <- risk.premium.up / risk.increment + 1
  loop <- 1

  # Initialize a matrix to contain allocation and statistics
  # This is not necessary, but speeds up processing and uses less memory
  eff <- matrix(nrow = loops, ncol = n + 3)
  # Now I need to give the matrix column names
  colnames(eff) <-
    c(colnames(returns), "Std.Dev", "Exp.Return", "sharpe")

  # Loop through the quadratic program solver
  for (i in seq(from = 0, to = risk.premium.up, by = risk.increment)) {
    dvec <-
      colMeans(returns) * i # This moves the solution up along the efficient frontier
    sol <-
      solve.QP(
        covariance,
        dvec = dvec,
        Amat = Amat,
        bvec = bvec,
        meq = meq
      )
    eff[loop, "Std.Dev"] <-
      sqrt(sum(sol$solution * colSums((
        covariance * sol$solution
      ))))
    eff[loop, "Exp.Return"] <-
      as.numeric(sol$solution %*% colMeans(returns))
    eff[loop, "sharpe"] <-
      eff[loop, "Exp.Return"] / eff[loop, "Std.Dev"]
    eff[loop, 1:n] <- sol$solution
    loop <- loop + 1
  }

  return(as.data.frame(eff))
}

eff <-
  eff.frontier(
    returns = returns$R,
    short = "yes",
    max.allocation = .45,
    risk.premium.up = .5,
    risk.increment = .001
  )

eff.optimal.point <- eff[eff$sharpe == max(eff$sharpe),]

ealred  <- "#7D110C"
ealtan  <- "#CDC4B6"
eallighttan <- "#F7F6F0"
ealdark  <- "#423C30"
ggplot(eff, aes(x = Std.Dev, y = Exp.Return)) + geom_point(alpha = .1, color =
                                                             ealdark) +
  geom_point(
    data = eff.optimal.point,
    aes(x = Std.Dev, y = Exp.Return, label = sharpe),
    color = ealred,
    size = 5
  ) +
  annotate(
    geom = "text",
    x = eff.optimal.point$Std.Dev,
    y = eff.optimal.point$Exp.Return,
    label = paste(
      "Risk: ",
      round(eff.optimal.point$Std.Dev * 100, digits = 3),
      "\nReturn: ",
      round(eff.optimal.point$Exp.Return * 100, digits =
              4),
      "%\nSharpe: ",
      round(eff.optimal.point$sharpe * 100, digits = 2),
      "%",
      sep = ""
    ),
    hjust = 0,
    vjust = 1.2
  ) +
  ggtitle("Efficient Frontier\nand Optimal Portfolio") + labs(x = "Risk (standard deviation of portfolio variance)", y =
                                                                "Return") +
  theme(
    panel.background = element_rect(fill = eallighttan),
    text = element_text(color = ealdark),
    plot.title = element_text(size = 24, color = ealred)
  )
</code>```

This should help as well.

https://www.r-bloggers.com/a-gentle-introduction-to-finance-using-r-efficient-frontier-and-capm-part-1/

Body:
How about this?

library(stockPortfolio)
library(quadprog)
library(ggplot2)
stocks <- c("SPY",  "EFA",  "IWM",  "VWO",  "LQD",  "HYG")

returns <- getReturns(stocks, freq = "week")

eff.frontier <-  function (returns,
                           short = "no",
                           max.allocation = NULL,
                           risk.premium.up = .5,
                           risk.increment = .005) {
  covariance <- cov(returns)
  print(covariance)
  n <- ncol(covariance)

  # Create initial Amat and bvec assuming only equality constraint (short-selling is allowed, no allocation constraints)
  Amat <- matrix (1, nrow = n)
  bvec <- 1
  meq <- 1

  # Then modify the Amat and bvec if short-selling is prohibited
  if (short == "no") {
    Amat <- cbind(1, diag(n))
    bvec <- c(bvec, rep(0, n))
  }

  # And modify Amat and bvec if a max allocation (concentration) is specified
  if (!is.null(max.allocation)) {
    if (max.allocation > 1 | max.allocation < 0) {
      stop("max.allocation must be greater than 0 and less than 1")
    }
    if (max.allocation * n < 1) {
      stop("Need to set max.allocation higher; not enough assets to add to 1")
    }
    Amat <- cbind(Amat, -diag(n))
    bvec <- c(bvec, rep(-max.allocation, n))
  }

  # Calculate the number of loops based on how high to vary the risk premium and by what increment
  loops <- risk.premium.up / risk.increment + 1
  loop <- 1

  # Initialize a matrix to contain allocation and statistics
  # This is not necessary, but speeds up processing and uses less memory
  eff <- matrix(nrow = loops, ncol = n + 3)
  # Now I need to give the matrix column names
  colnames(eff) <-
    c(colnames(returns), "Std.Dev", "Exp.Return", "sharpe")

  # Loop through the quadratic program solver
  for (i in seq(from = 0, to = risk.premium.up, by = risk.increment)) {
    dvec <-
      colMeans(returns) * i # This moves the solution up along the efficient frontier
    sol <-
      solve.QP(
        covariance,
        dvec = dvec,
        Amat = Amat,
        bvec = bvec,
        meq = meq
      )
    eff[loop, "Std.Dev"] <-
      sqrt(sum(sol$solution * colSums((
        covariance * sol$solution
      ))))
    eff[loop, "Exp.Return"] <-
      as.numeric(sol$solution %*% colMeans(returns))
    eff[loop, "sharpe"] <-
      eff[loop, "Exp.Return"] / eff[loop, "Std.Dev"]
    eff[loop, 1:n] <- sol$solution
    loop <- loop + 1
  }

  return(as.data.frame(eff))
}

eff <-
  eff.frontier(
    returns = returns$R,
    short = "yes",
    max.allocation = .45,
    risk.premium.up = .5,
    risk.increment = .001
  )

eff.optimal.point <- eff[eff$sharpe == max(eff$sharpe),]

ealred  <- "#7D110C"
ealtan  <- "#CDC4B6"
eallighttan <- "#F7F6F0"
ealdark  <- "#423C30"
ggplot(eff, aes(x = Std.Dev, y = Exp.Return)) + geom_point(alpha = .1, color =
                                                             ealdark) +
  geom_point(
    data = eff.optimal.point,
    aes(x = Std.Dev, y = Exp.Return, label = sharpe),
    color = ealred,
    size = 5
  ) +
  annotate(
    geom = "text",
    x = eff.optimal.point$Std.Dev,
    y = eff.optimal.point$Exp.Return,
    label = paste(
      "Risk: ",
      round(eff.optimal.point$Std.Dev * 100, digits = 3),
      "\nReturn: ",
      round(eff.optimal.point$Exp.Return * 100, digits =
              4),
      "%\nSharpe: ",
      round(eff.optimal.point$sharpe * 100, digits = 2),
      "%",
      sep = ""
    ),
    hjust = 0,
    vjust = 1.2
  ) +
  ggtitle("Efficient Frontier\nand Optimal Portfolio") + labs(x = "Risk (standard deviation of portfolio variance)", y =
                                                                "Return") +
  theme(
    panel.background = element_rect(fill = eallighttan),
    text = element_text(color = ealdark),
    plot.title = element_text(size = 24, color = ealred)
  )

This should help as well.

https://www.r-bloggers.com/a-gentle-introduction-to-finance-using-r-efficient-frontier-and-capm-part-1/


问:
get string value from HashMap depending on key name
I have a HashMap with various keys and values, how can I get one value out?

I have a key in the map called my_code, it should contain a string, how can I just get that without having to iterate through the map?

So far I've got..

```<code>   HashMap newMap = new HashMap(paramMap);
   String s = newMap.get("my_code").toString();
</code>```

I'm expecting to see a String, such as "ABC" or "DEF" as that is what I put in there initially, but if I do a System.out.println() I get something like java.lang.string#F0454

Sorry, I'm not too familiar with maps as you can probably guess ;)

答:
This is another example of how to use keySet(), get(), values() and entrySet() functions to obtain Keys and Values in a Map:</p>

```<code>        Map<Integer, String> testKeyset = new HashMap<Integer, String>();

        testKeyset.put(1, "first");
        testKeyset.put(2, "second");
        testKeyset.put(3, "third");
        testKeyset.put(4, "fourth");

        // Print a single value relevant to a specified Key. (uses keySet())
        for(int mapKey: testKeyset.keySet())
            System.out.println(testKeyset.get(mapKey));

        // Print all values regardless of the key.
        for(String mapVal: testKeyset.values())
            System.out.println(mapVal.trim());

        // Displays the Map in Key-Value pairs (e.g: [1=first, 2=second, 3=third, 4=fourth])
        System.out.println(testKeyset.entrySet());
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a HashMap with various keys and values, how can I get one value out?

I have a key in the map called my_code, it should contain a string, how can I just get that without having to iterate through the map?

So far I've got..

   HashMap newMap = new HashMap(paramMap);
   String s = newMap.get("my_code").toString();

I'm expecting to see a String, such as "ABC" or "DEF" as that is what I put in there initially, but if I do a System.out.println() I get something like java.lang.string#F0454

Sorry, I'm not too familiar with maps as you can probably guess ;)

Body:
This is another example of how to use keySet(), get(), values() and entrySet() functions to obtain Keys and Values in a Map:

        Map<Integer, String> testKeyset = new HashMap<Integer, String>();

        testKeyset.put(1, "first");
        testKeyset.put(2, "second");
        testKeyset.put(3, "third");
        testKeyset.put(4, "fourth");

        // Print a single value relevant to a specified Key. (uses keySet())
        for(int mapKey: testKeyset.keySet())
            System.out.println(testKeyset.get(mapKey));

        // Print all values regardless of the key.
        for(String mapVal: testKeyset.values())
            System.out.println(mapVal.trim());

        // Displays the Map in Key-Value pairs (e.g: [1=first, 2=second, 3=third, 4=fourth])
        System.out.println(testKeyset.entrySet());


问:
RegEx find string containing numbers with one space, two spaces or no space at all followed by / and four numbers
I need to use RegEx to find a string in Word document. The string contains numbers{1;5} with one space, two spaces or no space at all followed by / and four numbers{4} which denotes a year in which the document was created.

The strings I need to find are like these:

45 /2017

125 /2019

1245 /2018

12577 /2019

37589 /2017

but sometimes there is no space in between:

45/2017

125/2019

1245/2018

12577/2019

37589/2017

and sometimes there is two spaces:

45  /2017

125  /2019

1245  /2018

12577  /2019

37589  /2017

but it's always in the same place - the space or two spaces. It's always after the first string of numbers, which are never more than 5 digits - therefore I type [0-9]{1;5} in RegEx.

But when I tried to build this RegEx expression in Word's Ctrl+H find and replace dialog box, and I test it against the Word's document I cannot build universal expression to find these strings with space and no space. The ? is not working for me. I've read here that ? should find one space or no space, but when I'm testing it in my Word document it finds a string with two spaces inside, but not the one with one space or no space at all.

Here are the RegExs I've tried, which failed to match both strings with no space inside like 4125/2019, as well as similar strings with one or two spaces:

[0-9]{1;5} ?/[0-9]{4}

[0-9]{1;5}\s?/[0-9]{4}

[0-9]{1;5}[ ]{0;2}/[0-9]{4}    this gives an error but [0-9]{1;5}[ ]{1;2}/[0-9]{4} finds 125 /2019 but doesn't find 125/2019 and 12577/2019.

In Polish version of MS Word/Excel we use ; instead of , in formulas, but I tried it all with colon or semi-colon interchangeably.

I've read these sources: How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

and

Regex- Space or no space

Analyst_Cave

Regular Expression Tester

Body:
Try

([0-9]{1,5})([ ]{0,4})([/])([0-9]{4})

or

([0-9]{1,5})([\s]{0,4})(/[0-9]{4})

According to the test, all three are good.


问:
How do i get inputs when opening my electron app from the browser
So Basically i want to call

```<code>masslinker://123/456
</code>```

and it's supposed to goto show id 123 episode number 456. How do i get those inputs?

I Currently have this line of code

```<code>app.setAsDefaultProtocolClient('masslinker');
</code>```

答:
Citing from the corresponding docs:

Once registered, all links with your-protocol:// will be opened with
  the current executable. The whole link, including protocol, will be
  passed to your application as a parameter.

That means that a new instance of your app will be launched whenever a URL of that type is requested.

You should therefore check for arguments on app startup and if there is one, you can handle it:

```<code>if (process.argv.length >= 3) {
    const url_to_open = process.argv[2];
    console.log("Received: " + url_to_open);

    // should print:
    // Received: masslinker://123/456
    // now take URL apart using string operations ..
}
</code>```

The exact number of parameters may change depending on how you launch your app and/or when you go into production. You may work around that by checking if the last argument matches your protocol prefix.

Note that if you don't take further measures, this will open a new instance of your app for each URL you open. You can counteract that using app.requestSingleInstanceLock() and the second-instance event. The event handler will get as second parameter all the command line parameters of the new instance, so that you can handle them in the first instance.

Further note that setting up a protocol handler seems to be quite dependent on the operating system and may be part of the installation procedure of your app. However, once the handler is set up, processing incoming calls should work as above regardless of the operating system.

Body:
So Basically i want to call

masslinker://123/456

and it's supposed to goto show id 123 episode number 456. How do i get those inputs?

I Currently have this line of code

app.setAsDefaultProtocolClient('masslinker');

Body:
Citing from the corresponding docs:

Once registered, all links with your-protocol:// will be opened with
  the current executable. The whole link, including protocol, will be
  passed to your application as a parameter.

That means that a new instance of your app will be launched whenever a URL of that type is requested.

You should therefore check for arguments on app startup and if there is one, you can handle it:

if (process.argv.length >= 3) {
    const url_to_open = process.argv[2];
    console.log("Received: " + url_to_open);

    // should print:
    // Received: masslinker://123/456
    // now take URL apart using string operations ..
}

The exact number of parameters may change depending on how you launch your app and/or when you go into production. You may work around that by checking if the last argument matches your protocol prefix.

Note that if you don't take further measures, this will open a new instance of your app for each URL you open. You can counteract that using app.requestSingleInstanceLock() and the second-instance event. The event handler will get as second parameter all the command line parameters of the new instance, so that you can handle them in the first instance.

Further note that setting up a protocol handler seems to be quite dependent on the operating system and may be part of the installation procedure of your app. However, once the handler is set up, processing incoming calls should work as above regardless of the operating system.


问:
How to navigate to a new page when a grid is tapped in flutter?
This is a part of code from an app under development , I have created dart file for each of the item present in the list but i don't know how to give onpress function on the  list so that it will navigate me to next page

Here is the code

```<code>class GridDashboard extends StatelessWidget {
  final Items item1 = new Items(
      title: "Call",
      img: "assets/call.png");

  final Items item2 = new Items(
    title: "Message",
    img: "assets/message.png",
  );
  final Items item3 = new Items(
    title: "Music",
    img: "assets/music.png",
  );
  final Items item4 = new Items(
    title: "Navigation",
    img: "assets/navigation.png",
  );
  final Items item5 = new Items(
    title: "News",
    img: "assets/news.png",
  );
  final Items item6 = new Items(
    title: "To Do List",
    img: "assets/todolist.png",
  );

  @override
  Widget build(BuildContext context) {
    List<Items> myList = [item1, item2, item3, item4, item5, item6];
    var color = 0xff616161;
    return Flexible(
      child: GridView.count(
          childAspectRatio: 1.0,
          padding: EdgeInsets.only(left: 16, right: 16),
          crossAxisCount: 2,
          crossAxisSpacing: 18,
          mainAxisSpacing: 18,
          children: myList.map((data) {
            return Container(
              decoration: BoxDecoration(
                  color: Color(color), borderRadius: BorderRadius.circular(10)),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset(
                    data.img,
                    width: 42,
                  ),
                  SizedBox(
                    height: 14,
                  ),
                  Text(
                    data.title,
                    style: GoogleFonts.openSans(
                        textStyle: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.w600)),
                  ),
                  SizedBox(
                    height: 8,
                  ),
                  Text(
                    data.subtitle,
                    style: GoogleFonts.openSans(
                        textStyle: TextStyle(
                            color: Colors.white38,
                            fontSize: 10,
                            fontWeight: FontWeight.w600)),
                  ),
                  SizedBox(
                    height: 14,
                  ),
                  Text(
                    data.event,
                    style: GoogleFonts.openSans(
                        textStyle: TextStyle(
                            color: Colors.white70,
                            fontSize: 11,
                            fontWeight: FontWeight.w600)),
                  ),
                ],
              ),
            );
          }).toList()),
    );
  }
}

</code>```

I want to navigate to the new page when each item is tapped by the user. How to navigate it?

答:
Here your modified Build Method

```<code>@override
  Widget build(BuildContext context) {
    List<Items> myList = [item1, item2, item3, item4, item5, item6];
    var color = 0xff616161;
    return Flexible(
      child: GridView.count(
          childAspectRatio: 1.0,
          padding: EdgeInsets.only(left: 16, right: 16),
          crossAxisCount: 2,
          crossAxisSpacing: 18,
          mainAxisSpacing: 18,
          children: myList.map((data) {
            return GridTile(
              child: InkResponse(
                child: Container(
                  decoration: BoxDecoration(color: Color(color), borderRadius: BorderRadius.circular(10)),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Image.asset(
                        data.img,
                        width: 42,
                      ),
                      SizedBox(
                        height: 14,
                      ),
                      Text(
                        data.title,
                        style: GoogleFonts.openSans(textStyle: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w600)),
                      ),
                      SizedBox(
                        height: 8,
                      ),
                      Text(
                        data.subtitle,
                        style: GoogleFonts.openSans(textStyle: TextStyle(color: Colors.white38, fontSize: 10, fontWeight: FontWeight.w600)),
                      ),
                      SizedBox(
                        height: 14,
                      ),
                      Text(
                        data.event,
                        style: GoogleFonts.openSans(textStyle: TextStyle(color: Colors.white70, fontSize: 11, fontWeight: FontWeight.w600)),
                      ),
                    ],
                  ),
                ),
                onTap: () {
                  // Handle On Tap
                },
              ),
            );
          }).toList()),
    );
  }
</code>```

Another Way Use InkWell

```<code>@override
  Widget build(BuildContext context) {
    List<Items> myList = [item1, item2, item3, item4, item5, item6];
    var color = 0xff616161;
    return Flexible(
      child: GridView.count(
          childAspectRatio: 1.0,
          padding: EdgeInsets.only(left: 16, right: 16),
          crossAxisCount: 2,
          crossAxisSpacing: 18,
          mainAxisSpacing: 18,
          children: myList.map((data) {
            return InkWell(
              onTap: (){
                // Handle On Tap
              },
              child: Container(
                decoration: BoxDecoration(color: Color(color), borderRadius: BorderRadius.circular(10)),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Image.asset(
                      data.img,
                      width: 42,
                    ),
                    SizedBox(
                      height: 14,
                    ),
                    Text(
                      data.title,
                      style: GoogleFonts.openSans(textStyle: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w600)),
                    ),
                    SizedBox(
                      height: 8,
                    ),
                    Text(
                      data.subtitle,
                      style: GoogleFonts.openSans(textStyle: TextStyle(color: Colors.white38, fontSize: 10, fontWeight: FontWeight.w600)),
                    ),
                    SizedBox(
                      height: 14,
                    ),
                    Text(
                      data.event,
                      style: GoogleFonts.openSans(textStyle: TextStyle(color: Colors.white70, fontSize: 11, fontWeight: FontWeight.w600)),
                    ),
                  ],
                ),
              ),
            );
          }).toList()),
    );
  }
</code>```

Body:
This is a part of code from an app under development , I have created dart file for each of the item present in the list but i don't know how to give onpress function on the  list so that it will navigate me to next page

Here is the code

class GridDashboard extends StatelessWidget {
  final Items item1 = new Items(
      title: "Call",
      img: "assets/call.png");

  final Items item2 = new Items(
    title: "Message",
    img: "assets/message.png",
  );
  final Items item3 = new Items(
    title: "Music",
    img: "assets/music.png",
  );
  final Items item4 = new Items(
    title: "Navigation",
    img: "assets/navigation.png",
  );
  final Items item5 = new Items(
    title: "News",
    img: "assets/news.png",
  );
  final Items item6 = new Items(
    title: "To Do List",
    img: "assets/todolist.png",
  );

  @override
  Widget build(BuildContext context) {
    List<Items> myList = [item1, item2, item3, item4, item5, item6];
    var color = 0xff616161;
    return Flexible(
      child: GridView.count(
          childAspectRatio: 1.0,
          padding: EdgeInsets.only(left: 16, right: 16),
          crossAxisCount: 2,
          crossAxisSpacing: 18,
          mainAxisSpacing: 18,
          children: myList.map((data) {
            return Container(
              decoration: BoxDecoration(
                  color: Color(color), borderRadius: BorderRadius.circular(10)),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset(
                    data.img,
                    width: 42,
                  ),
                  SizedBox(
                    height: 14,
                  ),
                  Text(
                    data.title,
                    style: GoogleFonts.openSans(
                        textStyle: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.w600)),
                  ),
                  SizedBox(
                    height: 8,
                  ),
                  Text(
                    data.subtitle,
                    style: GoogleFonts.openSans(
                        textStyle: TextStyle(
                            color: Colors.white38,
                            fontSize: 10,
                            fontWeight: FontWeight.w600)),
                  ),
                  SizedBox(
                    height: 14,
                  ),
                  Text(
                    data.event,
                    style: GoogleFonts.openSans(
                        textStyle: TextStyle(
                            color: Colors.white70,
                            fontSize: 11,
                            fontWeight: FontWeight.w600)),
                  ),
                ],
              ),
            );
          }).toList()),
    );
  }
}

I want to navigate to the new page when each item is tapped by the user. How to navigate it?

Body:
Here your modified Build Method

@override
  Widget build(BuildContext context) {
    List<Items> myList = [item1, item2, item3, item4, item5, item6];
    var color = 0xff616161;
    return Flexible(
      child: GridView.count(
          childAspectRatio: 1.0,
          padding: EdgeInsets.only(left: 16, right: 16),
          crossAxisCount: 2,
          crossAxisSpacing: 18,
          mainAxisSpacing: 18,
          children: myList.map((data) {
            return GridTile(
              child: InkResponse(
                child: Container(
                  decoration: BoxDecoration(color: Color(color), borderRadius: BorderRadius.circular(10)),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Image.asset(
                        data.img,
                        width: 42,
                      ),
                      SizedBox(
                        height: 14,
                      ),
                      Text(
                        data.title,
                        style: GoogleFonts.openSans(textStyle: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w600)),
                      ),
                      SizedBox(
                        height: 8,
                      ),
                      Text(
                        data.subtitle,
                        style: GoogleFonts.openSans(textStyle: TextStyle(color: Colors.white38, fontSize: 10, fontWeight: FontWeight.w600)),
                      ),
                      SizedBox(
                        height: 14,
                      ),
                      Text(
                        data.event,
                        style: GoogleFonts.openSans(textStyle: TextStyle(color: Colors.white70, fontSize: 11, fontWeight: FontWeight.w600)),
                      ),
                    ],
                  ),
                ),
                onTap: () {
                  // Handle On Tap
                },
              ),
            );
          }).toList()),
    );
  }

Another Way Use InkWell

@override
  Widget build(BuildContext context) {
    List<Items> myList = [item1, item2, item3, item4, item5, item6];
    var color = 0xff616161;
    return Flexible(
      child: GridView.count(
          childAspectRatio: 1.0,
          padding: EdgeInsets.only(left: 16, right: 16),
          crossAxisCount: 2,
          crossAxisSpacing: 18,
          mainAxisSpacing: 18,
          children: myList.map((data) {
            return InkWell(
              onTap: (){
                // Handle On Tap
              },
              child: Container(
                decoration: BoxDecoration(color: Color(color), borderRadius: BorderRadius.circular(10)),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Image.asset(
                      data.img,
                      width: 42,
                    ),
                    SizedBox(
                      height: 14,
                    ),
                    Text(
                      data.title,
                      style: GoogleFonts.openSans(textStyle: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w600)),
                    ),
                    SizedBox(
                      height: 8,
                    ),
                    Text(
                      data.subtitle,
                      style: GoogleFonts.openSans(textStyle: TextStyle(color: Colors.white38, fontSize: 10, fontWeight: FontWeight.w600)),
                    ),
                    SizedBox(
                      height: 14,
                    ),
                    Text(
                      data.event,
                      style: GoogleFonts.openSans(textStyle: TextStyle(color: Colors.white70, fontSize: 11, fontWeight: FontWeight.w600)),
                    ),
                  ],
                ),
              ),
            );
          }).toList()),
    );
  }


问:
How to find first element in a column by group, that fulfills a condition? If the condition is fulfilled start the counter from 0 in R
I have a large dataset similar to this. I have been trying to add a counter from zero based on a condition of the first element in a column by group.
I want to get liked this:

```<code>ID YEAR STOf counter
1 2000 0     0
1 2001 1     0
1 2002 0     1
1 2003 0     2
2 2000 0     0
2 2001 0     0
2 2002 1     0
2 2003 0     1
2 2004 0     2
</code>```

I tried this code:

```<code>ov28<- ov27 %>% group_by(ID, idx = cumsum(STOf == 1L)) %>%
       mutate(counter = row_number()) %>%
       ungroup %>%
       select(-idx)
</code>```

The issue is: counter starts from 1 and the counter needs to start only based on condition as opposed to starting from the new id as well as condition. In short, I want the counter to start only if condition is satisfied, that too from 0.

Thanks!

答:
We can find the row number when STOf == 1 and increment the counter from that row.

```<code>library(dplyr)

ov27 %>%
  group_by(ID) %>%
  mutate(counter1 = cumsum(row_number() > which.max(STOf == 1))
  #Can also use which
  #mutate(counter1 = cumsum(row_number() > which(STOf == 1)[1])

#     ID  YEAR  STOf counter counter1
#  <int> <int> <int>   <int>    <dbl>
#1     1  2000     0       0        0
#2     1  2001     1       0        0
#3     1  2002     0       1        1
#4     1  2003     0       2        2
#5     2  2000     0       0        0
#6     2  2001     0       0        0
#7     2  2002     1       0        0
#8     2  2003     0       1        1
#9     2  2004     0       2        2
</code>```

Body:
I have a large dataset similar to this. I have been trying to add a counter from zero based on a condition of the first element in a column by group.
I want to get liked this:

ID YEAR STOf counter
1 2000 0     0
1 2001 1     0
1 2002 0     1
1 2003 0     2
2 2000 0     0
2 2001 0     0
2 2002 1     0
2 2003 0     1
2 2004 0     2

I tried this code:

ov28<- ov27 %>% group_by(ID, idx = cumsum(STOf == 1L)) %>%
       mutate(counter = row_number()) %>%
       ungroup %>%
       select(-idx)

The issue is: counter starts from 1 and the counter needs to start only based on condition as opposed to starting from the new id as well as condition. In short, I want the counter to start only if condition is satisfied, that too from 0.

Thanks!

Body:
We can find the row number when STOf == 1 and increment the counter from that row.

library(dplyr)

ov27 %>%
  group_by(ID) %>%
  mutate(counter1 = cumsum(row_number() > which.max(STOf == 1))
  #Can also use which
  #mutate(counter1 = cumsum(row_number() > which(STOf == 1)[1])

#     ID  YEAR  STOf counter counter1
#  <int> <int> <int>   <int>    <dbl>
#1     1  2000     0       0        0
#2     1  2001     1       0        0
#3     1  2002     0       1        1
#4     1  2003     0       2        2
#5     2  2000     0       0        0
#6     2  2001     0       0        0
#7     2  2002     1       0        0
#8     2  2003     0       1        1
#9     2  2004     0       2        2


问:
React, how to change dropdown menu option? JQuery?
Here is the HTML code;

```<code>    <div class="gl-native-dropdown" autoid="shippingAddress-stateCode" optionsautoid="shippingAddress-stateCode-options" data-auto-id="shippingAddress-stateCode">
        <div class="gl-native-dropdown__select">
<span class="gl-native-dropdown__select-label">
<span class="gl-native-dropdown__select-label-text">State</span>
<span class="gl-native-dropdown__select-label-hint gl-form-asterisk"></span></span>
            <svg class="gl-icon gl-native-dropdown__select-icon">
                <use xlink:href="#dropdown"></use>
            </svg>
        </div>
        <select class="gl-native-dropdown__select-element">
            <option></option>
            <option>AA Military</option>
            <option>AE Military</option>
            <option>AP Military</option>
            <option>Alabama</option>
            <option>Alaska</option>
            <option>Nebraska</option>
            <option>Nevada</option>
            <option>New Hampshire</option>
            <option>New Jersey</option>
            <option>New Mexico</option>
            <option>New York</option>
        </select>
    </div>
</code>```

Here is what I have tried;

```<code>let selectedValue = $('select[class="gl-native-dropdown__select-element"] > option:contains(“New York")').val();

    let select = document.querySelectorAll('.gl-native-dropdown__select-element')[0];
    select.value = selectedValue;
    var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLSelectElement.prototype, "value").set;
    nativeInputValueSetter.call(select, selectedValue);
    var ev2 = new Event('change', { bubbles: true});
    select.dispatchEvent(ev2);
</code>```

But my code does not work, the dropdown menu text is not changed to "New York"

Anything helps, all is appreciated.

I do not know how to fix my code (not HTML code), and I know I am close.

Thanks.

答:
```<code>let selectedValue = 'New York';

    let select = document.querySelectorAll('.gl-native-dropdown__select-element')[0];
    select.value = selectedValue;
    var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLSelectElement.prototype, "value").set;
    nativeInputValueSetter.call(select, selectedValue);
    var ev2 = new Event('change', { bubbles: true});
    select.dispatchEvent(ev2);
</code>```

Body:
Here is the HTML code;

State

            <svg class="gl-icon gl-native-dropdown__select-icon">
                <use xlink:href="#dropdown"></use>
            </svg>

        <select class="gl-native-dropdown__select-element">
            <option></option>
            <option>AA Military</option>
            <option>AE Military</option>
            <option>AP Military</option>
            <option>Alabama</option>
            <option>Alaska</option>
            <option>Nebraska</option>
            <option>Nevada</option>
            <option>New Hampshire</option>
            <option>New Jersey</option>
            <option>New Mexico</option>
            <option>New York</option>
        </select>

Here is what I have tried;

let selectedValue = $('select[class="gl-native-dropdown__select-element"] > option:contains(“New York")').val();

    let select = document.querySelectorAll('.gl-native-dropdown__select-element')[0];
    select.value = selectedValue;
    var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLSelectElement.prototype, "value").set;
    nativeInputValueSetter.call(select, selectedValue);
    var ev2 = new Event('change', { bubbles: true});
    select.dispatchEvent(ev2);

But my code does not work, the dropdown menu text is not changed to "New York"

Anything helps, all is appreciated.

I do not know how to fix my code (not HTML code), and I know I am close.

Thanks.


问:
Is it a good idea to use triggers to link to time dimension in fact tables in a dataware house?
I am in the middle of design a data-ware house. There are multiple fact tables and its highly likely that hundreds of facts are inserted into each fact table. Even though its a bit early but still I was thinking of optimizations.

I have two tables for time

date                      (unique row
for each day)

time of the day           (unique row
for each minute in a day)

in all my fact tables I do have the full date column.

What does your experience say, should I used select statements in code to query the dimension Ids from time dimension table or I allow the time dimension columns in fact tables to be null able and  use triggers  to fill in the values?

答:
No nulls allowed for FKs in fact tables.

Simply use your ETL to lookup keys from date and time dimension for each row of the fact table.

No triggers in DW, all loading and key-lookup is done through the ETL application.

ContentLicense: CC BY-SA 3.0


问:
Given an array of numbers, return array of products of all other numbers (no division)
I was asked this question in a job interview, and I'd like to know how others would solve it. I'm most comfortable with Java, but solutions in other languages are welcome.

Given an array of numbers, nums, return an array of numbers products, where products[i] is the product of all nums[j], j != i.

```<code>Input : [1, 2, 3, 4, 5]
Output: [(2*3*4*5), (1*3*4*5), (1*2*4*5), (1*2*3*5), (1*2*3*4)]
      = [120, 60, 40, 30, 24]
</code>```

You must do this in O(N) without using division.

答:
Just 2 passes up and down. Job done in O(N)</p>

```<code>private static int[] multiply(int[] numbers) {
        int[] multiplied = new int[numbers.length];
        int total = 1;

        multiplied[0] = 1;
        for (int i = 1; i < numbers.length; i++) {
            multiplied[i] = numbers[i - 1] * multiplied[i - 1];
        }

        for (int j = numbers.length - 2; j >= 0; j--) {
            total *= numbers[j + 1];
            multiplied[j] = total * multiplied[j];
        }

        return multiplied;
    }
</code>```

Body:
I was asked this question in a job interview, and I'd like to know how others would solve it. I'm most comfortable with Java, but solutions in other languages are welcome.

Given an array of numbers, nums, return an array of numbers products, where products[i] is the product of all nums[j], j != i.

Input : [1, 2, 3, 4, 5]
Output: [(2*3*4*5), (1*3*4*5), (1*2*4*5), (1*2*3*5), (1*2*3*4)]
      = [120, 60, 40, 30, 24]

You must do this in O(N) without using division.

Body:
Just 2 passes up and down. Job done in O(N)

private static int[] multiply(int[] numbers) {
        int[] multiplied = new int[numbers.length];
        int total = 1;

        multiplied[0] = 1;
        for (int i = 1; i < numbers.length; i++) {
            multiplied[i] = numbers[i - 1] * multiplied[i - 1];
        }

        for (int j = numbers.length - 2; j >= 0; j--) {
            total *= numbers[j + 1];
            multiplied[j] = total * multiplied[j];
        }

        return multiplied;
    }


问:
How can I refresh Angular Material Table data back to it's initial state within the page?
Some notes:

My goal is to implement some "discard" and "save" changes type of functionality.

The "companyService" service calls an api which fetches the top "X"
companies (in this case, 5)   from a database.

The table gets populated through a DataSource instance.

This application will eventually be put into production.

So the user will be able to toggle the on/off buttons and select "allow" or "deny" from the dropdown menu. Upon a user interacting with these buttons I would like to display some text next to the save button saying that there are unsaved changes. But the part that I can't seem to figure out is how to handle the click event on the Discard Changes button and "reset" the data in the table back to its initial state after the user makes some changes. I'm just confused because the data source of the table is tied to a database on the server.

If you could maybe give me specific advice on using DataSource or just point me in the right direction it would be much appreciated!

[![][1]][1]

My component class references this CompanyDataSource class to populate the table.

company-config-table.component.ts

HTML CODE

```<code><table mat-table #companyTable [trackBy]="trackByIndex" [dataSource]="dataSource" matSort class="mat-elevation-z8">

        <!-- Client ID Column -->
        <ng-container matColumnDef="clientId">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Client ID </th>
        <td mat-cell *matCellDef="let company">{{ company.clientId }}</td>
        <td mat-footer-cell *matFooterCellDef>
            <button mat-button (click)="onDiscardChanges()">Discard Changes</button>
        </td>
        </ng-container>

        <!-- Name Column -->
        <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Company </th>
        <td mat-cell *matCellDef="let company"> {{ company.name }}</td>
        <td mat-footer-cell *matFooterCellDef></td>
        </ng-container>

        <!-- Include Bsa Details Column -->
        <ng-container matColumnDef="includeBsaDetails">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Include BSA Details </th>
        <td mat-cell *matCellDef="let company">
            <mat-button-toggle-group #toggleGroup="matButtonToggleGroup">
                <mat-button-toggle class="on"   [checked]="company.includeBsaDetails"  [value]="true"  (change)="onIncludeBsaDetailsButtonToggleEvent($event, company)">ON</mat-button-toggle>
                <mat-button-toggle class="off"  [checked]="!company.includeBsaDetails" [value]="false" (change)="onIncludeBsaDetailsButtonToggleEvent($event, company)">OFF</mat-button-toggle>
            </mat-button-toggle-group>
        </td>
        <td mat-footer-cell *matFooterCellDef></td>
        </ng-container>

        <!-- Bsa Tool Permission Column -->
        <ng-container matColumnDef="bsaToolPermission">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Implicit BSA Permission </th>
        <td mat-cell *matCellDef="let company">
            <mat-form-field>
                <mat-select [(value)]="company.bsaToolPermission" (change)="onBsaToolPermissionSelectChangeEvent($event, company)">
                  <mat-option value="ALLOW">ALLOW</mat-option>
                  <mat-option value="DENY">DENY</mat-option>
                </mat-select>
            </mat-form-field>
        </td>
        <td mat-footer-cell *matFooterCellDef>

        </td>
        </ng-container>

        <!-- Auto Lock Confirmation Column -->
        <ng-container matColumnDef="autoLockConfirm">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Automated Lock Confirmation </th>
        <td mat-cell *matCellDef="let company">
            <mat-button-toggle-group #toggleGroup2="matButtonToggleGroup">
                <mat-button-toggle class="on"   [checked]="company.autoLockConfirm"  [value]="true"  (change)="onAutoLockConfirmButtonToggleEvent($event, company)">ON</mat-button-toggle>
                <mat-button-toggle class="off"  [checked]="!company.autoLockConfirm" [value]="false" (change)="onAutoLockConfirmButtonToggleEvent($event, company)">OFF</mat-button-toggle>
            </mat-button-toggle-group>
        </td>
        <td mat-footer-cell *matFooterCellDef>
            <button mat-button>Save Changes</button>
        </td>
        </ng-container>

        <!-- Table Configuration for rows, header, and footer -->
        <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
        <tr mat-row *matRowDef="let row; columns: columnsToDisplay;"></tr>
        <tr mat-footer-row *matFooterRowDef="columnsToDisplay"></tr>
    </table>
</code>```

答:
Can't you just call loadCompanies() to refetch the data from the server? That should replace the table to the values that the database has.

If this doesn't work for some reason, another idea would be to keep track of the original data, and then reset the grid to that original data.

```<code>class CompanyDataSource extends DataSource<any> {
    public companiesSubject = new BehaviorSubject<Company[]>([]);
    public originalData: Company[];
    constructor(private companyService: CompanyService) {
        super();
    }
    connect(): Observable<Company[]> {
        return this.companiesSubject.asObservable();
    }
    disconnect() {
        this.companiesSubject.complete();
    }
    loadCompanies(amount: number) {
        this.companyService.GetTopXCompanies(amount).subscribe((companies) => {
            this.originalData = companies;
            const deepCopyData = JSON.parse(JSON.stringify(companies));
            this.companiesSubject.next(deepCopyData);
        });
    }
    discardChanges() {
        const deepCopyData = JSON.parse(JSON.stringify(this.originalData));
        this.companiesSubject.next(deepCopyData);
    }
}
</code>```

Body:
Some notes:

My goal is to implement some "discard" and "save" changes type of functionality.

The "companyService" service calls an api which fetches the top "X"
companies (in this case, 5)   from a database.

The table gets populated through a DataSource instance.

This application will eventually be put into production.

So the user will be able to toggle the on/off buttons and select "allow" or "deny" from the dropdown menu. Upon a user interacting with these buttons I would like to display some text next to the save button saying that there are unsaved changes. But the part that I can't seem to figure out is how to handle the click event on the Discard Changes button and "reset" the data in the table back to its initial state after the user makes some changes. I'm just confused because the data source of the table is tied to a database on the server.

If you could maybe give me specific advice on using DataSource or just point me in the right direction it would be much appreciated!

[![][1]][1]

My component class references this CompanyDataSource class to populate the table.

company-config-table.component.ts

HTML CODE

        <ng-container matColumnDef="clientId">
         Client ID
        {{ company.clientId }}

            <button mat-button (click)="onDiscardChanges()">Discard Changes</button>

        </ng-container>

        <ng-container matColumnDef="name">
         Company
         {{ company.name }}

        </ng-container>

        <ng-container matColumnDef="includeBsaDetails">
         Include BSA Details

            <mat-button-toggle-group #toggleGroup="matButtonToggleGroup">
                <mat-button-toggle class="on"   [checked]="company.includeBsaDetails"  [value]="true"  (change)="onIncludeBsaDetailsButtonToggleEvent($event, company)">ON</mat-button-toggle>
                <mat-button-toggle class="off"  [checked]="!company.includeBsaDetails" [value]="false" (change)="onIncludeBsaDetailsButtonToggleEvent($event, company)">OFF</mat-button-toggle>
            </mat-button-toggle-group>

        </ng-container>

        <ng-container matColumnDef="bsaToolPermission">
         Implicit BSA Permission

            <mat-form-field>
                <mat-select [(value)]="company.bsaToolPermission" (change)="onBsaToolPermissionSelectChangeEvent($event, company)">
                  <mat-option value="ALLOW">ALLOW</mat-option>
                  <mat-option value="DENY">DENY</mat-option>
                </mat-select>
            </mat-form-field>

        </ng-container>

        <ng-container matColumnDef="autoLockConfirm">
         Automated Lock Confirmation

            <mat-button-toggle-group #toggleGroup2="matButtonToggleGroup">
                <mat-button-toggle class="on"   [checked]="company.autoLockConfirm"  [value]="true"  (change)="onAutoLockConfirmButtonToggleEvent($event, company)">ON</mat-button-toggle>
                <mat-button-toggle class="off"  [checked]="!company.autoLockConfirm" [value]="false" (change)="onAutoLockConfirmButtonToggleEvent($event, company)">OFF</mat-button-toggle>
            </mat-button-toggle-group>

            <button mat-button>Save Changes</button>

        </ng-container>

Body:
Can't you just call loadCompanies() to refetch the data from the server? That should replace the table to the values that the database has.

If this doesn't work for some reason, another idea would be to keep track of the original data, and then reset the grid to that original data.

class CompanyDataSource extends DataSource<any> {
    public companiesSubject = new BehaviorSubject<Company[]>([]);
    public originalData: Company[];
    constructor(private companyService: CompanyService) {
        super();
    }
    connect(): Observable<Company[]> {
        return this.companiesSubject.asObservable();
    }
    disconnect() {
        this.companiesSubject.complete();
    }
    loadCompanies(amount: number) {
        this.companyService.GetTopXCompanies(amount).subscribe((companies) => {
            this.originalData = companies;
            const deepCopyData = JSON.parse(JSON.stringify(companies));
            this.companiesSubject.next(deepCopyData);
        });
    }
    discardChanges() {
        const deepCopyData = JSON.parse(JSON.stringify(this.originalData));
        this.companiesSubject.next(deepCopyData);
    }
}


问:
Does HTML5 Canvas pixel size depend on the canvas size?
I'm drawing simple lines with the HTML5 canvas:

```<code>context = $('canvas')[0].getContext('2d');
context.moveTo(150, 20);
context.lineTo(300, 20);
context.stroke();
</code>```

When my canvas CSS changes from:

```<code>canvas {
    width: 500px;
    height: 500px;
}
</code>```

to

```<code>canvas {
    width: 1000px;
    height: 1000px;
}
</code>```

the stroke width and height also double! What gives?

答: The CSS only determines its visible size. Change the width and height attributes in the HTML to adjust the actual number of pixels that make it up. If in the HTML it is 100x100, and in the CSS 200x200, it will be visually scaled by 2X.

Body:
I'm drawing simple lines with the HTML5 canvas:

context = $('canvas')[0].getContext('2d');
context.moveTo(150, 20);
context.lineTo(300, 20);
context.stroke();

When my canvas CSS changes from:

canvas {
    width: 500px;
    height: 500px;
}

to

canvas {
    width: 1000px;
    height: 1000px;
}

the stroke width and height also double! What gives?


问:
Operands could not be broadcast together with shapes (12,999) (12,1000) error using scipy.integrate.solve_BVP
I have previously asked a question where I asked about where I was generally going wrong with my attempts to solve the BVP here: Solving a BVP using scipy.solve_bvp where the function returns an array

One of the responses I received while answering this stated that the function that i was passing to  solve_bvp() was not of shape (12,1000) as per the documentation. I have rectified this by creating a function which generates solutions with the required shape, by first initialising a 12 by 1000 array and then setting each of the 12 arrays of shape 1000 equal to the value of its associated differential equation for each time point at which my functon is called. The code I have written is below, with the new code clearly annotated.

##find our velocity at time t=-1000, where the BVP is started from
def find_vel_past():
    daynum=1000
    ts=np.linspace(0,-daynum*day2sec,daynum)
    angles=np.zeros([daynum,2])
    trange =(ts[0],ts[-1])
    fi=np.ndarray.flatten(np.array(rs+vs))
    sol= integrate.solve_ivp(earth_mars_motion,trange,fi,t_eval=ts, max_step=3*day2sec,dense_output=True)
    return(sol.y[0:6][:,-1])
##return an array of six velocities at this time
def estimate_errors_improved():
    daynum=1000
    ##generating np arrays for bouundary conditions
    a=np.ndarray.flatten(np.array(find_vel_past()))
    rpast=np.ndarray.flatten(np.array(rspast))
    acond=np.concatenate([rpast,a])
    bcond=np.ndarray.flatten(np.array(rs+vs))
    t=np.linspace(0,daynum*day2sec,daynum)
    y=np.zeros(([12,daynum]))
    y[:,0]=acond
    ## THE FUNCTION I HAVE UPDATED AS PER ADVICE RECIEVED
    def earth_mars_motion1(t,y):
        x=np.zeros([12,daynum])
        y1=earth_mars_motion(t,y[:,0])
        for i in range(daynum):
            for i in range(len(y)):
                x[i]=y1[i]
        return x
    def bc(ya,yb):
        a=ya.ravel()[0:6]-bcond[0:6]
        b=yb.ravel()[0:6]-rpast
        c=np.array([a,b])
        return np.reshape(c,(12))
        #return np.concatenate(ya.ravel()[0:6]-bcond[0:6],yb.ravel()[0:6]-rpast)
    sol = integrate.solve_bvp(earth_mars_motion1,bc,t,y,verbose=1)
    data1=np.transpose(sol.sol(t))
    angles=np.zeros(daynum)
    print(sol.sol(t))
    for i in range(daynum):
        angles[i]=angle_between_planets(np.transpose(sol.sol(t)[:,0]))
        x = t/day2sec
    plt.plot(x,angles)
    plt.show()
estimate_errors_improved()
```

The output I am getting is: ValueError: operands could not be broadcast together with shapes (12,999) (12,1000). Could anyone please provide a quick solution to this problem. Thanks.

答: I believe that integrate.solve.bvp(fun,bc,t,x) works by iterating over the time steps in the problem and plugging into fun. Each time it does this, the input for t gets shorter. Your x that is returned should also be shortened at each step. Try replacing x=np.zeros([12,daynum]) with x=np.zeros([12,len(t)]), and adjust the code following this to match.

Body:
I have previously asked a question where I asked about where I was generally going wrong with my attempts to solve the BVP here: Solving a BVP using scipy.solve_bvp where the function returns an array

One of the responses I received while answering this stated that the function that i was passing to  solve_bvp() was not of shape (12,1000) as per the documentation. I have rectified this by creating a function which generates solutions with the required shape, by first initialising a 12 by 1000 array and then setting each of the 12 arrays of shape 1000 equal to the value of its associated differential equation for each time point at which my functon is called. The code I have written is below, with the new code clearly annotated.

##find our velocity at time t=-1000, where the BVP is started from
def find_vel_past():
    daynum=1000
    ts=np.linspace(0,-daynum*day2sec,daynum)
    angles=np.zeros([daynum,2])
    trange =(ts[0],ts[-1])
    fi=np.ndarray.flatten(np.array(rs+vs))
    sol= integrate.solve_ivp(earth_mars_motion,trange,fi,t_eval=ts, max_step=3*day2sec,dense_output=True)
    return(sol.y[0:6][:,-1])
##return an array of six velocities at this time
def estimate_errors_improved():
    daynum=1000
    ##generating np arrays for bouundary conditions
    a=np.ndarray.flatten(np.array(find_vel_past()))
    rpast=np.ndarray.flatten(np.array(rspast))
    acond=np.concatenate([rpast,a])
    bcond=np.ndarray.flatten(np.array(rs+vs))
    t=np.linspace(0,daynum*day2sec,daynum)
    y=np.zeros(([12,daynum]))
    y[:,0]=acond
    ## THE FUNCTION I HAVE UPDATED AS PER ADVICE RECIEVED
    def earth_mars_motion1(t,y):
        x=np.zeros([12,daynum])
        y1=earth_mars_motion(t,y[:,0])
        for i in range(daynum):
            for i in range(len(y)):
                x[i]=y1[i]
        return x
    def bc(ya,yb):
        a=ya.ravel()[0:6]-bcond[0:6]
        b=yb.ravel()[0:6]-rpast
        c=np.array([a,b])
        return np.reshape(c,(12))
        #return np.concatenate(ya.ravel()[0:6]-bcond[0:6],yb.ravel()[0:6]-rpast)
    sol = integrate.solve_bvp(earth_mars_motion1,bc,t,y,verbose=1)
    data1=np.transpose(sol.sol(t))
    angles=np.zeros(daynum)
    print(sol.sol(t))
    for i in range(daynum):
        angles[i]=angle_between_planets(np.transpose(sol.sol(t)[:,0]))
        x = t/day2sec
    plt.plot(x,angles)
    plt.show()
estimate_errors_improved()

The output I am getting is: ValueError: operands could not be broadcast together with shapes (12,999) (12,1000). Could anyone please provide a quick solution to this problem. Thanks.