问:
Pandas: How to merge all rows into a single row?
I have the following dataframe:

```<code>  text
1 "abc"
2 "def"
3 "ghi"
4 "jkl"
</code>```

How can I merge these rows into a dataframe with a single row like the following one?

```<code>  text
1 "abc, def, ghi, jkl"
</code>```

Comma separation is not a must but all the values should be in a single row. The values can also be stored in a comma separated list of strings.

答:
If you just want the list of values, use to_list:

```<code>sr = pd.Series(', '.join(df['text'].to_list()), name='text')

# OR

df = pd.DataFrame([', '.join(df['text'].to_list())], columns=['text'])
</code>```

Output:

```<code>>>> sr
0    abc, def, ghi, jkl
Name: text, dtype: object

>>> df
                 text
0  abc, def, ghi, jkl
</code>```

Body:
I have the following dataframe:

  text
1 "abc"
2 "def"
3 "ghi"
4 "jkl"

How can I merge these rows into a dataframe with a single row like the following one?

  text
1 "abc, def, ghi, jkl"

Comma separation is not a must but all the values should be in a single row. The values can also be stored in a comma separated list of strings.

Body:
If you just want the list of values, use to_list:

sr = pd.Series(', '.join(df['text'].to_list()), name='text')

# OR

df = pd.DataFrame([', '.join(df['text'].to_list())], columns=['text'])

Output:

>>> sr
0    abc, def, ghi, jkl
Name: text, dtype: object

>>> df
                 text
0  abc, def, ghi, jkl


来源: stackexchange

问:
Mask credit card number in PHP
I have credit card number which I want to mask as below:

```<code>$cc = 1234123412341234

echo cc_masking($cc)

1234XXXXXXXX1234

function cc_masking($number) {.....}
</code>```

Please suggest the regular expression for this.

答:
```<code>str_pad(substr($value,-4),strlen($value), "X", STR_PAD_LEFT); //output: XXXXXXXXXXXX9494
</code>```

ContentLicense: CC BY-SA 3.0

Title: Mask credit card number in PHP

Body:
I have credit card number which I want to mask as below:

$cc = 1234123412341234

echo cc_masking($cc)

1234XXXXXXXX1234

function cc_masking($number) {.....}

Please suggest the regular expression for this.

ContentLicense: CC BY-SA 4.0


问:
Python Package Creation
I have a package i am trying to create.  The directory hierarchy looks like this.

```<code>Package/
    __init__.py
    Part1/
        __init__.py
        item.py
        load_items.py
    Part2/
        __init__.py
        section.py
    Part3/
        __init__.py
        mappings/
            file1.txt
            file2.txt
            ...
            file10.txt
        map.py
        unmapped.txt
</code>```

I have some other file main.py that is not in the package and inside I have put

```<code>import Package
print(dir(Package))
</code>```

The output from this is

```<code>['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
</code>```

however I was expecting to see "Part1", "Part2", and "Part3" in this list.  I also tried

```<code>print(Package.Part1)
</code>```

and I got an attribute error: Package has no attribute Part1.

This is the first package I have made and I am also unsure why __init__.py is needed in every directory?  Or perhaps this is wrong and it isn't.  I've read a bunch of the other questions on stack overflow but none of them have really helped me understand.  Basically, I'm looking for whether my package is structured correctly and why when I do dir(Package) the parts of it are not listed.

答:
dir return all variables and methodes of an object

for example :

```<code>class Person:
  name = "John"

  def foo(self):
        return "Hello"

print(dir(Person))

>> out
    [... 'foo', 'name']
</code>```

If you want to list all directories and files in a directory, you can do

```<code>import os
os.listdir(path)
</code>```

You can retrieve the path of an installed package with importlib

Here is an example with the requests package

```<code>import importlib.util
path = importlib.util.find_spec("requests").origin

>> out :
    ..../python3.7/site-packages/requests/__init__.py'
</code>```

By combining both method, we can list all directories of our package

```<code>import importlib.util
import os

path = importlib.util.find_spec("requests").origin

# remove the "/__init__.py" part
path = path[:-11]
os.listdir(path)

>> out :
    ['cookies.py',
     'auth.py',
     'sessions.py',
      ...
     ]
</code>```

The __init__.py is required in each directory.
This file tells your python interpreter that the folder is a python package. Without it, you won't be able to import the package in an other folder.

Title: Python Package Creation

Body:
I have a package i am trying to create.  The directory hierarchy looks like this.

Package/
    __init__.py
    Part1/
        __init__.py
        item.py
        load_items.py
    Part2/
        __init__.py
        section.py
    Part3/
        __init__.py
        mappings/
            file1.txt
            file2.txt
            ...
            file10.txt
        map.py
        unmapped.txt

I have some other file main.py that is not in the package and inside I have put

import Package
print(dir(Package))

The output from this is

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']

however I was expecting to see "Part1", "Part2", and "Part3" in this list.  I also tried

print(Package.Part1)

and I got an attribute error: Package has no attribute Part1.

This is the first package I have made and I am also unsure why __init__.py is needed in every directory?  Or perhaps this is wrong and it isn't.  I've read a bunch of the other questions on stack overflow but none of them have really helped me understand.  Basically, I'm looking for whether my package is structured correctly and why when I do dir(Package) the parts of it are not listed.

Body:
dir return all variables and methodes of an object

for example :

class Person:
  name = "John"

  def foo(self):
        return "Hello"

print(dir(Person))

>> out
    [... 'foo', 'name']

If you want to list all directories and files in a directory, you can do

import os
os.listdir(path)

You can retrieve the path of an installed package with importlib

Here is an example with the requests package

import importlib.util
path = importlib.util.find_spec("requests").origin

>> out :
    ..../python3.7/site-packages/requests/__init__.py'

By combining both method, we can list all directories of our package

import importlib.util
import os

path = importlib.util.find_spec("requests").origin

# remove the "/__init__.py" part
path = path[:-11]
os.listdir(path)

>> out :
    ['cookies.py',
     'auth.py',
     'sessions.py',
      ...
     ]

The __init__.py is required in each directory.
This file tells your python interpreter that the folder is a python package. Without it, you won't be able to import the package in an other folder.


问:
ASP API CORE : Get relation Many to One
I have two entities : Article and PrixVariation.
One Article has Many Prix variation.
One Prix variation has One Article.

```<code>public partial class Article
            {
                public Article()
                {
                    PrixVariations = new HashSet<PrixVariation>();
                }

                public int Id { get; set; }
                public DateTime DateTime { get; set; }
    ...
                public virtual ICollection<PrixVariation> PrixVariations { get; set; }

            }
public partial class PrixVariation
    {
        public int Id { get; set; }
        public DateTime DateTime { get; set; }
        public int Article { get; set; }
        public double Prix { get; set; }

        public virtual Article ArticleNavigation { get; set; } = null!;

    }
</code>```

My Context is as follow :

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Article>(entity =>
            {
                entity.ToTable("articles");

                entity.Property(e => e.Id).HasColumnName("id");

                entity.Property(e => e.DateTime)
                    .HasColumnType("datetime")
                    .HasColumnName("dateTime")
                    .HasDefaultValueSql("(getdate())");

            });

 modelBuilder.Entity<PrixVariation>(entity =>
            {
                entity.ToTable("prix_variation");

                entity.Property(e => e.Id)
                    .ValueGeneratedNever()
                    .HasColumnName("id");

                entity.Property(e => e.Article).HasColumnName("article");

                entity.Property(e => e.DateTime)
                    .HasColumnType("datetime")
                    .HasColumnName("dateTime")
                    .HasDefaultValueSql("(getdate())");

                entity.Property(e => e.Prix).HasColumnName("prix");

                entity.HasOne(d => d.ArticleNavigation)
                    .WithMany(p => p.PrixVariations)
                    .HasForeignKey(d => d.Article)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_prix_variation_articles");
            });
</code>```

And my controller is as follow :

```<code>public class ArticlesController : ControllerBase
    {
        private readonly STGEORGESContext _context;

        public ArticlesController(STGEORGESContext context)
        {
            _context = context;
        }

        // GET: api/Articles
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Article>>> GetArticles()
        {
            return await _context.Articles.ToListAsync();
        }
....
</code>```

There is something not working here because when I launch the debogger, the collection of PrixVaration is always empty :

```<code>{"id":1,"dateTime":"2021-11-28T08:37:17","prixVariations":[]}
</code>```

And of course in the database there is one PrixVaration linked to that Article..

Can anyone can help ?? Thaks a lot !!!

Pierre

答:
It is called  lazy loading. Ef doesn't load any object collections if you don't ask about it explicitly. So try this</p>
```<code>return await _context.Articles.Include(i=> i.PrixVariations).ToListAsync();
</code>```

Title: ASP API CORE : Get relation Many to One

Body:
I have two entities : Article and PrixVariation.
One Article has Many Prix variation.
One Prix variation has One Article.

public partial class Article
            {
                public Article()
                {
                    PrixVariations = new HashSet<PrixVariation>();
                }

                public int Id { get; set; }
                public DateTime DateTime { get; set; }
    ...
                public virtual ICollection<PrixVariation> PrixVariations { get; set; }

            }
public partial class PrixVariation
    {
        public int Id { get; set; }
        public DateTime DateTime { get; set; }
        public int Article { get; set; }
        public double Prix { get; set; }

        public virtual Article ArticleNavigation { get; set; } = null!;

    }

My Context is as follow :

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity
(entity =>
            {
                entity.ToTable("articles");

                entity.Property(e => e.Id).HasColumnName("id");

                entity.Property(e => e.DateTime)
                    .HasColumnType("datetime")
                    .HasColumnName("dateTime")
                    .HasDefaultValueSql("(getdate())");

            });

 modelBuilder.Entity<PrixVariation>(entity =>
            {
                entity.ToTable("prix_variation");

                entity.Property(e => e.Id)
                    .ValueGeneratedNever()
                    .HasColumnName("id");

                entity.Property(e => e.Article).HasColumnName("article");

                entity.Property(e => e.DateTime)
                    .HasColumnType("datetime")
                    .HasColumnName("dateTime")
                    .HasDefaultValueSql("(getdate())");

                entity.Property(e => e.Prix).HasColumnName("prix");

                entity.HasOne(d => d.ArticleNavigation)
                    .WithMany(p => p.PrixVariations)
                    .HasForeignKey(d => d.Article)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_prix_variation_articles");
            });

And my controller is as follow :

public class ArticlesController : ControllerBase
    {
        private readonly STGEORGESContext _context;

        public ArticlesController(STGEORGESContext context)
        {
            _context = context;
        }

        // GET: api/Articles
        [HttpGet]
        public async Task<ActionResult<IEnumerable
>> GetArticles()
        {
            return await _context.Articles.ToListAsync();
        }
....

There is something not working here because when I launch the debogger, the collection of PrixVaration is always empty :

{"id":1,"dateTime":"2021-11-28T08:37:17","prixVariations":[]}

And of course in the database there is one PrixVaration linked to that Article..

Can anyone can help ?? Thaks a lot !!!

Pierre

Body:
It is called  lazy loading. Ef doesn't load any object collections if you don't ask about it explicitly. So try this

return await _context.Articles.Include(i=> i.PrixVariations).ToListAsync();


问:
React.js/React-Native how to skip Map() iteration if condition is falsy?
I have this simple component in React-Native, My goal is to skip the iteration if the given argument gradeIsMandatory is false, it should only iterate over warranty and price,
How can I achieve this result without affecting performance? I will take any advice thanks

import React, { useCallback } from 'react';
import { View, Text, SafeAreaView, SectionList, StyleSheet, Image, TouchableOpacity, Alert} from 'react-native';

export const ModalHeader: React.FC<{}> = () => {
    const gradeIsMandatory = false

    //code I tried to use
    useEffect(()=>{
        if(!gradeIsMandatory){
            let appendGrade =  { key: 'grade', title: 'Grade' }
            modalTabs.push(appendGrade)
        }
    },[])
    return (
        <View>
            <View>
                <View>
                    {modalTabs.map((tab, i) => (
                        <TouchableOpacity>
                          <Text>{tab.title}</Text>
                        </TouchableOpacity>
                    ))}
                </View>
            </View>
        </View>
    );
}

const modalTabs = [
    { key: 'warranty', title: 'Your Waranty' },
    { key: 'price', title: 'Your price' }
]```

答:
Try a conditional append.</p>
```<code>const extendedTabs = [...modalTabs, ...(gradeIsMandatory ? [{ key: 'grade', title: 'Grade' }] : [] )];
</code>```

Body:
Try a conditional append.

const extendedTabs = [...modalTabs, ...(gradeIsMandatory ? [{ key: 'grade', title: 'Grade' }] : [] )];


问:
Is there a way to pass unicode symbols in the PAM conv function?
I am creating a PAM module to show a QR code to users that are trying to log onto a system over SSH to allow them to scan it and authenticate using biometrics on their phone. Is there a way to pass unicode characters into the PAM conv function to allow the application to display them to the user?

The reason I need to hand in unicode characters is because I want to use the uincode character █ (U+2588 Full Block) as a way to print the QR code to the screen.

I have tried using the type wchar_t to hand in the value and also just trying to hand it in as char but both end up printing the missing character question mark to the screen.

If this is not possible is there a way of being able to show a QR code prior to authentication at all or is regular text the only possible thing to show?

Pam conv struct from PAM source:

```<code>struct pam_conv {
    int (*conv)(int num_msg, const struct pam_message **msg,
        struct pam_response **resp, void *appdata_ptr);
    void *appdata_ptr;
};
</code>```

Edit (31/10/21): I have tried the suggestion of encoding as UTF8 which I beleive is done like so: \u[unicode char code]. This produced the following compiler warning:

```<code>src/pam-qr.c:118:58: warning: multi-character character constant [-Wmultichar]
  118 |             row[x] = qrcodegen_getModule(qrcode, x, y) ? '\u2588' : ' ';
</code>```

and this output:

```<code>\210\210\210\210\210\210\210 \210  \210\210\210 \210\210 \210\210\210\210\210\210\210\214\2723O\177
\210     \210      \210  \210 \210     \210\214\2723O\177
\210 \210\210\210 \210  \210\210 \210  \210\210 \210 \210\210\210 \210\214\2723O\177
\210 \210\210\210 \210 \210    \210 \210\210 \210 \210\210\210 \210\214\2723O\177
\210 \210\210\210 \210 \210\210    \210\210\210 \210 \210\210\210 \210\214\2723O\177
\210     \210 \210         \210     \210\214\2723O\177
\210\210\210\210\210\210\210 \210 \210 \210 \210 \210 \210\210\210\210\210\210\210\214\2723O\177
        \210\210\210    \210\210        \214\2723O\177
\210   \210 \210\210\210\210  \210 \210\210 \210\210\210\210\210  \210\214\2723O\177
 \210     \210 \210\210 \210 \210\210\210  \210\210    \214\2723O\177
\210\210\210  \210\210    \210\210\210\210\210 \210 \210 \210\210\210 \214\2723O\177
 \210\210\210\210\210  \210  \210\210    \210    \210\210 \214\2723O\177
  \210\210  \210\210\210  \210\210 \210 \210\210\210\210 \210\210\210\210\214\272
</code>```

The following is the output I get when using # instead of the block character:

```<code>####### #  ### ## #######
#     #      #  # #     #
# ### #  ## #  ## # ### #
# ### # #    # ## # ### #
# ### # ##    ### # ### #
#     # #         #     #
####### # # # # # #######
        ###    ##
#   # ####  # ## #####  #
 #     # ## # ###  ##
###  ##    ##### # # ###
 #####  #  ##    #    ##
  ##  ###  ## # #### ####
#  ##  # #    #### ### #
   #  ## ##  ### # ##
  #### # ## #  #  #   #
###  ## ## # ## ##### #
        ### # # #   ### #
####### # ##### # # #
#     #   ## #  #   # #
# ### # # # ##  #########
# ### #  #   ### ##    ##
# ### #  ##      ### # #
#     #     # ##  ### ##
####### ## # ### # #  ###
</code>```

This can't be scanned but the printed version with the block character can be hence why I want to use it. This is the desired output using the block character that I'm trying to achieve:

```<code>███████ █  ███ ██ ███████
█     █      █  █ █     █
█ ███ █  ██ █  ██ █ ███ █
█ ███ █ █    █ ██ █ ███ █
█ ███ █ ██    ███ █ ███ █
█     █ █         █     █
███████ █ █ █ █ █ ███████
        ███    ██
█   █ ████  █ ██ █████  █
 █     █ ██ █ ███  ██
███  ██    █████ █ █ ███
 █████  █  ██    █    ██
  ██  ███  ██ █ ████ ████
█  ██  █ █    ████ ███ █
   █  ██ ██  ███ █ ██
  ████ █ ██ █  █  █   █
███  ██ ██ █ ██ █████ █
        ███ █ █ █   ███ █
███████ █ █████ █ █ █
█     █   ██ █  █   █ █
█ ███ █ █ █ ██  █████████
█ ███ █  █   ███ ██    ██
█ ███ █  ██      ███ █ █
█     █     █ ██  ███ ██
███████ ██ █ ███ █ █  ███
</code>```

答:
I found out the issue. I wasn't actually putting in the ASCII block character to the conv function but rather I was putting in code to change the colour of the terminal. This ended up being printed as is during auth hence why the QR code didn't show up.

Fixed it now by sending in the proper ASCII block character which when treated as a string prints perfectly well to the user during PAM auth.

Body:
I am creating a PAM module to show a QR code to users that are trying to log onto a system over SSH to allow them to scan it and authenticate using biometrics on their phone. Is there a way to pass unicode characters into the PAM conv function to allow the application to display them to the user?

The reason I need to hand in unicode characters is because I want to use the uincode character █ (U+2588 Full Block) as a way to print the QR code to the screen.

I have tried using the type wchar_t to hand in the value and also just trying to hand it in as char but both end up printing the missing character question mark to the screen.

If this is not possible is there a way of being able to show a QR code prior to authentication at all or is regular text the only possible thing to show?

Pam conv struct from PAM source:

struct pam_conv {
    int (*conv)(int num_msg, const struct pam_message **msg,
        struct pam_response **resp, void *appdata_ptr);
    void *appdata_ptr;
};

Edit (31/10/21): I have tried the suggestion of encoding as UTF8 which I beleive is done like so: \u[unicode char code]. This produced the following compiler warning:

src/pam-qr.c:118:58: warning: multi-character character constant [-Wmultichar]
  118 |             row[x] = qrcodegen_getModule(qrcode, x, y) ? '\u2588' : ' ';

and this output:

\210\210\210\210\210\210\210 \210  \210\210\210 \210\210 \210\210\210\210\210\210\210\214\2723O\177
\210     \210      \210  \210 \210     \210\214\2723O\177
\210 \210\210\210 \210  \210\210 \210  \210\210 \210 \210\210\210 \210\214\2723O\177
\210 \210\210\210 \210 \210    \210 \210\210 \210 \210\210\210 \210\214\2723O\177
\210 \210\210\210 \210 \210\210    \210\210\210 \210 \210\210\210 \210\214\2723O\177
\210     \210 \210         \210     \210\214\2723O\177
\210\210\210\210\210\210\210 \210 \210 \210 \210 \210 \210\210\210\210\210\210\210\214\2723O\177
        \210\210\210    \210\210        \214\2723O\177
\210   \210 \210\210\210\210  \210 \210\210 \210\210\210\210\210  \210\214\2723O\177
 \210     \210 \210\210 \210 \210\210\210  \210\210    \214\2723O\177
\210\210\210  \210\210    \210\210\210\210\210 \210 \210 \210\210\210 \214\2723O\177
 \210\210\210\210\210  \210  \210\210    \210    \210\210 \214\2723O\177
  \210\210  \210\210\210  \210\210 \210 \210\210\210\210 \210\210\210\210\214\272

The following is the output I get when using # instead of the block character:

####### #  ### ## #######
#     #      #  # #     #
# ### #  ## #  ## # ### #
# ### # #    # ## # ### #
# ### # ##    ### # ### #
#     # #         #     #
####### # # # # # #######
        ###    ##
#   # ####  # ## #####  #
 #     # ## # ###  ##
###  ##    ##### # # ###
 #####  #  ##    #    ##
  ##  ###  ## # #### ####
#  ##  # #    #### ### #
   #  ## ##  ### # ##
  #### # ## #  #  #   #
###  ## ## # ## ##### #
        ### # # #   ### #
####### # ##### # # #
#     #   ## #  #   # #
# ### # # # ##  #########
# ### #  #   ### ##    ##
# ### #  ##      ### # #
#     #     # ##  ### ##
####### ## # ### # #  ###

This can't be scanned but the printed version with the block character can be hence why I want to use it. This is the desired output using the block character that I'm trying to achieve:

███████ █  ███ ██ ███████
█     █      █  █ █     █
█ ███ █  ██ █  ██ █ ███ █
█ ███ █ █    █ ██ █ ███ █
█ ███ █ ██    ███ █ ███ █
█     █ █         █     █
███████ █ █ █ █ █ ███████
        ███    ██
█   █ ████  █ ██ █████  █
 █     █ ██ █ ███  ██
███  ██    █████ █ █ ███
 █████  █  ██    █    ██
  ██  ███  ██ █ ████ ████
█  ██  █ █    ████ ███ █
   █  ██ ██  ███ █ ██
  ████ █ ██ █  █  █   █
███  ██ ██ █ ██ █████ █
        ███ █ █ █   ███ █
███████ █ █████ █ █ █
█     █   ██ █  █   █ █
█ ███ █ █ █ ██  █████████
█ ███ █  █   ███ ██    ██
█ ███ █  ██      ███ █ █
█     █     █ ██  ███ ██
███████ ██ █ ███ █ █  ███


问:
Node.js: Python not found exception due to node-sass and node-gyp
Suddenly in one of my jenkins environment build has started failing, while in local machine it seems to be working fine as i have python installed,

From the logs i was able to detect that the problem is with internal dependency that is node-gyp v3.5.0 from node-sass v3.8.0 when i researched by visiting this about node-gyp and found the prerequisite that Python needs to be installed.

So my question is that what version of node-sass can i install to bypass this or is there a better solution as my build was running fine till this morning on the same environment.

Node v5.10.1

ERROR LOG

```<code>gyp verb check python checking for Python executable "python2" in the PATH
gyp verb `which` failed Error: not found: python2
gyp verb `which` failed     at getNotFoundError (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:13:12)
gyp verb `which` failed     at F (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:68:19)
gyp verb `which` failed     at E (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:80:29)
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:89:16
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\index.js:44:5
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\windows.js:29:5
gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:82:15)
gyp verb `which` failed  python2 { [Error: not found: python2] code: 'ENOENT' }
gyp verb check python checking for Python executable "python" in the PATH
gyp verb `which` failed Error: not found: python
gyp verb `which` failed     at getNotFoundError (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:13:12)
gyp verb `which` failed     at F (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:68:19)
gyp verb `which` failed     at E (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:80:29)
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:89:16
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\index.js:44:5
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\windows.js:29:5
gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:82:15)
gyp verb `which` failed  python { [Error: not found: python] code: 'ENOENT' }
gyp verb could not find "python". checking python launcher
gyp verb could not find "python". guessing location
gyp verb ensuring that file exists: C:\Python27\python.exe
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable.
gyp ERR! stack     at Object.failNoPython (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\node-gyp\lib\configure.js:454:19)
gyp ERR! stack     at Object.<anonymous> (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\node-gyp\lib\configure.js:480:16)
gyp ERR! stack     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\graceful-fs\polyfills.js:284:29
gyp ERR! stack     at FSReqWrap.oncomplete (fs.js:82:15)
gyp ERR! System Windows_NT 6.3.9600
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files (x86)\\Jenkins\\jobs\\NdbSite-hot-fix-Manual-PreBuild\\workspace\\src\\NdbSite.UI\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\node-sass
gyp ERR! node -v v5.10.1
gyp ERR! node-gyp -v v3.5.0
gyp ERR! not ok
Build failed
</code>```

Any thoughts are much appreciated, Thanks.

答: npm i npm -g will work if node version is updated. I ran into this issue, and npm install -g --production windows-build-tools worked as interim solution. But upgrading Node.js, NPM, and associated package versions is a better long term option.

Body:
Suddenly in one of my jenkins environment build has started failing, while in local machine it seems to be working fine as i have python installed,

From the logs i was able to detect that the problem is with internal dependency that is node-gyp v3.5.0 from node-sass v3.8.0 when i researched by visiting this about node-gyp and found the prerequisite that Python needs to be installed.

So my question is that what version of node-sass can i install to bypass this or is there a better solution as my build was running fine till this morning on the same environment.

Node v5.10.1

ERROR LOG

gyp verb check python checking for Python executable "python2" in the PATH
gyp verb `which` failed Error: not found: python2
gyp verb `which` failed     at getNotFoundError (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:13:12)
gyp verb `which` failed     at F (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:68:19)
gyp verb `which` failed     at E (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:80:29)
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:89:16
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\index.js:44:5
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\windows.js:29:5
gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:82:15)
gyp verb `which` failed  python2 { [Error: not found: python2] code: 'ENOENT' }
gyp verb check python checking for Python executable "python" in the PATH
gyp verb `which` failed Error: not found: python
gyp verb `which` failed     at getNotFoundError (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:13:12)
gyp verb `which` failed     at F (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:68:19)
gyp verb `which` failed     at E (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:80:29)
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:89:16
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\index.js:44:5
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\windows.js:29:5
gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:82:15)
gyp verb `which` failed  python { [Error: not found: python] code: 'ENOENT' }
gyp verb could not find "python". checking python launcher
gyp verb could not find "python". guessing location
gyp verb ensuring that file exists: C:\Python27\python.exe
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable.
gyp ERR! stack     at Object.failNoPython (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\node-gyp\lib\configure.js:454:19)
gyp ERR! stack     at Object.<anonymous> (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\node-gyp\lib\configure.js:480:16)
gyp ERR! stack     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\graceful-fs\polyfills.js:284:29
gyp ERR! stack     at FSReqWrap.oncomplete (fs.js:82:15)
gyp ERR! System Windows_NT 6.3.9600
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files (x86)\\Jenkins\\jobs\\NdbSite-hot-fix-Manual-PreBuild\\workspace\\src\\NdbSite.UI\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\node-sass
gyp ERR! node -v v5.10.1
gyp ERR! node-gyp -v v3.5.0
gyp ERR! not ok
Build failed

Any thoughts are much appreciated, Thanks.


问:
Ruby on Rails: How to Permit parameters with "_json"
I am trying to get POST requests to work coming from a React.js application to a Ruby on Rails API.

The parameters are:

```<code>Parameters: {"_json"=>"{'Name': 'ExampleSurvey', 'Draft_Status': 'true', 'Active_Status': 'false' }", "survey"=>{}}
</code>```

My survey_params method is:

```<code> def survey_params
    params.permit(:Name, :Draft_Status, :Active_Status)
 end
</code>```

My API Call from React is:

```<code>const post = (endpoint, body) => {
    const url = ANAMNESIS_CONFIG.backend.location + endpoint ?? '';
    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Anamnesis-Secret': ANAMNESIS_CONFIG.backend.secret
        },
        body: JSON.stringify(body)
    }).then(response => response.json())
};
</code>```
```<code>const submitHandler = e => {
        e.preventDefault();
        console.log({ surveyDetails })
        post('survey',`{'Name': '${surveyDetails.name}', 'Draft_Status': 'true', 'Active_Status': 'false' }`)
    }
</code>```

The following Curl Request allows me to enter new surveys without any issues:

```<code>curl -X POST -d "Name=Example&Draft_Status=true&Active_Status=false" http://localhost:3000/survey
</code>```

How can I edit Rails or React to get the Post request to work properly in a way that allows the curl request to still work?

Update:
Here is a picture from the logs: The first request is from Curl. The second request is from React. Hope this helps make the error more clear. Thanks for the help so far.

[

答:
Changed the POST body from a string to a JSON object. This caused Rails to accept the params.

```<code>post('survey',{Name: surveyDetails.name, Draft_Status: true, Active_Status: false})
</code>```

Shoutout to max (https://stackoverflow.com/users/544825/max) for coming up with solution!

Body:
I am trying to get POST requests to work coming from a React.js application to a Ruby on Rails API.

The parameters are:

Parameters: {"_json"=>"{'Name': 'ExampleSurvey', 'Draft_Status': 'true', 'Active_Status': 'false' }", "survey"=>{}}

My survey_params method is:

 def survey_params
    params.permit(:Name, :Draft_Status, :Active_Status)
 end

My API Call from React is:

const post = (endpoint, body) => {
    const url = ANAMNESIS_CONFIG.backend.location + endpoint ?? '';
    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Anamnesis-Secret': ANAMNESIS_CONFIG.backend.secret
        },
        body: JSON.stringify(body)
    }).then(response => response.json())
};

const submitHandler = e => {
        e.preventDefault();
        console.log({ surveyDetails })
        post('survey',`{'Name': '${surveyDetails.name}', 'Draft_Status': 'true', 'Active_Status': 'false' }`)
    }

The following Curl Request allows me to enter new surveys without any issues:

curl -X POST -d "Name=Example&Draft_Status=true&Active_Status=false" http://localhost:3000/survey

How can I edit Rails or React to get the Post request to work properly in a way that allows the curl request to still work?

Update:
Here is a picture from the logs: The first request is from Curl. The second request is from React. Hope this helps make the error more clear. Thanks for the help so far.

[

Body:
Changed the POST body from a string to a JSON object. This caused Rails to accept the params.

post('survey',{Name: surveyDetails.name, Draft_Status: true, Active_Status: false})

Shoutout to max (https://stackoverflow.com/users/544825/max) for coming up with solution!


问:
Convert words (string) to Int
I'm sure this has been done a hundred times, but i'm hoping there is a really simple way to accomplished this.  I'm wanting to change words to an int.

Like the following example

```One = 1
Two = 2
Three = 3
```

So basically if I have the string "One" it gets converted to 1, even if I could get back a string "1" I can just convert that.

答:
I took a slightly different approach to error handling…</p>
```<code>  public static bool ParseEnglishNumberPhrase(string pNumberPhrase, out int pValue) {
     pValue = 0;
     string[]
        temporaryWords = pNumberPhrase.ToLower().Split(new char[] { '_', ' ', '-', ',' }, StringSplitOptions.RemoveEmptyEntries),
        ones = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" },
        teens = { "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" },
        tens = { "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" },
        minusWords = { "minus", "negative", "hyphen" };
     List<string> words = temporaryWords.ToList();
     bool minusFlag = false;
     Dictionary<string, int> modifiers = new Dictionary<string, int>() {
        { "billion", 1000000000 },
        { "million", 1000000 },
        { "thousand", 1000 },
        { "hundred", 100 } };
     int result = 0, currentResult = 0, lastModifier = 1;

     if (pNumberPhrase.Equals("eleventy billion")) {
        pValue = int.MaxValue; // 110,000,000,000 is out of range for an int!
        return false;
     }
     if (words[0].Equals("zero") && (words.Count == 1)) {
        pValue = 0;
        return true;
     }
     else if (words[0].Equals("zero"))
        words.RemoveAt(0);
     if (pNumberPhrase.StartsWith("-"))
        minusFlag = true;
     foreach (string word in minusWords) {
        if (pNumberPhrase.Contains(word)) {
           minusFlag = true;
           words.Remove(word);
        }
     }
     if (words.Count == 1) {
        if (int.TryParse(words[0], out int pOutValue)) {
           pValue = pOutValue;
           if (minusFlag)
              pValue *= -1;
           return true;
        }
     }
     foreach (string word in words) {
        if (modifiers.ContainsKey(word))
           lastModifier *= modifiers[word];
        else {
           int n;

           if (lastModifier > 1) {
              result += currentResult * lastModifier;
              lastModifier = 1;
              currentResult = 0;
           }
           if ((n = Array.IndexOf(ones, word) + 1) > 0)
              currentResult += n;
           else if ((n = Array.IndexOf(teens, word) + 1) > 0)
              currentResult += n + 10;
           else if ((n = Array.IndexOf(tens, word) + 1) > 0)
              currentResult += n * 10;
           else if (word != "and") {
              pValue = -1;
              return false;
           }
        }
     }
     pValue = result + currentResult * lastModifier;
     if (minusFlag)
        pValue *= -1;
     return true;
  }
</code>```

Title: Convert words (string) to Int

Body:
I'm sure this has been done a hundred times, but i'm hoping there is a really simple way to accomplished this.  I'm wanting to change words to an int.

Like the following example

One = 1
Two = 2
Three = 3

So basically if I have the string "One" it gets converted to 1, even if I could get back a string "1" I can just convert that.

Body:
I took a slightly different approach to error handling…

  public static bool ParseEnglishNumberPhrase(string pNumberPhrase, out int pValue) {
     pValue = 0;
     string[]
        temporaryWords = pNumberPhrase.ToLower().Split(new char[] { '_', ' ', '-', ',' }, StringSplitOptions.RemoveEmptyEntries),
        ones = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" },
        teens = { "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" },
        tens = { "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" },
        minusWords = { "minus", "negative", "hyphen" };
     List<string> words = temporaryWords.ToList();
     bool minusFlag = false;
     Dictionary<string, int> modifiers = new Dictionary<string, int>() {
        { "billion", 1000000000 },
        { "million", 1000000 },
        { "thousand", 1000 },
        { "hundred", 100 } };
     int result = 0, currentResult = 0, lastModifier = 1;

     if (pNumberPhrase.Equals("eleventy billion")) {
        pValue = int.MaxValue; // 110,000,000,000 is out of range for an int!
        return false;
     }
     if (words[0].Equals("zero") && (words.Count == 1)) {
        pValue = 0;
        return true;
     }
     else if (words[0].Equals("zero"))
        words.RemoveAt(0);
     if (pNumberPhrase.StartsWith("-"))
        minusFlag = true;
     foreach (string word in minusWords) {
        if (pNumberPhrase.Contains(word)) {
           minusFlag = true;
           words.Remove(word);
        }
     }
     if (words.Count == 1) {
        if (int.TryParse(words[0], out int pOutValue)) {
           pValue = pOutValue;
           if (minusFlag)
              pValue *= -1;
           return true;
        }
     }
     foreach (string word in words) {
        if (modifiers.ContainsKey(word))
           lastModifier *= modifiers[word];
        else {
           int n;

           if (lastModifier > 1) {
              result += currentResult * lastModifier;
              lastModifier = 1;
              currentResult = 0;
           }
           if ((n = Array.IndexOf(ones, word) + 1) > 0)
              currentResult += n;
           else if ((n = Array.IndexOf(teens, word) + 1) > 0)
              currentResult += n + 10;
           else if ((n = Array.IndexOf(tens, word) + 1) > 0)
              currentResult += n * 10;
           else if (word != "and") {
              pValue = -1;
              return false;
           }
        }
     }
     pValue = result + currentResult * lastModifier;
     if (minusFlag)
        pValue *= -1;
     return true;
  }


问:
@AfterMapping mehod is not called in generated class
I'm trying to customize a mapping use a string to determine an object attribute so I wrote this:

```<code>@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public abstract class ProductMapper {

public abstract ProductInput asProductInputFromIdentifier(String identifier);

@AfterMapping
protected void determineIdentifier(String identifier, @MappingTarget ProductInput out) {
    if (StringUtils.contains(identifier, '?')) {
        out.setExternalId(identifier);
    } else {
        out.setInernalId(identifier);
    }
}
}
</code>```

The generated class doesn't call the determineIdentifier method. I found another solution by using directly the Java expression on the asProductInputFromIdentifier method but I really want to write a clear code using the @AfterMapping.

```<code>@Mapping(target = "externalId", expression = "java( org.apache.commons.lang3.StringUtils.contains(identifier, '|') ? identifier : null )")
@Mapping(target = "internalId", expression = "java( !org.apache.commons.lang3.StringUtils.contains(identifier, '|') ? identifier : null )")
public abstract ProductInput asProductDetailInputFromIdentifier(String identifier);
</code>```

I didn't understand why it doesn't work Is it because I don't have an Object in method parameter?

答:
Method with @AfterMapping will be executed at the end of map method and it should have same input parameter as map method for example in below sample

```<code>@Mapper(
    componentModel = "spring",
    injectionStrategy = InjectionStrategy.CONSTRUCTOR,
    uses = {IdentifierMapper.class})
public interface HistoryMapper {

  HistoryDynamo toHistoryDynamo(History history);

  @AfterMapping
  default void changeReason(History history) {
    System.out.println(history.getReason());
  }
}
</code>```

Refer github working sample for the same https://github.com/rakesh-singh-samples/map-struct-samples/tree/stack-question-60523230/src/sample/mapstruct/mapper

Body:
I'm trying to customize a mapping use a string to determine an object attribute so I wrote this:

@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public abstract class ProductMapper {

public abstract ProductInput asProductInputFromIdentifier(String identifier);

@AfterMapping
protected void determineIdentifier(String identifier, @MappingTarget ProductInput out) {
    if (StringUtils.contains(identifier, '?')) {
        out.setExternalId(identifier);
    } else {
        out.setInernalId(identifier);
    }
}
}

The generated class doesn't call the determineIdentifier method. I found another solution by using directly the Java expression on the asProductInputFromIdentifier method but I really want to write a clear code using the @AfterMapping.

@Mapping(target = "externalId", expression = "java( org.apache.commons.lang3.StringUtils.contains(identifier, '|') ? identifier : null )")
@Mapping(target = "internalId", expression = "java( !org.apache.commons.lang3.StringUtils.contains(identifier, '|') ? identifier : null )")
public abstract ProductInput asProductDetailInputFromIdentifier(String identifier);

I didn't understand why it doesn't work Is it because I don't have an Object in method parameter?

Body:
Method with @AfterMapping will be executed at the end of map method and it should have same input parameter as map method for example in below sample

@Mapper(
    componentModel = "spring",
    injectionStrategy = InjectionStrategy.CONSTRUCTOR,
    uses = {IdentifierMapper.class})
public interface HistoryMapper {

  HistoryDynamo toHistoryDynamo(History history);

  @AfterMapping
  default void changeReason(History history) {
    System.out.println(history.getReason());
  }
}

Refer github working sample for the same https://github.com/rakesh-singh-samples/map-struct-samples/tree/stack-question-60523230/src/sample/mapstruct/mapper


问:
What's the purpose of a React Functional Component when it can be used to modify state?
I am new to React and learning it. From this link:

There are mainly two components in React:

Functional Components also known as Stateless component

Class Component also known as Stateful component

and it seems that functional components are the rage these days e.g., I inherited some code and it uses functional components everywhere. The same article is then saying:

... a functional component is just a plain JavaScript function, we
cannot use setState() method inside component. That’s why they also
get called functional stateless components. ... useState can be used
to store state in a functional component.

and I do see tons of code using useState in functional components to modify state. Can someone explain this to me?

答:
Answering my own question.

Functional components were referred to as stateless components but its no longer correct to think of them as stateless. This link from official documentation explains it:

You might have previously known these as “stateless components”. We’re
now introducing the ability to use React state from these, so we
prefer the name “function components”.

To answer the second part of the question, functional components are indeed the rage these days because that's the official guidance and recommendation. From this page:

In the longer term, we expect Hooks to be the primary way people write
React components.

Also see this page for some background and comparison of class components vs. functional components.


问:
TypeError: Cannot convert undefined or null to object in Ionic/Angular
I'm trying to setup a crypto currency live market price. But it's not displaying. I'm only seeing this error in my chrome developer console.

ERROR TypeError: Cannot convert undefined or null to object

mycomponent.ts

```<code>
  ngOnInit() {
    this.refreshData();
  }

  refreshData(reset:boolean = false) {
    // Reset table index to 1
    if (reset) {
      this._data._previousIndex = 1;
    }

    // Set table page index and size to previous resevered data
    if (this._data._previousIndex !== null && this._data._previousPageSize !== null) {
      this._current = this._data._previousIndex;
      this._pageSize = this._data._previousPageSize;
      this._sortMap.name = this._data._previousSortMapName;
      this._sortMap.symbol = this._data._previousSortMapSymbol;
      //console.log("reserve data called");
    }

    this._loading = true;
    // Sort dataset before get
    if (this._sortName !== null || this._sortValue !== null) {
      this._data.sortData(this._sortName, this._sortValue);
      //console.log("sort method called");
    }

    this.cryData = [];
    this.cryptoLastPrices = [];
    this.cryptoPriceCompare = [];
    this.cryptoNames = this._data.getNamesFull();
    this.cryptoImages = this._data.getImagesFull();
    this._placeHolderSafe = this._sanitizer.bypassSecurityTrustUrl(this._placeholderBase64);

    this._data.getPricesFull()
      .subscribe(res => {
        this.receiveData = res.DISPLAY;
        //console.log(this.receiveData);

        let coinKeys: any = Object.keys(this.receiveData);
        let coinValues: any = Object.values(this.receiveData);

        // Price compare first time check
        if (this.cryptoLastPrices.length === 0) {
          for (let _i = 0; _i < coinKeys.length; _i++) {
            let _currentPrice = parseFloat((coinValues[_i].USD.PRICE).substring(2).replace(/,/g, ''));
            this.cryptoLastPrices[_i] = _currentPrice;
            this.cryptoPriceCompare[_i] = _currentPrice - this.cryptoLastPrices[_i];
          }
        } else {
          for (let _i = 0; _i < coinKeys.length; _i++) {
            this.cryptoPriceCompare[_i] = (parseFloat((coinValues[_i].USD.PRICE).substring(2).replace(/,/g, '')) -
              this.cryptoLastPrices[_i]);
          }
        }
        //console.log(this.cryptoLastPrices);

        for (let _i = 0; _i < coinKeys.length; _i++) {
          this.cryData[coinKeys[_i]] = {
            image: this.cryptoImages[_i],
            name: this.cryptoNames[_i],
            symbol: coinKeys[_i],
            price: coinValues[_i].USD.PRICE,
            marketCap: coinValues[_i].USD.MKTCAP,
            change24Num: parseFloat((coinValues[_i].USD.CHANGE24HOUR).substring(2).replace(/,/g, '')),
            priceCompare: this.cryptoPriceCompare[_i]
          }

          this.cryptoLastPrices[_i] = parseFloat((coinValues[_i].USD.PRICE).substring(2).replace(/,/g, ''));
          this.cryptos = JSON.parse(JSON.stringify(Object.values(this.cryData)));
        }
        //console.log(Object.values(this.cryData));
        this._loading = false;
        this.setTimer();
      });
  }
</code>```

I think the error is sitting on these lines

```<code>let coinKeys: any = Object.keys(this.receiveData);
let coinValues: any = Object.values(this.receiveData);
</code>```

This is how i defined it in export class code private receiveData: any;, i've tried changing any to any[] and to string, i've tried some few other method to fix it but didn't work out, been battling with this for some days now. Someone should kindly help me out.

答:
You seem to be correct about your analysis that might be causing the issue.

You will encounter the TypeError: Cannot convert undefined or null to object while trying to pass null or undefined values when the function expects an Object. In your case there are several code snippets that may result in the error:

Object.keys(this.receiveData)
Object.values(this.receiveData)
Object.values(this.cryData)
```

This is how i defined it in export class code private receiveData: any;, i've tried changing any to any[] and to string, i've tried some few other method to fix it but didn't work out

Simply specifying the Typescript type for the variables won't resolve the issue. You actually need to ensure that the value you are passing to Object.keys() and Object.values() is neither null nor undefined.

Body:
I'm trying to setup a crypto currency live market price. But it's not displaying. I'm only seeing this error in my chrome developer console.

ERROR TypeError: Cannot convert undefined or null to object

mycomponent.ts

  ngOnInit() {
    this.refreshData();
  }

  refreshData(reset:boolean = false) {
    // Reset table index to 1
    if (reset) {
      this._data._previousIndex = 1;
    }

    // Set table page index and size to previous resevered data
    if (this._data._previousIndex !== null && this._data._previousPageSize !== null) {
      this._current = this._data._previousIndex;
      this._pageSize = this._data._previousPageSize;
      this._sortMap.name = this._data._previousSortMapName;
      this._sortMap.symbol = this._data._previousSortMapSymbol;
      //console.log("reserve data called");
    }

    this._loading = true;
    // Sort dataset before get
    if (this._sortName !== null || this._sortValue !== null) {
      this._data.sortData(this._sortName, this._sortValue);
      //console.log("sort method called");
    }

    this.cryData = [];
    this.cryptoLastPrices = [];
    this.cryptoPriceCompare = [];
    this.cryptoNames = this._data.getNamesFull();
    this.cryptoImages = this._data.getImagesFull();
    this._placeHolderSafe = this._sanitizer.bypassSecurityTrustUrl(this._placeholderBase64);

    this._data.getPricesFull()
      .subscribe(res => {
        this.receiveData = res.DISPLAY;
        //console.log(this.receiveData);

        let coinKeys: any = Object.keys(this.receiveData);
        let coinValues: any = Object.values(this.receiveData);

        // Price compare first time check
        if (this.cryptoLastPrices.length === 0) {
          for (let _i = 0; _i < coinKeys.length; _i++) {
            let _currentPrice = parseFloat((coinValues[_i].USD.PRICE).substring(2).replace(/,/g, ''));
            this.cryptoLastPrices[_i] = _currentPrice;
            this.cryptoPriceCompare[_i] = _currentPrice - this.cryptoLastPrices[_i];
          }
        } else {
          for (let _i = 0; _i < coinKeys.length; _i++) {
            this.cryptoPriceCompare[_i] = (parseFloat((coinValues[_i].USD.PRICE).substring(2).replace(/,/g, '')) -
              this.cryptoLastPrices[_i]);
          }
        }
        //console.log(this.cryptoLastPrices);

        for (let _i = 0; _i < coinKeys.length; _i++) {
          this.cryData[coinKeys[_i]] = {
            image: this.cryptoImages[_i],
            name: this.cryptoNames[_i],
            symbol: coinKeys[_i],
            price: coinValues[_i].USD.PRICE,
            marketCap: coinValues[_i].USD.MKTCAP,
            change24Num: parseFloat((coinValues[_i].USD.CHANGE24HOUR).substring(2).replace(/,/g, '')),
            priceCompare: this.cryptoPriceCompare[_i]
          }

          this.cryptoLastPrices[_i] = parseFloat((coinValues[_i].USD.PRICE).substring(2).replace(/,/g, ''));
          this.cryptos = JSON.parse(JSON.stringify(Object.values(this.cryData)));
        }
        //console.log(Object.values(this.cryData));
        this._loading = false;
        this.setTimer();
      });
  }

I think the error is sitting on these lines

let coinKeys: any = Object.keys(this.receiveData);
let coinValues: any = Object.values(this.receiveData);

This is how i defined it in export class code private receiveData: any;, i've tried changing any to any[] and to string, i've tried some few other method to fix it but didn't work out, been battling with this for some days now. Someone should kindly help me out.

Body:
You seem to be correct about your analysis that might be causing the issue.

You will encounter the TypeError: Cannot convert undefined or null to object while trying to pass null or undefined values when the function expects an Object. In your case there are several code snippets that may result in the error:

Object.keys(this.receiveData)
Object.values(this.receiveData)
Object.values(this.cryData)

This is how i defined it in export class code private receiveData: any;, i've tried changing any to any[] and to string, i've tried some few other method to fix it but didn't work out

Simply specifying the Typescript type for the variables won't resolve the issue. You actually need to ensure that the value you are passing to Object.keys() and Object.values() is neither null nor undefined.


问:
Sequence to Sequence Loss
I'm trying to figure out how sequence to sequence loss is calculated. I am using the huggingface transformers library in this case, but this might actually be relevant to other DL libraries.

So to get the required data we can do:

from transformers import EncoderDecoderModel, BertTokenizer
import torch
import torch.nn.functional as F
torch.manual_seed(42)

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
MAX_LEN = 128
tokenize = lambda x: tokenizer(x, max_length=MAX_LEN, truncation=True, padding=True, return_tensors="pt")

model = EncoderDecoderModel.from_encoder_decoder_pretrained('bert-base-uncased', 'bert-base-uncased') # initialize Bert2Bert from pre-trained checkpoints
input_seq = ["Hello, my dog is cute", "my cat cute"]
output_seq = ["Yes it is", "ok"]
input_tokens = tokenize(input_seq)
output_tokens = tokenize(output_seq)

outputs = model(
    input_ids=input_tokens["input_ids"],
    attention_mask=input_tokens["attention_mask"],
    decoder_input_ids=output_tokens["input_ids"],
    decoder_attention_mask=output_tokens["attention_mask"],
    labels=output_tokens["input_ids"],
    return_dict=True)

idx = output_tokens["input_ids"]
logits = F.log_softmax(outputs["logits"], dim=-1)
mask = output_tokens["attention_mask"]
```
<h2>Edit 1</h2>
<p>Thanks to @cronoik I was able to replicate the loss calculated by huggingface as being:</p>
<pre class="lang-py prettyprint-override"><code>output_logits = logits[:,:-1,:]
output_mask = mask[:,:-1]
label_tokens = output_tokens["input_ids"][:, 1:].unsqueeze(-1)
select_logits = torch.gather(output_logits, -1, label_tokens).squeeze()
huggingface_loss = -select_logits.mean()
</code>```

However, since the last two tokens of the second input is just padding, shouldn't we calculate the loss to be:

seq_loss = (select_logits * output_mask).sum(dim=-1, keepdims=True) / output_mask.sum(dim=-1, keepdims=True)
seq_loss = -seq_loss.mean()
```

^This takes into account the length of the sequence of each row of outputs, and the padding by masking it out. Think this is especially useful when we have batches of varying length outputs.

答:
thanks for sharing. However, the new version of transformers as of today actually does not "shift" anymore. The following is not needed.</p>
```<code>#shift things
output_logits = logits[:,:-1,:]
label_tokens = idx[:, 1:].unsqueeze(-1)
output_mask = mask[:,1:
</code>```

Title: Sequence to Sequence Loss

Body:
I'm trying to figure out how sequence to sequence loss is calculated. I am using the huggingface transformers library in this case, but this might actually be relevant to other DL libraries.

So to get the required data we can do:

from transformers import EncoderDecoderModel, BertTokenizer
import torch
import torch.nn.functional as F
torch.manual_seed(42)

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
MAX_LEN = 128
tokenize = lambda x: tokenizer(x, max_length=MAX_LEN, truncation=True, padding=True, return_tensors="pt")

model = EncoderDecoderModel.from_encoder_decoder_pretrained('bert-base-uncased', 'bert-base-uncased') # initialize Bert2Bert from pre-trained checkpoints
input_seq = ["Hello, my dog is cute", "my cat cute"]
output_seq = ["Yes it is", "ok"]
input_tokens = tokenize(input_seq)
output_tokens = tokenize(output_seq)

outputs = model(
    input_ids=input_tokens["input_ids"],
    attention_mask=input_tokens["attention_mask"],
    decoder_input_ids=output_tokens["input_ids"],
    decoder_attention_mask=output_tokens["attention_mask"],
    labels=output_tokens["input_ids"],
    return_dict=True)

idx = output_tokens["input_ids"]
logits = F.log_softmax(outputs["logits"], dim=-1)
mask = output_tokens["attention_mask"]

Edit 1

Thanks to @cronoik I was able to replicate the loss calculated by huggingface as being:

output_logits = logits[:,:-1,:]
output_mask = mask[:,:-1]
label_tokens = output_tokens["input_ids"][:, 1:].unsqueeze(-1)
select_logits = torch.gather(output_logits, -1, label_tokens).squeeze()
huggingface_loss = -select_logits.mean()

However, since the last two tokens of the second input is just padding, shouldn't we calculate the loss to be:

seq_loss = (select_logits * output_mask).sum(dim=-1, keepdims=True) / output_mask.sum(dim=-1, keepdims=True)
seq_loss = -seq_loss.mean()

^This takes into account the length of the sequence of each row of outputs, and the padding by masking it out. Think this is especially useful when we have batches of varying length outputs.

Body:
thanks for sharing. However, the new version of transformers as of today actually does not "shift" anymore. The following is not needed.

#shift things
output_logits = logits[:,:-1,:]
label_tokens = idx[:, 1:].unsqueeze(-1)
output_mask = mask[:,1:


问:
How can I use a debounce function for an axios call in Vue 3
I've got code that gets JSON data from a PHP script using axios. Currently this call is triggered on input of an input field.

This is fine except the call is triggered every key press. I would like to debounce this function for maybe half a second.

I've tried importing a function from another file that I created called debounce.js which contains:

```<code>const debounce = (fn, delay) => {
    let timeout

    return (...args) => {
      if (timeout) {
        clearTimeout(timeout)
      }

      timeout = setTimeout(() => {
        fn(...args)
      }, delay)
    }
  }

  export default debounce
</code>```

I want to add the debounce to this method:

```<code>async fetchResults(){
    await axios.post('includes/searchproducts_json.php', {
        // Post data, add value of input to searchterm
        searchterm: this.$refs.searchterm.value

    })
    .then((response)=>{
        // Check if status is 200 (OK) and total_results is not 0
        // If true show results div and fill data
        if (response.status === 200 && response.data.total_results != 0) {
            this.showResultDiv = true
            this.results = response.data.results
            this.totalResults = response.data.total_results
            this.finishedCall = true
        }else{
            this.showResultDiv = false
        }
    })
    .catch((error)=>{
        console.log(error)
    })
    .then((response)=>{
        // Get length of returned object and add to results
        this.finishedCall = true
    })
}
</code>```

I thought to wrap this debounce function around the entire method because I want to debounce the entire method, not just the retrieving data part. So I tried this:

```<code>setup(){
    async fetchResults = debounce(() => {
        await axios.post('includes/searchproducts_json.php', {
            // Post data, add value of input to searchterm
            searchterm: this.$refs.searchterm.value

        })
        .then((response)=>{
            // Check if status is 200 (OK) and total_results is not 0
            // If true show results div and fill data
            if (response.status === 200 && response.data.total_results != 0) {
                this.showResultDiv = true
                this.results = response.data.results
                this.totalResults = response.data.total_results
                this.finishedCall = true
            }else{
                this.showResultDiv = false
            }
        })
        .catch((error)=>{
            console.log(error)
        })
        .then((response)=>{
            // Get length of returned object and add to results
            this.finishedCall = true
        })

    }, 500)
    return { fetchResults }
}
</code>```

But I get syntax errors like this. How can I correctly implement this debounce for the entire fetchResults method?

This is my entire JS code without the syntax errors:

```<code>import debounce from './assets/js/debounce.js'
let app = Vue.createApp({
    data: function(){
        return{
            // Object to fill with JSON response
            results:[],
            showResultDiv: false,
            totalResults: 0,
            finishedCall: false
        }
    },
    computed: {
        // Limit total results in searchdropdown to 6
        resultsToShow() {
            return this.results.slice(0, 6)
        },
        // Set the actual unlimited result amount to totalResults with matching string
        resultString(){
            if(this.totalResults == 1){
                return this.totalResults + ' resultaat'
            }else{
                return this.totalResults + ' resultaten'
            }
        }
    },
    methods:{
        // Function to show div with loading dots until json returned
        loadDiv(condition){
            this.showResultDiv = condition
        },
        async fetchResults(){
            await axios.post('includes/searchproducts_json.php', {
                // Post data, add value of input to searchterm
                searchterm: this.$refs.searchterm.value

            })
            .then((response)=>{
                // Check if status is 200 (OK) and total_results is not 0
                // If true show results div and fill data
                if (response.status === 200 && response.data.total_results != 0) {
                    this.showResultDiv = true
                    this.results = response.data.results
                    this.totalResults = response.data.total_results
                    this.finishedCall = true
                }else{
                    this.showResultDiv = false
                }
            })
            .catch((error)=>{
                console.log(error)
            })
            .then((response)=>{
                // Get length of returned object and add to results
                this.finishedCall = true
            })
        }
    }
})

app.mount('#v_search');
</code>```

答:
You can use debounce in Vue 3 like this if you don't want to use any additional packages.

<input type="search" v-model="query" />
```
<pre class="lang-js prettyprint-override"><code>const app = Vue.createApp({
  data() {
    return {
      query: "",
      results: [],
    };
  },
  methods: {
    debounce(func, timeout = 300) {
      let timer;
      return (...args) => {
        clearTimeout(timer);
        timer = setTimeout(() => {
          func.apply(this, args);
        }, timeout);
      };
    },
    fetchResults(query) {
      this.debounce(async () => {
        await axios
          .post("includes/searchproducts_json.php", {
            searchterm: query,
          })
          .then((response) => {
            if (response.status === 200 && response.data.total_results != 0) {
              this.showResultDiv = true;
              this.results = response.data.results;
              this.totalResults = response.data.total_results;
              this.finishedCall = true;
            } else {
              this.showResultDiv = false;
            }
          })
          .catch((error) => {
            console.error(error);
          })
          .finally(() => {
            this.finishedCall = true;
          });
      }, 500);
    },
  },
  computed: {
    query: {
      get() {
        return this.query;
      },
      set(val) {
        this.fetchResults(val);
        this.query = val;
      },
    },
  },
});
</code>```

Body:
I've got code that gets JSON data from a PHP script using axios. Currently this call is triggered on input of an input field.

This is fine except the call is triggered every key press. I would like to debounce this function for maybe half a second.

I've tried importing a function from another file that I created called debounce.js which contains:

const debounce = (fn, delay) => {
    let timeout

    return (...args) => {
      if (timeout) {
        clearTimeout(timeout)
      }

      timeout = setTimeout(() => {
        fn(...args)
      }, delay)
    }
  }

  export default debounce

I want to add the debounce to this method:

async fetchResults(){
    await axios.post('includes/searchproducts_json.php', {
        // Post data, add value of input to searchterm
        searchterm: this.$refs.searchterm.value

    })
    .then((response)=>{
        // Check if status is 200 (OK) and total_results is not 0
        // If true show results div and fill data
        if (response.status === 200 && response.data.total_results != 0) {
            this.showResultDiv = true
            this.results = response.data.results
            this.totalResults = response.data.total_results
            this.finishedCall = true
        }else{
            this.showResultDiv = false
        }
    })
    .catch((error)=>{
        console.log(error)
    })
    .then((response)=>{
        // Get length of returned object and add to results
        this.finishedCall = true
    })
}

I thought to wrap this debounce function around the entire method because I want to debounce the entire method, not just the retrieving data part. So I tried this:

setup(){
    async fetchResults = debounce(() => {
        await axios.post('includes/searchproducts_json.php', {
            // Post data, add value of input to searchterm
            searchterm: this.$refs.searchterm.value

        })
        .then((response)=>{
            // Check if status is 200 (OK) and total_results is not 0
            // If true show results div and fill data
            if (response.status === 200 && response.data.total_results != 0) {
                this.showResultDiv = true
                this.results = response.data.results
                this.totalResults = response.data.total_results
                this.finishedCall = true
            }else{
                this.showResultDiv = false
            }
        })
        .catch((error)=>{
            console.log(error)
        })
        .then((response)=>{
            // Get length of returned object and add to results
            this.finishedCall = true
        })

    }, 500)
    return { fetchResults }
}

But I get syntax errors like this. How can I correctly implement this debounce for the entire fetchResults method?

This is my entire JS code without the syntax errors:

import debounce from './assets/js/debounce.js'
let app = Vue.createApp({
    data: function(){
        return{
            // Object to fill with JSON response
            results:[],
            showResultDiv: false,
            totalResults: 0,
            finishedCall: false
        }
    },
    computed: {
        // Limit total results in searchdropdown to 6
        resultsToShow() {
            return this.results.slice(0, 6)
        },
        // Set the actual unlimited result amount to totalResults with matching string
        resultString(){
            if(this.totalResults == 1){
                return this.totalResults + ' resultaat'
            }else{
                return this.totalResults + ' resultaten'
            }
        }
    },
    methods:{
        // Function to show div with loading dots until json returned
        loadDiv(condition){
            this.showResultDiv = condition
        },
        async fetchResults(){
            await axios.post('includes/searchproducts_json.php', {
                // Post data, add value of input to searchterm
                searchterm: this.$refs.searchterm.value

            })
            .then((response)=>{
                // Check if status is 200 (OK) and total_results is not 0
                // If true show results div and fill data
                if (response.status === 200 && response.data.total_results != 0) {
                    this.showResultDiv = true
                    this.results = response.data.results
                    this.totalResults = response.data.total_results
                    this.finishedCall = true
                }else{
                    this.showResultDiv = false
                }
            })
            .catch((error)=>{
                console.log(error)
            })
            .then((response)=>{
                // Get length of returned object and add to results
                this.finishedCall = true
            })
        }
    }
})

app.mount('#v_search');

Body:
You can use debounce in Vue 3 like this if you don't want to use any additional packages.

<input type="search" v-model="query" />

const app = Vue.createApp({
  data() {
    return {
      query: "",
      results: [],
    };
  },
  methods: {
    debounce(func, timeout = 300) {
      let timer;
      return (...args) => {
        clearTimeout(timer);
        timer = setTimeout(() => {
          func.apply(this, args);
        }, timeout);
      };
    },
    fetchResults(query) {
      this.debounce(async () => {
        await axios
          .post("includes/searchproducts_json.php", {
            searchterm: query,
          })
          .then((response) => {
            if (response.status === 200 && response.data.total_results != 0) {
              this.showResultDiv = true;
              this.results = response.data.results;
              this.totalResults = response.data.total_results;
              this.finishedCall = true;
            } else {
              this.showResultDiv = false;
            }
          })
          .catch((error) => {
            console.error(error);
          })
          .finally(() => {
            this.finishedCall = true;
          });
      }, 500);
    },
  },
  computed: {
    query: {
      get() {
        return this.query;
      },
      set(val) {
        this.fetchResults(val);
        this.query = val;
      },
    },
  },
});


问:
How to go over a 2 columns and set the colour of a cell under a condition
Im trying to go over 2 column and set the colour of them into red if they are not equal to specefic string, but its not working with me.

Here is my code.

```<code>function setCellColors() {
  //Get the sheet you want to work with.
   const thisSheet = SpreadsheetApp.openByUrl(THIS).getSheetByName('Project');
   var range = thisSheet.getRange("V3:W").getValues();
   var newData = range;
   for (var i in newData) {
  if(newData!== "There is no NCR" && newData !=="N/A" && newData!=="There is no Reason Codes"){
  newData.setBackground("red");
  }
  }
}
</code>```

I,m keep getting this error "TypeError: newData.setBackground is not a function" which I think because newData ia=s an array but how would I change it to string in that case, and is the rest of the code right?

If you need more information please let me know

Thank you.

答:
Set selected backgrounds to red

```<code>function setCellColors() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getActiveSheet(Project);
  const tA = ["There is no NCR", "N/A", "There is no Reason Codes"];
  const vs = sh.getRange(3, 22, sh.getLastRow() - 2, 1).getValues();
  const newData = vs;
  vs.forEach((r, i) => {
    if (!~tA.indexOf(r[0])) {
      sh.getRange(i + 3, 22).setBackground("red");
    }
  });
}
</code>```

Body:
Im trying to go over 2 column and set the colour of them into red if they are not equal to specefic string, but its not working with me.

Here is my code.

function setCellColors() {
  //Get the sheet you want to work with.
   const thisSheet = SpreadsheetApp.openByUrl(THIS).getSheetByName('Project');
   var range = thisSheet.getRange("V3:W").getValues();
   var newData = range;
   for (var i in newData) {
  if(newData!== "There is no NCR" && newData !=="N/A" && newData!=="There is no Reason Codes"){
  newData.setBackground("red");
  }
  }
}

I,m keep getting this error "TypeError: newData.setBackground is not a function" which I think because newData ia=s an array but how would I change it to string in that case, and is the rest of the code right?

If you need more information please let me know

Thank you.

Body:
Set selected backgrounds to red

function setCellColors() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getActiveSheet(Project);
  const tA = ["There is no NCR", "N/A", "There is no Reason Codes"];
  const vs = sh.getRange(3, 22, sh.getLastRow() - 2, 1).getValues();
  const newData = vs;
  vs.forEach((r, i) => {
    if (!~tA.indexOf(r[0])) {
      sh.getRange(i + 3, 22).setBackground("red");
    }
  });
}


答:
It's not quite clear what of the columns should or should not contain one of the texts. I suppose it's the column 'V'. It this case you can try this code:

```<code>function setCellColors() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var texts = ['There is no NCR', 'N/A', 'There is no Reason Codes'];
  var range = sheet.getRange('V3:W');
  var values = range.getValues();
  var backgrounds = range.getBackgrounds();

  for (var row in values) {
    if (texts.includes(values[row][0])) {
      backgrounds[row][0] = 'red';
      backgrounds[row][1] = 'red';
    }
  }

  range.setBackgrounds(backgrounds);
}
</code>```

The result:

If you want to check both of the columns you can change this line:

```<code>if (texts.includes(values[row][0])) {
</code>```

with this:

```<code>if (texts.includes(values[row][0]) || texts.includes(values[row][1])) {
</code>```

Title: How to go over a 2 columns and set the colour of a cell under a condition

Body:
It's not quite clear what of the columns should or should not contain one of the texts. I suppose it's the column 'V'. It this case you can try this code:

function setCellColors() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var texts = ['There is no NCR', 'N/A', 'There is no Reason Codes'];
  var range = sheet.getRange('V3:W');
  var values = range.getValues();
  var backgrounds = range.getBackgrounds();

  for (var row in values) {
    if (texts.includes(values[row][0])) {
      backgrounds[row][0] = 'red';
      backgrounds[row][1] = 'red';
    }
  }

  range.setBackgrounds(backgrounds);
}

The result:

If you want to check both of the columns you can change this line:

if (texts.includes(values[row][0])) {

with this:

if (texts.includes(values[row][0]) || texts.includes(values[row][1])) {


问:
Typescript Can't bind to parse errors
I am not sure why I am getting this error message about not able to bind the model. I have an Input that is a type of Pagebreakable. Is there anything else I need to do for this to work?

Unhandled Promise rejection: Template parse errors:
Can't bind to 'model' since it isn't a known property of 'div'. ("

```<code><div class="pagebreak" [ERROR ->][model]="evaluatePagebreak()" (change)="onPagebreakChange($event)"></div>"): TemplateEditorComponent@9:23 ; Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors:
Can't bind to 'model' since it isn't a known property of 'div'. ("
<div class="clear-comments"></div>
</code>```

view

```<code><div class="pagebreak" [model]="evaluatePagebreak()" (change)="onPagebreakChange($event)"></div>
</code>```

Component

```<code>@Component({
    selector: ".pagebreak",
    template:
    `
      <hr class='narrow' *ngIf="model.HasPagebreak" />
      <span *ngIf="model.HasPagebreak" class='narrow'><a class='glyphicon glyphicon-remove' (click)='remove()'></a></span>
      <div *ngIf="!model.HasPagebreak" class='placeholder' (click)='add()'>put placeholder here</div>
      <hr class='wide' [class.enabled]="model.HasPagebreak"/>
    `
})
export class PageBreakComponent implements AfterViewInit, AfterViewChecked {

    @Input() model: Pagebreakable;
    @Output() change = new EventEmitter();

    constructor(@Inject(ElementRef) private elementRef: ElementRef) {
    }

    add() {
        this.model.HasPagebreak = true;
        this.onChange();
    }

    remove() {
        this.model.HasPagebreak = false;
        this.onChange();
    }

    onChange() {
        this.change.next({ value: this.model.HasPagebreak });
    }

    ngAfterViewInit() {
        var offset = $(this.elementRef.nativeElement).offset().left;
        $(this.elementRef.nativeElement).css('margin-left', '-' + offset + 'px');
        $(this.elementRef.nativeElement).css({ 'width': 'calc(100% + ' + offset + 'px)' });
    }

    ngAfterViewChecked() {
        if (this.isActive()) {
            if (!$(this.elementRef.nativeElement).hasClass('active')) {
                $(this.elementRef.nativeElement).addClass('active');
            }
        } else {
            if ($(this.elementRef.nativeElement).hasClass('active')) {
                $(this.elementRef.nativeElement).addClass('active');
            }
        }
    }

    isActive(): boolean {
        return (<any>window).pagebreakMode === true;
    }
}
</code>```

答:
The component you are referencing the pagebreak component from belongs to a Module. The pagebreak component also belongs to a Module.
Make sure both are in the "declarations" list of their respective Modules.
If they are in different modules, ensure that the pagebreak component is also listed in the "exports" list of its module, and that pagebreak's module is in the "imports" of the referencing component's module.</p>

Title: Typescript Can't bind to parse errors

Body:
I am not sure why I am getting this error message about not able to bind the model. I have an Input that is a type of Pagebreakable. Is there anything else I need to do for this to work?

Unhandled Promise rejection: Template parse errors:
Can't bind to 'model' since it isn't a known property of 'div'. ("

][model]="evaluatePagebreak()" (change)="onPagebreakChange($event)">
"): TemplateEditorComponent@9:23 ; Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors:
Can't bind to 'model' since it isn't a known property of 'div'. ("

view

Component

@Component({
    selector: ".pagebreak",
    template:
    `

put placeholder here

    `
})
export class PageBreakComponent implements AfterViewInit, AfterViewChecked {

    @Input() model: Pagebreakable;
    @Output() change = new EventEmitter();

    constructor(@Inject(ElementRef) private elementRef: ElementRef) {
    }

    add() {
        this.model.HasPagebreak = true;
        this.onChange();
    }

    remove() {
        this.model.HasPagebreak = false;
        this.onChange();
    }

    onChange() {
        this.change.next({ value: this.model.HasPagebreak });
    }

    ngAfterViewInit() {
        var offset = $(this.elementRef.nativeElement).offset().left;
        $(this.elementRef.nativeElement).css('margin-left', '-' + offset + 'px');
        $(this.elementRef.nativeElement).css({ 'width': 'calc(100% + ' + offset + 'px)' });
    }

    ngAfterViewChecked() {
        if (this.isActive()) {
            if (!$(this.elementRef.nativeElement).hasClass('active')) {
                $(this.elementRef.nativeElement).addClass('active');
            }
        } else {
            if ($(this.elementRef.nativeElement).hasClass('active')) {
                $(this.elementRef.nativeElement).addClass('active');
            }
        }
    }

    isActive(): boolean {
        return (<any>window).pagebreakMode === true;
    }
}


问:
Python pandas how to use a lamda function to convert duplicated code in 1 line
I have a pandas python code like this:

```<code>def mul3(df):
    df['mul31'] = df['tpx1'].values * df['tqy1'].values * df['vtin1'].values * df[
        'slife1'].values
    df['mul32'] = df['tpx2'].values * df['tqy2'].values * df['vtin2'].values * df[
        'slife1'].values
    df['mul33'] = df['tpx3'].values * df['tqy3'].values * df['vtin3'].values * df[
        'slife1'].values
    df['mul34'] = df['tpx4'].values * df['tqy4'].values * df['vtin4'].values * df[
        'slife1'].values
    df['mul35'] = df['tpx5'].values * df['tqy5'].values * df['vtin5'].values * df[
        'slife1'].values
    return df
</code>```

Is there anyway I can use a lamda function to replace it to 1 line code?
Any friend can help?

答:
You could probably do it like this:</p>
```<code>N = 5
df[[f'mul3{i}' for i in range(1, N+1)]] = [df[f'tpx{i}'].values * df[f'tqy{i}'].values * df[f'vtin{i}'].values * df['slife1'].values for i in range(1, N+1)]
</code>```

Body:
I have a pandas python code like this:

def mul3(df):
    df['mul31'] = df['tpx1'].values * df['tqy1'].values * df['vtin1'].values * df[
        'slife1'].values
    df['mul32'] = df['tpx2'].values * df['tqy2'].values * df['vtin2'].values * df[
        'slife1'].values
    df['mul33'] = df['tpx3'].values * df['tqy3'].values * df['vtin3'].values * df[
        'slife1'].values
    df['mul34'] = df['tpx4'].values * df['tqy4'].values * df['vtin4'].values * df[
        'slife1'].values
    df['mul35'] = df['tpx5'].values * df['tqy5'].values * df['vtin5'].values * df[
        'slife1'].values
    return df

Is there anyway I can use a lamda function to replace it to 1 line code?
Any friend can help?

Body:
You could probably do it like this:

N = 5
df[[f'mul3{i}' for i in range(1, N+1)]] = [df[f'tpx{i}'].values * df[f'tqy{i}'].values * df[f'vtin{i}'].values * df['slife1'].values for i in range(1, N+1)]


问:
How to visualize a time series in react with hooks
I went through different tutorials on how to show a simple time series on React. Most of them don't use hook, so I tried to adapt the code. I got stuck when tried to retrieve data with Axios from an open API. The error I got are ERROR in ./src/App.js Module build failed (from ./node_modules/babel-loader/lib/index.js) and ERROR in src/App.js Line 27:  Parsing error: Unexpected token, expected "," (27:0)

I am encountered these errors even before to try to show something. It seems something linked with the axios.get or there is something wrong with my useEffect hook.
Could you please help me with this?
Many thanks

```<code>import React , { useState, useEffect} from 'react';
import logo from './logo.svg';
import axios from 'axios';
import './App.css';

const  App =()=> {

  useEffect(() => {
    let x = [];
    let y = [];

    axios.get('https://data.cityofnewyork.us/resource/rc75-m7u3.json').then(response=>{
      console.log('response',response)
      response.map(each => {
      x.push(each.date_of_interest)
      y.push(each.case_count)

      .catch((error) => {console.log(error)})
        }, [])

    return (
      <div>Hello </div>
    )}

export default App;
</code>```

答:
You have several issues here:

There are typos in your code - you're missing a closing }); after pushing your data

You need to use an additional 'state' hook in order to access your data outside the effect function.

You need to parse your response as json, after fetching it.

You need to iterate over the data inside the render function in order to print it:

import React , { useState, useEffect} from 'react';
import logo from './logo.svg';
import axios from 'axios';
import './App.css';

const  App =()=> {
  const [xCoords, setXCoord] = useState([]);
  const [yCoords, setYCoord] = useState([]);

  useEffect(() => {
    axios.get('https://data.cityofnewyork.us/resource/rc75-m7u3.json')
      .then(response=> response.json())
      .then(data => {
        setXCoords(data.date_of_interest);
        setYCoords(data.case_count);
      }).catch((error) => {console.log(error)})
  }, [])

    return (

Hello

      ```
         { xCoords.map(x => <span>{x}</span>) }
      ```
    )}

export default App;
```

Body:
I went through different tutorials on how to show a simple time series on React. Most of them don't use hook, so I tried to adapt the code. I got stuck when tried to retrieve data with Axios from an open API. The error I got are ERROR in ./src/App.js Module build failed (from ./node_modules/babel-loader/lib/index.js) and ERROR in src/App.js Line 27:  Parsing error: Unexpected token, expected "," (27:0)

I am encountered these errors even before to try to show something. It seems something linked with the axios.get or there is something wrong with my useEffect hook.
Could you please help me with this?
Many thanks

import React , { useState, useEffect} from 'react';
import logo from './logo.svg';
import axios from 'axios';
import './App.css';

const  App =()=> {

  useEffect(() => {
    let x = [];
    let y = [];

    axios.get('https://data.cityofnewyork.us/resource/rc75-m7u3.json').then(response=>{
      console.log('response',response)
      response.map(each => {
      x.push(each.date_of_interest)
      y.push(each.case_count)

      .catch((error) => {console.log(error)})
        }, [])

    return (

Hello

    )}

export default App;

Body:
You have several issues here:

There are typos in your code - you're missing a closing }); after pushing your data

You need to use an additional 'state' hook in order to access your data outside the effect function.

You need to parse your response as json, after fetching it.

You need to iterate over the data inside the render function in order to print it:

import React , { useState, useEffect} from 'react';
import logo from './logo.svg';
import axios from 'axios';
import './App.css';

const  App =()=> {
  const [xCoords, setXCoord] = useState([]);
  const [yCoords, setYCoord] = useState([]);

  useEffect(() => {
    axios.get('https://data.cityofnewyork.us/resource/rc75-m7u3.json')
      .then(response=> response.json())
      .then(data => {
        setXCoords(data.date_of_interest);
        setYCoords(data.case_count);
      }).catch((error) => {console.log(error)})
  }, [])

    return (
      <div>Hello </div>
      <pre>
         { xCoords.map(x => <span>{x}</span>) }
      </pre>
    )}

export default App;


问:
Javascript: I need to find the average, min max sum and product of three variable
I am currently working on a project on finding the Min, Max, sum, product, and average of three numbers inputted by the user on the website and I just can't figure out how to get it to work and I have been working on it for the last two days and just can't seem to understand how to get it to work.

<!DOCTYPE html>

        <title>Homework Number Two Part Two</title>
        <meta charset="utf-8">
        <meta name="description" content= "My Homework Website">

        <form name="myform">
        First Number: <input type="text" id="num1" size="10">

        Second Number: <input type="text" id="num2" size="10">

        Third Number: <input type="text" id="num3" size="10">

        Results: <textarea rows="4" cols="40" id="result"></textarea>

        <input type="button" onclick="process()" value="SUBMIT">
        <input type="reset" value="RESET">```

答:
Use parseInt on each variable because every value is regarded as a string. So instead of doing the arithmetic operations, your code is actually concatenating strings.

Your code should look something like this to have an expected output.

```<code>x = parseInt(document.getElementById("num1").value);
y = parseInt(document.getElementById("num2").value);
z = parseInt(document.getElementById("num3").value);
result = (x+y+z)/3
document.getElementById("result").value = ("The result is " + result);
</code>```

Here is the correct program

https://jsfiddle.net/seh4wbmt/1/

For more detail follow this documentation

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Body:
Use parseInt on each variable because every value is regarded as a string. So instead of doing the arithmetic operations, your code is actually concatenating strings.

Your code should look something like this to have an expected output.

x = parseInt(document.getElementById("num1").value);
y = parseInt(document.getElementById("num2").value);
z = parseInt(document.getElementById("num3").value);
result = (x+y+z)/3
document.getElementById("result").value = ("The result is " + result);

Here is the correct program

https://jsfiddle.net/seh4wbmt/1/

For more detail follow this documentation

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt


问:
How to turn these C# foreach loops into LINQ to Objects and return a bool?
I'm writing a .Net 3.5 C# script for Sony Vegas Pro. I've created this method which returns true if it finds a video event with the same timecode as a given audio event.

This works but I'm wondering if I could get rid of the foreach loops using LINQ. I'm just learning LINQ and I'm finding it quite hard so if you could explain your thought steps in getting to the solution, that'd be great.

```<code>private bool videoExistsWithSameStart(TrackEvent currentEvent)
    {
        //Look through each video track - we don't want audio tracks.
        var videoTracks = from t in myVegas.Project.Tracks
                          where t.IsVideo()
                          select t;

        foreach (Track t in videoTracks)
        {
            foreach (TrackEvent te in t.Events)
            {
                if (te.Start == currentEvent.Start)
                    return true;
            }
        }
        return false;
    }
</code>```

答:
Forgive me, I don't have access to Visual Studio right now, but care to try?</p>

```<code>return myVegas.Projects.Tracks.Any(t => t.IsVideo() && t.Events.Any(e => e.Start == currentEvent.Start));
</code>```

Body:
I'm writing a .Net 3.5 C# script for Sony Vegas Pro. I've created this method which returns true if it finds a video event with the same timecode as a given audio event.

This works but I'm wondering if I could get rid of the foreach loops using LINQ. I'm just learning LINQ and I'm finding it quite hard so if you could explain your thought steps in getting to the solution, that'd be great.

private bool videoExistsWithSameStart(TrackEvent currentEvent)
    {
        //Look through each video track - we don't want audio tracks.
        var videoTracks = from t in myVegas.Project.Tracks
                          where t.IsVideo()
                          select t;

        foreach (Track t in videoTracks)
        {
            foreach (TrackEvent te in t.Events)
            {
                if (te.Start == currentEvent.Start)
                    return true;
            }
        }
        return false;
    }

Body:
Forgive me, I don't have access to Visual Studio right now, but care to try?

return myVegas.Projects.Tracks.Any(t => t.IsVideo() && t.Events.Any(e => e.Start == currentEvent.Start));


问:
Vue app (data out of scope) - Data is not defined at Proxy.calc
*Greetings Stackoverflow peeps.

I am developing my first Vue app and having issues with using the find function to loop through my metals list to pull the specificGravity value based on a matching type prop.
It seems that the list is out of scope and I am unable to find a solution through good ole' Google, so I turn to you all.

TIA*

Error:

"vue@next:1751 Uncaught ReferenceError: data is not defined
at Proxy.calc (index.html:101:45)
at onClick (eval at compileToFunction (vue@next:15591:23), :142:35)
at callWithErrorHandling (vue@next:1688:24)
at callWithAsyncErrorHandling (vue@next:1697:23)
at HTMLButtonElement.invoker (vue@next:9486:15)"

```<code><script>
        var app = Vue.createApp({
            data: function() {

                return {

                    waxWeight: null,
                    isVisible: true,
                    buttonSize: null,
                    specificGravity: null,
                    metalType: null
                }
            },

            // <!-- COMPONENTS -->
            components: {
                    },

            // <!-- METHODS -->
            // `this` inside methods point to the current Vue instance
            methods: {
                calc: function (waxWeight, buttonSize, metalType) {

                    var waxWeight = waxWeight
                    var buttonSize = buttonSize
                    var metalType = metalType

                var metals = {metals:[
                    { type: 'silver', specificGravity: 10.3 },
                    { type: 'wGold14', specificGravity: 12.1 },
                    { type: 'wGold18', specificGravity: 11.5 },
                    { type: 'yGold14', specificGravity: 13.6 }]}

                    // method does not have access to data list
                    const specificGravity = data.metals.find(function(elem){
                        if(elem.name == metalType)

                        return elem.specificGravity;

                        alert(metalType)
                    });
                }
            },
        })
        app.mount('#app')
    </script>
</code>```

答:
i'm not sure what you are trying to do in this function, but I will try to help you.

The problem is data is not accessible like that, data is a function that return a JSON object. So imagine you want to access the isVisible declared in the Data. You use this.isVisible.

However I can't understand why you need to access data there. It seems that you want to access the array inside the json object, so try metals.metals.find(...). And if you want to access the array metals, when you are calling elem.name you are always going to get undefined since this is not a key of the object, you should use elem.type instead. Here is a code pen that I made for you to exemplify what I'm saying

Sorry for the long answer, if this not help you please provide more context so I can help you


问:
How can I add a counter column that records the number of occurrences of a value in a data frame in R?
I have the following data frame:

df <- data.frame(catergory=c("a","b","b","b","b","a","c"), value=c(1,5,3,6,7,4,6))

and I want to record the number of occurrences of each category so the output would be:

```<code>df <- data.frame(catergory=c("a","b","b","b","b","a","c"), value=c(1,5,3,6,7,4,6),
category_count=c(2,4,4,4,4,2,1))
</code>```

Is there a simple way to do this?

答:
base

df <- data.frame(catergory=c("a","b","b","b","b","a","c"), value=c(1,5,3,6,7,4,6),
                 category_count=c(2,4,4,4,4,2,1))

df$res <- with(df, ave(x = seq(nrow(df)), list(catergory), FUN = length))
df
#>   catergory value category_count res
#> 1         a     1              2   2
#> 2         b     5              4   4
#> 3         b     3              4   4
#> 4         b     6              4   4
#> 5         b     7              4   4
#> 6         a     4              2   2
#> 7         c     6              1   1
```

Created on 2022-02-08 by the reprex package (v2.0.1)

Body:
I have the following data frame:

df <- data.frame(catergory=c("a","b","b","b","b","a","c"), value=c(1,5,3,6,7,4,6))

and I want to record the number of occurrences of each category so the output would be:

df <- data.frame(catergory=c("a","b","b","b","b","a","c"), value=c(1,5,3,6,7,4,6),
category_count=c(2,4,4,4,4,2,1))

Is there a simple way to do this?

Body:
base

df <- data.frame(catergory=c("a","b","b","b","b","a","c"), value=c(1,5,3,6,7,4,6),
                 category_count=c(2,4,4,4,4,2,1))

df$res <- with(df, ave(x = seq(nrow(df)), list(catergory), FUN = length))
df
#>   catergory value category_count res
#> 1         a     1              2   2
#> 2         b     5              4   4
#> 3         b     3              4   4
#> 4         b     6              4   4
#> 5         b     7              4   4
#> 6         a     4              2   2
#> 7         c     6              1   1

Created on 2022-02-08 by the reprex package (v2.0.1)