问:
R Studio can not read chinese character in txt file properly
While i was trying to read a txt file with read.table(), I met problems viewing the dataset in Rstudio. The original txt.file consists of three columns data including ID, Content(Cantonese) and Time, like the following format:

100008251304976   你又知喎 2019-10-04 16:52:15

  100027970365477   甘你買多幾包花生，小心熱氣   2019-10-04 16:23:43

I wrote the code to read it into Rstudio

```<code>x = read.table('comment.txt', encoding = 'utf-8', quote = "",fill = T,sep = '\t')
</code>```

but the result is messey data.

ç”˜ä½ è²·å¤šå¹¾åŒ…èŠ±ç”Ÿï¼Œå°å¿ƒç†±æ°£   2019å¹´10æ

Then i checked my env and locale as follows

```<code>sessionInfo()
#R version 3.6.1 (2019-07-05)
#Platform: x86_64-w64-mingw32/x64 (64-bit)
#Running under: Windows 10 x64 (build 18362)

#Matrix products: default

#locale:
#[1] LC_COLLATE=English_Hong Kong SAR.1252  LC_CTYPE=English_Hong Kong SAR.1252
#[3] LC_MONETARY=English_Hong Kong SAR.1252 LC_NUMERIC=C
#[5] LC_TIME=English_Hong Kong SAR.1252

#attached base packages:
#[1] stats     graphics  grDevices utils     datasets  methods   base

#loaded via a namespace (and not attached):
#[1] compiler_3.6.1   rsconnect_0.8.16 tools_3.6.1      tinytex_0.16     xfun_0.10
#[6] packrat_0.5.0

Sys.getlocale()
# "LC_COLLATE=English_Hong Kong SAR.1252;LC_CTYPE=English_Hong Kong SAR.1252;LC_MONETARY=English_Hong Kong SAR.1252;LC_NUMERIC=C;LC_TIME=English_Hong Kong SAR.1252"

Sys.getenv("LANG")
# "C.UTF-8"
</code>```

Any ideas why I can not load txt file properly? By the way, i am able to tpye or print traditional Chinese in the Rstudio.

```<code>print("試試")
# [1] "試試"
</code>```

答:
Input file (added a line in my native locale):

```<code>100008251304976 Třiatřicet žlutých šišinek  2019-10-04 16:52:15
100008251304976 你又知喎    2019-10-04 16:52:15
100027970365477 甘你買多幾包花生，小心熱氣   2019-10-04 16:23:43
</code>```

R code snippet (converting individual rows of the x data frame could be done in a loop, I know…):

```<code>sessionInfo()

library(stringi)
library(magrittr)

x <- read.table('d:\\bat\\R\\comment.txt', encoding = 'UTF-8', quote = "\"", fill = TRUE, sep = '\t')

print(x)

x['V2'][1,] %>%
  stri_replace_all_regex("<U\\+([[:alnum:]]+)>", "\\\\u$1") %>%
  stri_unescape_unicode() %>%
  stri_enc_toutf8()
x['V2'][2,] %>%
  stri_replace_all_regex("<U\\+([[:alnum:]]+)>", "\\\\u$1") %>%
  stri_unescape_unicode() %>%
  stri_enc_toutf8()
x['V2'][3,] %>%
  stri_replace_all_regex("<U\\+([[:alnum:]]+)>", "\\\\u$1") %>%
  stri_unescape_unicode() %>%
  stri_enc_toutf8()
</code>```

Result (paste the code snippet to an open Rstudio console):

```<code>> sessionInfo()
R version 3.4.1 (2017-06-30)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18363)

Matrix products: default

locale:
[1] LC_COLLATE=Czech_Czechia.1250  LC_CTYPE=Czech_Czechia.1250    LC_MONETARY=Czech_Czechia.1250
[4] LC_NUMERIC=C                   LC_TIME=Czech_Czechia.1250

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] magrittr_1.5  stringi_1.1.5

loaded via a namespace (and not attached):
[1] compiler_3.4.1 tools_3.4.1
> library(stringi)
> library(magrittr)
>
> x <- read.table('d:\\bat\\R\\comment.txt', encoding = 'UTF-8', quote = "\"", fill = TRUE, sep = '\t')
>
> print(x)
            V1                                                                                V2
1 1.000083e+14                                                                        Třiatřicet žlutých šišinek
2 1.000083e+14                                                                  <U+4F60><U+53C8><U+77E5><U+558E>
3 1.000280e+14 <U+7518><U+4F60><U+8CB7><U+591A><U+5E7E><U+5305><U+82B1><U+751F>,<U+5C0F><U+5FC3><U+71B1><U+6C23>
                   V3
1 2019-10-04 16:52:15
2 2019-10-04 16:52:15
3 2019-10-04 16:23:43
>
> x['V2'][1,] %>%
+   stri_replace_all_regex("<U\\+([[:alnum:]]+)>", "\\\\u$1") %>%
+   stri_unescape_unicode() %>%
+   stri_enc_toutf8()
[1] "Třiatřicet žlutých šišinek"
> x['V2'][2,] %>%
+   stri_replace_all_regex("<U\\+([[:alnum:]]+)>", "\\\\u$1") %>%
+   stri_unescape_unicode() %>%
+   stri_enc_toutf8()
[1] "你又知喎"
> x['V2'][3,] %>%
+   stri_replace_all_regex("<U\\+([[:alnum:]]+)>", "\\\\u$1") %>%
+   stri_unescape_unicode() %>%
+   stri_enc_toutf8()
[1] "甘你買多幾包花生，小心熱氣"
>
</code>```

Used the accepted answer to convert utf8 code point strings like  to utf8.

Body:
While i was trying to read a txt file with read.table(), I met problems viewing the dataset in Rstudio. The original txt.file consists of three columns data including ID, Content(Cantonese) and Time, like the following format:

100008251304976   你又知喎 2019-10-04 16:52:15

  100027970365477   甘你買多幾包花生，小心熱氣   2019-10-04 16:23:43

I wrote the code to read it into Rstudio

x = read.table('comment.txt', encoding = 'utf-8', quote = "",fill = T,sep = '\t')

but the result is messey data.

ç”˜ä½ è²·å¤šå¹¾åŒ…èŠ±ç”Ÿï¼Œå°å¿ƒç†±æ°£   2019å¹´10æ

Then i checked my env and locale as follows

sessionInfo()
#R version 3.6.1 (2019-07-05)
#Platform: x86_64-w64-mingw32/x64 (64-bit)
#Running under: Windows 10 x64 (build 18362)

#Matrix products: default

#locale:
#[1] LC_COLLATE=English_Hong Kong SAR.1252  LC_CTYPE=English_Hong Kong SAR.1252
#[3] LC_MONETARY=English_Hong Kong SAR.1252 LC_NUMERIC=C
#[5] LC_TIME=English_Hong Kong SAR.1252

#attached base packages:
#[1] stats     graphics  grDevices utils     datasets  methods   base

#loaded via a namespace (and not attached):
#[1] compiler_3.6.1   rsconnect_0.8.16 tools_3.6.1      tinytex_0.16     xfun_0.10
#[6] packrat_0.5.0

Sys.getlocale()
# "LC_COLLATE=English_Hong Kong SAR.1252;LC_CTYPE=English_Hong Kong SAR.1252;LC_MONETARY=English_Hong Kong SAR.1252;LC_NUMERIC=C;LC_TIME=English_Hong Kong SAR.1252"

Sys.getenv("LANG")
# "C.UTF-8"

Any ideas why I can not load txt file properly? By the way, i am able to tpye or print traditional Chinese in the Rstudio.

print("試試")
# [1] "試試"

Body:
Input file (added a line in my native locale):

100008251304976 Třiatřicet žlutých šišinek  2019-10-04 16:52:15
100008251304976 你又知喎    2019-10-04 16:52:15
100027970365477 甘你買多幾包花生，小心熱氣   2019-10-04 16:23:43

R code snippet (converting individual rows of the x data frame could be done in a loop, I know…):

sessionInfo()

library(stringi)
library(magrittr)

x <- read.table('d:\\bat\\R\\comment.txt', encoding = 'UTF-8', quote = "\"", fill = TRUE, sep = '\t')

print(x)

x['V2'][1,] %>%
  stri_replace_all_regex("<U\\+([[:alnum:]]+)>", "\\\\u$1") %>%
  stri_unescape_unicode() %>%
  stri_enc_toutf8()
x['V2'][2,] %>%
  stri_replace_all_regex("<U\\+([[:alnum:]]+)>", "\\\\u$1") %>%
  stri_unescape_unicode() %>%
  stri_enc_toutf8()
x['V2'][3,] %>%
  stri_replace_all_regex("<U\\+([[:alnum:]]+)>", "\\\\u$1") %>%
  stri_unescape_unicode() %>%
  stri_enc_toutf8()

Result (paste the code snippet to an open Rstudio console):

> sessionInfo()
R version 3.4.1 (2017-06-30)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18363)

Matrix products: default

locale:
[1] LC_COLLATE=Czech_Czechia.1250  LC_CTYPE=Czech_Czechia.1250    LC_MONETARY=Czech_Czechia.1250
[4] LC_NUMERIC=C                   LC_TIME=Czech_Czechia.1250

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] magrittr_1.5  stringi_1.1.5

loaded via a namespace (and not attached):
[1] compiler_3.4.1 tools_3.4.1
> library(stringi)
> library(magrittr)
>
> x <- read.table('d:\\bat\\R\\comment.txt', encoding = 'UTF-8', quote = "\"", fill = TRUE, sep = '\t')
>
> print(x)
            V1                                                                                V2
1 1.000083e+14                                                                        Třiatřicet žlutých šišinek
2 1.000083e+14                                                                  <U+4F60><U+53C8><U+77E5><U+558E>
3 1.000280e+14 <U+7518><U+4F60><U+8CB7><U+591A><U+5E7E><U+5305><U+82B1><U+751F>,<U+5C0F><U+5FC3><U+71B1><U+6C23>
                   V3
1 2019-10-04 16:52:15
2 2019-10-04 16:52:15
3 2019-10-04 16:23:43
>
> x['V2'][1,] %>%
+   stri_replace_all_regex("<U\\+([[:alnum:]]+)>", "\\\\u$1") %>%
+   stri_unescape_unicode() %>%
+   stri_enc_toutf8()
[1] "Třiatřicet žlutých šišinek"
> x['V2'][2,] %>%
+   stri_replace_all_regex("<U\\+([[:alnum:]]+)>", "\\\\u$1") %>%
+   stri_unescape_unicode() %>%
+   stri_enc_toutf8()
[1] "你又知喎"
> x['V2'][3,] %>%
+   stri_replace_all_regex("<U\\+([[:alnum:]]+)>", "\\\\u$1") %>%
+   stri_unescape_unicode() %>%
+   stri_enc_toutf8()
[1] "甘你買多幾包花生，小心熱氣"
>

Used the accepted answer to convert utf8 code point strings like  to utf8.


来源: stackexchange

问:
Visual Studio 2010: Keyboard Shortcut to "Override Method" in C#?
In Visual Studio 2010, what is the keyboard shortcut to drop-down a list of C# virtual methods, and clicking them will generate an "override method" code?

In IntelliJ IDEA, that feature's shortcut is CTRL+Shift+O.

答: If you type overridespace, or just ovtabspace you will get this list. Select the one you want tab and it will generate the full override signature and place you in the body (the caret will be placed immediately before the base.blah(...) call it generates).

ContentLicense: CC BY-SA 3.0


问:
Key error when using regex quantifier python
I am trying to capture words following specified stocks in a pandas df. I have several stocks in the format $IBM and am setting a python regex pattern to search each tweet for 3-5 words following the stock if found.

My df called stock_news looks as such:

```<code>   Word       Count

0  $IBM     10
1  $GOOGL   8
etc

pattern = ''
for word in stock_news.Word:
    pattern += '{} (\w+\s*\S*){3,5}|'.format(re.escape(word))
</code>```

However my understanding is that {} should be a quantifier, in my case matching between 3 to 5 times however I receive the following KeyError:

```<code>KeyError: '3,5'
</code>```

I have also tried using rawstrings with r'{} (\w+\s*\S*){3,5}|' but to no avail. I also tried using this pattern on regex101 and it seems to work there but not in my Pycharm IDE. Any help would be appreciated.

Code for finding:

```<code>pat = re.compile(pattern, re.I)

for i in tweet_df.Tweets:
    for x in pat.findall(i):
        print(x)
</code>```

答:
When you build your pattern, there is an empty alternative left at the end, so your pattern effectively matches any string, every empty space before non-matching texts.

You need to build the pattern like

```<code>(?:\$IBM|\$GOOGLE)\s+(\w+(?:\s+\S+){3,5})
</code>```

You may use

```<code>pattern = r'(?:{})\s+(\w+(?:\s+\S+){{3,5}})'.format(
              "|".join(map(re.escape, stock_news['Word'])))
</code>```

Mind that the literal curly braces inside an f-string or a format string must be doubled.

Regex details

(?:\$IBM|\$GOOGLE) - a non-capturing group matching either $IBM or $GOOGLE

\s+ - 1+ whitespaces

(\w+(?:\s+\S+){3,5}) - Capturing group 1 (when using str.findall, only this part will be returned):

\w+ - 1+ word chars

(?:\s+\S+){3,5} - a non-capturing* group matching three, four or five occurrences of 1+ whitespaces followed with 1+ non-whitespace characters

Note that non-capturing groups are meant to group some patterns, or quantify them, without actually allocating any memory buffer for the values they match, so that you could capture only what you need to return/keep.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to capture words following specified stocks in a pandas df. I have several stocks in the format $IBM and am setting a python regex pattern to search each tweet for 3-5 words following the stock if found.

My df called stock_news looks as such:

   Word       Count

0  $IBM     10
1  $GOOGL   8
etc

pattern = ''
for word in stock_news.Word:
    pattern += '{} (\w+\s*\S*){3,5}|'.format(re.escape(word))

However my understanding is that {} should be a quantifier, in my case matching between 3 to 5 times however I receive the following KeyError:

KeyError: '3,5'

I have also tried using rawstrings with r'{} (\w+\s*\S*){3,5}|' but to no avail. I also tried using this pattern on regex101 and it seems to work there but not in my Pycharm IDE. Any help would be appreciated.

Code for finding:

pat = re.compile(pattern, re.I)

for i in tweet_df.Tweets:
    for x in pat.findall(i):
        print(x)

Body:
When you build your pattern, there is an empty alternative left at the end, so your pattern effectively matches any string, every empty space before non-matching texts.

You need to build the pattern like

(?:\$IBM|\$GOOGLE)\s+(\w+(?:\s+\S+){3,5})

You may use

pattern = r'(?:{})\s+(\w+(?:\s+\S+){{3,5}})'.format(
              "|".join(map(re.escape, stock_news['Word'])))

Mind that the literal curly braces inside an f-string or a format string must be doubled.

Regex details

(?:\$IBM|\$GOOGLE) - a non-capturing group matching either $IBM or $GOOGLE

\s+ - 1+ whitespaces

(\w+(?:\s+\S+){3,5}) - Capturing group 1 (when using str.findall, only this part will be returned):

\w+ - 1+ word chars

(?:\s+\S+){3,5} - a non-capturing* group matching three, four or five occurrences of 1+ whitespaces followed with 1+ non-whitespace characters

Note that non-capturing groups are meant to group some patterns, or quantify them, without actually allocating any memory buffer for the values they match, so that you could capture only what you need to return/keep.


问:
Python: Remove division decimal
I have made a program that divides numbers and then returns the number, But the thing is that when it returns the number it has a decimal like this:

```<code>2.0
</code>```

But I want it to give me:

```<code>2
</code>```

so is there anyway I can do this?

答:
if val % 1 == 0:
    val = int(val)

else:
    val = float(val)
```

<p>This worked for me.</p>

<p>How it works: if the remainder of the quotient of val and 1 is 0, val has to be an integer and can, therefore, be declared to be int without having to worry about losing decimal numbers.</p>

<p>Compare these two situations:</p>

<p>A:</p>

<pre class="lang-py prettyprint-override"><code>val = 12.00

if val % 1 == 0:
    val = int(val)
else:
    val = float(val)

print(val)
</code>```

In this scenario, the output is 12, because 12.00 divided by 1 has the remainder of 0. With this information we know, that val doesn't have any decimals and we can declare val to be int.

B:

val = 13.58

if val % 1 == 0:
    val = int(val)
else:
    val = float(val)

print(val)
```

This time the output is 13.58, because when val is divided by 1 there is a remainder (0.58) and therefore val is declared to be a float.

By just declaring the number to be an int (without testing the remainder) decimal numbers will be cut off.

This way there are no zeros in the end and no other than the zeros will be ignored.

Title: Python: Remove division decimal

Body:
I have made a program that divides numbers and then returns the number, But the thing is that when it returns the number it has a decimal like this:

2.0

But I want it to give me:

2

so is there anyway I can do this?

Body:
if val % 1 == 0:
    val = int(val)

else:
    val = float(val)

This worked for me.

How it works: if the remainder of the quotient of val and 1 is 0, val has to be an integer and can, therefore, be declared to be int without having to worry about losing decimal numbers.

Compare these two situations:

A:

val = 12.00

if val % 1 == 0:
    val = int(val)
else:
    val = float(val)

print(val)

In this scenario, the output is 12, because 12.00 divided by 1 has the remainder of 0. With this information we know, that val doesn't have any decimals and we can declare val to be int.

B:

val = 13.58

if val % 1 == 0:
    val = int(val)
else:
    val = float(val)

print(val)

This time the output is 13.58, because when val is divided by 1 there is a remainder (0.58) and therefore val is declared to be a float.

By just declaring the number to be an int (without testing the remainder) decimal numbers will be cut off.

This way there are no zeros in the end and no other than the zeros will be ignored.


问:
Display modal based on page / url
I'm working on a site that has TWO home pages (different langauges). Each homepage displays a pop up modal in the homepage language when the user gets to the site. As of now it's working when the user first goes to the "English" page and THEN goes to the "French" page but if the user is first sent to the French page BOTH modals are showing. How can I assure only the given language modal will show on each page? I am using Jquery to achieve this.

URL's / page: index.html - English, index-fr.html - French

JQuery:

```<code>  window.setTimeout(function () {
  var url = location.pathname;

  if (
    url.indexOf("index") > -1 &&
    !disableWelcomeModal &&
    _siteNS.Utils.readCookie("modal_english") !== "accepted"
  ) {
    openPopUpModal($modalEnglish);

    var expiration = new Date();
    var timeCurrent = expiration.getTime();
    var oneHour = timeCurrent + 3600 * 1000;

    expiration.setTime(oneHour);

    _siteNS.Utils.setCookieCustomDuration(
      "modal_english",
      "accepted",
      expiration.toUTCString()
    );
  }
  if (
    url.indexOf("index-fr") > -1 &&
    _siteNS.Utils.readCookie("modal_french") !== "accepted"
  ) {
    openPopUpModal($modalPopUpFrench);

    var expiration = new Date();
    var timeCurrent = expiration.getTime();
    var oneHour = timeCurrent + 3600 * 1000;

    expiration.setTime(oneHour);

    _siteNS.Utils.setCookieCustomDuration(
      "modal_french",
      "accepted",
      expiration.toUTCString()
    );
  }
}, 4000);
</code>```

答:
It should work if you adjust your first if clause like this:

```<code> if (
    url.indexOf("index") > -1 &&
    url.indexOf("index-fr") == -1 &&
    !disableWelcomeModal &&
    _siteNS.Utils.readCookie("modal_english") !== "accepted"
 )
</code>```

Title: Display modal based on page / url

Body:
I'm working on a site that has TWO home pages (different langauges). Each homepage displays a pop up modal in the homepage language when the user gets to the site. As of now it's working when the user first goes to the "English" page and THEN goes to the "French" page but if the user is first sent to the French page BOTH modals are showing. How can I assure only the given language modal will show on each page? I am using Jquery to achieve this.

URL's / page: index.html - English, index-fr.html - French

JQuery:

  window.setTimeout(function () {
  var url = location.pathname;

  if (
    url.indexOf("index") > -1 &&
    !disableWelcomeModal &&
    _siteNS.Utils.readCookie("modal_english") !== "accepted"
  ) {
    openPopUpModal($modalEnglish);

    var expiration = new Date();
    var timeCurrent = expiration.getTime();
    var oneHour = timeCurrent + 3600 * 1000;

    expiration.setTime(oneHour);

    _siteNS.Utils.setCookieCustomDuration(
      "modal_english",
      "accepted",
      expiration.toUTCString()
    );
  }
  if (
    url.indexOf("index-fr") > -1 &&
    _siteNS.Utils.readCookie("modal_french") !== "accepted"
  ) {
    openPopUpModal($modalPopUpFrench);

    var expiration = new Date();
    var timeCurrent = expiration.getTime();
    var oneHour = timeCurrent + 3600 * 1000;

    expiration.setTime(oneHour);

    _siteNS.Utils.setCookieCustomDuration(
      "modal_french",
      "accepted",
      expiration.toUTCString()
    );
  }
}, 4000);

Body:
It should work if you adjust your first if clause like this:

 if (
    url.indexOf("index") > -1 &&
    url.indexOf("index-fr") == -1 &&
    !disableWelcomeModal &&
    _siteNS.Utils.readCookie("modal_english") !== "accepted"
 )


问:
Upgrading from .NET 1.1 to .NET 2.0, what to expect?
I'm working on a big .NET 1.1 project, and there exists a wish to upgrade this, majorily to be able to use better tools like Visual Studio 2008, but also because of the new features and smaller amount of bugs in the .NET 2.0 framework.

The project consist for the bigger part of VB.NET, but there are also parts in C#. It is a Windows Forms application, using various third party controls. Using .NET remoting the rich client talks to a server process which interfaces with a MSSQL 2000 database.

What kind of issues can we expect in case we decide to perform the upgrade?

答:
There is a change to the theading model in .Net 2.0 onwards where unhandled exceptions in a thread will cause the whole app to terminate. I ran into this when updating an app that did lots of threading and occasionally crashed. Obviously the .Net 2.0 model is more robust as you should certainly be catching these anyway, but it was the only really issue I came across when making the migration.

This article talks all about it:
http://odetocode.com/blogs/scott/archive/2005/12/14/2618.aspx

OwnerDisplayName: Tobi

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: swilliams

OwnerDisplayName: MikeeMike


问:
Compare complex object and get difference C# .NET Core 3.1
I have two object of the class Profile and I want to compare it to get the difference. To explain better:

```<code>    public partial class Profile
    {
        public long Id { get; set; }
        public long VisitorId { get; set; }
        public string Description { get; set; }
        public long Age { get; set; }
        public DateTime? LastUpdate { get; set;}
    }
</code>```

I want to know in my method the differences between the object oldProfile and newProfile to make a changelog.

For example, if oldProfile had Age = 10 and Description = "old" and newProfile has Age = 11 and Description = "new", I would now this differences to make two different insert in my database:

```<code>public void PostChangelogProfileDetail(Profile oldProfile, Profile newProfile)
{
    ProfileDetailChangeLog profileDetailChangeLog = new ProfileDetailChangeLog();

    //COMPARE oldProfile AND newProfile

    foreach ( //difference resulted in the compare)
    {
        profileDetailChangeLog.VisitorId = newProfile.VisitorId;
        profileDetailChangeLog.ModifiedRecord = //name of the attribute modified (Age, Description, etc...)

        _profileDetailChangeLog.Create(profileDetailChangeLog);
    }
}
</code>```

答:
When you call Add or Update ef core returns EntityEntry.
From which EntityEntry you can get the current and old values via the OriginalValues(returns the old values) and the CurrentValues(returns the new values) properties.

From where you can compare and log the differences from the original and the current values via Reflection to see the type/name of the property and the value as their return type is PropertyValues .

Body:
I have two object of the class Profile and I want to compare it to get the difference. To explain better:

    public partial class Profile
    {
        public long Id { get; set; }
        public long VisitorId { get; set; }
        public string Description { get; set; }
        public long Age { get; set; }
        public DateTime? LastUpdate { get; set;}
    }

I want to know in my method the differences between the object oldProfile and newProfile to make a changelog.

For example, if oldProfile had Age = 10 and Description = "old" and newProfile has Age = 11 and Description = "new", I would now this differences to make two different insert in my database:

public void PostChangelogProfileDetail(Profile oldProfile, Profile newProfile)
{
    ProfileDetailChangeLog profileDetailChangeLog = new ProfileDetailChangeLog();

    //COMPARE oldProfile AND newProfile

    foreach ( //difference resulted in the compare)
    {
        profileDetailChangeLog.VisitorId = newProfile.VisitorId;
        profileDetailChangeLog.ModifiedRecord = //name of the attribute modified (Age, Description, etc...)

        _profileDetailChangeLog.Create(profileDetailChangeLog);
    }
}


问:
Need help retargeting .NET application
I am trying to get vscode to enable c# code completion with unity, as this guide shows. I had a problem earlier that for some reason the .NET targeting pack was installed but the SDK was not, which someone was able to help me with. However, I am still getting errors that say the reference assemblies cannot be found. I have re-installed the developer pack, the .NET SDK and targeting pack, restarted my computer, and uninstalled/ reinstalled extensions. The logs say I might have to retarget the application but that is very vague and I cannot find any guides on how to do that. Thanks for your help.

EDIT: I have tried changing the target framework to 4.8, but omnisharp has the same error log with a different version that I also installed. Could this be a problem with having multiple drives?

.csproj target framework:

v4.7.1

Omnisharp error log:

Starting OmniSharp server at 5/31/2020, 7:56:50 PM
      Target: a:\Github\Unity\2_Terminal_Hacker\2_Terminal_Hacker.sln

OmniSharp server started.
      Path: c:\Users\0dps1.vscode\extensions\ms-dotnettools.csharp-1.22.0.omnisharp\1.35.2\OmniSharp.exe
      PID: 5544

[info]: OmniSharp.Stdio.Host
          Starting OmniSharp on Windows 6.2.9200.0 (x64) [info]: OmniSharp.Services.DotNetCliService
          DotNetPath set to dotnet [info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
          Located 2 MSBuild instance(s)
              1: Visual Studio Community 2019 16.6.30114.105 - "A:\Program Files\Microsoft Visual
  Studio\2019\Community\MSBuild\Current\Bin"
              2: StandAlone 16.4 - "c:\Users\0dps1.vscode\extensions\ms-dotnettools.csharp-1.22.0.omnisharp\1.35.2.msbuild\Current\Bin"
  [info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
          Registered MSBuild instance: Visual Studio Community 2019 16.6.30114.105 - "A:\Program Files\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin" [info]:
  OmniSharp.Cake.CakeProjectSystem
          Detecting Cake files in 'a:\Github\Unity\2_Terminal_Hacker'. [info]: OmniSharp.Cake.CakeProjectSystem
          Could not find any Cake files [info]: OmniSharp.MSBuild.ProjectSystem
          Detecting projects in 'a:\Github\Unity\2_Terminal_Hacker\2_Terminal_Hacker.sln'. [info]:
  OmniSharp.MSBuild.ProjectManager
          Queue project update for 'a:\Github\Unity\2_Terminal_Hacker\Assembly-CSharp.csproj' [info]:
  OmniSharp.Script.ScriptProjectSystem
          Detecting CSX files in 'a:\Github\Unity\2_Terminal_Hacker'. [info]: OmniSharp.Script.ScriptProjectSystem
          Could not find any CSX files [info]: OmniSharp.WorkspaceInitializer
          Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.CSharpFormattingWorkspaceOptionsProvider,
  Order: 0 [info]: OmniSharp.MSBuild.ProjectManager
          Loading project: a:\Github\Unity\2_Terminal_Hacker\Assembly-CSharp.csproj [info]:
  OmniSharp.WorkspaceInitializer
          Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.RenameWorkspaceOptionsProvider,
  Order: 100 [info]: OmniSharp.WorkspaceInitializer
          Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.ImplementTypeWorkspaceOptionsProvider,
  Order: 110 [info]: OmniSharp.WorkspaceInitializer
          Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.BlockStructureWorkspaceOptionsProvider,
  Order: 140 [info]: OmniSharp.WorkspaceInitializer
          Configuration finished. [info]: OmniSharp.Stdio.Host
          Omnisharp server running using Stdio at location 'a:\Github\Unity\2_Terminal_Hacker' on host 4260. [fail]:
  OmniSharp.MSBuild.ProjectLoader
          The reference assemblies for .NETFramework,Version=v4.7.1 were not found. To resolve this, install the Developer Pack (SDK/Targeting
  Pack) for this framework version or retarget your application. You can
  download .NET Framework Developer Packs at
  https://aka.ms/msbuild/developerpacks [warn]:
  OmniSharp.MSBuild.ProjectManager
          Failed to load project file 'a:\Github\Unity\2_Terminal_Hacker\Assembly-CSharp.csproj'.
  a:\Github\Unity\2_Terminal_Hacker\Assembly-CSharp.csproj A:\Program
  Files\Microsoft Visual
  Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(1177,5):
  Error: The reference assemblies for .NETFramework,Version=v4.7.1 were
  not found. To resolve this, install the Developer Pack (SDK/Targeting
  Pack) for this framework version or retarget your application. You can
  download .NET Framework Developer Packs at
  https://aka.ms/msbuild/developerpacks

[fail]: OmniSharp.MSBuild.ProjectManager
          Attempted to update project that is not loaded: a:\Github\Unity\2_Terminal_Hacker\Assembly-CSharp.csproj

答:
https://learn.microsoft.com/en-us/dotnet/standard/frameworks

If you open .csproj files  you will see "TargetFramework" tag, and inside it, one of the possible values from the link. "Retarget" means changing "Target Framework" value from "net471" to, say, "net46".

Unfortunately, since this is Unity project, Unity likes to have full control of the content of the csproj files, and any changes you make will be only temporary. So you may retarget to something and make the error go away, but Unity will revert this to "net471" on its whim later.

Your options are:

Fix .net sdk /vscode installation so you get the targetting pack. You may try to open the solution in VS community and maybe it will offer a fix from the UI

Unity has an inbuilt dropdown in player settings to target net2 or something like that instead of net471, but thats a really ancient version of c#/net. It might have been completely deprecated recently.

Do hacks to inject yourself in unity csproj generation so it always use some version you have (not recommended)

EDIT - yes, it's actually very possible it's multiple drive issue. I see from your logs that Visual Studio Community is installed on A:\drive. Reference assemblies are usually found in "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework". So it's very likely that where MSBuild.exe is looking for those and where the targetting pack is actually installed are mismatched.

Don't really have any idea how to fix this other than trying to install VS in default location on C:\ - probably there are some magic environment variables that can be set to trigger MSBuild to look in the right place.

Title: Need help retargeting .NET application


问:
Why does the MessagePack error extension (0x03) have top-level MP_MAP?
In Tarantool 2.4.1, a new MessagePack extension was introduced to serialize errors. At the very top level of the extension body there is a map with only one element, an error stack (an array consisting of error maps). I wonder if this top-level map can contain more than one element, and if not, why it is needed at all? Why not just have an error stack as the extension body?</p>

答:
Short answer.

Currently (in 2.4.1) it contains only one field, IPROTO_ERROR_STACK (0). But in future more fields may be added to this map. The format of MP_MAP with a single key is chosen for better extendibility. All connectors should be able to parse IPROTO_ERROR_STACK key, and skip any other key. So even if in future Tarantool versions new fields are added to the map, the old connectors still would be able to parse responses.

Long answer.

In Tarantool most of the responses of the binary protocol (IProto) have form of a MessagePack map: MP_MAP. Even if there is just 1 or 2 fields in this map, it is still MP_MAP, not an MP_ARRAY, and of course not just a non-formatted byte array.

Some such responses exist for many years. There appear lots of connectors to Tarantool, which are able to send/receive and parse responses from Tarantool in IProto protocol.

And when it becomes necessary to change something in these responses after all the years of exploitation with all the created software to handle the responses, the MP_MAP comes in hand. With MP_MAP it is easy to add new fields into the response not breaking all the old connectors. Assuming that they are ready that some new unknown keys may be received, and they just skip them.

This is why MP_MAP is used in Tarantool a lot as a top level of response type. It is easy to extend and not break old code. Error MessagePack format, with IPROTO_ERROR_STACK, is MP_MAP by the same reason. In future there may be added more keys to the error object.


问:
Ways round the \r function
Whenever I'm coding, I find I need to use \r quite often. And for some reason, it's ignored entirely. I'm working with Mac OS Catalina at the moment. If anyone has solutions for code where instead of using \r I can use something else which is compatible with my device. (I will be moving to Windows 10 very soon)
Some examples may be I wish to delete a printed line and replace it with something else.
The output might be something like this:

```<code>Hello
how are you?
</code>```

The output I aim for is:
Hello, **wait one second**
And after the one second:
how are you?
simply replaces the Hello because the carriage return was used.

But the code I used had a \r in it. It's totally ignored. I also had this issue when I used a single-iterating for i in range() string which contained '(Hello'+'\r') or even using print or sys.stdout.write which contained (Hello, end='\r'). None of these worked. Then I removed the \r and found it had the same results. Why is \r ignored and is there a way to clear a line of print without using \r?

答:
This code bellow works fine for me, can you try it too?

print('Hello!', end='\r')
print('How Are you?')
```

<p>About the <code>for i in range()</code>, if you are trying something like that</p>

<pre class="lang-py prettyprint-override"><code>for i in range(10):
    print('Hello'+'\r')
</code>```

this doesn't work because print() function by default ends to an \n so the string will look like Hello\r\n so what you need to do is to prevent that by adding the keyword argument end='' so it will look like

for i in range(10):
    print('Hello'+'\r', end='')
```

<p>or better</p>

<pre class="lang-py prettyprint-override"><code>for i in range(10):
    print('Hello', end='\r')
</code>```

but this will look like it doesn't print nothing, that's because we need to add a newline after the iteration because the terminal prompt is gonna "sit" on top of the Hello because it ended with the \r, so the code would look like:

for i in range(10):
    print('Hello', end='\r')
else:
    print()
```

EDIT: BTW \r doesn't delete the line, it places the cursor at the start of the line. Wiki

Hope that makes sense and helps!

~ PanTrakX

Title: Ways round the \r function

Body:
Whenever I'm coding, I find I need to use \r quite often. And for some reason, it's ignored entirely. I'm working with Mac OS Catalina at the moment. If anyone has solutions for code where instead of using \r I can use something else which is compatible with my device. (I will be moving to Windows 10 very soon)
Some examples may be I wish to delete a printed line and replace it with something else.
The output might be something like this:

Hello
how are you?

The output I aim for is:
Hello, **wait one second**
And after the one second:
how are you?
simply replaces the Hello because the carriage return was used.

But the code I used had a \r in it. It's totally ignored. I also had this issue when I used a single-iterating for i in range() string which contained '(Hello'+'\r') or even using print or sys.stdout.write which contained (Hello, end='\r'). None of these worked. Then I removed the \r and found it had the same results. Why is \r ignored and is there a way to clear a line of print without using \r?

Body:
This code bellow works fine for me, can you try it too?

print('Hello!', end='\r')
print('How Are you?')

About the for i in range(), if you are trying something like that

for i in range(10):
    print('Hello'+'\r')

this doesn't work because print() function by default ends to an \n so the string will look like Hello\r\n so what you need to do is to prevent that by adding the keyword argument end='' so it will look like

for i in range(10):
    print('Hello'+'\r', end='')

or better

for i in range(10):
    print('Hello', end='\r')

but this will look like it doesn't print nothing, that's because we need to add a newline after the iteration because the terminal prompt is gonna "sit" on top of the Hello because it ended with the \r, so the code would look like:

for i in range(10):
    print('Hello', end='\r')
else:
    print()

EDIT: BTW \r doesn't delete the line, it places the cursor at the start of the line. Wiki

Hope that makes sense and helps!

~ PanTrakX


问:
How to store the address of the variable without pointer
how can we store the address of the variable without using the pointer?</p>

```<code>#include<stdio.h>
int main ()
{
    double sum;
    double x= ∑

    printf("\n %lf",x);
}
</code>```

答:
By definition, a pointer is an object that stores the address of another.  How can you store something without using the appropiate storage variable for that kind of data? There are no other objects to store addresses, so what do you suggest?

If you just want to print the address to stdout, just do the following:

```<code>    printf("%p\n", &sum);
</code>```

The format specifier %p allows you to pass a pointer, and you can use &sum directly to pass the value of the address of sum.

Body:
how can we store the address of the variable without using the pointer?

#include<stdio.h>
int main ()
{
    double sum;
    double x= ∑

    printf("\n %lf",x);
}

Body:
By definition, a pointer is an object that stores the address of another.  How can you store something without using the appropiate storage variable for that kind of data? There are no other objects to store addresses, so what do you suggest?

If you just want to print the address to stdout, just do the following:

    printf("%p\n", &sum);

The format specifier %p allows you to pass a pointer, and you can use &sum directly to pass the value of the address of sum.


问:
CoreLocation - Continuous location update in background with authorizedWhenInUse authorization
I need to track the user location in background, like the navigation feature in waze and apple maps.

However, I want to use it with authorizedWhenInUse  permission.

As I understand, application can keep track of user location even with authorizedWhenInUse permission, as in this state, application considered foreground (Blue line appears on top of the status bar - means that the user knows that the application doing location work)

It all works fine when I grant authorizedAlways permission.

However, when the permission is authorizedWhenInUse, and I send the application to background, the blue line appears, but application gets terminated after about one minute, and the following message appears in the log:

Message from debugger: Terminated due to signal 9

Here is how I track location updates before going to background:

```<code>locationManager.allowsBackgroundLocationUpdates = true
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.delegate = self
locationManager.startUpdatingLocation()
</code>```

And my plist contains the background mode:

```<code><key>UIBackgroundModes</key>
<array>
    <string>location</string>
</array>
</code>```

答: This probably has nothing to do with Core Location. Signal 9 indicates you’ve been killed for using too much memory or similar. You probably need to release resources before going into the background. Or you may be trying to do other things in the background that you have not told us about. </p>

Body:
I need to track the user location in background, like the navigation feature in waze and apple maps.

However, I want to use it with authorizedWhenInUse  permission.

As I understand, application can keep track of user location even with authorizedWhenInUse permission, as in this state, application considered foreground (Blue line appears on top of the status bar - means that the user knows that the application doing location work)

It all works fine when I grant authorizedAlways permission.

However, when the permission is authorizedWhenInUse, and I send the application to background, the blue line appears, but application gets terminated after about one minute, and the following message appears in the log:

Message from debugger: Terminated due to signal 9

Here is how I track location updates before going to background:

locationManager.allowsBackgroundLocationUpdates = true
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.delegate = self
locationManager.startUpdatingLocation()

And my plist contains the background mode:

<key>UIBackgroundModes</key>
<array>
    <string>location</string>
</array>


问:
j2me to get cellid,mcc,mnc,lcc for fetching lon lat
I want to get the cellid,mcc,mnc,lac data of mobile for any device like nokia,motorola,samsung
 i had google it and able to found it for sony..But cant able to find it for samsung ,nokia,motorola.

For sony erricson device i had used the below:-

```<code>    String cellid = System.getProperty("com.sonyericsson.net.cellid");
    String mcc = System.getProperty("com.sonyericsson.net.cmcc");
    String mnc = System.getProperty("com.sonyericsson.net.cmnc");
    String lac = System.getProperty("com.sonyericsson.net.lac");
</code>```

please help me

答:
See this article, How to get CellId and other Imformation from mobile phones via J2ME.

Also read this wiki article.

Body:
I want to get the cellid,mcc,mnc,lac data of mobile for any device like nokia,motorola,samsung
 i had google it and able to found it for sony..But cant able to find it for samsung ,nokia,motorola.

For sony erricson device i had used the below:-

    String cellid = System.getProperty("com.sonyericsson.net.cellid");
    String mcc = System.getProperty("com.sonyericsson.net.cmcc");
    String mnc = System.getProperty("com.sonyericsson.net.cmnc");
    String lac = System.getProperty("com.sonyericsson.net.lac");

please help me


问:
Generating SSH key in git bash, i can't get git agent
When I am trying to generate SSH key in git bash, I can't get git agent when we run this command

```<code>eval $(ssh-agent -s)
</code>```

then I will get this error

```<code>unix_listener: cannot listen on path /tmp/ssh-xoEnzGUu8XxU/agent.1287: Permission denied
</code>```

How can I resolve this?

答:
As seen here, that could be a permission issue for writing the SSH socket.

Check the permission associated to /tmp or /tmp/ssh-xoEnzGUu8XxU/agent.1287

Or try:

```<code>eval $(ssh-agent -a ~/.ssh-agent.$$)
</code>```

The socket will be written in your $HOME instead of /tmp: no more permission issue.

Body:
When I am trying to generate SSH key in git bash, I can't get git agent when we run this command

eval $(ssh-agent -s)

then I will get this error

unix_listener: cannot listen on path /tmp/ssh-xoEnzGUu8XxU/agent.1287: Permission denied

How can I resolve this?

Body:
As seen here, that could be a permission issue for writing the SSH socket.

Check the permission associated to /tmp or /tmp/ssh-xoEnzGUu8XxU/agent.1287

Or try:

eval $(ssh-agent -a ~/.ssh-agent.$$)

The socket will be written in your $HOME instead of /tmp: no more permission issue.


问:
Filter array by dict values and keep only unique values
How can I filter this array by the key value "name"

```<code>arr = [
  {name: "A", val: 1},
  {name: "B", val: 4},
  {name: "C", val: 5},
  {name: "A", val: 2},
  {name: "C", val: 3},
]
</code>```

So that the output looks like this:

```<code>newArr = [
  {name: "A", val: 1},
  {name: "B", val: 4},
  {name: "C", val: 5},
]
</code>```

答:
In ES6, you can make use of Set:

var array =[ {name: "A", val: 1}, {name: "B", val: 4}, {name: "C", val: 5}, {name: "A", val: 2}, {name: "C", val: 3},];

var filter = array.filter((s=>({name})=>!s.has(name) && s.add(name))(new Set));

console.log(filter);```

Body:
How can I filter this array by the key value "name"

arr = [
  {name: "A", val: 1},
  {name: "B", val: 4},
  {name: "C", val: 5},
  {name: "A", val: 2},
  {name: "C", val: 3},
]

So that the output looks like this:

newArr = [
  {name: "A", val: 1},
  {name: "B", val: 4},
  {name: "C", val: 5},
]


问:
Fast check of first inequality
I am looking for a function similar to match, but it should have an inequality as test and stop at the first occurrence.

```<code>a <- c(1,3,5,7,9,12)
b <- 6
# the output should be 4
# i tried this one:  match(min(a [b <= a ]),a ), but with much data it is slow
</code>```

Title: Fast check of first inequality

Body:
I am looking for a function similar to match, but it should have an inequality as test and stop at the first occurrence.

a <- c(1,3,5,7,9,12)
b <- 6
# the output should be 4
# i tried this one:  match(min(a [b <= a ]),a ), but with much data it is slow

Body:
Probably this is was fastest. @Gregor found a faster one.

which(b <= a)[1]
# [1] 4

Benchmark

set.seed(42)
a <- sort(sample(1:100, 1e6, replace=T))
b <- 6

microbenchmark::microbenchmark(match(min(a[b <= a ]), a),
                               min(which(a >= b)),
                               which(b <= a)[1],
                               match(TRUE, b <= a))

Unit: milliseconds
                    expr       min        lq      mean    median        uq       max neval cld
match(min(a[b <= a]), a) 14.273060 14.770065 27.228264 26.043620 29.675095 273.45221   100   b
      min(which(a >= b))  9.537230  9.781012 13.306348 10.207344 10.445258  27.28422   100  a
        which(b <= a)[1]  8.192664  8.475993 14.774976  8.869157 19.935542 267.22919   100  a
     match(TRUE, b <= a)  6.045952  6.274809  9.125632  6.404545  6.845165  24.42210   100  a


问:
databinding recyclerview adapter received null list from livedata
I want to feed the recyclerview with a list of elements and livedata. I used data binding adapter and when I want to send data to adapter the list return null from livedata. the whole code are below.
thanks

I debugged the code and I saw when the data came from the AppDbHelper.java to HomeViewmodel.java and set to the live data the bindingadapter didn't change. thus, although the livedata is not null, the arraylist at databinding adapter(heartRateResultsModels) is null and made the app crashed.

1.fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="viewModel"
            type="ir.basamadazmanovin.heartrate.ui.main.home.HomeViewModel" />
    </data>

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:refreshing="@{viewModel.isLoading}">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".ui.main.home.HomeFragment">

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/fragment_home_recyclerView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:adapter="@{viewModel.heartRateResultsLiveData}"
                tools:listitem="@layout/row_fragment_home" />

        </FrameLayout>
    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</layout>
```

<p>2.BaseFragment.java</p>

<pre class="lang-java prettyprint-override"><code>public abstract class BaseFragment<T extends ViewDataBinding, V extends BaseViewModel> extends Fragment {

    protected FragmentNavigation mFragmentNavigation;
    private BaseActivity mActivity;
    private View mRootView;
    private T mViewDataBinding;
    private V mViewModel;

    public abstract int getBindingVariable();

    public abstract
    @LayoutRes
    int getLayoutId();

    public abstract V getViewModel();

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof BaseActivity) {
            BaseActivity activity = (BaseActivity) context;
            this.mActivity = activity;
            activity.onFragmentAttached();
        }
        if (context instanceof FragmentNavigation) {
            mFragmentNavigation = (FragmentNavigation) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        performDependencyInjection();
        super.onCreate(savedInstanceState);
        mViewModel = getViewModel();
        setHasOptionsMenu(false);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mViewDataBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false);
        mRootView = mViewDataBinding.getRoot();
        return mRootView;
    }

    public BaseActivity getBaseActivity() {
        return mActivity;
    }

    public T getViewDataBinding() {
        return mViewDataBinding;
    }

    public void hideKeyboard() {
        if (mActivity != null) {
            mActivity.hideKeyboard();
        }
    }

    public boolean isNetworkConnected() {
        return mActivity != null && mActivity.isNetworkConnected();
    }

    public void openActivityOnTokenExpire() {
        if (mActivity != null) {
            mActivity.openActivityOnTokenExpire();
        }
    }

    private void performDependencyInjection() {
        AndroidSupportInjection.inject(this);
    }

    public interface Callback {

        void onFragmentAttached();

        void onFragmentDetached(String tag);
    }
}
</code>```

3.HomeFragment.java

public class HomeFragment extends BaseFragment<FragmentHomeBinding,HomeViewModel> implements HomeNavigator {

    FragmentHomeBinding mFragmentHomeBinding;
    @Inject
    LinearLayoutManager mLayoutManager;
    @Inject
    HeartRateResultsAdapter mAdapter;
    @Inject
    ViewModelProviderFactory factory;

    private HomeViewModel mHomeViewModel;

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    public int getBindingVariable() {
        return BR.viewModel;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    public HomeViewModel getViewModel() {
        mHomeViewModel = ViewModelProviders.of(this, factory).get(HomeViewModel.class);
        return null;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHomeViewModel.setNavigator(this);

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mFragmentHomeBinding = getViewDataBinding();
        setUp();
    }

    private void setUp() {
        mLayoutManager.setOrientation(RecyclerView.VERTICAL);
        mFragmentHomeBinding.fragmentHomeRecyclerView.setLayoutManager(mLayoutManager);
        mFragmentHomeBinding.fragmentHomeRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mFragmentHomeBinding.fragmentHomeRecyclerView.setAdapter(mAdapter);
    }

    @Override
    public void handleError(Throwable throwable) {

    }
}

```

<p>4.BaseViewModel.java</p>

<pre class="lang-java prettyprint-override"><code>public class BaseViewModel<N> extends ViewModel {
    private final DataManager mDataManager;

    private final ObservableBoolean mIsLoading = new ObservableBoolean(false);

    private final SchedulerProvider mSchedulerProvider;

    private CompositeDisposable mCompositeDisposable;

    private WeakReference<N> mNavigator;

    public BaseViewModel(DataManager dataManager,
                         SchedulerProvider schedulerProvider) {
        this.mDataManager = dataManager;
        this.mSchedulerProvider = schedulerProvider;
        this.mCompositeDisposable = new CompositeDisposable();
    }

    @Override
    protected void onCleared() {
        mCompositeDisposable.dispose();
        super.onCleared();
    }

    public CompositeDisposable getCompositeDisposable() {
        return mCompositeDisposable;
    }

    public DataManager getDataManager() {
        return mDataManager;
    }

    public ObservableBoolean getIsLoading() {
        return mIsLoading;
    }

    public void setIsLoading(boolean isLoading) {
        mIsLoading.set(isLoading);
    }

    public N getNavigator() {
        return mNavigator.get();
    }

    public void setNavigator(N navigator) {
        this.mNavigator = new WeakReference<>(navigator);
    }

    public SchedulerProvider getSchedulerProvider() {
        return mSchedulerProvider;
    }
}

</code>```

5.HomeViewModel.java

public class HomeViewModel extends BaseViewModel<HomeNavigator> {
    private  MutableLiveData<ArrayList<HeartRateResultsModel>> heartRateResultsLiveData;

    public HomeViewModel(DataManager dataManager, SchedulerProvider schedulerProvider) {
        super(dataManager, schedulerProvider);
        heartRateResultsLiveData = new MutableLiveData<>();
        fetchRepos();
    }
    public void fetchRepos() {
        setIsLoading(true);
        getCompositeDisposable().add(getDataManager()
                .getHeartRateResults()
                .subscribeOn(getSchedulerProvider().io())
                .observeOn(getSchedulerProvider().ui())
                .subscribe(heartRateResultsModels -> {
                    heartRateResultsLiveData.setValue(heartRateResultsModels);
                    setIsLoading(false);
                }, throwable -> {
                    setIsLoading(false);
                    getNavigator().handleError(throwable);
                }));
    }

    public LiveData<ArrayList<HeartRateResultsModel>> getHeartRateResultsLiveData() {
        return heartRateResultsLiveData;
    }
}
```

<p>6.BindingUtils.java</p>

<pre class="lang-java prettyprint-override"><code>public final class BindingUtils {

    private BindingUtils() {
        // This class is not publicly instantiable
    }

    @BindingAdapter("imageUrl")
    public static void setImageUrl(ImageView imageView, String url) {
        Context context = imageView.getContext();
        Glide.with(context).load(url).into(imageView);
    }

    @BindingAdapter("onNavigationItemSelected")
    public static void setOnNavigationItemSelectedListener(
            BottomNavigationView view, OnNavigationItemSelectedListener listener) {
        view.setOnNavigationItemSelectedListener(listener);
    }

    @BindingAdapter({"adapter"})
    public static void addHeartRateResultsItems(RecyclerView recyclerView,
                                                ArrayList<HeartRateResultsModel> heartRateResultsModels) {
        HeartRateResultsAdapter adapter = (HeartRateResultsAdapter) recyclerView.getAdapter();
        if (adapter != null) {
            adapter.clearItems();
            adapter.addItems(heartRateResultsModels);
        }
    }
}
</code>```

7.DataManager.java

public interface DataManager extends DbHelper, PreferencesHelper, ApiHelper {

}
```

<p>8.DbHelper.java</p>

<pre class="lang-java prettyprint-override"><code>public interface DbHelper {
    Single<ArrayList<HeartRateResultsModel>> getHeartRateResults();

}
</code>```

9.AppDataManager.java

public class AppDataManager implements DataManager{

    private final ApiHelper mApiHelper;

    private final Context mContext;

    private final DbHelper mDbHelper;

    private final Gson mGson;

    private final PreferencesHelper mPreferencesHelper;

    @Inject
    public AppDataManager(Context context,
                          DbHelper dbHelper,
                          PreferencesHelper preferencesHelper,
                          ApiHelper apiHelper,
                          Gson gson) {
        mContext = context;
        mDbHelper = dbHelper;
        mPreferencesHelper = preferencesHelper;
        mApiHelper = apiHelper;
        mGson = gson;
    }

    @Override
    public Single<ArrayList<HeartRateResultsModel>> getHeartRateResults() {
        return mDbHelper.getHeartRateResults();
    }

}
```

<p>10.AppDbHelper.java</p>

<pre class="lang-java prettyprint-override"><code>@Singleton
public class AppDbHelper implements DbHelper{

    private final AppDatabase mAppDatabase;

    @Inject
    public AppDbHelper(AppDatabase appDatabase) {
        this.mAppDatabase = appDatabase;

    }

    @Override
    public Single<ArrayList<HeartRateResultsModel>> getHeartRateResults() {
        return Single.fromCallable(new Callable<ArrayList<HeartRateResultsModel>>() {
            @Override
            public ArrayList<HeartRateResultsModel> call() throws Exception {
                ArrayList<HeartRateResultsModel> models = new ArrayList<>();
                models.add(new HeartRateResultsModel("","1"));
                models.add(new HeartRateResultsModel("","2"));
                return models;
            }
        });
    }
}

</code>```

答:
1. Always make sure to set your XML binding variables in your UI controller(Fragment or Activity)

In your XML layout

```<code><data>
<variable
    name="viewModel"
    type="com.felixfavour.ViewModel" />
</data>
</code>```

In your UI controller (Fragment in this case)

```<code>listViewModel = ViewModel(this).get(ListViewModel::class)
bindingObj.viewModel = listViewModel
</code>```

2. It is necessary that you set the setLifecycleOwner() to the LifeCycleOwner which is inherently your UI controller, without this your LiveData will lose its Live effect as it will not be able to be observed, essentially your LiveData will not be propagated to the UI.

```<code>bindingObj.setLifeCycleOwner = this
</code>```

where this = UI Controller(again Activity/Fragment)

Body:
I want to feed the recyclerview with a list of elements and livedata. I used data binding adapter and when I want to send data to adapter the list return null from livedata. the whole code are below.
thanks

I debugged the code and I saw when the data came from the AppDbHelper.java to HomeViewmodel.java and set to the live data the bindingadapter didn't change. thus, although the livedata is not null, the arraylist at databinding adapter(heartRateResultsModels) is null and made the app crashed.

1.fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="viewModel"
            type="ir.basamadazmanovin.heartrate.ui.main.home.HomeViewModel" />
    </data>

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:refreshing="@{viewModel.isLoading}">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".ui.main.home.HomeFragment">

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/fragment_home_recyclerView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:adapter="@{viewModel.heartRateResultsLiveData}"
                tools:listitem="@layout/row_fragment_home" />

        </FrameLayout>
    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</layout>

2.BaseFragment.java

public abstract class BaseFragment<T extends ViewDataBinding, V extends BaseViewModel> extends Fragment {

    protected FragmentNavigation mFragmentNavigation;
    private BaseActivity mActivity;
    private View mRootView;
    private T mViewDataBinding;
    private V mViewModel;

    public abstract int getBindingVariable();

    public abstract
    @LayoutRes
    int getLayoutId();

    public abstract V getViewModel();

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof BaseActivity) {
            BaseActivity activity = (BaseActivity) context;
            this.mActivity = activity;
            activity.onFragmentAttached();
        }
        if (context instanceof FragmentNavigation) {
            mFragmentNavigation = (FragmentNavigation) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        performDependencyInjection();
        super.onCreate(savedInstanceState);
        mViewModel = getViewModel();
        setHasOptionsMenu(false);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mViewDataBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false);
        mRootView = mViewDataBinding.getRoot();
        return mRootView;
    }

    public BaseActivity getBaseActivity() {
        return mActivity;
    }

    public T getViewDataBinding() {
        return mViewDataBinding;
    }

    public void hideKeyboard() {
        if (mActivity != null) {
            mActivity.hideKeyboard();
        }
    }

    public boolean isNetworkConnected() {
        return mActivity != null && mActivity.isNetworkConnected();
    }

    public void openActivityOnTokenExpire() {
        if (mActivity != null) {
            mActivity.openActivityOnTokenExpire();
        }
    }

    private void performDependencyInjection() {
        AndroidSupportInjection.inject(this);
    }

    public interface Callback {

        void onFragmentAttached();

        void onFragmentDetached(String tag);
    }
}

3.HomeFragment.java

public class HomeFragment extends BaseFragment<FragmentHomeBinding,HomeViewModel> implements HomeNavigator {

    FragmentHomeBinding mFragmentHomeBinding;
    @Inject
    LinearLayoutManager mLayoutManager;
    @Inject
    HeartRateResultsAdapter mAdapter;
    @Inject
    ViewModelProviderFactory factory;

    private HomeViewModel mHomeViewModel;

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    public int getBindingVariable() {
        return BR.viewModel;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    public HomeViewModel getViewModel() {
        mHomeViewModel = ViewModelProviders.of(this, factory).get(HomeViewModel.class);
        return null;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHomeViewModel.setNavigator(this);

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mFragmentHomeBinding = getViewDataBinding();
        setUp();
    }

    private void setUp() {
        mLayoutManager.setOrientation(RecyclerView.VERTICAL);
        mFragmentHomeBinding.fragmentHomeRecyclerView.setLayoutManager(mLayoutManager);
        mFragmentHomeBinding.fragmentHomeRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mFragmentHomeBinding.fragmentHomeRecyclerView.setAdapter(mAdapter);
    }

    @Override
    public void handleError(Throwable throwable) {

    }
}

4.BaseViewModel.java

public class BaseViewModel<N> extends ViewModel {
    private final DataManager mDataManager;

    private final ObservableBoolean mIsLoading = new ObservableBoolean(false);

    private final SchedulerProvider mSchedulerProvider;

    private CompositeDisposable mCompositeDisposable;

    private WeakReference<N> mNavigator;

    public BaseViewModel(DataManager dataManager,
                         SchedulerProvider schedulerProvider) {
        this.mDataManager = dataManager;
        this.mSchedulerProvider = schedulerProvider;
        this.mCompositeDisposable = new CompositeDisposable();
    }

    @Override
    protected void onCleared() {
        mCompositeDisposable.dispose();
        super.onCleared();
    }

    public CompositeDisposable getCompositeDisposable() {
        return mCompositeDisposable;
    }

    public DataManager getDataManager() {
        return mDataManager;
    }

    public ObservableBoolean getIsLoading() {
        return mIsLoading;
    }

    public void setIsLoading(boolean isLoading) {
        mIsLoading.set(isLoading);
    }

    public N getNavigator() {
        return mNavigator.get();
    }

    public void setNavigator(N navigator) {
        this.mNavigator = new WeakReference<>(navigator);
    }

    public SchedulerProvider getSchedulerProvider() {
        return mSchedulerProvider;
    }
}

5.HomeViewModel.java

public class HomeViewModel extends BaseViewModel<HomeNavigator> {
    private  MutableLiveData<ArrayList<HeartRateResultsModel>> heartRateResultsLiveData;

    public HomeViewModel(DataManager dataManager, SchedulerProvider schedulerProvider) {
        super(dataManager, schedulerProvider);
        heartRateResultsLiveData = new MutableLiveData<>();
        fetchRepos();
    }
    public void fetchRepos() {
        setIsLoading(true);
        getCompositeDisposable().add(getDataManager()
                .getHeartRateResults()
                .subscribeOn(getSchedulerProvider().io())
                .observeOn(getSchedulerProvider().ui())
                .subscribe(heartRateResultsModels -> {
                    heartRateResultsLiveData.setValue(heartRateResultsModels);
                    setIsLoading(false);
                }, throwable -> {
                    setIsLoading(false);
                    getNavigator().handleError(throwable);
                }));
    }

    public LiveData<ArrayList<HeartRateResultsModel>> getHeartRateResultsLiveData() {
        return heartRateResultsLiveData;
    }
}

6.BindingUtils.java

public final class BindingUtils {

    private BindingUtils() {
        // This class is not publicly instantiable
    }

    @BindingAdapter("imageUrl")
    public static void setImageUrl(ImageView imageView, String url) {
        Context context = imageView.getContext();
        Glide.with(context).load(url).into(imageView);
    }

    @BindingAdapter("onNavigationItemSelected")
    public static void setOnNavigationItemSelectedListener(
            BottomNavigationView view, OnNavigationItemSelectedListener listener) {
        view.setOnNavigationItemSelectedListener(listener);
    }

    @BindingAdapter({"adapter"})
    public static void addHeartRateResultsItems(RecyclerView recyclerView,
                                                ArrayList<HeartRateResultsModel> heartRateResultsModels) {
        HeartRateResultsAdapter adapter = (HeartRateResultsAdapter) recyclerView.getAdapter();
        if (adapter != null) {
            adapter.clearItems();
            adapter.addItems(heartRateResultsModels);
        }
    }
}

7.DataManager.java

public interface DataManager extends DbHelper, PreferencesHelper, ApiHelper {

}

8.DbHelper.java

public interface DbHelper {
    Single<ArrayList<HeartRateResultsModel>> getHeartRateResults();

}

9.AppDataManager.java

public class AppDataManager implements DataManager{

    private final ApiHelper mApiHelper;

    private final Context mContext;

    private final DbHelper mDbHelper;

    private final Gson mGson;

    private final PreferencesHelper mPreferencesHelper;

    @Inject
    public AppDataManager(Context context,
                          DbHelper dbHelper,
                          PreferencesHelper preferencesHelper,
                          ApiHelper apiHelper,
                          Gson gson) {
        mContext = context;
        mDbHelper = dbHelper;
        mPreferencesHelper = preferencesHelper;
        mApiHelper = apiHelper;
        mGson = gson;
    }

    @Override
    public Single<ArrayList<HeartRateResultsModel>> getHeartRateResults() {
        return mDbHelper.getHeartRateResults();
    }

}

10.AppDbHelper.java

@Singleton
public class AppDbHelper implements DbHelper{

    private final AppDatabase mAppDatabase;

    @Inject
    public AppDbHelper(AppDatabase appDatabase) {
        this.mAppDatabase = appDatabase;

    }

    @Override
    public Single<ArrayList<HeartRateResultsModel>> getHeartRateResults() {
        return Single.fromCallable(new Callable<ArrayList<HeartRateResultsModel>>() {
            @Override
            public ArrayList<HeartRateResultsModel> call() throws Exception {
                ArrayList<HeartRateResultsModel> models = new ArrayList<>();
                models.add(new HeartRateResultsModel("","1"));
                models.add(new HeartRateResultsModel("","2"));
                return models;
            }
        });
    }
}

Body:
1. Always make sure to set your XML binding variables in your UI controller(Fragment or Activity)

In your XML layout

<data>
<variable
    name="viewModel"
    type="com.felixfavour.ViewModel" />
</data>

In your UI controller (Fragment in this case)

listViewModel = ViewModel(this).get(ListViewModel::class)
bindingObj.viewModel = listViewModel

2. It is necessary that you set the setLifecycleOwner() to the LifeCycleOwner which is inherently your UI controller, without this your LiveData will lose its Live effect as it will not be able to be observed, essentially your LiveData will not be propagated to the UI.

bindingObj.setLifeCycleOwner = this

where this = UI Controller(again Activity/Fragment)


问:
Rails 3 form_tag opens javascript in a new page instead of loading it in the current page
View:

```<code>form_tag(url_for(:controller => :matchers,
                :action => :show_matched_alarms_list),
        :remote => true,
        :method =>:get,
        :class => "matcher_ajax_form") do |f|
</code>```

Controller:

```<code>layout 'application',:except=>[:show_matched_alarms_list]
def show_matched_alarms_list
  @matcher= ...
  render :update do |page|
    page.replace('matched_alarms_list',
                 :partial => 'matchers/matched_alarms_list',
                 :locals=>{:matcher=>@matcher})
  end
end
</code>```

This is opening the Returned Javascript in a new page instead of loading it in the opened page. Does anyone know how to fix this?

I am using prototype. The form looks like this:

```<code><form accept-charset="UTF-8"
      action="/matchers/show_matched_alarms_list"
      class="matcher_ajax_form"
      data-remote="true"
      method="get">
</code>```

答:
I have fixed this.

The problem was that I submiting the form using the form.submit() method, which apparently doesn not work fine when using a remote form. I replaced it for the form.request() method and it worked as expected.

Body:
View:

form_tag(url_for(:controller => :matchers,
                :action => :show_matched_alarms_list),
        :remote => true,
        :method =>:get,
        :class => "matcher_ajax_form") do |f|

Controller:

layout 'application',:except=>[:show_matched_alarms_list]
def show_matched_alarms_list
  @matcher= ...
  render :update do |page|
    page.replace('matched_alarms_list',
                 :partial => 'matchers/matched_alarms_list',
                 :locals=>{:matcher=>@matcher})
  end
end

This is opening the Returned Javascript in a new page instead of loading it in the opened page. Does anyone know how to fix this?

I am using prototype. The form looks like this:

<form accept-charset="UTF-8"
      action="/matchers/show_matched_alarms_list"
      class="matcher_ajax_form"
      data-remote="true"
      method="get">


问:
Is there any case in which the Form's Activated event is not raised?
I don't understand why it could be that, I thought Activated should be raised when the form is shown. In fact my form has TopLevel set to false and it's added to another form. When the main form shows, it's also visible, and I can interact with its controls but I tested and saw that the Activated is not raised.

```<code>public MainForm(){
     InitializeComponent();
     Form child = new Form();
     child.Activated += (s,e) => {
        MessageBox.Show("Activated!");
     };
     child.Size = new Size(200,100);
     child.TopLevel = false;
     child.Show();
     child.Parent = this;
}
</code>```

After running the MainForm the child form is appeared inside the main one and there isn't any MessageBox displayed with the message "Activated!".

What is the additional job to do to make it raise?

答: Once the TopLevel property of Form is set to false then the form becomes a normal control, hence Activated() event will not fire.

Body:
I don't understand why it could be that, I thought Activated should be raised when the form is shown. In fact my form has TopLevel set to false and it's added to another form. When the main form shows, it's also visible, and I can interact with its controls but I tested and saw that the Activated is not raised.

public MainForm(){
     InitializeComponent();
     Form child = new Form();
     child.Activated += (s,e) => {
        MessageBox.Show("Activated!");
     };
     child.Size = new Size(200,100);
     child.TopLevel = false;
     child.Show();
     child.Parent = this;
}

After running the MainForm the child form is appeared inside the main one and there isn't any MessageBox displayed with the message "Activated!".

What is the additional job to do to make it raise?


问:
Recurrence event Google Calendar Request Failed
I am working on Google Calendar Service and I have problem with "Recurrence Event". Here is my code:

And in catch I got a error message: "Request failed". I don know why because in Interface "ICalendarEvent" I have recurrence. Here is the par of code in Interface:

I am first time working with Google provider and I can say that I am a beginner :) If someone can help me please add comment. Thank you!

答:
Problem is fixed. We must to send a timeZone too.
enter image description here</p>


问:
Promises JS: function response is not returned to main code
I'm building a code in Node which returns a response when a promise is solved (function called: multicreation.userCreation()):

```<code>const express = require("express")
const app = express()
const csv=require('csvtojson')
const multer = require("multer")
const csvfilename = `Users-${Date.now()}.csv`
const multiUserCreation = require("./modules/fbadmin")

const multicreation = new multiUserCreation()
const upload = multer({
     storage: storage,
     limits: { fileSize: 1e6}
   }).single("usersdata")

app.post("/uploadCSV",function (req, res, next) {
    upload(req,res,function(err) {
        if(err) {
            res.send(err)
        }
        else {
            const converter=csv()
            .fromFile(`./temp/${csvfilename}`)
            .then((json)=>{
                res.send(multicreation.userCreation(json))
            })
        }
    })
}
</code>```

By the other hand, the class "multiuserCreation" code is described as below:

```<code>const admin = require("firebase-admin");
require("dotenv").config();

class multiUserCreation {
  userCreation(jsonUsers) {
    if (!admin.apps.length) {
      admin.initializeApp({
        credential: admin.credential.cert(),
        databaseURL: `https://${process.env.PROJECT_ID}.firebaseio.com/`,
      });
    }
    const db = admin.firestore();

    async function insertUsers(jsonUsers) {
      let messages = [];
      const users = jsonUsers
      for (let i = 0; i < jsonUsers.length; i++) {
        const message = await admin
          .auth()
          .createUser({
            email: jsonUsers[i]["email"],
            emailVerified: false,
            password: "password",
            disabled: false,
          })
          .then(function (userRecord) {
            return {
              "User email": jsonUsers[i]["email"],
              Result: "Succesfully created",
            };
          })
          .catch(function (error) {
            return { "User email": jsonUsers[i]["email"], Result: error.code };
          });
        messages.push(message);
      }
      return messages;
    }

    const messageFinal = insertUsers(jsonUsers);
    messageFinal.then(function (result) {
      return messageFinal;
    });
  }
}

module.exports = multiUserCreation;
</code>```

Actually, despite "messages" array is fullfiled succesffuly, multiUserCreation is not returning anything to main code. Thanks for your help

答:
You need to return the promise from multicreation.userCreation
Check the change below

const admin = require("firebase-admin");
require("dotenv").config();

class multiUserCreation {
  userCreation(jsonUsers) {
    if (!admin.apps.length) {
      admin.initializeApp({
        credential: admin.credential.cert(),
        databaseURL: `https://${process.env.PROJECT_ID}.firebaseio.com/`,
      });
    }
    const db = admin.firestore();

    async function insertUsers(jsonUsers) {
      let messages = [];
      const users = jsonUsers
      for (let i = 0; i < jsonUsers.length; i++) {
        const message = await admin
          .auth()
          .createUser({
            email: jsonUsers[i]["email"],
            emailVerified: false,
            password: "password",
            disabled: false,
          })
          .then(function (userRecord) {
            return {
              "User email": jsonUsers[i]["email"],
              Result: "Succesfully created",
            };
          })
          .catch(function (error) {
            return { "User email": jsonUsers[i]["email"], Result: error.code };
          });
        messages.push(message);
      }
      return messages;
    }

    const messageFinal = insertUsers(jsonUsers);
    return messageFinal.then(function (result) {
      return messageFinal;
    });
  }
}

module.exports = multiUserCreation;
```

<p>Also, while calling the userCreation, you need to handle it in a callback</p>

```  const converter=csv()
            .fromFile(`./temp/${csvfilename}`)
            .then((json)=>{
                multicreation.userCreation(json).then(function (response) {
                   res.send(multicreation.userCreation(response))
                })
            })
```

Body:
I'm building a code in Node which returns a response when a promise is solved (function called: multicreation.userCreation()):

const express = require("express")
const app = express()
const csv=require('csvtojson')
const multer = require("multer")
const csvfilename = `Users-${Date.now()}.csv`
const multiUserCreation = require("./modules/fbadmin")

const multicreation = new multiUserCreation()
const upload = multer({
     storage: storage,
     limits: { fileSize: 1e6}
   }).single("usersdata")

app.post("/uploadCSV",function (req, res, next) {
    upload(req,res,function(err) {
        if(err) {
            res.send(err)
        }
        else {
            const converter=csv()
            .fromFile(`./temp/${csvfilename}`)
            .then((json)=>{
                res.send(multicreation.userCreation(json))
            })
        }
    })
}

By the other hand, the class "multiuserCreation" code is described as below:

const admin = require("firebase-admin");
require("dotenv").config();

class multiUserCreation {
  userCreation(jsonUsers) {
    if (!admin.apps.length) {
      admin.initializeApp({
        credential: admin.credential.cert(),
        databaseURL: `https://${process.env.PROJECT_ID}.firebaseio.com/`,
      });
    }
    const db = admin.firestore();

    async function insertUsers(jsonUsers) {
      let messages = [];
      const users = jsonUsers
      for (let i = 0; i < jsonUsers.length; i++) {
        const message = await admin
          .auth()
          .createUser({
            email: jsonUsers[i]["email"],
            emailVerified: false,
            password: "password",
            disabled: false,
          })
          .then(function (userRecord) {
            return {
              "User email": jsonUsers[i]["email"],
              Result: "Succesfully created",
            };
          })
          .catch(function (error) {
            return { "User email": jsonUsers[i]["email"], Result: error.code };
          });
        messages.push(message);
      }
      return messages;
    }

    const messageFinal = insertUsers(jsonUsers);
    messageFinal.then(function (result) {
      return messageFinal;
    });
  }
}

module.exports = multiUserCreation;

Actually, despite "messages" array is fullfiled succesffuly, multiUserCreation is not returning anything to main code. Thanks for your help

Body:
You need to return the promise from multicreation.userCreation
Check the change below

const admin = require("firebase-admin");
require("dotenv").config();

class multiUserCreation {
  userCreation(jsonUsers) {
    if (!admin.apps.length) {
      admin.initializeApp({
        credential: admin.credential.cert(),
        databaseURL: `https://${process.env.PROJECT_ID}.firebaseio.com/`,
      });
    }
    const db = admin.firestore();

    async function insertUsers(jsonUsers) {
      let messages = [];
      const users = jsonUsers
      for (let i = 0; i < jsonUsers.length; i++) {
        const message = await admin
          .auth()
          .createUser({
            email: jsonUsers[i]["email"],
            emailVerified: false,
            password: "password",
            disabled: false,
          })
          .then(function (userRecord) {
            return {
              "User email": jsonUsers[i]["email"],
              Result: "Succesfully created",
            };
          })
          .catch(function (error) {
            return { "User email": jsonUsers[i]["email"], Result: error.code };
          });
        messages.push(message);
      }
      return messages;
    }

    const messageFinal = insertUsers(jsonUsers);
    return messageFinal.then(function (result) {
      return messageFinal;
    });
  }
}

module.exports = multiUserCreation;

Also, while calling the userCreation, you need to handle it in a callback

  const converter=csv()
            .fromFile(`./temp/${csvfilename}`)
            .then((json)=>{
                multicreation.userCreation(json).then(function (response) {
                   res.send(multicreation.userCreation(response))
                })
            })


问:
Send file URL and args to (running) macOS app via command line
I've been trying to create a way to tell my (running) macOS app to open some files and supply some additional arguments to the command.

For cold-start apps, using the

```<code>$ open MyApp.app fileA.txt --args --foo-arg
</code>```

would launch the app and I would be able to inspect the --foo-arg via UserDefaults/CommandLine/ProcessInfo. However, if the app is already running, the --foo-arg is missing from UserDefaults/ProcessInfo/CommandLine.

I've been struggling to wrap my head around a solution here because I have a few requirements which make things a tad more difficult.

Requirements

File paths sent to app must be opened/saved with sandbox permissions

Arguments and file paths must be intercepted by app at the same time.

Potential Solutions

XPC

Some people have suggested I use XPC but after reading about it, I'm not sure how that solution might look?

Do I have to create a Launch Agent app-companion which is always running so that it can detect command line operations and pass it to my app?

How does this work with sandboxing because each process has their own permission entitlements?

Apple Script

Should I use Apple script to tell my app to open these files with arguments, thus getting around the sandboxing feature?

When opening files via AppleScript, can I save those files swell?

URL Scheme

I can register my app to have its own URL scheme but the way NSApplicationDelegate handles the incoming URLs comes in two batches. First, the URLs it can open, followed by the URL schemes or the file paths it can't open. ie:

```<code>open -a MyApp.app myapp:foo; open -a MyApp.app file.txt
</code>```

I can probably make this work but it's a tad tacky and I really want to do this the right way.

答:
A command-line tool which ingests its arguments and turns them in to Apple Events is the way to go. You can see how this works from the user's point of view by installing the BBEdit command-line tools and then running man bbedit or man bbdiff in a Terminal window.

From your command-line tool's point of view, the "interesting" parts are:

Figure out whether the application is running: +[NSRunningApplication runningApplicationsWithBundleIdentifier:] will help with that.

If the application is not running, then use -[NSWorkspaceURLForApplicationWithBundleIdentifier:] to first locate the application by bundle ID, then -[NSWorkspace launchApplicationAtURL:options:configuration:error:] to launch the application. This will return an NSRunningApplication instance, or NIL and an error. (Make sure to handle the error case.)

Using the NSRunningApplication instance obtained from either step 1 or step 2, you can now use either the NSAppleEventDescriptor APIs or the low-level AppleEvent C APIs to construct an event. (The higher-level API is probably easier to use.)

That would go something like this:

Construct a target descriptor using the processIdentifier from your running application:

```<code>targetDesc = [NSAppleEventDescriptor descriptorWithProcessIdentifier: myRunningApplication.processIdentifier;
</code>```

Construct an "open documents" event, addressed to your target application:

```<code>event = [NSAppleEventDescriptor appleEventWithEventClass: kCoreEventClass eventID: kAEOpenDocuments targetDescriptor: targetDesc returnID: kAutoGenerateReturnID transactionID: kAnyTransactionID];
</code>```

Note: I use kCoreEventClass/kAEOpenDocuments as an example - if you're trying to open one or more files with additional information, that's fine. If you're doing some other work, then you should invent a four-character code for an event class which is specific to your application, and a four-character event ID which is unique to the operation you're requesting.

Add the command arguments to the event. For each argument, this consists of creating an appropriate descriptor based on the argument's intrinsic type (boolean, int, string, file URL), and then adding it to the event using a keyword parameter.

(An Apple Event "keyword" is a four-character code. You can invent your own, with constraints (don't use all-lowercase, and you can use ones defined in AEDataModel.h or AERegistry.h where they fit with your needs).

For each descriptor you create, add it to the event using -[setParamDescriptor: forKeyword:]:

```<code>myURLParamDesc = [NSAppleEventDescriptor descriptorWithFileURL: myFileURL];
[event setParamDescriptor: myURLParamDesc forKey: kMyFileParamKeyword];
</code>```

When you've added all of the parameters to the event, send it:

```<code>[event sendWithOptions: kAENoReply timeout: FLOAT_MAX error: &error];
</code>```

On the application side, you'll need to use -[NSAppleEventManager setEventHandler: andSelector: forEventClass: andID:]. This will get called for your custom event class and ID that you invented above, at which point you can use the descriptor APIs to pull the event apart and run your operation.

Sandboxing takes care of itself: your application automatically gets a sandboxing extension for files that it's been passed via Apple Events.

Your command-line tool is not sandboxed -- it can't be, because it's run from Terminal and (potentially) other nonsandboxed apps.

However, the tool must be signed with the hardened runtime, and with com.apple.security.automation.apple-events = YES and a com.apple.security.temporary-exception.apple-events naming your application's bundle identifier, so that the tool can send Apple Events to your application.

(And the tool will need an Info.plist with an NSAppleEventsUsageDescription string.)

I've left a fair amount as an exercise for the reader; but hopefully this will get you started.

Body:
I've been trying to create a way to tell my (running) macOS app to open some files and supply some additional arguments to the command.

For cold-start apps, using the

$ open MyApp.app fileA.txt --args --foo-arg

would launch the app and I would be able to inspect the --foo-arg via UserDefaults/CommandLine/ProcessInfo. However, if the app is already running, the --foo-arg is missing from UserDefaults/ProcessInfo/CommandLine.

I've been struggling to wrap my head around a solution here because I have a few requirements which make things a tad more difficult.

Requirements

File paths sent to app must be opened/saved with sandbox permissions

Arguments and file paths must be intercepted by app at the same time.

Potential Solutions

XPC

Some people have suggested I use XPC but after reading about it, I'm not sure how that solution might look?

Do I have to create a Launch Agent app-companion which is always running so that it can detect command line operations and pass it to my app?

How does this work with sandboxing because each process has their own permission entitlements?

Apple Script

Should I use Apple script to tell my app to open these files with arguments, thus getting around the sandboxing feature?

When opening files via AppleScript, can I save those files swell?

URL Scheme

I can register my app to have its own URL scheme but the way NSApplicationDelegate handles the incoming URLs comes in two batches. First, the URLs it can open, followed by the URL schemes or the file paths it can't open. ie:

open -a MyApp.app myapp:foo; open -a MyApp.app file.txt

I can probably make this work but it's a tad tacky and I really want to do this the right way.

Body:
A command-line tool which ingests its arguments and turns them in to Apple Events is the way to go. You can see how this works from the user's point of view by installing the BBEdit command-line tools and then running man bbedit or man bbdiff in a Terminal window.

From your command-line tool's point of view, the "interesting" parts are:

Figure out whether the application is running: +[NSRunningApplication runningApplicationsWithBundleIdentifier:] will help with that.

If the application is not running, then use -[NSWorkspaceURLForApplicationWithBundleIdentifier:] to first locate the application by bundle ID, then -[NSWorkspace launchApplicationAtURL:options:configuration:error:] to launch the application. This will return an NSRunningApplication instance, or NIL and an error. (Make sure to handle the error case.)

Using the NSRunningApplication instance obtained from either step 1 or step 2, you can now use either the NSAppleEventDescriptor APIs or the low-level AppleEvent C APIs to construct an event. (The higher-level API is probably easier to use.)

That would go something like this:

Construct a target descriptor using the processIdentifier from your running application:

targetDesc = [NSAppleEventDescriptor descriptorWithProcessIdentifier: myRunningApplication.processIdentifier;

Construct an "open documents" event, addressed to your target application:

event = [NSAppleEventDescriptor appleEventWithEventClass: kCoreEventClass eventID: kAEOpenDocuments targetDescriptor: targetDesc returnID: kAutoGenerateReturnID transactionID: kAnyTransactionID];

Note: I use kCoreEventClass/kAEOpenDocuments as an example - if you're trying to open one or more files with additional information, that's fine. If you're doing some other work, then you should invent a four-character code for an event class which is specific to your application, and a four-character event ID which is unique to the operation you're requesting.

Add the command arguments to the event. For each argument, this consists of creating an appropriate descriptor based on the argument's intrinsic type (boolean, int, string, file URL), and then adding it to the event using a keyword parameter.

(An Apple Event "keyword" is a four-character code. You can invent your own, with constraints (don't use all-lowercase, and you can use ones defined in AEDataModel.h or AERegistry.h where they fit with your needs).

For each descriptor you create, add it to the event using -[setParamDescriptor: forKeyword:]:

myURLParamDesc = [NSAppleEventDescriptor descriptorWithFileURL: myFileURL];
[event setParamDescriptor: myURLParamDesc forKey: kMyFileParamKeyword];

When you've added all of the parameters to the event, send it:

[event sendWithOptions: kAENoReply timeout: FLOAT_MAX error: &error];

On the application side, you'll need to use -[NSAppleEventManager setEventHandler: andSelector: forEventClass: andID:]. This will get called for your custom event class and ID that you invented above, at which point you can use the descriptor APIs to pull the event apart and run your operation.

Sandboxing takes care of itself: your application automatically gets a sandboxing extension for files that it's been passed via Apple Events.

Your command-line tool is not sandboxed -- it can't be, because it's run from Terminal and (potentially) other nonsandboxed apps.

However, the tool must be signed with the hardened runtime, and with com.apple.security.automation.apple-events = YES and a com.apple.security.temporary-exception.apple-events naming your application's bundle identifier, so that the tool can send Apple Events to your application.

(And the tool will need an Info.plist with an NSAppleEventsUsageDescription string.)

I've left a fair amount as an exercise for the reader; but hopefully this will get you started.


问:
Having trouble splitting a dataframe into fixed chunks (per row)
I've read several topics on this site about splitting a pandas dataframe into fixed size chunks, but I'm having a problem that I didn't see adressed here. So here's the process: I ask user for inputs as to how many chunks he wishes to have, then ask for the percentage of the dataframe to allocate per chunk, I verify that the percentages given do not go above 1, then proceed to split accordingly. The following is the last part, the one I'm struggling with:

```<code>def dataframe_splitting(df:pd.DataFrame, fracs:list):
    split_frac = []
    print('Size of the dataframe:', df.shape)
    print('fracs:', fracs)
    for i in fracs:
        x = int(i*len(df))
        split_frac.append(x)
    print('split_frac:', split_frac)
    chunks = np.array_split(df, split_frac)
    for x in chunks:
        print(x.shape)
    return chunks
</code>```

And here is the result given when parameters were: 5 chunks and fracs = [0.1, 0.1, 0.3, 0.2]

```<code>Size of the dataframe: (2122905, 79)
fracs: [0.1, 0.1, 0.3, 0.2]
split_fracs: [212290, 212290, 636871, 424581]
(212290, 79)
(0, 79)
(424581, 79)
(0, 79)
(1698324, 79)
</code>```

As you can see, for the same parameter (0.1) I have one dataframe whose number of rows is 212290 and the one after it is empty. I tried using np.split at first and the results were no different. I really don't know where I'm wrong with this code and why the behaviour is like this.

答:
In order to split into different size data frames it's probably easier to use iloc and iterate over the ranges generated by your calculations.  I did something similar to calculate the number of rows per frame, then used a loop and counter to keep track of the start and stop row indicies.

Here's a sample dataframe you can copy and read with pd.read_clipboard()

I printed the results of each dataframe, but feel free to do whatever you like with them.

```<code>    a       b           c
1   43.91   -0.041619   43.91
2   43.39   0.011913    43.91
3   45.56   -0.048801   43.91
4   45.43   0.002857    43.91
5   45.33   0.002204    43.91
6   45.68   -0.007692   43.91
7   46.37   -0.014992   43.91
8   48.04   -0.035381   43.91
9   48.38   -0.007053   43.91

fracs = [0.1, 0.1, 0.3, 0.2]

start = 0
for x in [round(df.shape[0]*x) for x in fracs]:
    print(df.iloc[start:start+x])
    start += x
</code>```

Output

```<code>       a         b      c
1  43.91 -0.041619  43.91
       a         b      c
2  43.39  0.011913  43.91
       a         b      c
3  45.56 -0.048801  43.91
4  45.43  0.002857  43.91
5  45.33  0.002204  43.91
       a         b      c
6  45.68 -0.007692  43.91
7  46.37 -0.014992  43.91
</code>```

Body:
I've read several topics on this site about splitting a pandas dataframe into fixed size chunks, but I'm having a problem that I didn't see adressed here. So here's the process: I ask user for inputs as to how many chunks he wishes to have, then ask for the percentage of the dataframe to allocate per chunk, I verify that the percentages given do not go above 1, then proceed to split accordingly. The following is the last part, the one I'm struggling with:

def dataframe_splitting(df:pd.DataFrame, fracs:list):
    split_frac = []
    print('Size of the dataframe:', df.shape)
    print('fracs:', fracs)
    for i in fracs:
        x = int(i*len(df))
        split_frac.append(x)
    print('split_frac:', split_frac)
    chunks = np.array_split(df, split_frac)
    for x in chunks:
        print(x.shape)
    return chunks

And here is the result given when parameters were: 5 chunks and fracs = [0.1, 0.1, 0.3, 0.2]

Size of the dataframe: (2122905, 79)
fracs: [0.1, 0.1, 0.3, 0.2]
split_fracs: [212290, 212290, 636871, 424581]
(212290, 79)
(0, 79)
(424581, 79)
(0, 79)
(1698324, 79)

As you can see, for the same parameter (0.1) I have one dataframe whose number of rows is 212290 and the one after it is empty. I tried using np.split at first and the results were no different. I really don't know where I'm wrong with this code and why the behaviour is like this.

Body:
In order to split into different size data frames it's probably easier to use iloc and iterate over the ranges generated by your calculations.  I did something similar to calculate the number of rows per frame, then used a loop and counter to keep track of the start and stop row indicies.

Here's a sample dataframe you can copy and read with pd.read_clipboard()

I printed the results of each dataframe, but feel free to do whatever you like with them.

    a       b           c
1   43.91   -0.041619   43.91
2   43.39   0.011913    43.91
3   45.56   -0.048801   43.91
4   45.43   0.002857    43.91
5   45.33   0.002204    43.91
6   45.68   -0.007692   43.91
7   46.37   -0.014992   43.91
8   48.04   -0.035381   43.91
9   48.38   -0.007053   43.91

fracs = [0.1, 0.1, 0.3, 0.2]

start = 0
for x in [round(df.shape[0]*x) for x in fracs]:
    print(df.iloc[start:start+x])
    start += x

Output

       a         b      c
1  43.91 -0.041619  43.91
       a         b      c
2  43.39  0.011913  43.91
       a         b      c
3  45.56 -0.048801  43.91
4  45.43  0.002857  43.91
5  45.33  0.002204  43.91
       a         b      c
6  45.68 -0.007692  43.91
7  46.37 -0.014992  43.91